Professional Documents
Culture Documents
Programming Problem and Solution Book 1 Mahbubul Hasan
Programming Problem and Solution Book 1 Mahbubul Hasan
} -
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
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 . . . . . . . . . . . . . . . . . . . . . . . . . .
. 30/i . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
- 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
: 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 ,
- !
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
: - 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!
: ""
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. !
, !
: (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]);
}
// 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
: 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
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])
:
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 133 The Dole Queue UVa 1368 DNA Consensus String
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
Medium
..
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
( ) "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
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
while(iS >> w) w stl string (string w). stl
set
set istringstream ,
(set size ) set erase ,
set lower bound upper bound
stl
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
) 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
) 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
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
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
( )
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 12504 Updating a Dictionary UVa 511 Do You Know the Way to San Jose?
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
..
, substr(x, y)- x
y - 1 substring email address
, for loop
Mathematics
: 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
: 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
: 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
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
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
:
-
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
"" ""
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
L. n 1 dp[n 1]
UL. n 2 dp[n 2]
UUL. n 3 dp[n 3]
: 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
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
expectation , log n!
? , log n! = log 1 2 . . . n = log 1 + log 2 + . . . + log n.
n log n!
) 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.
(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.
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
:
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
, 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
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
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
: 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 )
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.
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
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.
: 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
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
: 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
(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
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
LOJ 1340 Story of Tomisu Ghost LOJ 1370 Bi-shoe and Phi-shoe
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
LOJ 1298 One Theorem, One Year LOJ 1318 Strange Game
Bruteforce Backtrack
: fghij 5 0 99999
input N abcde
optimization fghij 0
1000
N fghij 99999 1000
optimization
,
1018 long long long long variable
int , overflow
s1
s1 s2
s1 n 0 s1 1
optimal
.: 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
, move ?
power x10
?
optimization 1 1000 optimization
,
optimization
... , ,
optimization / heuristic IDA* backtrack
accepted
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
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
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 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
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
( , 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
: 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
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
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
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 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 ?
:
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 , (
)
d
?
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
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
.
..
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
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 1343 Aladdin and the Black Stones LOJ 1204 Weird Advertisement
..
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
, 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
score
score score
( ) assign
O n
binary search
binary search binary search
" g "
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
?
( )
: 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
a b pair a / b
ab ba a b ,
a b abbbbcaaaab. a b
? ab
a b
a b
c a
a b
: t
? s
t s
s = abac, t = abob a s c
t b s b a ab
s acab. ?
5000
,
character t character
: 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
Easy
Codeforces 76 B Mice
Codeforces Round 67 D Big Maximum Sum
Codeforces Round 71 C Beaver
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
Hard
Codeforces 128 Div 2 E Transportation
Dynamic Programming
: 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
: - 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
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
: 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).
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.
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 .
S[i] closing bracket
, greedy
- bracket sequence character balance
greedy ! Stack
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 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
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
,
/ /
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
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
:
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
!
: 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 !
: 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
: 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 .
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
: 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
Easy
UVa 242 Stamp and Envelope Size UVa 10723 Cyborg Genes
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
Hard
..
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
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 10129 Play on Words
: 100,000
:
(
) directed
edge
directed edge. ?
- edge traverse
directed euler path
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 .
0 edge
edge order lexicographically
DP , DP mod length
, state
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
: 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 1221 Travel Company
:
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
: , -
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
,
a a
n pair (u, u) pair
2 "mincost" maxflow
cost
x cost. " "
f
t infinity cost edge
t t
infinity cost mincut
, ? s
( f )
edge s t
Maxflow mincut
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.
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
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 1025 A spy in the metro UVa 1601 The Morning after Halloween
Medium
UVa 1279 Asteroid Rangers UVa 12549 Sentry Robots
Adhoc
:
,
valid sequence
30
: ? ?
?
? ?
complexity
: 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 .
! 2d 1d
, ? Greedy. line sweep
,
data structure data
structure ( )
? ,
, Data structure
, data strcture
map multiset
: greedy
optimal Greedy -
, i
edge
( ) ( ) :
3, 1, 5, 1. 3. 3
4 4
1 , 1
/ 0
3 + 4 + 1 = 8 cost
: 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 )
: , 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
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
, weight ,
?
, root
? Huffman
coding
weight ( )
weight ( )
, huffman coding length ,
?
cost , cost
huffman coding ?
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
: -
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
:
- 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
: 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
( )
, 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
: 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
,
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
: 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
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
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
Geometry
: -
- 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
, C
, ? C
coordinate
convince
, intersection
: 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 !
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
: 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
vertex
edge
vertex
vertex
duplicate
:
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
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.
:
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 ,
.: 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
convex hull
( ) ai
ai
equation, x y ,
ai 0
,
,
intuition
..
Simple
Easy
Timus 1703 Robotic Arm
Timus 3114 Spherical Mirrors
UVa 10287 Gifts in a Hexagonal Box
Medium
UVa 11580 Finding the Transmitter
UVa 10402 Triangle Covering
UVa 11123 Counting Trapezoid