You are on page 1of 178

}

} -


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

STL
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Mathematics
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Bruteforce Backtrack
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Data Structure
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Greedy
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Dynamic Programming
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Graph Theory
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .


Adhoc
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Geometry
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. Pascal Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. UVa 1638 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. (a, b) = (4, 3) S = 4 . . . . . . . . . . . . . . . . . . . . . . .
. Ellipse n = 9 . . . . . . . . . . . . . . . . . . . . .

. UVa 1343 . . . . . . . . . . . . . . . . . . . . . . . . . .

. tree Euler path . . . . . . . . . . . . . . . . . . . . . . .

. Latitude Longitude, wikipedia . . . . . . . . . . . . . . .

. 30/i . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ACM ICPC World


Finals prize giving ceremony ?
,
1977
40 2017
platform ACM ICPC World Finals, IOI, Codejam,
Hackercup, Codefestival, Codechef Snackdown onsite event
online
4


(2011 )
NHSPC
, ,


onsite quality
quality quality
10 7-8
10 2 3
8-9

,
bfs dp bfs dp
,
fft kmp convex hull algorithm
theory

bfs , modify
bfs
bfs, dfs, mst, kmp, dp, gcd
,


- fft, nft,
persistent data structure, link cut tree


advanced contestant
advanced
contestant , advanced
, ? ?
" - "
2011 2013
2015 pdf 2016
5
theory ,
, 300-400
( 2013 icpc regional problem solution ,
neerc, ceerc chinese regional )
(
theory
!) ( )
( )

( )
timus beginner LightOJ

Greedy
codeforces


,

!
,
, ,

difficulty

,

(
) ()
, O n3 O n2


( )
4-5
1
,
,


( )
advanced coder

""

2400+ " "

UVa, Timus, Codeforces, LightOJ

codeforces
statement




git repository -
(https://bitbucket.org/shanto86/problem-book-1-solutions).
ac


Nayeem Jahan Rafi, Evan Hossain, Rezwan Arefin, Md Sahedul Islam Sohel,
Mohtasim Bellah, Moudud Khan Shahriar, Abdullah Al Raqibul Islam, Imran
Ziad Sumit Saha


algorithm online judge (oj) c/c++
online judge



!
c/c++

,
debug


Timus 1000 A+B Problem


: a b

: a b


judge clarification
offline online judge

OJ
, ambiguous

C prompt Prompt
"please enter your number", "please input a"
(UVa 100)
prompt prompt wrong answer (
output limit exceed presentation error) ?


online judge Online judge
, compile
input standard input
( scanf, cin ) oj
(fscanf, fopen, freopen )
frequently asked question
, output
output output
prompt output ?
prompt
prompt ?
prompt prompt
, oj ,
,
,
a b int ,
- !

Timus 1001 Reverse Root


: 1018
square root ( 4 decimal digit )
square root , square root
square root
256KB. - 1, 4
2, 1.
:
256KB. character 1 byte .
256K
, space
exact estimate 256K

square root
int , long long
double 1018 .

256K long long , memory
? long long
int 32 4 long long 64 8
(1 = 8 ) 8 256 = 23 28 = 211
2 float double ?
float int double long long compiler
os compiler os

2 ?
character text 1
K(Kilo) 210 , 1000 M(Mega) 220 G(Giga) 230 .


time limit memory limit memory limit
64
memory limit exceed !
DP DP

-
stl vector vector push back
vector iterator (iterator
, )
vector iterator vector
.

.: timus1001.cpp
#include <stdio.h>
#include <math.h>
#include <vector>
using namespace std;

int main() {
vector<long long> V;
long long a;
while (scanf("%lld" &a) != EOF) {
V.push back(a);
}
for (int i = V.size() 1; i >= 0; i) {
printf("%.4lf\n", sqrt(V[i]));
}
return 0;
}

EOF.
EOF
scanf EOF (End Of File)
scanf EOF

UVa 12108 Extraordinarily Tired Students


:
a
, b , a , b - (a b 5
) 1 a + b - a = 2 b
= 3 3 2 (3 2
1 ), 2 , 3 , 2 , 3
- a b

-1


: - trade-off Trade-off

-
, ! ,

10 (a+b). a + b
, lcm(1, 2, . . . 10).
? , a + b ,
a + b

lcm lcm
lcm
1, 2
state

lcm
106 107
!
" " " " state
a, b
,

n
n

main
WA
n


vector



! trade-off!

UVa 253 Cube painting


:
orientation
, ,
-

: ""



trade-off! , dumb
?
?
if-else
////-
/
if-else 24 if (
6 == )

orientation
xyz axis axis (x+, x-,
...). x+ x axis
orientation ( y+ -
)
, if else

if-else 24 6 ( i
) loop if

ugly
(statement ) 1 6 , 2 5 3 4
7. , ,
,
24 6 24 3 ,

? ,
fix 1 2, 3, 5,
4. circular

(4 )
1 2, 3, 5 4. 4 2, 1, 5 6

,
,
? ? 6 4. !
, !

Timus 1005 Stone Pile


: n n 20 100, 000
,
A B. A B

: (100, 000)
coin change dp
- dp


DP A B
!
backtrack 1
n
backtrack parameter
( 1- n- )


( ) ,
time complexity O 2n n
,
n 2 2n ( " 2n "-
combinatorics discrete math )
Backtrack 0 2n 1
binary representation n bit binary
n 0 1
0
1
n 2. 0
22 1 = 3 ( binary ) 0(00), 1(01), 2(10), 3(11).
00 , 10
( i least significant bit, i
0 indexed ,
0 ) ()2
3 time complexity O n2n
0 2n 1 n 0-1
Backtrack
n complexity
backtrack
n
bitmask 0-1
n
bitmask n
mask (bitmask ) 0 2n 1
mask ( mask
) ,
,
1
mask = x mask < x
1 mask = x
on (1) (mask^ = 1).
mask sum on mask
mask mask
on mask
on n
: Dynamic Programming Coin change dp
variation
bitmask "all possible" bitmask



on on
? , 2 3 2nd bit on, 4 7 3rd bit , 8 15
4th bit 2i1 2i 1 i on.
0 2n 1 0 n 1 i
mask i (
) observation on
2i 2(i+1) 1 complexity O 2n
backtrack bitmask .

.: timus1005.cpp
int num[22], n;
int onBit[1 << 20], sum[1 << 20];

void backtrack(int at, int group1Sum) {
if (at == n) {
// Find group2Sum
// Keep a global variable to track answer.
return;
}
// Don ' t take num[at].
backtrack(at + 1, group1Sum);
// Take num[at].
backtrack(at + 1, group1Sum + num[at]);
}

int main() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &num[i]);
}

bktk(0, 0); // Solution in backtrack.

// Solution in bitmask.
sum[0] = 0;
for (int i = 0; i < n; i++) {
for (int mask = (1 << i); mask < (1 << (i + 1))-
; mask++) {
// i is the on bit.
sum[mask] = sum[mask (1 << i)] + num[i];
// Update answer, one part is: sum[mask] -
and another part is
// total sum[mask].
}
}
return 0;
}


n

(
) , complexity
O 2n1

Timus 1014 Product of Digits

: 0 109 N
Q Q N
1 N = 10 Q 25.

: Q N
N N 2, 3, . . . 9
N 1 Q
N 26 2 9
13 Q
? Q 2 9 ? 0 1

"specially handle" 2 9
N 2, 3, 5 7 prime
, prime N 2, 3, 5 7
3 2 8
, 2
2 4 , 2 3 6 3
9 combine

Q (758 578 )
2, 3, 5 7 combine 5
7 combine , combine 2 3 5 7
combine 1
case 2 3
2
8 4 4 2.
? 21 , 22 , 23 . . . 21 0 10 N
risky
,
-
! , 3
2 3 case analysis
9 , 8, 6, 4 ,
, Case analysis
intuition
codejam hackercup contest submit
dp backtrack claim
N = 1 1000
N


Timus 1020 Rope
: N ( 100) ( R ) convex polygon
N
?
:

convex
polygon ?
,
R
360 R


Timus 1044 Lucky Tickets. Easy!


: n ( 9 n )
1322 4

: leading zero allowed
allowed. n n/2

S k k
k S ,
k 2 S
k 2 n/2
? , Timus 1005 backtrack
, n 9 n/2
4.
? n/2
0 10n/2 1 Timus 1005
x
sum[x] = sum[x/10] + (x%10).
x
optimization ,

Timus 1197 Lonesome Knight


:
a1, g6
: row
column string


string character a ascii
character 1 ascii (word[0] - 'a' )
(r, c) ?
(r + 2, c + 1), (r + 2, c 1), (r 2, c + 1)
8 (r + 2, c + 1) ?
8
(r + 2, c + 1)
8
a1 (r 2, c 1)
(0 newR 7
)

row column
: dr[] = {2, 2, 2, 2, 1, 1, 1, 1} dc[] = {1, 1, 1, 1, 2, 2, 2, 2}.
i 0 7 (r +dr[i], c+dc[i])

UVa 202 Repeating Decimals

: a b (0 a 3000, 1 b 3000). a/b


: 2/15 = 0.1(3).

:
confusion


? , (
), ,

, a b
? 0 b 1
? b
? 2 15
2 5, 5 5
0.1(3). , 655/990.
655, 610, 160, 610. 160, 610,
160, 610
0.6(61). b

0/1 0
1
1
, x
x
x ,


.
..
Simple
Timus 1264 Workdays Timus 1293 Eniya
UVa 1583 Digit Generator Timus 1409 Two Gangsters
Timus 2012 About Grisha N Timus 2023 Donald is a postman

UVa 10082 WERTYU UVa 401 Palindromes

UVa 1584 Circular Sequence UVa 1585 Score

UVa 1586 Molar mass UVa 1225 Digit Counting

UVa 455 Periodic Strings UVa 227 Puzzle

UVa 133 The Dole Queue UVa 1368 DNA Consensus String

UVa 10340 All in All UVa 1587 Box

UVa 1588 Kickdown UVa 11809 Floating-Point Numbers

UVa 1339 Ancient Cipher UVa 489 Hangman Judge

UVa 1591 Data Mining UVa 815 Flooded!

UVa 272 TEX Quotes Timus 1068 Sum

Timus 1082 Gaby Ivanushka

Easy
Timus 1025 Democracy in Danger Timus 1313 Some Words about Sport
Timus 1079 Maximum Timus 1149 Sinus Dances
Timus 1319 Hotel UVa 340 Master-Mind Hints

UVa 232 Crossword Answers UVa 213 Message Decoding

UVa 512 Spreadsheet Tracking UVa 201 Squares

UVa 220 Othello UVa 1590 IP Networks

UVa 508 Morse Mismatches UVa 509 RAID!

Medium

UVa 12412 A Typical Homework UVa 1589 Xiangqi

..

UVa 272:
gets scanf, printf gets

" "
, gets

Timus 1068: N 1

Timus 1025:
Timus 1313: row column 0
N 1 diagonal


row id column id


!
Timus 1079: n overflow
!
Timus 1149: ,

STL

STL Standard Template Library.


(sort, binary search ) data structure (queue, stack -
) STL STL
STL STL -
STL STL
STL STL
STL
interview
STL implement
STL complexity
STL
STL
STL , STL
STL

STL
STL
STL
STL

UVa 10474 Where is the Marble?


: N (N 10, 000) 10, 000
query
( 10, 000 query) query q
q , : 1, 3, 3,
5 2 3 2nd
: A
STL sort
algorithm include "using namespace std;"
include

namespace stl


( ) "sort(A, A + N)"
A[0] A[N - 1] A[1] A[N]
"sort(A + 1, A + N + 1)" A[a] A[b]
sort "sort(A + a, A + b + 1)".
pointer
, query
, ? binary search
stl lower bound upper bound
algorithm Lower bound upper bound
Lower
bound upper bound
Lower bound query
upper bound
query
1, 2, 2, 4, 5 2 lower bound call 2
, upper bound call 4 lower bound
upper bound call ? "lower bound(A, A + N, q)"
A 0 indexed ,
- ? Index? , pointer. index
lower bound return A 0-indexed
"lower bound(A, A + N, q) - A".
index 0 indexed 1 indexed
? sort "lower bound(A+1,
A+N+1, q)".
time complexity binary search
, time complexity
complexity random
access data structure (random access
constant
( ) index access )
(O n ) list, set linear list set
i index constant
element lower bound upper bound

,
,

place[A[i]] = i 10,000
, ? - ?
index
stl map.
M["hasan"] = 3 hasan
3 () M["hasan"] 3
map declare syntax
"map<string, int> M;" ,
"M[?] = ?"
map "? = M[?]"
Set lower bound upper bound "set<int> S" set
"S.lower bound(q);" lower bound
"lower bound(S.begin(), S.end(), q);"



long long
( )int Map
( )
O log n n map n O n
memory

UVa 101 The Blocks Problem


: 0 n - 1 n n 25 0 n -
1 n pile id id pile i
i pile instruction Instruction 5
"move a onto b" a b

pile
,
, ( !)
instruction "move a over b" a b pile top
a
"pile a onto b" b
a b "pile
a over b" a b pile
"quit"

: Pile stack pile
a pile
? ,
a stack
vector vector

vector ( )
"V.push back(10);" 10 "pop
back" constant
vector
"V[4]" 4 index access
vector push back, pop
back size (vector
), clear ( vector )
, vector
erase, insert, find "
insert, erase vector find "
insert erase find
worst case push back, pop back index V [i]
access constant
resize. 100 vector V
V.resize(50) 50 50
V.resize(100) 50
garbage value 0 initialize
Find vector algorithm sort/lower bound

find(V.begin(), V.end(), x)


V.resize(100, 0). n n
V.resize(n) n V
&V[i] V[i]
vector -
implement pile
pile
pile pop back -
pile push back
vector

UVa 10815 Andy's First Dictionary


: punctuation
capital small letter
lexicographical case insensitive -
apple, AppLE, APPLE
lower case
: lower case
? , character
character upper case ('A' <= word[i] && word[i] <= 'Z')
lower case (word[i] = word[i] - 'A' + 'a'). word stl
set set stl set
set lexicographical
string set
declare "set<string> S;"
stl string (string )
char* set char* set
( comparison function )
"char word[20];" set
"S.insert(word);" char string
convert set c++11
range based loop "for(string w : S)" cout printf
w print cout
printf stl string printf
printf("%s", w.c str());. set
size() - unique count
insert count , count
empty() - ? count(x) - x ,
0 1 count complexity
?
space gets
char line[100]
non alphabet character space ( )
upper case letter lower case (
upper case, lower case ) stl istringstream
(sstream ) declare "istringstream iS(line);".
line istringstream ( input string stream) ,
iS. -


while(iS >> w) w stl string (string w). stl
set
set istringstream ,
(set size ) set erase ,
set lower bound upper bound
stl

Timus 1209 1, 10, 100, 1000...


: sequence : 110100100010000 . . .. k
1 k 231 1.
:
1 1, 2, 4, 7, 11
pattern :
1 = 1 + (0), 2 = 1 + (0 + 1), 4 = 1 + (0 + 1 + 2), 7 = 1 + (0 + 1 + 2 + 3). i
1 + (0 + 1 + . . . i). !
k i quadratic equation

sequence 1
1 linear 1 0,
1
1, 2 3, 4, 5... 2
31

2 1 ? , i 1
31

i2 (
(i(i + 1)/2 + 1) ) 231
231 1 1
( 0 + 1 + . . . i ) set
set
binary search stl
count, find, lower bound upper bound

UVa 156 Anagrams


: letter anagram
SPOT POTS. case
anagram
case anagram spot spot
anagram , spot SpoT anagram.
anagram ananagram text
ananagram lexicographical
: UVa 10815
anagram
anagram anagram letter
case
sort
(case insensitive comparison , string compare case


) S1 S2
(S1 != S2) (sort(S1.begin(), S1.end()) S2
) upper case letter small case
S1 S2 (S1 == S2). character
upper case letter lower case
canonical form ? -
anagram canonical
form anagram canonical
form
anagram
set
anagram - , -
case
-

canonical form
canonical form -
? canonical form anagram
ananagram canonical form
anagram canonical form.
canonical form canonical form ananagram
anagram. ananagram
canonical canonical form anagram
insert ananagram -
anagram anagram.
canonical form anagram
anagram ananagram.
canonical ananagram insert
ananagram canonical form
- canonical form
canonical form ananagram
ananagram. ananagram -
, lexicographcal order
? set ,
vector
anagram lexicographical
set vector
set ( )
, set vector

UVa 12096 The SetStack Computer


: stack 2000
Push {} Dup stack
Union Intersect stack
element pop union intersection Add
stack element (stack


) A = {{}, {{}}} stack
B = {{}, {{{}}}} stack union
{{}, {{}}, {{{}}}}, intersection {{}} add {{}, {{{}}}, {{}, {{}}}}.
stack
: ! !
id
nested id , nested
id, id
id set<int>. stack
map
, id map
map<set<int>, int> int int map
reverse map id
map vector (vector<set<int>>).
stack stack ,
id stack id
id stack Push
map , id map
id stack push Dup stack
element push Union Intersect stack
id vector set. union
intersect map, stack vector (
map , map vector ) Add
id map, stack vector
, vector
id insert copy
debug
map vector
stack stack
stack int stack declare
stack<int> S push(x) - x
pop() - element pop return
, element top() - stack element return
empty() - true stack size()
- stack

UVa 540 Team Queue


:



200,000 instruction
: Stl queue queue
queue (
queue), queue.
queue queue


queue (
id ) queue queue
, queue
queue queue

Stl queue queue int queue
declare queue<int> Q - push(x) -
x , pop() - , front() - queue
, size(), empty() stl

UVa 136 Ugly Numbers


: 2, 3 5 ugly
1, 2, 3, 4, 5, 6, 8, 9 1500 ugly
:
ugly (
), ugly 2, 3 5
,
ugly 2, 3 5
1500 1
minimum stl
set priority queue Priority
queue
6 ( 2 3
3 2). set set

"*S.begin()" ( star )
x
"S.erase(x)"

UVa 1592 Database


: 10,000 row 10 column
text row column text
column text row
(r1 , r2 ) column (c1 , c2 ) (r1 , c1 ) = (r1 , c2 ) (r2 , c1 ) = (r2 , c2 )

: r1 , r2 , c1 , c2
c1 , c2
r1 , r2 condition
row string
set map row
- 6 simulate


r1 , r2
, r1 , r2 , set
map string row
row string map
r1 , r2
string ?
vector string structure declare
string structure map
structure comparison function
< operator overload "
" functor declare
vector operator overload
, string vector < operator define
string pair
Pair stl member variable structure
utility declare
pair<string, string>. variable pair
"pair<string, string> P = make pair(A, B);" A B
string. pair element "P.first"
"P.second". Pair pair
vector array sort comparison

variable pair extend
structure
tuple tuple

string represent

? string push back gets
( space ) push back
string string
vector row column
vector

UVa 12100 Printer Queue


: queue priority
queue priority queue

Queue mark
1 , queue
100
: priority
priority queue priority
priority queue ,
queue priority queue ( queue)
100 O n2 +n log n


( )
O n2 -
( ) ( )
O n O n queue
( )
priority queue O log n .
( )
n O n log n . priority queue
constant
, priority queue queue -
queue , front() top()
top set
set insert -
set map count
priority queue

.
..
Simple
UVa 1593 Alignment of Code UVa 1594 Ducci Sequence
UVa 10935 Throwing cards away I UVa 10763 Foreign Exchange
UVa 1595 Symmetry UVa 230 Borrowers

UVa 1596 Bug Hunt UVa 822 Queue and A

UVa 12504 Updating a Dictionary UVa 511 Do You Know the Way to San Jose?

UVa 400 Unix Is

Easy
UVa 1598 Exchange UVa 12333 Revenge of Fibonacci
UVa 212 Use of Hospital Facilities UVa 207 PGA Tour Prize Money
UVa 814 The Letter Carrier's Rounds UVa 221 Urban Elevations

UVa 1597 Searching the Web

..

UVa 1594: sequence


vector map 200 500
,
200 500 !
UVa 10763: pair vector
pair pair (a,b b,a). vector sort
== compare
UVa 207: %s , %20s %9.2lf %-20s
? stl
sort comparison
UVa 814: string find
character character


, substr(x, y)- x
y - 1 substring email address
, for loop

Mathematics

UVa 11582 Colossal Fibonacci Numbers!


: Fibonacci ? f (0) = 0, f (1) = 1, f (n) =
f (n 1) + f (n 2). a, b, n (0 a, b < 264 , 1 n 1000)
f (ab ) mod n

: n f (i) mod
n theoretically
ab
matrix exponent
sequence recent matrix exponent -
,
, ab fibonacci ab
Matrix exponent i fibonacci
log (i), ab fibonacci log (ab ) = b log (a)
matrix exponent
sequence n = 6 f (i) mod n
- 0, 1, 1, 2, 3, 5, 2, 1, 3, 4, 1, 5, 0, 5, 5, 4, 3, 1, 4, 5, 3, 2, 5, 1, 0, 1.
, 0 1 ,

, , -
, length

- ? mod n
, 0 n 1
n2 n2 + 1 length
pair n2 pair
-
0, 1 . . . , 0, 1, . . . ? 0, 1 ,
a, b f (i) mod n 0, 1 . . . , a, b, . . . , a, b, . . .. a, b
? b - a. a, b b - a.
a, b ,
? 0, 1
- length n2


practically n
1000 3000 ? ,
7-8
n vector
(vector ) n length
c. ab mod c bigmod
overflow f (ab ) mod n vector
ab mod c

UVa 12169 Disgruntled Judge


: x1 , a, b, T (0 x1 , a, b 10000). -
xi = (axi1 +b) mod 10001 x2 , x3 , . . . x2T
x1 , x3 , x5 , . . . x2T 1 x2 , x4 , x6 , . . . x2T

a, b x1 , x3 , x5 , . . . x2T 1
x2 , x4 , x6 , . . . x2T T
100

: a b 2T
a b T = 1010 . ?
- a b -
x1 x3 a b

x3 x1 - x3 ax2 + b a(ax1 + b) + b
a2 x1 +ab+b( mod 10001) x3 a2 x1 = b(a+1)+10001c c integer .
a equation unknown b c.
equation - bp+cq = r p, q, r constant
b 10000 ? ,
p = a + 1, q = 10001 r = x3 a2 x1 bp + cq = r
b 10000
unknown x, y, z b
x c y px + qy = r.
euclid -
extended gcd x0 , y0 px0 +
qy0 = g g p q gcd. general solution p(x0 +tq)+q(y0 tp) =
g t integer constant. extended gcd properties.
r integer constant
k (k = r/g). kp(x0 + tq) + kq(y0 tp) = r.
b ( x )
equation satisfy 10001 ( 10000
10001 ) 0 k(x0 + tq) < 10001
x0 /q t < 10001/qk x0 /q. q = 10001.
x0 /10001 t < 1/k x0 /10001. 1/k
, [x0 /10001, 1/k x0 /10001) integer
constant, equation
a b(modc) a = b + kc k integer.


, a 1 b
x1 x3
- a Extended gcd b
T x1 . . . x2T
aT = 106 . extended gcd
, x1 . . . x2T
a

UVa 10375 Choose and divide

: p, q, r, s (
) ( )
10000. p q r s. pq / rs
108 5 digit precision

:
( )
( )
pq rs
decimal
perfectly ( )
? rs ,
(
) precision loss double
pq precision loss 101
100 100 100 (
precision )? ? term
(pq+1)...p
1...q (rs+1)...r
1...s
. ,
108 , 104
variable ans. L R ans
lower upper bound L R
, ans 1
L ,
ans R

condition ,
L = 1 R = 1012
ans
vector
vector
variable

, double

, 0


UVa 10791 Minimum Sum LCM
: N (< 231 ) ( )
N N
= 12 3 4. 12 7
100 test case

: ?
prime factorization
prime
power prime power
4, 6, 18
4 = 22 , 6 = 2 3 18 = 2 32 . 2 power 2,
3 power 2 22 32 = 36.
prime factorize
231 N prime factorize
N prime generate N prime
factorize prime factorization pk11 pk22 pk33 . . ..
p1 , p2 . . . prime
, power k1 , k2 . . .
prime distribute ?

, prime
prime power
? 12 = 22 3
22 22 2
22 3
22 , 3 22 3 ? 22 + 3 < 22 3.
prime ?
2
pk11 , pk2 , . . . ?
ab a + b? , ab?a + b ab b?a b? a1 a
. ?
<, > =. 1
2. ab a + b
a, b prime power ( ,
ab > a + b 1 1 > 1 + 1 ) optimal
2
pk11 , pk2 , . . ..
,
N

UVa 12716 GCD XOR


: 10,000 N ( 3 107 ) -
(A, B) 1 B A N gcd(A, B) =
xor(A, B) N = 7 4 (A, B) (3, 2), (5, 4), (6, 4), (7, 5).
: gcd xor
gcd xor bitwise representation


pattern
N 100 pair
pattern pair (85, 68), (90, 72)
pattern pattern
gcd xor
pair gcd xor
xor gcd N 100
pair -
? ? - efficiently


N 1000 10,000
claim N
claim
, A B xor(A, B). ? B bit 1
A 1 A B xor(A, B) xor
gcd(A, B) A B
gcd(A, B) A B gcd(A, B) A B.
gcd(A, B) A B xor(A, B). xor gcd A B

A B A B
gcd xor pattern explore


A B A B
candidate gcd.
gcd gcd variable
g. A B ? A B g multiple
( ) A - B g ( )
A B A g. A
? () 1 N i i g
O N g multiple
g N g [for(A
= g; A <= N; A += g)] 1 N /g ( ) i A i g.
nested loop O N /g . g 1 N
N /1 + N /2 + . . . N /N N log N .
nested A, B g ( )
xor(A, B) = g gcd(A, B) = g O log N
A B
g multiple. A = ig B = (i 1)g g
g i i 1. coprime.
? coprime p
i (i 1) p ( p p
) 1 p ?
gcd
A gcd multiple. B = A g.
xor(A, B) = g !
? pattern


UVa 1635 Irrelevant Elements
: n m (1 n 105 , 2 m
109 ). n a0 , a1 , . . . an1 0
m 1 a0 + a1 , a1 +
a2 . . . an2 + an1 n 1 n 2

modm ai
n = 3 m = 2 a1 ?
n = 3 a0 + 2a1 + a2 mod m 2 mod
a1
:

common
n
n = 2 a0 + a1 . n = 3 a0 + 2a1 + a(2 . n) = 3
a + 3a + 3a2 + a3 . ? n n1 0 a0 +
(n1) 0 (n1)1 (n1)
1 a1 + 2 a2 + . . . n1 an1 . ? pascal
triangle contribution .


contribution
a1 ()
(41
)
1 L 2 R 2+1 1 = 1
( n 4) (n1
) ai
ai coefficient i .

a0 a1 a2 a3

.: Pascal Triangle
( )
i ni (n
( )
1 ) m m prime nr
( ) ()
plan n0 m , n1
( n)
n ( )

( ) ( n )
, ni ni = ni+1 i i1 . m prime
factorize () prime power
ni n i + 1
i m prime
divisor prime
prime power power


m power
- m prime
( ) factorize prime divisor
power ni (i 0 n )
m
prime count
prime power m power
,
n prime factor
complexity

UVa 10820 Send a Table


: N ( 50, 000) (x, y) x
y (1 x, y N ). 600 test case

: x y - phi function
Euler's totient function phi(i) i
i
N
x y i=1 phi(i) i = y fix
x phi(i)
phi phi
cumulative sum Cumulative sum
sum(i) = phi(1) + . . . phi(i) sum(i) = sum(i 1) + phi(i).
phi(i) i i coprime
x y i > j
i j ,

UVa 1262 Password


: 6 5 (6 row, 5 column) character
5 length valid password i character
i K K lexicographically smallest
valid password
: Counting lexicographically smallest common
character
i1 K
i A
X A , X K
A K X i B
C, D, E Z
password

? column
character


10 ,
A , A ,
valid ? 1 10
A A
9 ( ) B
valid 50
B A
BA ? 4
9 A 5
B BB 0
C

character , A Z character
character
character

character

UVa 1636 Headshot


: n slot slot slot
russian roulette
slot random slot
fire
option. - slot random slot -

n 100.

:
-
slot n
slot a n a slot randomly
slot na n . ? n slot
randomly n slot n a
slot n a n a n
slot

triggure
slot

slot 0011 (0 , 1
) slot


0.5. slot 010101 1.
0 1
basic


UVa 10491 Cows and Cars
: game show a b

c (c < b)

: n = a + b n.
, na . n 1 c

n 1 c (
a/n probability )
n 1 c a 1 n 1 c
n1ca1
.
na n1c
a1
.

nb . n 1 c
n 1 c a n 1 c
randomly n1c a
.
n n1c .
b a

na n1c
a1
+ nb n1c
a
.
probability
coin
head p1 , p2 , p3 . coin head
coin, coin tail coin
head , coin
p1 head , coin
head p2 . p1 p2 .
coin tail coin (1 p1 )p3 .

coin head coin coin
coin coin head "" coin head
p1 p2 + (1 p1 )p3 . ,
"" ""
"" ? - dart
board dart board ,

dart board random
1/3 (
) 1/3, 1/3.
"" ? ?
1/3, 1/3 1/3 + 1/3 = 2/3.
" "
2/3
board dart ?
1/3 1/3 = 1/9 ? dart 9 - (, ), (, ),
(, ), 6
combination 1/9.


1/9. counting Counting
"" ""

UVa 11181 Probability Given


: N (N 20).
p1 , p2 . . . pN . r

: i pi .
" r "
p1 , p2 . . . pN unconditional.
, i
pi . condition -
r ...
Real Madrid Barcelona
cup (!) status
Messi Barcelona 30% Real
Madrid 70%. Barcelona
"Barcelona , barcelona
" ? "100%".
"Barcelona " Barcelona
"r "

p1 = 0.3 p2 = 0.8. -

1 2 0.3 0.8 = 0.24

1 2 0.3 0.2 = 0.06

1 2 0.7 0.8 = 0.56

0.7 0.2 = 0.14

r = 1
space
1 0.06 + 0.56 = 0.62
space. space ( 1 2 )
0.06/0.62 ( 1 2 )
0.56/0.62. 1 6/62 2 56/62.
? condition
space. space
weighted
, 0.56 0.06
0.56+0.06
0.56
0.56+0.06
0.06
.
- r 1 n = 4 r = 2
, !

r
space (S)


1 ? 1
() S ? N 20
Nr backtrack N
r bitmask

UVa 580 Critical Mass


: N (N 30). N U
L 3 U
: U U
? U " "
" " character
U character
U
U , character
, U
N U 2N

U
counting counting DP
dp[n] n valid n valid
-

L. n 1 dp[n 1]

UL. n 2 dp[n 2]

UUL. n 3 dp[n 3]

UUU recurrence dp[n] =


dp[n 1] + dp[n 2] + dp[n 3]. Base case
Base case n
base case. n 1, 2 3
negative 0 dp (
0 ) 1, 2 3 base case ,
n dp[n]

UVa 12034 Race


: n (N 1000). -


- , - , -
mod10056


: counting dp. dp[n] n
( ) i
i ni n i
? dp[n i] n
1 1000 dp[n] (
) i
ni dp[n i] dp[n]
( ) ()
ni ji
(n) (n1) (n1) ( )
i = i1 + i recurrance O n2
generate

UVa 1638 Pole Arrangement


: n building (n 20) 1, 2, . . . n. building
order - 4, 2, 3, 1 ( .)
4 building
building 1, 3, 4. 2
building 3 building
building (L) (R).
n building

.: UVa 1638

: coutning dp order building


building ,
building order n 20
order building
- building height order
1 i building building
state
building
20, 10, 30 20, 30. 20 30 40
, building
?

building n.
n L n R building
n building


height n x building
building height 1 x map building 1,
2 x.


n building i
i building
( ) height ,
n building. n1 i i building
i building 1 i height map
n 1 i building mapping (1
n 1 i ) i building
L 1 building (L n height )
n 1 i building R 1
building count i i

reduce 1 n n building (
height 1 n) X building
n building
building (ncr ) i building.
i building X - 1 building
building dp state (n, X).
i (i, X 1) call n i building

UVa 1639 Candy


: n (n 200, 000). p
, 1 p

expected
: i
(a) n
, (b) n i n
a a ( n )
b n i order n+ni n
order , probability
a n probability pn , b n i
probability (1p)ni . (
) n+1 a (ni)
,
p. probability 2nin p (1p) . b n

(n) ?
n i , p n

logarithm
logarithm -
log (2n i)! log n! log (n i)! + (n + 1) log p + (n i) log (1 p).
exponent (e power). probability
b ( ) i i probability i


expectation , log n!
? , log n! = log 1 2 . . . n = log 1 + log 2 + . . . + log n.
n log n!

UVa 10288 Coupons


: n (n 33)
random n
expected
: expected value expectation
approach iP (i)
i expected
? i
n i n i
p = nin . expected 1/p
i + 1 expected
i + 2, i + 3 . . . n
probability p expected
1/p ? j
j1 , (1p)(j1) j ,
p. j ( j

) P (j) = p (j1)
(1 p)(j1) . expected value
j P (j) = j p (1 p) . series
jsum
calculus 1/(1 p) = p .
(1 p) power

series sum p 1 p 1/p = (1 p)j .
p differentiate 1/p(i1)
2
= j (1 p)(j1) .
1/p = j p (1 p)
expected value
E. p 1 p 1 p
E
( ) (1 p)(1 + E)
E = p + (1 p)(1 + E) E = 1/p.

UVa 11346 Probability


: (a, b) (a, b) rectangle special special
(x, y) randomly (x y
) (0, 0) (x, y) rectangle S
S, a, b

: calculus -
quadrant quadrant
symmetric special (x, y)
rectangle symmetric. first quadrant


(0, 0) (a, b) special
(x, y) S
, xy = S S
(up) S
S xy = S
special ab
(x, y) S
ab
xy = S

3 (4, 3)

2 xy
=
4

0
0 1 2 3 4 5

.: (a, b) = (4, 3) S = 4

(a, b) = (4, 3)
S = 4. first quadrant . xy = S = 4
(0, 0) (4, 3)
shaded
(x, y) S
shaded
xy = 4
(S/b, b) = (4/3, 3) S/b b = 4/3 3 = 4 = S.
S/b = 4/3 a = 4 xy = 4
a S a

integration x dx = S ln x S ) .
= S(ln (a) ln (S/b)) = S ln( ab
S/b S/b

a b
S ab
(0, 0) (a, b)
S ab
probability
special case Case
(0, b) (a, b) xy = S , S/b > b.

ln (a) ln (b) = ln (a/b)


UVa 10900 So you want to be a 2n -aire?
: game show 1 n
(n 30)
t 1 random (0 t 1).
quit quit
quit

0 expected
maximize expected
: dp i
expected base case ? n
, n + 1
2n
base case f (n + 1) = 2n . recurrence i
expected t 1
p. - quit
2i1 -
? p f (i+1) (1-p) 0
expected p f (i + 1). maximize
? ? - expected
max(2i1 , p f (i + 1)). p
expected p t 1 ?
t 1 expected
t 1 t 1
1
? integration- 1t 1
t
max(2i1 , pf (i + 1))dp.
(1 t) ? t 1 integrate

integration ? f (i + 1) constant p
C = f (i+1). integration
1
1t 1
t
max(2i1 , pC)dp. pC < 2i1 p < 2i1 /C
max 2i1 pC. integral
t 2i1 /C 2i1 /C 1.
2i1 /C t 1

expectation
calculus Integration max

UVa 11971 Polygon


: N randomly K
(1 N 106 , 1 K 50) K + 1
polygon probability ?

:
idea pattern



chinese site 4

K + 1
1/2
1/2 probability ? 1/2 ?

1/2
1/2
, polygon 1/2 polygon
, N
1 ? , N
? 1 valid, 100 valid
propotionally - 1 1/3 100
100/3 - 1 valid 100 valid
N
1.
" segment 1/2 " probability
" segment 1/2 " probability
segment 1/2 1/2
(
K > 1 K = 1 polygon
) K randomly K + 1
x0 , x1 , . . . xk x0
x0 [1/2, 1] ,
K [1/2, 1] probability ?
[0, 1] probability 1/2. K
probability K 1/2 21K . ? ,
x0 segment
random K
? random K segment
y0 , y1 , . . . yK . cyclically
y1 , y2 , . . . yK , y0 y2 , . . . , yK , y0 , y1 cyclically



? K +1 K ,
K + 1 1/2
K+1 2K
21K K + 1

polygon probability 1 K+1 2K
.
calculus
segment x. x integration 1/2
integration [0.5, 1]. segment

x dx x
dx
1 = dx 1 K
? K (


? K K )
1 x K 1
(1 x) probability (1 x)K1 . x
K(1 x)K1 dx. x probability
( 2 ).

x x
(1 x)
(1 x). x dx.
K x
K (K 1) (
- ) K(K 1)
x
K 2 x x
(1 x) (1 x)K2 x
K(K 1)(1 x)(1 x)K2 dx. x
integration

translate

UVa 1640 The Counting Problem


: a b (1 a b 108 ).
( ) digit 0
, 1 9 digit
a b condition
b < a swap
: mathematical a b
count
f (n) 1 n f (b) f (a 1)
, a b

, n 1 n
- 315097.
1 315097
6
0 9 1 n
i ( lsb
i = 0, i = 1 ) d d
0 9 , i 0 5 ( 6
0 indexing ) 315097 i = 3 d = 1 count
i = 3 (L = 31)?
(R = 097)? (S = 5)? d S ,
d = 1 S = 5
1 ? i = 3 1
0 31 32 (L + 1)


000 999 1000 (10i ) 1
32 1000 (L + 1)10i d > S ?
31 ? d = 7 > S = 5 (31)7(???)
1 315097
0 30 31 1000
7 d = 5 = S = 5 case.
31 31 000 999
000 097 (R) 0 30
d > S case L
R + 1 i d

i = 5 d = 0
i = 0 R ? R
risk R
315097 ( i = 0 ) 1 ? 1
0 31509 31510
R d = S d > S

,
step
step

UVa 10213 How Many Pieces of Land?


: ellipse n (1 n 231 )
ellipse

:
polynomial degree
polynomial n
n = 1, 2, . . . 6 n
n

n i polynomial ,
6 p(n) = ai n . n = 1 . . . 6 f (n)
n f (n) 6 variable (a0 , . . . a5 ) 6
equation gaussian elimination a0 . . . a5
Lagrange interpolation
advanced
wiki

euler's formula- V E + F = 2 V vertex ,
E edge F face Face ""
face
vertex,
edge face


3 3 + 2 = 2.
vertex 5 Edge 8
face 5 4
5 8 + 5 = 2.
! vertex edge
, face
( face count )

2 ellipse (ellipse
)

X I
face n
vertex ?

1
2 9

3
8

4
7

5 6

.: Ellipse n = 9

. ellipse 9 1 5
1 5 ? ,
3 4 3 4
i n i 2
i(n i 2) 1 2
i = 0. 3 i = 1 9
n2 i = 7.
i=0 i(n i + 2).
n
n , over count
over count ?
count AB CD ,
A, B, C D count 4
count sum 4
sum 4 n
vertex n sum
sum closed form .


closed form


n2
V = i(n i + 2)
i=0

n2
= ni i2 + 2i
i=0

n2
n2
n2
(.)
= ni i2 + 2i
i=0 i=0 i=0

n2
n2
n2
=n i i2 + 2 i
i=0 i=0 i=0
(n 2)(n 1) (n 2)(n 1)(2n 3) (n 2)(n 1)
=n +2
2 6 2

E E
vertex degree 2 E
degree degree 4
degree n + 1 ( 1 2 9 edge
1 ellipse border , edge, ellipse border
1 2 9 ) 2
E euler V E F

n 231 n3
long long overflow c++
bigint java java built in library
BigInteger c++ java

UVa 1363 Joseph's Problem


n
: n k (1 n, k 109 ). i=1 k mod i
: i i
(integer division) n
i 1 30 30/i .
1
30, 2 15 3 10.
16 30 30
1 11 15 2 i
k/i

? k

i 1
k/i k i
k/i > k.


i 30/i i 30/i i 30/i
1 30 11 2 21 1
2 15 12 2 22 1
3 10 13 2 23 1
4 7 14 2 24 1
5 6 15 2 25 1
6 5 16 1 26 1
7 4 17 1 27 1
8 3 18 1 28 1
9 3 19 1 29 1
10 3 20 1 30 1

.: 30/i

i i k/i
k j ( j 1 k )
j ? decimal division
a k/a = j a = k/j.
j = 1 30/1 = 30 1 ( 31
0 ) j = 2 30/2 = 15 (16
1 ) 2 j = 3 30/3 = 10
10 3

k integer
k ( j
) 9
30/9 = 3 3 10. 9
k
1
(30), 2 (15), 3 (10)

1 16 30, 2 11
15 j count ,


,
mod nk mod i = k (k/i)i

n integer division.
n i=1 k (k/i)i
i=1 (k/i)i i=1 k = nk
n k i = k + 1 n k/i
0 n k.
k i = 1 (k/i)i
k/i > k ( i n

) j 1
k j k/j. j + 1
k/(j + 1). k/(j + 1) + 1 k/j k/x = j
x sum (k/i)i
jx j x


j x k/(j + 1) + 1 k/j

n

UVa 11440 Help Mr. Tomisu


: M N (1 M N 107 N M 105 ). 2
N! (N factorial) prime divisor M ?
500 test case
: mathematical
observation
observation 2 N!
M! coprime ? M! M
prime M prime M!
coprime phi(M !) ? M !(1
1/p1 )(1 1/p2 ) . . . pi M prime. 107
prime generate 107 factorial
phi function ?
phi((i 1)!) phi(i!) close
term (i 1)! i! i prime (1 1/i)
term i prime phi((i 1)!) i
phi(i!) prime (i 1)
phi(i!) precalculate M !
coprime (M! ) N !
coprime (M! ) phi(M !) N !/M !
? 1 M! x M! coprime (2M ! + x)
coprime , (3M ! + x) 1 M! coprime M!+1
2M!, 2M! + 1 3M! phi(M !)
N !/M ! (M + 1)(M + 2) . . . N N M 105
case

UVa 10214 Trees in a Wood


: [a, a] [b, b] 1 a
2000, 1 b 2 106 . (0, 0)
, (0, 0) (1, 1), (1, 1)
(2, 2), (10, 10), (5, 0)
(0, 0)

: count output ,

, axis
(1, 0), (0, 1), (1, 0), (0, 1).


quadrant (axis ) ,
quadrant
quadrant symmetric. [1, a] [1, b]
(i, j)
(ki, kj) (i, j)
i j g (i/g, j/g) (i, j)
(i, j)
1 i a, 1 j b (i, j) gcd(i, j) = 1 i
j coprime
advanced hints
euler phi function i
coprime count phi(i).
(UVa 11440) coprime i repeat 1 i
i coprime, i + 1 2i coprime,
2i + 1 3i i 1
a i 1 b i
coprime. phi(i) b/i (integer division)
i(b/i) + 1 b b mod i
? i multiple b i
a 2000
2000 i 20002
gcd case
case (
) time
complexity O a2 . - i 1 a
phi(i) b/i i(b/i) + 1 b i
gcd gcd 1 gcd 1 pair count

coprime gcd g
gcd(i, j) = g
(i, j) ? gcd(i, j) g multiple
? (a/g)(b/g) (integer )
? [1, a/g] [1, b/g] (x, y) (gx, gy)
[1, a] [1, b] gcd g multiple.
[1, a] [1, b] (x, y) gcd M = min(a, b)
1 M i
gcd i multiple. -
f g n f [i] g i multiple

f [i] = j g[j] j i
multiple. f , g
common
reduce n log n g
, g[n], g[n 1], g[n 2]
g[1] g[i]
i index g
i i multiple
f [i] i i multiple index g
g[i] g[4]
g[4] = f [4] g[8] g[12] g[16] . . .. complexity sieve



mobious inversion
( )
complexity O n ( sieve
precalculation )

UVa 1393 Highways


: n m (1 n, m 300)
pair
overlap , (1, 1) (2, 2) (1, 1) (3, 3)
overlap
horizontal vertical
: i j gcd 1 (0, 0) (i, j)

overlap
? (0, 0) (1, 1) (1, 1) (2, 2)
cover count overcount
? count ?


direction
3 3 (1, 1) direction ? 3
(0, 0), (1, 0), (0, 1) (1, 1)
( (2, 0) ) (
(1, 1) ) i j gcd 1

? (x, y)

(x + i, y + j). overlap
(xi, y j) (xi, y j)
(i, j) (x, y) overlap
(x, y) (x + i m y + j n) (x i < 0
y j < 0) (x, y) ?
valid count
( )
case O nm complexity
( accepted
)
O 3002 precalculation dynamic
programming math
dynamic programming

UVa 1642 Magical GCD


: n n 105 1012
contiguous subsequence element gcd


subsequence length contiguous subsequence
- sequence 30, 60, 20, 20, 20
80 element contiguous subsequence

: observation -
i contiguous subsequence
gcd log a gcd a
i (i), (i 1, i), (i 2, i 1, i), . . . (1 . . . i) index
gcd(a[i]), gcd(a[i1], a[i]) . . . gcd(a[1], . . . a[i])
log a[i] gcd
? i contiguous subsequence
gcd gcd(a[i]), gcd(a[i], a[i 1]) gcd(a[i] . . . a[1])
non increasing sequence.
gcd

,
2
log(a[i]) gcd a[i] log a[i]
2 1 1

?
gcd gcd g gcd
i j (j < i), g' k (k < j).
i + 1
gcd (g, g' ) gcd gcd
range merge ,
sequence a[0] = 25, a[1] = 60.
60 1 , 5 0
35 (a[2] = 35). 35 2 5
1 (gcd(35, 60) = 5), 5 0 (gcd(35, 5) = 5). gcd
, merge 5 0
,
log n observation.

UVa 10868 Bungee Jumping


: w bungee jumping s
free fall body ,
accelaration g (
). l. l bungee
l l
kl force
10ms1
w, l, s, k

:


physics
theorem -
,
potential energy ( )
potential energy
? kinetic energy ( )
bungee potential energy , l
( ) energy

potential energy kinetic energy derivation
m h
potential energy mgh g v
kinetic energy 21 mv 2 . bungee
l kl
z potential energy ? x
kx. dx
z
kxdx ( = x ). 0 z 0 kxdx
2 kz .
1 2

equation

potential energy wgs.
kinetic energy 0. energy wgs.
x potential
energy wg(s x). kinetic energy? ,
v, kinetic energy 21 wv 2 . bungee potential energy?
x l potential energy 0.
,
wgs wg(s x) = 12 wv 2 potential energy
kinetic energy , potential energy
s l ,
v (x = s ) v 10

x > l ? potential energy
x l potential energy 12 k(x l)2 .
equation wgs wg(s x) = 12 wv 2 + 12 k(x l)2 . ?
x = s v ?

v = 0 equation v = 0 x
x < s
x = s v

LOJ 1278 Sum of Consecutive Integers


: N (1 N 1014 ). N
(consecutive positive integers)


N = 15 1 + 2 + 3 + 4 + 5, 4 + 5 + 6
7 + 8. Test case 200
:

a n
a, a + 1, . . . (a + n 1). N .
n > 1 a > 0 ?
n(2a+n1) n1
2 . i=0 a + i

, N .
n(2a+n1)2 = N n(2a + n 1) = 2N . N
a n valid a n
n 2N
? factor

n , 2a+n1 n
2a + n 1 , N = 6. n(2a + n 1) = 12.
12 factor 1 12, 2 6, 3 4. n 6
? n 2
2a + n 1 6 ( n(2a + n 1) = 12) a = 5/2.
n a
n valid valid ?
n a n > 1, a 1 valid.
N = 15. n(2a + n 1) = 30. 30 factorize
? 1 30, 2 15, 3 10, 5 6. n = 1, 2, 3, 5, 6, 10, 15, 30 8
N = 15 8? Problem Description
3. ? n > 1 1 7
n = 10 2a + n 1 = 3 a = 3. a
n = 10 n = 6, 15, 30
3 ? , 2N
factorize 2N factor n
? 1 n > 1. a > 0
? 2a + n 1 > n ? 2N
factor n factor 2a + n 1. a 2a + n 1 > n
( a > 0 integer 2a 1 > 0)?
2N divisor x 1 , x 2N /x
x < 2N /x 2N divisor
200 case costly
?
-
restriction relax
restriction restriction
divisor (q1 + 1)(q2 +
1) . . . (qk + 1) 2N = pq11 pq22 . . . pqkk . restriction

p1 = 2 (q1 + 1)
?


2 prime distribute 2
, 2N = 30.
2 15. 15 divisor 1, 3, 5, 15. 2
divisor ( y ) ( x
) y x (x = 2N/y)
x y x, y pair
n. n = 1 1
N = 1
2N = 30 = 235. (1+1)(1+1) = 4. 4 odd divisor.
2 4 8 xy
n 8/2 = 4 4 1.
4 1 = 3. (q2 + 1) . . . (qk + 1) 1.

LOJ 1282 Leading and Trailing


: n k (2 n < 231 , 1 k 107 ) nk 3
3
: nk mod 1000
(bigmod) ? log -
298751919 . log log 298751919 =
8751919 log 29 = 1.27987888233738 107 . base log
10 base log log ?

abc. nk 0.abc 10d d number
of digit, abc
consider , log
log (0.abc 10d ) = log 0.abc + d. 0 1
log negative Negative -
equation - log a.bc 10d1 = log a.bc + (d 1).
log a.bc a.bc > 1 (a nk ,
?) a.bc < 10.
0 < log a.bc < 1. log a.bc + (d 1)
d 1 log a.bc. -
log 298751919 = 1.27987888233738 107 = 12798788 + 0.8233738 . . ..
298751919 12798789 log a.bc . . . =
0.8233738 . . .. log nk floor log a.bc . . .
10 power ,
a.bc . . . = 100.8233738... = 6.6584605 . . .. 665. -
? wolframalpha.com python
298751919 bigint c++ java

LOJ 1289 LCM from 1 to n


: 10,000 case n 1 n 108 ,
lcm(1, 2, . . . n) 232 mod


: 232 mod , unsigned int
mod
lcm
LCM
power
1 n 1 n prime
power n ,
lcm prime power n 15 2
2 power n 23 = 8, 24 = 16
15 lcm 2 power 3. case 108
prime case
10,000 ?
optimize
n
,
1 power n

n case
n , ac square root decomposition
1 108 square root
segment segment n
n n prime Square
root decomposition

LOJ 1236 Pairs Forming LCM


: 200 case n 1 n 1014 ,
i j lcm(i, j) = n 1 i j n.
: n prime factorization pq11 pq22 . . .. px
i j px power qx . , i j qx
power restriction i j power 0, 1, . . . qx
i power qx + 1 , j
(qx + 1)(qx + 1) power combination
restriction qx i qx power j
, j power 0, 1, . . . qx 1 qx , j qx power
i , qx i j power qx 1
2qx + 1 power prime power
i j
i j
counting
, count
count

LOJ 1027 A Dangerous Maze


: maze n ( 100 )
ai . ai maze
ai ai abs(ai )
maze refresh ,


randomly
maze expected
maze impossible

: ai maze

ai
x ( x1 , x2 . . . ) ai
y maze expected
E. randomly
probability 1/n. xi maze
xi . yi yi + E. ? yi
maze , expected E. E
n1 (x1 + x2 + . . .) + n1 (y1 + E + y2 + E + . . .).
- randomly xi
xi yi yi E


expected value E E

mathematically incorrect xi
xi . ,
variable mathematically correct
variable definition

LOJ 1030 Discovering Gold


: n ( 1 n )
input
1 1 6
randomly , i. x i x + i
x + i > n n
n
n expected
n 100

: Ei i n expected
( ) E1
1 1 6
x 1 + x. expected E1+x
x 1/6. x 1 6
E1 = gold[1] + 61 (E2 + E3 + . . . E7 ) Ei
Ei
En1 2 En+1 En+1
? ?
expected En1 equation
En1 = gold[n 1] + 61 (En + En1 + En1 + . . .) ( 5 En1 )
i = n 1 Ei


base case En = gold[n] n

LOJ 1284 Lights inside 3D Grid


: X Y Z
off. K randomly
(x1 , y1 , z1 ) (x2 , y2 , z2 ). min(x1 , x2 )
x max(x1 , x2 ), min(y1 , y2 ) y max(y1 , y2 ), min(z1 , z2 ) z max(z1 , z2 )
(x, y, z) toggle K
expected on X, Y, Z 100 K 10,000

: Linearity of Expectation expectation
expectation , expected -
on expected on
K expected
on

(x, y, z) K expected on
K on probability ?
K on probability q. Expected
on ? q 1+(1q)0 = q. K on probability

p (x1 , y1 , z1 ) (x2 , y2 , z2 ) probability
(x, y, z) min(x1 , x2 ) x max(x1 , x2 ), min(y1 , y2 ) y max(y1 , y2 ),
min(z1 , z2 ) z max(z1 , z2 ) p
, x, y z [min(x1 , x2 ), max(x1 , x2 )], [min(y1 , y2 ), max(y1 , y2 )],
[min(z1 , z2 ), max(z1 , z2 )] probability
(x, y, z) range
probability x1 , x2
min(x1 , x2 ) x max(x1 , x2 ) x " "
" " x1 , x2 < x x < x1 , x2 x
x 1 , X x x1 , x2
probability x11
x1
1
probability Xx 1
Xx
1
.
1 x probability
y z probability p
p probability K
probability ,
binomial theorem
n ( ) n ( )
(x + y)n = i=0 ni xi y ni . (x + y)n = i=0 ni (x)i y ni .
( )
(x + y)n + (x + y)n = i 2 ni xi y ni i
0 n x p y
(1 p) p probability
1 probability
!

!


.
..
Simple
UVa 1648 Business Center LOJ 1007 Mathematically Hard
LOJ 1014 Ifter Party LOJ 1028 Trailing Zeroes (I)
LOJ 1035 Intelligent Factorial Factorization LOJ 1054 Efficient Pseudo Code

LOJ 1067 Combinations LOJ 1077 How Many Points?

LOJ 1090 Trailing Zeroes (II) LOJ 1098 A New Function

LOJ 1109 False Ordering LOJ 1163 Bank Robbery

Easy
UVa 11040 Add bricks in the wall UVa 1644 Prime Gap
UVa 1210 Sum of Consecutive Prime Numbers UVa 10539 Almost Prime Numbers
UVa 10622 Perfect Pth Powers UVa 1646 Edge Case

UVa 10886 Standard Deviation UVa 1647 Computer Transformation

UVa 11246 K-Multiple Free Set UVa 11166 Power Signs

UVa 11303 Permutation UVa 1655 Exam

LOJ 1024 Eid LOJ 1138 Trailing Zeroes (III)

LOJ 1197 Help Hanzo LOJ 1213 Fantasy of a Summation

LOJ 1214 Large Division LOJ 1259 Goldbach`s Conjecture

LOJ 1333 Grid Coloring LOJ 1336 Sigma Function

LOJ 1340 Story of Tomisu Ghost LOJ 1370 Bi-shoe and Phi-shoe

LOJ 1038 Race to 1 Again LOJ 1104 Birthday Paradox

LOJ 1151 Snakes and Ladders LOJ 1248 Dice (III)

LOJ 1256 Word Puzzle LOJ 1058 Parallelogram Counting

Medium
UVa 808 Bee Breeding UVa 294 Divisors
UVa 11526 H(n) UVa 11105 Semi-prime H-numbers
UVa 1649 Binomial coefficients UVa 10640 Planes around the World

UVa 10479 The Hendrie Sequence UVa 766 Sum of powers

UVa 12520 Square Garden UVa 12590 Guards II

UVa 1652 Fibonacci System UVa 11895 Honorary Tickets

UVa 10976 Fractions Again?! LOJ 1234 Harmonic Number

LOJ 1298 One Theorem, One Year LOJ 1318 Strange Game

LOJ 1161 Extreme GCD

Bruteforce Backtrack

Bruteforce backtrack smart algorithm




optimization run time

UVa 725 Division


: N (2 N 79). 5 abcde fghij
fabcde
ghij = N 5 10
N = 62 79546
01283 .

: fghij 5 0 99999
input N abcde


optimization fghij 0
1000
N fghij 99999 1000
optimization
,

UVa 11059 Maximum Product


: n S1 , S2 , . . . Sn 1 n 18
| Si | 10. continuous subarray

: n 18, sub array element
,
overflow 10 18


1018 long long long long variable
int , overflow

UVa 524 Prime Ring Problem


: n (1 n 16). 1 n

prime n = 6 143256
: 1 2 n n 1
(n 1)! n = 16
15!
prime


backtrack
backtrack bktk(at).
at 0-1

at
at


bktk(at + 1) , bktk(at + 1) ,
bktk(at + 1)
, bktk(at + 1) used[i] = 1
used[i] = 0

UVa 12325 Zombie's Treasure Chest


:
s1 v1 . s2 v2 .
n

n, s1 , s2 , v1 , v2 32 bit integer.
: interesting s1 > s2 .

case case, s 1 > n. n/s1
s1 > n n
s1
n
s1 n s1 > n n


( n ) i x = n is1
x/s2
s1 n s2
s2 s1 ( s1 s2 )
? vi /si ? v1 /s1 > v2 /s2 .


s1
s1 s2
s1 n 0 s1 1

optimal

UVa 1343 The Rotation Game


: . 1, 2 3 -
8 ( 24 ) 8
A, B . . . H
row column cyclically - -
A , C
8
8 2 -
lexicographically
smallest

.: UVa 1343

: IDA* IDA*
iterative deepening A*. " "
IDA*
IDA* searching
(state)

searching.
searching (

)
-
, - , - ,
rule
rule 8

searching bfs dfs
dfs ? A B
( A, B, C state ,
) A C B dfs A-C-B


B A-B dfs
bfs ?
state save visited
( ,
state save )
IDA* search. IDA* search
, state search
backtracking

IDA* ID-DFS iterative deepening
depth first search. unweighted. dfs
depthLimit depthLimit 1.
dfs depth limit depthLimit. dfs
depth , dfs
parameter x parameter ,
current depth max depth. dfs current depth
max depth -
? source
target shortest path ? 1 max depth
, dfs target 1
max depth 2 dfs , target
2 3 dfs.
target dfs visited
ID-DFS source target shortest path
, state ,


ID-DFS
improve -
heuristic. ? state
state move
" move " heuristic approximation
heuristic heuristic
8 x 1 x
move 1 2 3
cost heuristic
? move
? ( , )
heuristic ID-
DFS heuristic
optimization current depth depth
max depth. state heuristic
h. current depth h max depth
dfs
? state heuristic
(heuristic "at least"
) target
max depth


? IDA*
heuristic

IDA* ?

max depth ?
max depth
current depth h
? max depth
set , max depth
target estimate
estimate max depth
target ?
max depth , max depth
algorithm IDA* wiki IDA* pseudocode

UVa 1374 Power Calculus


: x , xn
n = 7 , x2 x x
x2 x2 x4 x2 x
x7 4
, x4 x8 x
x7 4 - n
(1 n 1000). xn

: dp xa
, power x100
x25 x75
x25 , x75
backtrack optimization
heuristic xa
xn move ?
move x2a , move x4a b move
b
x2 a xn move
b 2b a n heuristic

optimization move
x move x10
a

, move ?
power x10
?
optimization 1 1000 optimization
,
optimization
... , ,


optimization / heuristic IDA* backtrack
accepted

UVa 1602 Lattice Animals


: tetris ? tetris
n polymino
n connected polymino
flip (mirror) translate
n = 3 polymino , L
rotate flip n, w
h w h grid n polymino
(1 n 10, 1 w, h n)
:
shortest path
IDA* BFS/DFS
dp mathematically counting , backtrack
mathematical counting
n backtrack simulation

n i i polymino.
flip, rotate translate polymino
polymino cell i+1 -
polymino translate, rotate flip
i+1 i+2 polymino
i+1 similar polymino
polymino (2, 2), (2, 3).
cell (2, 2), (2, 3), (2, 4) , (2, 1), (2, 2), (2, 3) -
(translation )
polymino polymino
1 2, 3, 4 list
polymino polymino

polymino canonical
Canonical polymino
( flip, translate rotate ) polymino canonical
canonical ? polymino
polymino canonical canonical
polymino polymino
polymino canonical represent polymino
square coordinate set represent
canonical form 1 polymino (0, 0)
(1, 1) (translation )
canonical ?
translation polymino
polymino bounding rectangle (
) (0, 0) square x
y. square (x, y)


canonical form translation -
(0, 0) (1, 2) (0, 0)
, , Rotation flip
? polymino rotate
(4 rotate , 0 , 1 , 2 3 90 rotate ), flip
( flip horizontal vertical), flip rotate
( 4 rotate)- ( 8 ) polymino
? translation canonical form
polymino translation
canonical cell polymino
cell
? polymino ,
rotate flip translation canonical
canonical polymino
polymino
, - polymino
1 polymino
i polymino i + 1 polymino -
1, 2, . . . n polymino i polymino
i + 1 polymino i polymino square
square (i + 1 , i square )
polymino i + 1
square
i + 1
polymino
( canonical ) n

w h polymino w h
n polymino
n w h matrix precompute
n polymino w h
rotation, flip translation

UVa 225 Golygons


:
n (n 20) 1, 2
n (0, 0)
1 positive y
axis positive x negative x axis
(2 )
3 n
n
(0, 0)
: ,


(x, y)


d (x, y + d) ,
coordinate ,
abs(y) ,
y = 0
abs(x) x = 0
optimization. backtrack
(x, y1 ) (x, y2 ) ( x axis )

( ) row column consecutive sum
O 1 optimization

.
..
Easy
UVa 140 Bandwidth Uva 211 The Domino Effect

UVa 818 Cutting Chains UVa 690 Pipeline Scheduling

UVa 12113 Overlapping Squares UVa 1575 Factors

UVa 11214 Guaring the Chessboard UVa 1533 Moving Pegs

UVa 817 According to Bartjens UVa 11882 Biggest Number

UVa 12569 Planning mobile robot on Tree (Easy Version)

Medium
UVa 1354 Mobile Computing UVa 1603 Square Destroyer
UVa 12107 Digit Puzzle UVa 11846 Finding Seats Again
UVa 11694 Gokigen Naname UVa 10384 The Wall Pushers

UVa 10837 A Research Problem LOJ 1121 15 Puzzle

LOJ 1143 Knights in FEN LOJ 1397 Sudoku Solver

..

UVa 140: 8 all possible permutation -


backtrack algorithm next
permutation
UVa 211: order domino (1, 1), (1, 2),
(1, 3), . . . (1, c), (2, 1) . . . (2, c) . . . (r, 1), . . . (r, c) cell
domino
option. ,

UVa 818: , statement ambiguous
link bruteforce graph theory adhoc
greedy ( ?-
)


UVa 690: Reservation table
shift n shift
n overlap
shift
backtrack. ,
? bitmask
bitmask reservation table c overlap
c shift bitwise and
UVa 12113: ,
9 2 2 square 6
96 < 106 shape
hash hash shape
ac
UVa 817: 48 8 character
( ) bruteforce
UVa 11882: heuristic
( bfs ) IDA*
, goal

2345 12
pruning (pruning
backtrack )
UVa 1354: 6 tree
dynamic programming backtrack
, - root ,
, recursive call -
tree
tree tree tree
,
tree ( information
) return
subtree
subtree
return
UVa 1603: square border
Backtrack square
order remove ?
, square
? optimize ?
square square
backtrack square
count n optimization
optimization ,

Data Structure

UVa 210 Concurrency Simulator

: 5 instruction "variable = constant", "print


variable", "lock", "unlock", "end". variable a z character
constant 0 99
10 25 instruction
core machine
T. T , T
, T -
cyclically instruction
instruction T instruction

lock
lock lock lock
lock block queue
ready queue cpu ready queue T
ready queue lock lock
ready queue block queue
lock unlock block queue
ready queue

, variable shared.

0. sample input output
, 5 5 instruction
( ), T -
end ( end instruction)


Sample input: Output of the sample input:
3111111 1: 3
a=4 2: 3
print a 3: 17
lock 3: 9
b=9 1: 9
print b 1: 9
unlock 2: 8
print b 2: 8
end 3: 21
a=3 3: 21
print a
lock
b=8
print b
unlock
print b
end
b=5
a = 17
print a
print b
lock
b = 21
print b
unlock
print b
end

: , statement queue - running


queue blocked queue stl queue
queue index running queue 1 n
n global array
instruction run running
queue index run
global array instruction run
assignment print instruction end ,
running queue lock unlock
unlock , blocked queue
running queue lock ,
lock lock execute blocked queue
running queue lock
, execute
lock , flag unlock flag clear

instruction run T
instruction run T 0 negative
instruction running queue

UVa 514 Rails


: A ,
B Y
Y A B A Y
B A
1, 2, 3 1 , 2
, 2 B , 3 A B
1 B 1, 2, 3 2, 3, 1
A n (1, 2, . . . n )
B order n
1000.
: stack
B i A
1 i Y i B B

i = 3
1 1 2 2 1
B sequence B
Y A Y
B ,
Y , Y
? n ,
? ,
Y

Y
A j
A j + 1 n
Y
( ) A
O n

UVa 442 Matrix Chain Multiplication


: matrix dimension matrix
expression - (A(BC)), ((AB)(CD)
expression cost. A(p, q) B(q, r) matrix
cost p q r. 26
: stack

bracket sequence ,
bracket sequence balanced (()()) balanced
sequence (()( balanced sequence stack
? , ( stack ) stack


( , sequence balanced
stack , counter
stack , , stack
(
, stack balanced bracket sequence

stack stack , ,


, ( ignore
matrix dimension stack )
stack matrix dimension (a, b) [
] (c, d). d = a matrix
cost c a b
matrix dimension (c, b). matrix stack
cost

UVa 11988 Broken Keyboard (aka Beiju Text)

: string type String


letter underscore [ ]. [ home
typing cursor ]
end. cursor string
string abc[de]f
deabcf.

: stack
( ) stl
list
string ,
( )
list O 1 vector
insert cost constant list
constant
List insert , iterator
iterator insert list<char>::iterator it
variable iterator character
insert , iterator character
it L.end() , L
character home
iterator L.begin(), character
"" ,
character L.begin() ,
it
character end it
L.end()


UVa 12657 Boxes in a Line
: n , 1, 2 . . . n n
100,000 - X Y swap
, - X Y , - X Y , - sequence
100,000
( , ) id

: doubly linked list



X
,
stl list

UVa 679 Dropping Balls


: tree Tree complete binary tree
child leaf D
1, 2, 3. 4, 5, 6, 7. heap
represent index D 20
flag false. I
1 flag flip (true
false, false true). false (flip false )
, true
leaf I leaf
: i child 2i child 2i + 1. D depth
2D 1. ( )
simulate O D

50 ?
tree
1 ,
,
50 , 25
3 (= 2 1 + 1) 25

25 25/2 = 13
13 6 (= 2 3) ,
while loop recursive

UVa 122 Trees on the level


: binary tree ( child )
level
,


tree input 4 root
2 2 9. input 9 LR. root
Left-Right
, level
tree ( L LL ) not
complete
: parsing
parsing

LR tree
string tree ,
,
tree tree
invalid. root bfs level
bfs visit
child queue left child
right child

string print
string length sort length
lexicographically sort L R
valid
LR string S.
character S
parent

UVa 548 Tree


: binary tree root leaf path cost
path ( id ) cost
tree inorder post order traversal
Tree 10,000
: tree
dfs Dfs cost
handle parameter cost
dfs cost
leaf , child
global variable update global variable "
cost leaf path cost". child
cost cost
dfs call
- inorder post order traversal tree

inorder post order traversal
preorder traversal.
in, post, pre. root in root
, post root , pre root ?


pre root left subtree preorder
traversal , right subtree , post root
, , inorder root,
order fixed. root in, pre, post

inorder post order traversal
? Postorder traversal root. inorder
traversal root , left subtree
right subtree. inverse ( ( ) inorder traversal
) inorder traversal root O 1
left subtree L right subtree R post order
traversal L left subtree post order traversal, R
right subtree post order( traversal.
) inorder
post order traversal O 1 left subtree right subtree
inorder post order traversal
- inorder post order traversal ,
tree
tree tree dfs
inorder post order

LOJ 1101 A Secret Mission


: 50,000 100,000 edge weighted
50,000 query query ,
s t. query s t path
s t path ?
path path edge cost
s t path path edge
cost a, path edge
cost b. a b

: query ? Dijkstra
? Dijkstra cost s cost.
cost edge
dijkstra dist infinity initialize dist[s]
0 relax u v u-v
edge cost w. u v cost dist[u] w
dist[v] dist[v] update ,
dijkstra dijkstra dist[v] = min(dist[v], dist[u] + w),
( dist[v] = ) min(dist[v], max(dist[u], w)).
O E log V case
?
case ?
cost edge
cost edge Sum cost edge
? Minimum spanning


tree s t optimal
path minimum spanning tree path. ?
s t optimal path cost MST
cost optimal path cost
edge cost MST path
cost edge cost MST
cost edge
edge replace MST cost MST cost
? , s t MST

MST query s t
MST path path cost edge

( ) tree V 1 edge
query O V .
complexity LCA (Least Common Ancestor).
tree LCA
s root t root
-
root s t LCA. LCA
20 , 21 , 22 , 23 . . . 2log V
parent parent
parent path edge cost
s c t c path cost edge ,
c LCA. lca log V

LOJ 1128 Greatest Parent


: 100,000 rooted tree weight Tree
weight weight parent weight
50,000 query query v
w weight v ( root
) ancestor weight, w

: LOJ 1101
, tree binary
search tree ancestor
query list binary search ?
(
branching ) i list i ancestor
V 2 ? LCA
20 , 21 , 22 , 23 . . . ancestor v v 2k
ancestor weight w , 2 k1
ancestor
v 2k parent
2k1 parent ( ) k
k = log V O log V
log V k ( LCA )?


LOJ 1080 Binary Simulation

: 100,000 0-1
- i j element flip 0 1, 1 0. - i
operation 50,000.

:
( )
O log n .
lazy propagation. lazy propagation
flip update
update cover
lazy query lazy
lazy propagate segment tree
information - lazy
lazy parity (parity
) 3 lazy 1
lazy
propagate ? lazy i
0 1, segment tree i leaf
i flip flip
lazy lazy
propagate
, flip i
j 1 query parity
( ) equivalent.
segment
tree binary indexed tree ?
BIT BIT
segment update index update
query 1 i i
update i j.

x1 , x2 , x3 . . .. transform
x1 , x2 x1 , x3 x2 , . . .. ? , 1 i
x1 + (x2 x1 ) + (x3 x2 ) + . . . (xi xi1 ) = xi . xi
i , i j 1
, xi , xi+1 . . . xj 1
x1 , x2 , x3 . . . BIT , x1 , x2 x1 , x3 x2 , . . ..
sequence ! i
1 i xi xi1 , xi 1
j + 1 1 xj+1 xj
(i j )
?
sequence update query index
BIT


LOJ 1087 Diablo
: n ( 100,000 ) 50,000
(q) - sequence
- k ?

: binary search tree


? segment tree
n+q segment tree n
1 q 0 k segment tree k
1 binary search
" guess i k 1 " query
1 i 1 i 1
k i 1
k 1 i binary search k 1
( 2 )
query complexity O log n .
( )
O log n tree
left tree 1 right tree
k 1 k 1 index
( )
n 0 1 ,
0 1 segment tree
1 id
segment tree index k
id

LOJ 1089 Points in Segments (II)


: ( 50,000 )
( 50,000 )
108

:
segment tree [i, j]
segment tree 1 query
query 108
108 segment tree
memory ,
query , relative order
[1, 10] query 5 ,
[1, 3] 2
( )
sort O n assign sort (
duplicate ) 1, 2, 3
query range
Duplicate sort(A.begin(), A.end())
A.erase(unique(A.begin(), A.end()), A.end()).


segment tree LOJ 1080 BIT

segment tree BIT
, , ,


,
(A) (B).
A B
sorted array binary search
sorted array binary search
B
line sweep query ,
event event
sort line sweep
counter counter
query counter ?
query range
counter query
counter

- , query
, comparison function
-1 , query 0
1 , (
)

LOJ 1093 Ghajini


: 100,000 a
d v v =
a[i] a[j] abs(i j) + 1 d. d (index )
difference

: d subarray minimum maximum


segment tree
"static rmq"
prioirty queue priority queue
d subarray maximum minimum
maximum ?
index structure priority queue
index priority queue top
index d
(pop) priority queue top
index d d index
maximum ( d )


d
?

LOJ 1267 Points in Rectangle (II)


: 2d 50,000 50,000
query
coordinate 0
109
: LOJ 1266 ( exercise
) 1266 ? -
coordinate "
"
y axis segment tree line
sweep (x, y) segment tree y
1 segment tree
query [y1 , y2 ] range A.
query , B.
B A , border
count A B
details.
BIT

LOJ 1188 Fast Queries


: 100,000 50,000 query
query i j i j
0 105
: trick

, range query
offline
line sweep query
query query ?
unique ? line sweep
x index A[x].
A[x] map
A[x]
x 1
- x x unique
1 0. , x 10 10
1 , 10 0. query
- 10 1 10.
query 10
1 ? ? query index index


1 10 1 index index
query 10 count 10
1 , 0. 1 10 (
x ) segment tree BIT
( 2 )
query online query O log n
time complexity merge sort tree

online
merge sort tree

LOJ 1348 Aladdin and the Return Journey


: 30,000 tree weight
operation - i j , path
weight - i v i
weight v operation 100,000. Weight
1000
: LOJ 1128 LOJ 1101
weight LCA max, min sum
weight Heavy Light Decomposition

- "Euler path Segment Tree
"
tree euler path . Tree euler path
dfs tree - Child dfs call
subtree path edge
b d h h d e i i j j e b c f k k l l m m f g g c.
B parent edge b
edge , positive
negative , +b +d +h -h -d +e +i -i +j -j -e -b +c +f +k -k +l
-l +m -m -f +g -g -c. b B weight. +j
b+e+j root J cost
root cost a
a +a ,
root parent root edge cost a. handle
root
node path cost s
t path cost s t
lca c. cost(s, t) = cost(root, s) + cost(root, t) - 2cost(root, c)
cost(a, b) a b path cost
tree euler path sequence
s t
s t update
weight sequence 2
element update segment ( tree ) binary
indexed tree update segment sum O log V


sequence 2V element
(
)
segment tree update query O log V

b c

B C

d e f g

D E F G

h i j k l m

H I J K L M

.: tree Euler path

.
..
Simple
UVa 839 Not so Mobile UVa 699 The Falling Leaves
UVa 673 Parantheses Balance LOJ 1212 Double Ended Queue

Easy
UVa 297 Quadtrees UVa 712 S-Trees
UVa 536 Tree Recovery UVa 127 "Accordian" Patience
UVa 246 10-20-30 UVa 1322 Minimizing Maximizer

LOJ 1113 Discover the Web LOJ 1303 Ferris Wheel

LOJ 1082 Array Queries LOJ 1162 Min Max Roads

LOJ 1083 Histogram LOJ 1097 Lucky Number

LOJ 1103 Castle Walls LOJ 1112 Curious Robin Hood

LOJ 1135 Count the Multiples of 3 LOJ 1187 Lining up Students

LOJ 1207 Poster for Election LOJ 1266 Points in Rectangle

LOJ 1293 Document Analyzer

Medium
UVa 10562 Undraw the Trees UVa 12166 Equilibrium Mobile
UVa 806 Spatial Structures UVa 10410 Tree Reconstruction
UVa 1662 Brackets Removal LOJ 1081 Square Queries

LOJ 1120 Rectangle Union LOJ 1424 New Land

LOJ 1343 Aladdin and the Black Stones LOJ 1204 Weird Advertisement

Codeforces Round 121 Div 1 C Fools and Roads


..

LOJ 1212: Stl deque


LOJ 1113: ! stack
back forward back back
stack forward stack forward
forward back stack visit
forward stack back stack
?
( )
LOJ 1082: segment tree O n preprocessing
( ) ( )
query O log n complexity O n log n
( )
preprocessing query O 1
Data structure "Static Query"
LOJ 1083: stack
(0-1 matrix 1 )
LOJ 1135: Segment tree segment mod3 (0, 1
2) count LOJ 1080 lazy propagate

LOJ 1187: array array 1
x. ? x
array x + 1 1
, array 0
array
array operation (k 1
1 0 ) ? segment tree!
LOJ 1207:
order poster , ,
poster ,
poster
? poster array
poster
- poster , array
poster
segment tree
LOJ 1266: 2 dimensional BIT
LOJ 1293: -
range range
range range,
range
1 n. n
0 variable L R
0. variable L R
count count n n L R range
candidate. L count
count count 0


L R
count count n
R L R
count count count 0 ,
count
candidate best range
UVa 12166: bar horizontal bar
bar (
w ) bar bar bar 2w
2w d depth w
root w2d contribute ?
w2d
,
( )
LOJ 1081: linear preprocessing O 1
Adhoc
LOJ 1120: coordinate compress ( )
line sweep segment tree
support - i j -
0 segment tree
rectangle sort
( event) rectangle (x1 , y1 ) (x2 , y2 )
x1 x2 , y1 y2 . (x = x1 ) rectangle
1 (segment tree y axis ) segment
tree [y1 , y2 ] 1 (x = x2 )
segment tree 0 x axis
jump jump
Jump x event event
jump.
LOJ 1204: K 10
, K = 1
, K = 2 , segment tree K
i cover
[y1 , y2 ] segment update
lazy lazy propagate ? K
update ! coordinate
coordinate compress line sweep
! ,

Greedy

Codeforces Round 26 B: Regular Bracket Sequence


(26B)
: 106 bracket sequence "(" ")"
string. string bracket
balanced bracket sequence
: stack counter
bracket sequence balanced
balanced bracket sequence
character counter stack
( stack character (
index ) ) stack element
negative ( stack
stack ) invalid sequence , closing bracket
, ? opening bracket ? ? (()
( ) opening bracket ? counter
stack condition negative ,
condition ? stack counter
? , stack opening
bracket -
boolean

Codeforces 44 J: Triminoes (44J)


: 1000 1000
, ,
b, w .
triminoes Triminoes 1 3 3 1
triminoes
( ) triminoes


, triminoes trimino
trimino
trimino a, b, c d
trimino.
trimino
trimino

: trimino

horizontal trimino
vertically trimino
?
? ? ?

? vertically
horizontally trimino

,
trimino
?
,

, trimino a, b, c
d
? , ?
trimino
-
trimino
four color theorem
trimino
systematic trimino ,
trimino
trimino, ?

trimino

, , cover
horizontal trimino ,
vertical trimino
trimino trimino trimino
vertically trimino
( trimino , ,
trimino )
trimino horizontal trimino
, horizontally trimino ,

!
!


Codeforces 45 D: Event Dates (45D)
: N , i
[li , ri ].

N 100 1 li ri 107 .
test case
: Greedy N


unassigned. i 1
107 i
active active,
r , i assign
active assign
, i , active i
active variable r ,
,
,
N 107
assign
i heap priority queue
107 log N heap active
r r heap
, i
i , heap
heap ,
i ( )
O N log N -
order.
criteria -
variable i
i i -
variable , at, variable
at i 1.
priority queue priority queue
priority queue
while

at i
at priority queue , at
while loop continue
condition priority queue
at i
while loop continue
condition priority queue
priority queue


i
( ) i
i i while loop continue
( )
O N log N

Codeforces Round 57 D: Eternal Victory (61D)


: n 100,000
edge cost non-negative 20000.
path 1
: 1 1
? , edge cost ?
dfs traverse ,
edge


1 1
cost ,
cost

Codeforces Round 66 B: Need For Brake (73B)


: N a1 , a2 , . . . aN .
m
b1 , b2 , . . . bm a1 . -


lexicographical order rank N 105 .
: m = n
bi = 0
bi
bi rank

, score rank
,
,
(
)
rank O n
, index

rank ?
score score

score
score ,


score
score score
( ) assign
O n

binary search
binary search binary search
" g "

Codeforces Round 79 Div 1 D: Castle (101D)


: n rooted weighted (n 105 ) edge
weight (weight 1000), edge
weight. root
edge
Root treasure
edge weight treasure
expected
: edge
dfs traversal euler tour
, subtree
parent edge
edge
, subtree treasure
, subtree
subtree edge weight
? edge
, edge
subtree ?
, fixed.

treasure ,
fixed subtree subtree

child child
child subtree treasure expected
i child ai (
subtree treasure , optimal
expected treasure )
ai parent i child edge weight i child
subtree si .
subtree , m
(= si ). i subtree edge weight Ti
(parent i child edge weight )
k child
1 child subtree , 2 k
expected ? probability subtree


treasure s1 /k, a1 . subtree treasure
s2 /k, T1 + a2 . ? subtree
( T1 ) subtree
treasure a2 k child.
s1 /k (a1 )+s2 /k (T1 +a2 )+. . .+sk /k (T1 +T2 +. . . Tk1 +ak ).
, k child cost
i i + 1 i
cost sum
- s1 (a1 )+. . .+si (T1 +T2 +. . . Ti1 +ai )+si+1 (T1 +. . . Ti +ai+1 )+. . .
1/k constant
i + 1 cost - s1 (a1 ) + . . . + si+1 (T1 + T2 + . . . Ti1 +
ai+1 ) + si (T1 + . . . Ti1 + Ti+1 + ai ) + . . .. i cost A
i cost B A B?
A B A B = si+1 Ti si Ti+1 . i subtree
A B < 0 Tsii < Tsi+1 i+1
subtree
Ti /si
compare
?
( )

Codeforces Round 99 Div 1 D Digits Permutation (138B)

: n (n 105 )
permute
0
198 981 819 -
981 + 819 = 1800.

: 10
9 10 1 9 10
10 - (1, 9), (2, 8) . . .
9 - (0, 9), (1, 8), (2, 7), . . ..
10 9
greedy,
1 x
8 y , min(x, y) 9
case
10
10 + 10 = 20 0 + 0 = 0 case

0 ? ! ?
0 , 10
9


Codeforces Round 100 C New Year Snowmen (140C)
: n (n 105 ).
,

: ,
optimal solution
?
?
,
( )?
A B. {A, B, ?}
A
{A, X, Y }. B
X B X
B
X B

optimal solution

Codeforces Round 109 Div 1 A Hometask (154A)


: character forbidden pair (pair character
) pair character
13 pair character forbidden pair
105
character forbidden pair
ababa forbidden pair - ab b
aaa
: character
forbidden pair ?
pair
pair
! aba forbidden pair ab
a , character
b forbidden pair character

abbbb
a greedy
anti case
!
, ,
abbbb character

forbidden pair forbidden pair ab.


a b pair a / b
ab ba a b ,
a b abbbbcaaaab. a b
? ab
a b
a b
c a
a b

Codeforces Round 103 Div 2 E Competition (144E)


: coordinate (i, j) i j.
i = j target cell
target cell target cell

target cell
10, 12, 10. 10
10

, ,
( target cell )

target cell ( ),
105

: candidate target cell


target cell
(10, 5) target cell (10, 10), (9, 9) . . . (5, 5)
5

Codeforces 45 D Event Dates


heap priority queue
heap push
heap heap

?
case analysis !

Codeforces Round 116 Div 2 D Name (180D)


: s t s character permute
lexicographically t lexicographically
5000


: t
? s
t s
s = abac, t = abob a s c
t b s b a ab
s acab. ?
5000

,


character t character

Codeforces ABBY Cup 2.0 A3 Educational Game (178A3)

: n (n 105 ).
a1 , a2 , . . . an . (i, t)
1 i n i + 2t n. ai 1
ai+2t 1 (1, 0, 1, 2) (1, 1) (0, 0, 2, 2)
k k
k 1 n 1 n 1
k n 105

: a1
a2 - a1 a1
? -
? ! a1 2t1 2t2
t1 = t2 move 2t1 +1 move
t1 < t2 t2 move ,
k k ,
a1


.
..
Simple
Codeforces 67 A Partial Teacher
Codeforces Round 66 D FreeDiv
Codeforces Round 89 C Fancy Number

Codeforces Round 87 Div 1 B Lawnmower

Codeforces Round 98 B Permutation

Codeforces 158 B Taxi

Codeforces Round 111 Div 2 A Twins

Codeforces Round 111 Div 2 B Unlucky Ticket

Codeforces 159 B Matchmaker

Codeforces 169 B Replacing Digits

Codeforces Round 113 Div 2 C Median

Codeforces 174 B File List

Codeforces 176 A Trading Business

Codeforces 119 Div 1 A Permutations

Codeforces 142 Div 2 A Dragons

Easy
Codeforces 76 B Mice
Codeforces Round 67 D Big Maximum Sum
Codeforces Round 71 C Beaver

Codeforces 81 D Polycarp's Picture Gallery

Codeforces 120 F Spiders

Codeforces Round 93 Div 1 E-reader Display

Codeforces 159 E Zebra Tower

Codeforces 161 A Dress'em in Vests!

Codeforces 161 B Discounts

Codeforces Round 117 Div 2 C Optimal Sum

Codeforces Round 129 Div 2 B Little Elephant and Sorting

Codeforces Round 131 Div 2 B Hometask

Codeforces Round 148 Div 1 C World Eater Brothers

Medium
Codeforces 86 B Tetris Revisited
Codeforces Round 92 Div 1 C Brackets
Codeforces Round 96 Div 1 D Constants in the language of Shakespeare

Codeforces Round 97 Div 1 C Zero One

Codeforces Round 140 Div 1 B Naughty Stone Piles

Codeforces Round 140 Div 1 D The table

Hard
Codeforces 128 Div 2 E Transportation

Dynamic Programming

UVa 437 The tower of babylon


: n (n 30)
,
-
dimension dimension


: coin change dp
longest increasing subsequence
" ( ) "
?



,
? -


? !
? ?
- DP.
DP , i.
i ?
, i
( k) DP (k) + height[k]
k
0 DP
? DP
DP
,
,


( )
time complexity ? O n2 n
( ) ( )
state O n state O n

UVa 1347 Tour


: 2d plane n (
n 1000). x
( x ), ,

,
n

: - bitonic tour.
dynamic programming!
state -
,
,
state ?
State DP systematic

skip
? - ! ,

- -
- -
!
state ? state
1 n
state (i, j) - i
j DP (i, j)
optimal , i j n
DP (i, j) ?
i > j i + 1 j > i j + 1
consider
k = max(i, j) + 1 k ? i
j ? i k
DP (k, j) + dist(i, k) j DP (i, k) + dist(k, j)
DP (i, j) ? DP ?
DP (1, 1) 1 ? k = n + 1
i j n n
( ) DP
k n i j ( )n ( )
time complexity O n2 state O n2
state transition


UVa 116 Unidirectional TSP
: row 10 100

( 30 )

(r, c)
- (r1, c+1), (r, c+1), (r+1, c+1). (r1, c+1)
(r 1, c + 1)
(R, c + 1) R row.
(r + 1, c + 1)
(1, c + 1) ( x
axis )
: DP (r, c)

,

100
100 30



, DP (r 1, c +
1), (r, c + 1), (r + 1, c + 1) DP ( wrap
)
( )
time complexity O RC R row C
( )
O RC state (
) state 3 transition
complexity O RC .

lexicographically
DP optimal
transition ?
, -

lexicographically
lexicographically
path printing

UVa 12563 Jin Ge Jin Qu hao


: n (n 50)
3 180 n
678 t (t 109 ).
?

t


t
t 1 100
t + 99 t

:
Greedy t

condition greedy
t 6 2, 5, 678 greedy
2 678 optimal 5 678
?
observation. ?
-

x x 180.



,


n
t


DP
DP , t
50 180 + 678 t
t

DP state
? i j
i ? DP, n
n
, 2n i
,
i , " k i "
state (k, i, j) - k i
j BFS DFS
DP DP
j < t, i n (n, i, j)
(k, i, j) ? k
, (k 1, i 1, j song[k])
k , (k 1, i, j)
base case k = 0. i = j = 0
, , state
n2(t ) DP transition. time complexity
O n2 t .
state - (k, j) , k


j time complexity
n

UVa 11400 Lighting System Design


: n (n 1000). i voltage
rating Vi , voltage source Ki ,
Ci Li
voltage rating voltage
rating voltage rating
rating voltage source voltage source

: " voltage rating
" voltage rating
voltage
rating i j (i j) voltage rating
j replace
component j i
j replace j voltage source
i j j
- i j j replace
k (k > j) replace optimal ( j )?
i j j replace k
k ? k replace
? k i j
"" ? k replace ?
k ?
state ? State - i
replace , replace
i replace i voltage source
i i replace
DP(i). DP ? j j > i. ?
i + 1 j j replace ,
j voltage source j
DP(j). i j cost
DP(i) base case DP(n)
, cost 0.
state
( ) n state n
time complexity O n2 .

UVa 11584 Partitioning by Palindromes


: 1000
palindrome aaadbccb -
palindrome (aaa)(d)(bccb).
palindrome


: DP(i) - "
i , i
"? ? ! j i j
palindrome palindrome 1+DP(j+1) candidate.
j i j i j
palindrome costly. i
j i n ( i
) j
palindrome palindrome ( ) O n ()
DP(i) O n2 (j O n
(palindrome
) ) n state
O n3 .
? - costly ? palindrome
palindrome
? dp i
j palindrome ? i j
i j character
palindrome i + 1( ) j 1 palindrome
palindrome dp state O n2 transition.
( )
time complexity O n2 .
n2 n2 = n4 time complexity n2 + n2 = n2
(constant ) dp
dp ( ) dp state dp
dp state O n2 n
( )
- dp state O n2 . dp
( )
palindrome O 1 ? dp
( 2) ( 2)
O n . O n
, greedy ?
palindrome,
?
anticase anticase pppbbp. greedy
(ppp)(bb)(p) optimal (pp)(pbbp).

UVa 1625 Color Length


: 5000 A Z
26 character merge
Merge merge Formal
ABC DE merge ABDCE, ABDEC,
DEABC BDEAC, BCDE
? merge score
score ? character
score character score ? - character
, index
AABAB A 1 (1-indexing ) A 4 A
score 3. B score 2. score 5.
merge score
:


greedy dp. string
5000 greedy
dp , dp state ?
state (i, j) i index j
i j
state score ? score
, character
index index
(i, j) (i + 1, j) (i, j + 1)
? ! (i, j) (i + 1, j)
S[i + 1] ( S ) merged
index? i+j+1 ? i+j character ,
i + j + 1 ? , S[i + 1] character S[1 . . . i]
T [1 . . . j]
character occurance i + j + 1
character S[i + 2 . . .] T [j + 1 . . .] character
(i + 1, j) state dp
(i, j + 1) score
option score
DP (i, j)
character S[1 . . . i]
S[i . . .] - ?
character
character S
compare character S[1 (. . . i])
S[i . . .] complexity - O n2
( )
n length. state O n2 state
transition.

UVa 10003 Cutting Sticks


: 1000. n
(n 50). cost

10 - 2, 4
7. 2, 4, 7 10 + 8 + 6 = 24.
4, 2 7 10 + 4 + 6 = 20.
: greedy
greedy greedy
dp ? Experience, experience
intuition dp state ?
,
, ,

"" state represent
10 2 6
state (0, 2), (2, 6), (6, 10).


1000 10002 state
state 2, 4 7
8 5 n2 state
represent index
mark[1] = 2, mark[2] = 4, mark[3] = 7
(2, 7) (1, 3) mark[1] = 2 mark[3] = 7.
0 10 ( 0 l) mark
( )
- O n2 state
DP

, DP (i, j)
i < k < j DP (i, k) + DP (k, j) + length(i, j)
(
) DP
time complexity O n3 .

UVa 1626 Brackets sequence


: bracket sequence (, ), [, ]
sequence 100 character
balance

: dp state -
index , state i i
state ([]) opening
bracket closing bracket match
1
4 ?
state ? , substring state.
DP (i, j) i j index string
balance extra character string return
string 100
substring character
matching bracket character opening substring
matching closing bracket k ,
candidate S[i] + DP (i + 1, k 1) + S[k] + DP (k + 1, j)
( S bracket sequence, DP ?
i k match [i + 1, k 1] substring extra
character k
extra character k candidate
? S[i] matching closing bracket insert
, S[k] insert candidate S[i] + DP (i, k)+? +
DP (k + 1, j) ? matching closing bracket. S[i] closing bracket
, matching opening bracket ( )
DP time complexity O n3 .
-
( S[i] closing bracker ) S[i]
matching closing bracket ,


S[i] closing bracket

, greedy
- bracket sequence character balance
greedy ! Stack

UVa 1331 Minimax Triangulation


: m (m 50) chord
triangle
m m 3
? (
)

: dp ""
cyclic state 1D 2D
Cyclic , cycle
0 indexing i (i + 1)%m
(i + m 1)%m
, 0 1, 2 m 1 0
0 indexing
/
if-else
state dp
state polygon.
, , dp ,
merge merge dp
( ),
dp base case

state !
" index
" state (exponential)
systematic represent
, , state exponential
systematic ( ) vertex
vertex O n4
( )
edge O n3
vertex edge metaphorical
edge
vertex 0 n 1
0 (n 1) edge edge
?
0 n 1 i
0 i (n 1).
0 i


i (n 1). i = 1 0 i
i = n 2 i (n 1)
recursively DP merge
state (a, b) a b
a b DP
i a i b a i, i b DP

UVa 1220 Party at Hali-Bula


: n rooted tree (n 200).

parent.

: DP root DP DP state
, u DP return
subtree (
) (parent restriction
)
state
0 u 1 u
(u, 0) state u
u child
c (c, 0) (c, 1) u c
c (u, 1)
c child c (c, 0)


,
(u, 0) (u, 1)
(u, 1) (u, 1)
(c, 0) (c, 0)
(u, 1) 10 (c, 0)
20 200 (u, 1) ?
(u, 0) (u, 1)
,
, if else

overflow ( )
time complexity O n .
state 2 n child child
n (n 1 ) n2
child child
DP ? DP
child parent-child edge
edge n ( n1). DP (
) 2n
time complexity. DP complexity O n .


UVa 1218 Perfect Service
: n (n 10000)
neighbor
neighbor neighbor adjacent.

: DP
rooted root
dp
u

u child
state
neighbor

neighbor -
-
neighbor , - neighbor
state - u , u child
, u

child
neighbor
?
? ,
neighbor ?
neighbor


? ,
state state
, (child DP
)
fix (
) DP
time complexity O n2 . fix
( child
( ) ) child DP nested
O n nested
? ,
fix cost
?
child ,
S.
S cost
cost ()
? nested O n


UVa 1252 Twenty Questions
: n (n 128). n

n m (m 11).
- i 0 1.

n = 1
n = 2 100 110
( 1
0 1).

: ,
[i0 , i1 , . . .]
?
[b0 , b1 , . . .]. n

100, 110
[0]
[1].

ignore " "
" "
Dynamically
dynamically !
case
- 000, 001, 110, 100. 4

(msb)

[0, 0].
[1, 0]. (lsb)
[0, 0].

(msb)
0 1 0
000 001
000 001 1
110 100



? bitmask
valid,
valid
DP
try mask 2n
m 11. 2m
? 2m mark



eligible valid number
mask
( mask1 mask2,
0 1 , 0 )
state 2m 2m

0 1 DP
mask1 mask2
DP DP(mask1,
mask2) valid (n
mask1 and mask2 )
(0 )

(i 0 m-1 ) 0 1
0 DP(mask1 | (1<<i), mask2) 1
DP(mask1 | (1<<i), mask2 | (1<<i)).
( i 1) i
i

DP(mask1, mask2) ( )
complexity O 2m 2m (n + m) state
n m
precompute n n
mask1 mask2. DP
2m n 2m 2m precompute
mask1 ( mask2 ) time
complexity O 2m 2m m .
( )
, time complexity O 2m 2m m
( m )
complexity O 3 m . ? ,
3 " ", " 0 "
" 1 " m
state 3m , 2m 2m 2m 2m
3m bitmask bitmask
3 base 0 1
0 1. 3 base 0
, 1 0 2
1. state define

UVa 1412 Fund Management


: , 0.01 109 m
(1 m 100). n
(n 8).

2 3
1 1 , 2
8



8
,

: DP
(state). -
, -
DP
state state ? 8
8 9 (
0 , 1 8 ) state
98 = 43 106 100 4 109

time complexity 8 4 109 . !
, state
?
98 overestimate.
8 ,
overestimate? backtrack
valid state , 8
8 valid state
mathematically 8
8 distribute combinatorics
common 8 8 1 , 8 7 0
8 + 7 = 15 permute 0 1
, 0 0 1 ,
( ) 0 ( )
15 permute
state 15 8 1 7 0 7!8!
15!
= 6435 permute
- 7 8
7 7 state
98 8
0 0
8 7
6 8 , 9
0 . . . 8 8
? ? 8!8!16!
= 12870.
valid state
? memory 98
state represent TLE MLE
?
state save array
map DP map
state
map
9 base


vector map , vector map
9 base
cost efficient. cost efficient , 9 base
mod , costly
experiment 9 base ?
3 base

UVa 10934 Dropping Water balloons


: k (k 100). n
(n 64
)

,
63 63
: 100,
, , 63
DP state
, DP
, i j -
? i, j
n
i j

, i j 1 A

j 1 i 1 ,
B. i, j A + B + 1. i, j DP
base case
A + B + 1 1

UVa 1336 Fixing the great wall


:


(
) speed speed
constant. speed
1000.
:


,
optimal




,

/ /
optimal ? Zig-Zag
? , , ,
DP state ? DP design
?
?


state i, j, k i ,
j k 0 1 state
i 1, j, 0 i, j + 1, 1

DP parameter i, j, k. - i j
k i j

state i, j + 1, 1 i 1, j, 0 state
i, j + 1, 1 DP DP
state
parameter - state
? , , i a i
j
i a

variable , fixed.
DP DP

i = 1 a = 3 , j = 2. 1 3 x.
x
transition

UVa 12105 Bigger is Better


: LED display 0 6 , 1 2 , 2 5 , 3 5 ,
4 4 , 5 5 , 6 6 , 7 3 , 8 7 , 9 6
n
m n 100
m 3000
-1
: state
n m state
m mod
m mod DP value


details
,

clash of interest ,
mod mod a
mod 10a + d (mod m) d

mod a length b
d. mod d10b + a
(mod m). dp state
, d a m dp state
b b state
n 100 1 2
b 100/2 = 50 ( 50 1).


preliminary




mod a, n - state.
DP value n (
) m
state d d mod 10a+d (mod m).
n d recursive
DP base case state mod 0
n d

DP path printing
1 9
DP , mod ,
? 1 9
,

0 9
mod , DP
DP state
, mod -
DP path
printing path ,
,
7 DP 3
5 DP 3
, ?
DP DP return
,
bigint
50


path ( , lexicographically numerically)
DP

UVa 1204 Fun Game


: randomly
B , G
(clockwise anti-clockwise)
B G

16

valid. string 100

:
clockwise ?

N
substring
?

circle assumption
optimal -
S1 , overlap S2 ,
overlap S3 SN . SN
S1 overlap S3
S2 , S1 ? S3 S1
overlap S2 , S2 S3
? state

travelling salesman problem
? (TSP
)
circle ? ( S1 ).
state


cost ? Cost
overlap DP.
cost
DP DP
, circle Circle
base case
DP base case ?
overlap
circle ( ,
, )


( overlap)
cost DP time complexity O n2 2n
overlap precompute
( )
precompute cost ? O n2 L2
L.
circle
-
circle restriction



convince
:) anti case
case
, case

,
clockwise

bitmask N


!

UVa 12099 The Bookcase


: N (N 70). height thickness
Height 300 thickness 30
depth width ,
width depth


thickness tightly pack
( )

: parameter
expected time complexity state
naive state state ? ,
,
, complexity
,

,

7 ,
,


5 ,
5 independent,

DP 0 1,
?
-1 ? - (
), ,

state 4
? 4
complexity 21002 70 300.


optimize ?
-

,
state 21002 70 2 ( )
observation !

UVa 12170 Easy Climb


: n (n 100). hi
(hi 109 ). cost
unit ( integer unit )
d
(d 109 ). cost
impossible

: naive
state , modified height
state height
height 109
costly ?
- height important
height important i < j.
hj > hi + d (j i) hj < hi d (j i) i j
valid arrangement i
d , 2d, 3d,
j d (j i)

bound bound
observation () boundary
important height. i
bound bound important height.
, - optimal pattern height
- height optimal



, ()
intuition O n
( 2n 1, j i
, initial height )
i interesting height (
) interesting height
(d ) O n3
( )
O n2 , i
j interesting height optimal i 1
a b interesting height i
j + 1 interesting height optimal
i 1 interesting height ?
a b interesting height (a < b)? j + 1 interesting
height, j interesting height a j + 1
interesting height d
a ( ,
) b + 1 interesting height
d b
j +1 [a, b]
[a, b] i interesting
height linear ( linear ,
linear. amortized time )
- i j interesting height
, i 1 [a, b] interesting height
k (a k b), cost - dp[i
1][k] + ABS(height[i 1][k] height[i][j]). k
cost , RMQ
[a, b] [a, c], [c + 1, b]
height[i][j] height[i1][c] height[i][j] height[i1][c+1] [a, c]
cost dp[i1][k]height[i1][k]+height[i][j]
dp[i 1][k] + height[i 1][k] height[i][j].
i j interesting height
term constant. minimize
RMQ ([a, c] [c + 1, b])
query

UVa 1380 A scheduling problem


: n (n 200). edge directed
undirected undirected edge direction
direction edge.

: undirected edge ,
chain d. d
( x )
undirected edge direction
x
d, d + 1, d + 2 . . .


DP
, f g. i i
undirected edge direction x
chain orient i
? f [i].
i g[i]. f
g i child
child - a. i directed edge
child -b. i directed edge
child c. i undirected edge a
f f [a]. b g
g[b]. f [a] + g[b]
x c
i direction edge ,
direction c cf cg. i cf edge
cg i cf f
f [cf ]. cg f f [cf ]
, cg cf
f
cf , c
f
cf, cg. f [cf ] g[cg]
f [cf ] , g[cg]
precompute ,
4 - f [a], g[b], f [cf ], g[cg].
x optimal f [i]
i g
f, g x , x

, d d + 1. x = d
d d + 1. d + 1
(
) convince time
complexity O n2 .

UVa 10559 Blocks


: 200
(
) k
score k 2 .

score
:

state

state (i, j) i j

i cost (i + 1, j)
cost cost.
merge ,
k. i k merge (i + 1, k 1)
cost dp i k
merge dp ? ,
(i, j) parameter , prev.
i i merge ( (k, j)
parameter k i )
dp parameter ) j, prev), k
( (i,
dp O n4 visit

UVa 1228 Integer Transmission

: n
i i receiver i + 1
i + d + 1
receiver
sequence n d 64

: d d
d ? -
?
0 1

,
count

i 0 i 0 ( 1 ) , i 0
i 0 valid
i 0 0
0 1
0 1 information
0 1
i 1 0 j 1 1 0 ?
? i 1 0 j 1 1
t i 0 , s t
s , s t d


UVa 1628 Pizza Delivery

: 1d coordinate system n n
100. unit distance unit
waiting time
waiting time waiting time
waiting time
8 , 11 10
2,
3, 5
waiting time 2 5. waiting time 7.
waiting time 4.
waiting time

: zig zag ,
state
,
2n2 . ,
, state costly
,

(lef t, right, side) lef t1 right+1
left left ( right). side

waiting
waiting
waiting contribute
t ( ), k
kt waiting contribute
dp contribution waiting time

..

Simple

UVa 10285 Longest Run on a Snowboard UVa 1543 Telescope


UVa 1213 Sum of Different Primes UVa 1645 Count
UVa 1650 Number String UVa 12063 Zeros and Ones


Easy

UVa 10618 Tango Tango Insurrection UVa 10118 Free Candies


UVa 1629 Cake slicing UVa 1630 Folding

UVa 242 Stamp and Envelope Size UVa 10723 Cyborg Genes

UVa 1631 Locker UVa 1633 Dyslexic Gollum

UVa 12093 Protecting Zonk UVa 12589 Learning Vector

UVa 1379 Pitcher Rotation UVa 1371 Period

UVa 1637 Double Patience UVa 1393 Highways

UVa 1390 Interconnect UVa 1414 Hanoi Towers

LOJ 1085 All Possible Increasing Subsequences

Medium
UVa 1439 Exclusive Access 2 UVa 1375 The best name for your baby
UVa 1632 Alibaba UVa 10641 Barisal Stadium
UVa 1289 Stacking Plates UVa 1443 Garlands

UVa 1579 Matryoshka UVa 11982 Fantasy Cricket

UVa 12371 Guards UVa 12212 Password Remembering

UVa 1654 Pairs of integers

Hard

UVa 1634 The Picnic UVa 10271 Chopsticks

..

UVa 10118: tricky stack


! 404 205 .

stack

? odd
DP
, dp state

UVa 1439: represent
character character
edge - edge
direction cycle
15.
" deadlock
impossible " ?
edge
direction , topological sort
, L M N . . . , L N edge
L N
L N direction edge


chain ?
d. d
edge , edge
direction
edge
?
bitmask

submask submask edge
submask submask
precompute mask for
edge ( )
invalid valid. precompute O 2n n2
dp 3n
submask 2n 2n 3n

UVa 1375: A = XY Z
A = XT1 , T1 = Y Z
character dp dp state
character ( character
temporary character, T1 )
lexicographically empty
dp ?
character (terminal symbol) , 1
( 1 )
terminal symbol symbol expand
expand lexicographically
expand - ?
character expansion ,
,

Graph Theory

UVa 1599 Ideal Path


: n (n 100000). edge ( 200000
) undirected weighted. 1 n optimal path
optimal
lexicographically
: BFS. optimal path BFS
1 n BFS
1 n 1 v f[v] n v
g[v]. v f [v] + g[v] f [n]
v
1 1,
f [v] = 1 , n. f [v]
lexicographically

1 active, deactive.
( 1 ) active
neighbor edge
( weight) edge
, active active
1 n
edge

UVa 12171 Sculpture


: sculpture rectangular 3d ( 50 )
, overlap
sculpture sculpture volume
Coordinate 1 500
100
: coordinate 500
500 500 500



volume (
) 0, 0, 0
BFS unmark
(
structure volume ) ?
,

costly. test case 100
100 500 500 500 50
50 5003
? coordinate compression
(2, 2, 2) (5, 5, 5)
500 500 500 x = 100 x = 200
interesting coordinate x = 2, 5 y, z
coordinate
interested. 50
100 x coordinate interested ( y z coordinate )
5003 1003

x, y z coordinate
unique x 10, 30,
40. coordinate rename 10 1, 30 2,
40 3 1 10, 2 30
BFS volume area
real coordinate

UVa 11853 Paintball


: 1000 1000

(x, y) coordinate (radius).

1000
:
" connected circle " circle
( )
? ?
?
?
connected circle ? BFS
queue circle
queue adjacent visit
queue adjacent


UVa 10129 Play on Words
: 100,000


:
(
) directed
edge
directed edge. ?
- edge traverse
directed euler path

UVa 1572 Self Assembly


:
- B+, A+, A-
, character +
-. 00.
adjacent sign (+ -)
A+ A- 00
reflect
unbounded structure unbounded structure

: unbounded structure
infinite structure -
,

- state ( )

state (
) state directed edge
state directed edge directed
cycle unbounded structure

UVa 1395 Slim Span


: weighted graph 100
spanning tree cost edge
cost edge cost
: cost edge
cost ( b) ? edge
cost b Minimum Spanning Tree (MST)
MST cost edge b


edge b
1002 , 100 1002 edge (
)
edge MST MST complexity O m log m
( )
kruskal complexity O 1004 log 1002 .
accepted
edge
edge ( cost
) insert edge insert
connected edge
insert connected
a b. a b path path cost
edge graph edge insert
edge insert cost
cost edge
n 1 edge , connected
n 1 edge
n2( ) edge insert ( BFS
) cost
O n . complexity O n3 .

UVa 1653 Yet Another Multiple Problem


: n (n 104 )
n multiple
: -
, edge , BFS
DP BFS
DP DP
, mod ( n )
m mod d
(10m + d) (mod n). 0
?
DP n = 2.
0 1 (10 0 + 1) (mod 2)
recursively 1 1
1 , 1 1
DP 1
DP BFS
state ( ) mod n edge
edge 0 state
edge ( ) 0
( lexicographically )
0 0
0 state
state mod 0 state BFS ?
state digit
state ( edge). BFS
edge mod 0


0 edge
edge order lexicographically

DP , DP mod length
, state

UVa 10603 Fill


: a, b c. 200


d
d

: DP BFS
DP recursively state d

d DP.
DP BFS DFS state
state
/ / state
BFS DFS state state
state d
, d (
)
- O 2003 state
BFS state (i, j, k) i, j k
,
, c

(
) k = c i j. observation
state O 2002

UVa 10048 Audiophobia


: 100 weighted 10,000 query
query
edge cost
: query
query s t dijkstra s
t shortest path shortest path dijkstra
augment u u v edge
augment edge cost w. d[v]
d[u] + w d[v]
update u adjacent edge update
priority queue d[u] u
dijkstra d[v] d[u] + w


max(d[u], w)
(
)
complexity dijkstra O m log n
prim

prim kruskal
edge cost
edge edge merge s
t connected edge
cost priority queue prim
union find kruskal
10,000 query
TLE ?
-
query shortest ?
dijkstra
(
)
shortest path dijkstra O m log n . n
( )
O nm log n . modified dijkstra
n
- all pair shortest path algorithm
- floyd warshall. modify
Floyd warshall d[u][v] d[u][k] + d[k][v]
( ) d[u][v] max(d[u][k], d[k][v])
Complexity O n3 .


dijkstra prim
kruskal ?
edge cost
edge edge
connected
edge connected component
component A B. A B
edge cost. complexity
merge n 1 ( )(MST edge
) Worst case merge O n2 ( component
n/2 ()) n
complexity O n3 .
( ) ( )
O n log n preprocess O log n query
kruskal tree Least Common
Ancestor (LCA) Kruskal algorithm
tree v 2i parent
LCA , 2i parent
, 2i parent ( ) cost edge
cost O log n LCA ,
cost edge cost


UVa 11671 Sign of a Matrix
: nn element 0 (n 100)
element

n n element 0, + -. 0
0, +
-

: +1
-1 ? 10 +1
3 -1. 7 +1 ? /

+10, -5, +4, 0 ? +1 -1
,
i Ci i
Ri . ? (i, j)
0 Ri + Cj = 0. + Ri + Cj > 0
- Ri + Cj < 0. - equation

, abs(Ri ) + abs(Ci )

equation
di + w[i][j] dj di w[i][j] constant.
d1 . . . dn inequality

, abs(di )

,
? , d1 = R1 , . . . dn = Rn dn+1 =
C1 . . . d2n = Cn . equation Ri + Cj = 0
di dn+j 0 di dn+j 0 di dj + w[i][j]
? , Ri + Cj > 0 di dj+n 1.
equation


shortest path
?
-
u v w cost edge
shortest path u shortest path
d[u], v shortest path d[v]. d[u] + w[u][v] d[v]
d[u] + wuv < d[v] ? u d[u]
cost u v w[u][v] cost edge v
cost d[u] + w[u][v] equation d[v] d[v]
v shortest path. d[u] + w[u][v] d[v]
, d[u] + w[u][v] d[v] equation u
v w[u][v] cost directed edge
0 cost edge
shortest path w[u][v] negative bellman


ford negative cycle
negative cycle shortest path

optimal d[u] d[u]


abs(d[u]) ? Coreman

LOJ 1099 Not the Best


: N (N 5000) 105 undirected weighted
edge 1 N second shortest path
Second shortest path shortest path cost shortest path
edge

: cost
shortest path cost d1 [i] second shortest path cost
d2 [i]. dijkstra shortest path
d2 [N ] d1 [1] = 0 priority queue ,
d1 d2 . priority queue state
adjacent edge state
cost d edge cost w, edge v.
d + w d1 [v] d2 [v] d + w d1 [v]
d2 [v] d2 [v] = d1 [v] d1 [v] = d + w
, d1 [v] < d + w < d2 [v] d2 [v] = d + w v
second shortest path priority queue
d2 [N ] details ,
d1 d2 infinity initialize , d1 [v] d2 [v]
priority queue

LOJ 1034 Hit the Light Switches


: N (N 10000) directed 105 edge

directed edge ,
directed edge

: -
edge - , directed
edge ,
? directed edge indegree
0. ? 2
A B edge B A edge.
? , Strong Connected
Component SCC collapse
directed
indegree 0.
component represent
component


LOJ 1221 Travel Company

: N (N 100) directed 9900 edge


edge weight income
expense. edge
expense E income I profit
ratio I/E. profit ratio
P

:

I/ E > P I P E > 0 P E I < 0.
edge cost P E I
negative cycle profit
ratio P negative cycle finding algorithm

UVa 753 A Plug for UNIX

: 100 device 100


converter
,


: , -
max flow Maxflow - "
" (capacity), " " (maximum flow),
general , -
- general
DP many to many
,
?
edge
1. , edge
, edge obvious.
compatible edge edge capacity
1 infinity source

? , edge
, ,
( -
) edge ? Infinity. ?
?
Infinity ? 100 ,
100 infinity 100
maxflow


UVa 11082 Matrix Decompressing
: 20
( 20 20 )
1
20
:
1
1
adjust
edge edge edge
capacity
edge edge capacity 19 ( 20
1 )
,
capacity

capacity
19 capacity edge 19
maxflow - edge
saturated , - edge saturated
,

UVa 1349 Optimal Bus Route Design


: 99 vertex directed
weighted.
cost
2 length
:
edge ,
capacity 1 cost 0. edge
u v cost w. u
v w cost 1 capacity edge
mincost maxflow ( flow n
, ) ? maxflow
- u , u
edge u v (
edge , )
, - a ,
b ( a b ) (a, b)
n pair element ,
element capacity 1,
capacity 1. pair
? pair (a, b), b
pair , (b, c), (c, d) (d, a).


a a
n pair (u, u) pair
2 "mincost" maxflow
cost

UVa 1515 Pool Construction


: 2d # . #
. d
f


b
50 50 d, b, f
10,000
:
mincut Mincut weighted undirected
s t
edge s t disconnected
edge cost
s t flow ( weight edge capacity )
maxflow mincut theory

s
t s t mincut s
t
s t ? ,

edge edge capacity weight s t
edge

s-t b cost (
)? b cost edge
? edge

b cost edge i j
i j j i b cost edge
s edge x
s x edge cost
s-t s x
x ( s cut s )
s-x edge edge cost x
cost. x cost 0.
cost f. ? s-t s-x
s-x edge , x ( t
) cost ? x cost, ?
s-x cost. x-t edge cost


x cost. " "
f
t infinity cost edge
t t
infinity cost mincut
, ? s
( f )
edge s t
Maxflow mincut

UVa 10735 Euler Circuit


: 100 edge directed
undirected. undirected edge direction euler
circuit euler circuit
: directed euler circuit connected
( directed edge undirected ) indegree
outdegree condition

Euler circuit indegree outdegree
edge directed edge
edge
demand
edge flow network
undirected edge out-degree
undirected edge flow network edge
undirected edge edge
edge adjacent match
edge out-degree
directed edge
indegree outdegree
outdegree
flow network
capacity edge edge
1 capacity edge ( edge out-
degree ) edge direction
euler circuit

UVa 1659 Help Little Laura


: 2D 100
directed edge X Y
directed edge

edge d


c edge cost d X c Y .
cost

: Maxflow
flow experience
observation ,
indegree outdegree property
?
edge cost edge d
cost dX Y . cost
edge cost edge
indegree 5 outdegree 7. ?
outdegree indegree
, outdegree indegree
indegree outdegree
approach indegree
outdegree. indegree , indegree
outdegree indegree
outdegree
capacity
directed edge outdegree
outdegree outdegree indegree
outdegree indegree
capacity edge
edge ( cost negative)
capacity 1 edge
cost? dX Y negative.
score flow edge cost
maximize negative cost minimize
"mincost" maxflow , edge cost (dX Y ).
indegree
( outdegree ) , indegree
edge -
cancel ? u v
edge cost c. edge u outdegree
v u edge cost c. ?
v u edge u v edge cancel
c cost ( c > 0) edge
c, cost ,
outdegree - indegree convert
mincost maxflow
negative cycle cancellation algorithm.
,
score
score , edge cost
1 negative cycle
augment path , edge cost negate
negative cycle
negative cycle cost


negative cycle cancellation algorithm.

UVa 1664 Conquer a New Region


: 200,000 edge weight
u v path cost - path edge
weight
path cost
cost
:
DP
edge weight ( kruskal
) edge add
union find edge
connected component

weight edge u v weight w. u
c(u) v c(v)
center u edge cost c(v) w.
v edge cost c(u) w.
? v center w
cost edge. u w cost edge
cost edge
cost , ?
u
v independently u center
cost c(v) w v center
cost c(u) w
( ) ()
O n2 n O n2
?
, 1

edge
? u
v w weight edge , w weight
u ans[u] v
ans[v]. ? u
, ans[u] + c(v) w (c(u) u tree
)? u , w weight
edge v c(v) w u
u
u v ans[v] + c(u) w.
cost ? (
cost )? edge
edge


union find

.
..
Simple
UVa 1151 Buy or Build UVa 247 Calling Circles
UVa 1658 Admiral UVa 821 Page Hopping
UVa 820 Internet Bandwidth UVa 10305 Ordering Tasks

UVa 208 Firetruck UVa 439 Knight Moves

UVa 506 System Dependencies UVa 572 Oil Deposits

Easy
UVa 1600 Patrol Robot UVa 658 Its not a Bug, its a feature!
UVa 10651 Pebble Solitaire UVa 12661 Funny Car Racing
UVa 1001 Say Cheese UVa 1660 Cable TV Network

UVa 10801 Lift Hopping UVa 1663 Purifying Machine

UVa 12264 Risk UVa 12219 Common Subexpression Elimination

Uva 1025 A spy in the metro UVa 1601 The Morning after Halloween

UVa 1103 Ancient Message UVa 804 Petri Net Simulation

UVa 810 A Dicey Problem UVa 816 Abbott's Revenge

UVa 1665 Islands UVa 10653 Bombs! No they are mines!!

Medium
UVa 1279 Asteroid Rangers UVa 12549 Sentry Robots

UVa 1667 Network Mess UVa 1668 Let's Go Green

UVa 1669 Holiday's Accommodation UVa 1670 Kingdom Roadmap

UVa 1518 Train Delays

LOJ 1208 Dangerous Bull! Who wants to Pull?

Adhoc

UVa 120 Stacks of Flapjacks

:


,
valid sequence
30

: ? ?
?
? ?


complexity

UVa 1605 Building for UN

: n (n 50). 3d grid
-
-
connected
106

: Puzzle
-
connected.
connected connection -
connection


UVa 1152 4 Values whose Sum is 0
: 4 n n
4000 4 4
( ) 0
: 4 2
? scan x
x map, set, hash
( sort
) two pointer
( )
, O n log n (hash O n ).
, 4000.
( )
O n2
( )
element O n2 .

UVa 11134 Fabled Rooks


: nn n 5000.
n
rectangle rectangle
,
,
:

- -
flow bipartite matching experience
experience
1 capacity edge -
1 capacity edge
edge rectangle
, edge ,

2
edge capacity 1.
capacity -
1 capacity
edge constraint
? ,
, flow
maxflow n
powerful observation
axis independently




! 2d 1d

, ? Greedy. line sweep
,

data structure data
structure ( )
? ,
, Data structure


, data strcture
map multiset

UVa 11054 Wine trading in Gergovia


:


i j
cost abs(j i). cost
100,000

: greedy
optimal Greedy -





, i
edge

( ) ( ) :
3, 1, 5, 1. 3. 3
4 4
1 , 1
/ 0
3 + 4 + 1 = 8 cost

UVa 11572 Unique Snowflakes


: 100,000.


: last last[i]
i i index index
0 last
map scan
last
map last 0.
map last
map index map
index last

last
variable l r initial 1. l ,
r r r
last[r] l ? l = last[r]
r 1 n
( index 1 n) l
l r optimal (
r l + 1 )

UVa 1606 Amphiphilic Carbon Molecules


: 2d 1000 2d
plane


: , angle sweep ?
optimal line




,



candidate n2
candidate , ( )
candidate ( 3) O n
time complexity O n . time
complexity
angle sweep. fix
,

( ) fix
O n . fixed
fixed 0


1 . . . n 1 angle counter clockwise
0 1 -
,
( )
O n
3

(fixed point , 0 i ,
)? ? 0 1
0 2
? 0 1 0 2 1
, 2
adjust 0
, 1 0 , 2 0

, index
1 0
2 , , line sweep Line sweep
,
i () 1 . . . n 1
O n2
( )
time complexity O n2 log n
angle sweep linear.
simplify !
- fixed point reflect
- fixed point

simplify

!
, fixed
angle
entry angle
exit angle entry exit event
line sweep
active

UVa 1471 Defense Lines


: 200,000

- increasing
: i index
( i ) strictly increasing sequence
? , i
strictly increasing sequence sequence a[i]
a
i


i index i strictly increasing
sequence
length1[n] = 1 n 1. i
i + 1 ,
i i + 1
? , 1. i i strictly
increasing sequence
i i
a[i] strictly increasing sequence

strictly increasing sequence
i (i ) strictly increasing sequence ,
length2
- i j < i a[j] < a[i] length2[j]

i segment tree
segment tree - " a[i] index
?" i segment tree
- "a[i] length2[i] !"
, a[i] length2[i]
( )
segment tree O n log n

binary search set set
(a[j], length2[j]) i index a[i]
immediate a[j] ? lower bound -
a[j] length2[j]
immediate a[j] a[j] length2[j] ,
(a[j], length2[j]) a[k]
? length2[k] ? length2[j] ? (a[j], length2[j])
a increasing -
( property ) length2 increasing (
) (a[i], length2[i]) length2[k]
length2[i] , (a[k], length2[k]) -
maintain

UVa 10954 Add All


: n (n 5000).
a b cost a + b. cost

: huffman coding. Huffman coding
greedy section
-

prefix
- 5
3. 15. huffman coding.


, weight ,
?
, root
? Huffman
coding
weight ( )
weight ( )
, huffman coding length ,
?
cost , cost
huffman coding ?

UVa 12627 Erratic Expansion


: stage -
2 2 2 2

K stage (K 30)
A B
: A B
1 B 1 A 1
- 1
A -
observation K stage ? 1
stage 2 2, 2 stage 4 4, 3 stage 8 8 K
stage 2K 2K . , stage
, K stage
, K stage
A compare A ?
? K 1 stage
A = A 2K /2
recursively K 1 stage A
A
A
, stage
parameter recursively
stage , (A)
case A
,
case
( K 1 stage ) ?
i stage expand
expand

,
expand


UVa 1451 Average
: 100,000 element
0 1. L
s 1
a a/s s L. L
1000
: i j index j i + 1 L
i j 1 S ji+1
S

S ?
Cumulative sum. 1 cumulative sum p
S = p[j] p[i 1]. average 1 p[j]p[i1]
ji+1 .
i = i 1
p[j]p[i]
ji . ? slope
i, j x p y slope.
modify , n i < j
choose j i L 1 slope

q slope ,
q q ?
convex hull q tangent
slope convex hull upper left
hull
? i i + L
upper left hull insert i tangent -
upper left hull tangent
Upper left hull hull -
u[1], u[2] . . . u[m] p ,
p, u[m], u[m 1] counter clockwise , u[m]
turn turn clockwise
( 2 element ) p u insert
upper left hull maintain
, tangent ? , u
ternary search slope
log n factor
q tanget u[k]
u[1] . . . u[k 1] optimal slope property
ternary search amortized linear

UVa 714 Copying Books


: 500 k
( k )


: -
k ?
? S.
S


? ? Binary search.
guess , S1 S2 S1 <
S2 . S1 K1 S2 K2 . K1 K2 .
S ? binary
search S guess
K S
S (K ),
S K guess
K S
optimal S

UVa 11093 Just Finish it up


: N


( ) N 100000

:

- N circular


(
) 2N i index i + N
index (1 i N 1 indexed).
cumulative sum cumulative sum
S. i j
S[j] S[i]. i j > i
S[j] S[i] 0 2N
circular
[i, i + N 1] (1 i N )
( ,
) 1 i N i
[i + 1, i + N ] j S[j] S[i] 0
( j i + N j 2N
) S[j] S[i] i + 1 j
i ?
j S[j] fixed. S[i] S[j] S[i]
i N i + N
2N 1 i N S[i]


j S[j] S[i] 0

UVa 1607 Gates


: NAND

( )
x. x
base
x 0 1 circuit
x 0 1
200,000 base 100,000

: x 0
1 x
0 1 x 0 x
1 x
? x vary
vary x x
vary vary ?
00 . . . 0
11 . . . 1
x x = 0 00 . . . 0 ( A)
x = 1 11 . . . 1 ( B)
?
5 6
00000, 00001, 00011, 00111, 01111, 11111. A,
B A B sequence
A B. 00011 A
00111 B. 00x11
x
x x 0 A x 1 B
, ? N
N + 1 sequence TLE
200, 000 100, 000
?
Binary search. A B
, sequence AAA . . . AAABBB . . . B
AABBABBABBABB.
A B
A B ? -
sequence A B -
test A ? ?
, sequence A B
A ?
B
binary search sequence
A B.


UVa 12174 Shuffle
: s ( 100,000) 1 s
shuffle
random permutation random
permutation partial history
( n , n 100, 000)
shuffle
, " " , 2
, 4 ,
2 history , 0
: 1-indexed. 1 n
index n i i
, i i + s 1 index
i i + s 1 duplicate
i i
i
? i [i, i + s 1] intersect
[2 s, n] i
i ( ) s sequence i
O s ? sliding window
[2 s, 1] duplicate ,
[1 s, 2] window
window
segment
variable 2 2
window

shuffle
i shuffle i s, i 2s . . .
shuffle 0 s 1 mod
mod index shuffle

UVa 1608 Non boring sequence


: n (n 200, 000). non-boring
unique boring
non-boring.
: element

[1, n]. element
i [a, b] a < i < b element
[1, i 1] boring , [i + 1, n]
boring unique element
-
( ) element
? O n


( )
, O n2
? ( )
n, n 1 O n2
?
[i, j] i unique?
j unique? i + 1 unique j 1
? zigzag ?
a b
min(a, b) ? a = n 1 b = 1
a + b = j i + 1
a b (j i + 1)/2 ( )
O n .
element
? ,
, [i, j]

map precalculate

UVa 1609 Foul Play


: n (n 2 1024 )


,
n/2
n/4
-

: leaf

B
A. scenario - A B
, A A B
special A
planning B
A
A
schedule


- , n ( 2
power, 2k ). , A a, B
b. A B
B A a n/2 = 2k1
b < n/2 = 2k1 . schedule

n/2 = 2k1
schedule , , A


a n/4 = 2k2 B b < n/4 = 2k2
B A
schedule
?
schedule
schedule ?
A B B A
schedule
A B B
schedule A B
schedule B
schedule B
A schedule B A
B
A schedule A
schedule schedule

?


b < n/2 b < n/4
a n/2 a n/4
B' A'

B A B
scheduling A
A schedule
b t A schedule
b t A schedule t
b t
b t A
a t A ( a t 1 b
) a > b ? a > b
a + b = n/2 1 a > b
2b < n/2 1 b < n/4.
a > b . a > b , t
schedule a t > b t t
A , B
t 1 ( B ,
schedule ,
B ) b B A B
t A
B B A
a t 1 > b t 1. A
B A B
a b .
a = b case analysis a = b
? , a = b t = 1 b t


schedule b t 1
a t 1 B
A
A A B
?
A B
(a t 1)/2 > (b t 1).
details
convince


case analysis
,

UVa 1442 Cave


: n unit (n 1, 000, 000)
unit


-
-


( original problem )
:







, linear scan
i
height i height limit

h, f limit L.

L h > f . i L ,
h L h
h > L > f . L

h > f L. L

, L violate


, f
f
i L violate
L = f .


L L

UVa 12265 Selling Land

: R C (R, C 1, 000)

-

( )
: maximum 0 area subrectangle O n2

? subrectangle base
stack base
, rectangle base

() base
O n2 precompute stack
height stack stack
height. stack stack
height height
? height rectangle
stack
height
stack height height ?
stack

perimeter rectangle base
fixed. stack
r c (c stack element
, r ) perimeter c c + r (
1-2 )
stack r c
stack element stack
( ) r c


.
..
Simple
UVa 1149 Bin Packing UVa 1610 Party Games
UVa 12545 Bits Equalizer UVa 11491 Erasing and Winning
UVa 1611 Crane UVa 1616 Caravan Robbers

UVa 1617 Laptop UVa 1618 Weak Key

UVa 11536 Smallest Sub-Array

Easy
UVa 177 Paper Folding UVa 11925 Generating Permutations
UVa 1612 Guess UVa 1153 Keep the Customer Satisfied
UVa 1615 Highway UVa 10570 Meeting with Aliens

UVa 1619 Feel Good UVa 1312 Cricket FieldCircles

Medium
UVa 1613 K-Graph Oddity UVa 1614 Hell on the Markets
UVa 1620 Lazy Susan UVa 1621 Jumping Around
UVa 1622 Robot UVa 1623 Enter The Dragon

UVa 10366 Faucet Flow UVa 11175 From D to E and back

UVa 1580 Pirate Chest UVa 1624 Knots

Geometry

UVa 190 Circle Through Three Points


: 2d

- (x h)2 + (y k)2 = r2 , -
x2 + y 2 + cx + dy e = 0

: -


- x2 + y 2 + cx + dy e = 0 c, d, e
x y
equation unknown
(c, d, e). equation variable
determinate ,
gaussian elemination ,
- (x h)2 + (y k)2 = r2 h, k, r
x y
format h2 + ah + k 2 + bk + c r2 = 0
a, b, c constant ( x y a, b, c
constant )
ah+bk+c = 0
variable (h, k). h k
r

- R = abc 4A
R ( a, b, c
A )
R



UVa 378 Intersecting Lines
:
, , -
-
( parallel ), ,

, coordinate
: A B. C D.
ABC ABD signed
, ABC
A, B, C A, B D
A, B, C D
signed , signed
AB CD signed
AB C D AB
AB CD signed

?
,

vector

UVa 460 Overlapping Rectangles


: axis parallel (
coordinate ) intersection (intersection
) intersection
coordinate
: case by case
-
coordinate (Ax1 , Ay1 ) coordinate
(Ax2 , Ay2 ) (Ax1 < Ax2 Ay1 < Ay2 ). B
intersection C
Cx1 = max(Ax1 , Bx1 ), Cy1 = max(Ay1 , By1 ), Cx2 = min(Ax2 , Bx2 ),
Cy2 = min(Ay2 , By2 ). ? A B A
B A B
intersection intersection rectangle ? ,
A B , B ? A
B intersection , ?
C , ,
overlap ? , C
, C C
C C
C ,
C , C


, C
, ? C
coordinate
convince
, intersection

UVa 10175 Sphere


: r1 , r2 d
d > r1 , r2
d < r1 + r2
specific gravity

: specific gravity


d ?

A
B B ,
A B A
B spherical cap
calculus
spherical cap



(d, 0, 0) XY P, Q
r1 , r2 d. A B AB
AB PQ
PQ AB D. PD QD PD
P Q
, P Q ,


P Q ( AB )
P A = r1 , QA = r2 P Q = d
P D APQ AD (PQ
) P D2 = P A2 AD2 . APQ

AD
PQ PAD QAD
PD
PD PD cap

- r,


cap h cap


x = h x = r

x = h x = r
integration h r. h r dx
cylinder ?
x = 0 x = 1 plane
plane Plane cylinder
? , plane
,
cylinder ? dx
y. x y r2 x2 . integration
r
h f (x) f (x) = (r2 x2 ) dx

f (x) = 2 r2 x2 dx
integration ?
calculus !

UVa 10522 Height to Area


:

,
:
, -

Ha , Hb Hc A, B, C
a, b, c A, B C
a Ha , b Hb c Hc ,
a : b : c 1/Ha : 1/Hb : 1/Hc
k a = k/Ha , b = k/Hb , c = k/Hc .
aH2
a

equation k k
! ?
square root square root
negative square root
negative positive
height

UVa 10709 Intersection is not that Easy


:


: Vector

intersection intersection

0.
,
, 0.

? pair ( )

/
/
optimal ?
pair

candidate candidate

- /
parallel - pair

/
case analysis.
? parametric equation vector
C AB AB
P. parametric form P A + (B A)t.
CP AB CP.AB = 0. t
C(0, 2) AB
A(5, 0) B(1, 0). AB
P parametric form A + (B A)t (5, 0) + [(1, 0) (5, 0)]t
(5, 0) + (6, 0)t (1, 0)t (t, 0). CP AB
CP.AB = 0 [P C].[B A] = 0 [(t, 0) (0, 2)].[(1, 0) (5, 0)] = 0
(t, 2).(6, 0) = 0 6t = 0 t = 0. P P parametric
form (t, 0) t P (0, 0).

A, B, C C AB

UVa 10979 How many triangles?


:

:
-

vertex
vertex edge


vertex
edge
vertex
vertex
duplicate

UVa 10674 Tangents

:

coordinate
-1

:


, (
)

0 coordinate





,
X
X

O1 , O2 , r1 , r2 .
r1 r2 . P1 , P2
P1 P2 P1 , P2 coordinate
O1
O2 P2 , M . O1 O2 M
, , O1 O2
coordinate O2 M = r2 r1
O1 O2 M O2 M = 0
O1 O2 M = O1 O2 P2 O2 O1 P1
O1 P1 O2 P2 P1 O1 angle
, (r cos + xcenter , r sin + ycenter )
(polar coordinate ) P1 coordinate
P2 coordinate


Timus 1697 Sniper Shot
: 3d coordinate sniper Sniper
coordinate , S. A B A B -
coordinate XY
n (n 100) (rectangular parallelepiped).
XY XY
Sniper infinity.
A B
,
AB
sniper

:

AC
component , component
, corner case overlook
precision error
, time complexity

S AB A
AB S AB
( AB ) S A B

SAB plane
AB

SAB AB
SAB AB S
S S
AB S
AB
,

- SAB
convex convex polygon
concave
12 3d
( 12 ) SAB
intersect intersection
convex polygon 3d 2d
- 3d intersection
, 3d parallel,
intersection , 3d

parametric equation intersection
intersection
- intersection


convex hull
- AB
, 3d ,
2d S
T ST
(T ) AB
ST , AB
special condition, parametric vector
intersection line plane intersection
parameter ,
T ,
ST AB ST
AB , ST AB
infinity A B
ST SA SB ,
infinity

AB -

- 1d
AB , S
AB S , ,
[A, C] [C, B] (A < C < B).
C
[A, B] ,
C A B

event A event starting B event
ending. A event event
event ending starting
event event
counter starting event
, ending event
counter
candidate AB

, infinity

UVa 10283 The Kissing Circles


: R n (n 100)
,
statement

:



packing -
pack symmetry
binary search -

, n
(n sided regular polygon) n < 3

n 3.

,


r. 2r.
?
n 2
2n

2r. ?

r, n . r/ sin n .
r R.
r + r/ sin n = R r unknown.

UVa 10286 Trouble with a Pentagon


:

:



binary search


binary search

turn (point in
a polygon technique). , binary search
1 a, f
f a.


UVa 10695 Find the Point
: ABC coordinate
O AOB, BOC, AOC O coordinate
O
: AB. AB
AB
- AB O AB AOB
AB
AB AOB
A B fixed AOB fixed. O (locas)
AB O

AOB AB C
OA = OB.
OAB O coordinate
O coordinate AB C
A, O B A,
O C intersect O
O ,

UVa 10809 Great Circle


: longitude latitude
shortest distance
shortest path latitude
undefined
: latitude longitude
.
XY latitude. XY
z > 0 N north latitude
z < 0 S south latitude
z = 0 0N latitude
N S
1 z coordinate sin.
longitude north pole south pole
,
0 longitude. longitude
, north pole, south pole 0
west east.
, 0
-
longitude. west east ,


.: Latitude Longitude, wikipedia

longitude x, y
longitude. XY
x, y , x, y x, y.
cos . x = cos sin y = cos cos .
latitude longitude x, y, z

special case
shortest path shortest path
north most unique
undefined
shortest path 0.

north pole shortest path
north pole north pole
south pole , shortest path north
pole
opposite (
)
unique



,
shortest path

X, O A B.
AOB AOX + BOX AOB
X A B


shortest path A B
X
X vector calculus
OA OB vector , A B coordinate
(xA , yA , zA ) (xB , yB , zB ). cross product
plane normal vector normal vector
normal
? N = (xN , yN , zN ) component
optimal (x, y, z).

? ,
90 90 equation ? ,
dot product xxN + yyN + zzN = 0.
(x, y, z) x2 + y 2 + z 2 = 1.
equation z
equation x z equation
z
lagrange multiplier

UVa 10089 Repackaging


:

(1, 11, 5)
,

,



1000
: 3d coordinate pi

i ai ai pi coordinate x, y
z , ai 0 ai ai pi coordinate x,

y z ai pxi = ai pyi = ai pzi

ai (pxi pzi ) = ai (pyi pzi ) = 0. 3d 2d
p(x, y, z) q(x,y)
qx = px pz , qy = py pz ai qxi = ai qyi = 0.

? q
convex hull , convex hull
convex hull

, cancel
ai = 0 ,


convex hull
( ) ai
ai
equation, x y ,
ai 0
,
,
intuition

..

Simple

Timus 1710 Boris, You Are Wrong!


UVa 476 Points in Figures: Rectangles
UVa 477 Points in Figures: Rectangles and Circles

UVa 478 Points in Figures: Rectangles, Circles and Triangles

UVa 191 Intersection

UVa 438 The Circumference of the Circle

UVa 453 Intersecting Circles

UVa 10573 Geometry Paradox

UVa 10725 Triangular Square

UVa 10242 Fourth Point!!

UVa 10341 Solve It

UVa 218 Moth Eradication

UVa 361 Cops and Robbers

UVa 109 SCUD Busters

UVa 596 The Incredible Hull

Uva 10065 Useless Tile Packers

UVa 10245 UVa The Closest Pair Problem


Easy
Timus 1703 Robotic Arm
Timus 3114 Spherical Mirrors
UVa 10287 Gifts in a Hexagonal Box

UVa 10289 A Square and Equilateral Triangles

UVa 10353 Circles in Hexagon

UVa 10345 Cricket/Football Goes Down

UVa 10372 Leaps Tall Buildings (in a single bound)

UVa 10398 The Golden Pentagon

UVa 10566 Crossed Ladders

UVa 10668 Expanding Rods

UVa 10598 Find the Latitude

UVa 811 The Fortified Forest

UVa 10078 The Art Gallery

UVa 10209 Is This Integration?

UVa 10215 The Largest/Smallest Box

UVa 11186 Circum Triangle

Medium
UVa 11580 Finding the Transmitter
UVa 10402 Triangle Covering
UVa 11123 Counting Trapezoid

UVa 11009 Geometry Once Again

UVa 10322 The Four in One Stadium

UVa 10386 Circles in Triangle

UVa 10631 Normals

UVa 819 GIfts Large and Small

UVa 10135 Herding Frosh

UVa 10256 The Great Divide

UVa 10210 Romeo & Juliet!

UVa 10251 Min-Max Cake

UVa 10481 The Gift Wrappers of Hollywood

You might also like