Professional Documents
Culture Documents
.
. . . . . . . . .
.
? .
. ? . . . . . . . .
.
? . . . . .
. ? . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
C
.
. math.h .
. if - else if - else . . . . . . . . . .
. Loop . . . . . . . . . . . . . . . .
. Array String . . . . . . . . . . .
. Time Memory Complexity .
. Function Recursion . . . . .
. File Structure . . . . . . . . . .
. bitwise operation . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Mathematics
. Number Theory . . . . . . . . . . . . .
.. Prime Number . . . . . . . . .
.. Divisor . . . .
.. GCD LCM . . . . . . . . . . .
.. Euler Totient Function ( )
.. BigMod . . . . . . . . . . . . .
.. Modular Inverse . . . . . . . .
.. Extended GCD . . . . . . . . .
. Combinatorics . . . . . . . . . . . . . .
.. Factorial 0 . . . . . . .
.. Factorial Digit
( ) . . . . .
.. Combination: nr . . . . . . . .
.. special number . . . . . . .
.. Fibonacci Number . . . . . . .
.. Inclusion Exclusion Principle .
. . . . . . . . . . . . . . . . . . .
.. Probability . . . . . . . . . . .
.. Expectation . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. .
..
..
..
. . . . . . . . . . . . . . .
Base Conversion . . . .
BigInteger . . . . . . . .
Cycle Finding Algorithm
Sorting Searching
. Sorting . . . . . . . . . . . . . .
.. Insertion Sort . . . . . .
.. Bubble Sort . . . . . . .
.. Merge Sort . . . . . . .
.. Counting Sort . . . . . .
.. STL sort . . . . . . .
. Binary Search . . . . . . . . . .
. Backtracking . . . . . . . . . . .
.. Permutation Generate
.. Combination Generate
.. Eight Queen . . . . . . .
.. Knapsack . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. Linked List . . . . . . . . . . . . . . . . . . . . . .
. Stack . . . . . . . . . . . . . . . . . . . . . . . . .
.. 0 1 matrix 1
. Queue . . . . . . . . . . . . . . . . . . . . . . . .
. Graph representation . . . . . . . . . . . . .
. Tree . . . . . . . . . . . . . . . . . . . . . . . . . .
. Binary Search Tree (BST) . . . . . . . . . . . . . .
. Heap Priority Queye . . . . . . . . . . . . . . .
. Disjoint set Union . . . . . . . . . . . . . . . . . .
. Square Root segmentation . . . . . . . . . . . .
. Static Query . . . . . . . . . . . . . . . . . .
. Segment Tree . . . . . . . . . . . . . . . . . . . .
.. Segment Tree Build . . . . . . . . . .
.. Segment Tree Update . . . . . . . . .
.. Segment Tree Query . . . . . . . .
.. Lazy without Propagation . . . . . . . . .
.. Lazy With Propagation . . . . . . . . . .
. Binary Indexed Tree . . . . . . . . . . . . . . . .
. . .
. . .
. .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
. . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Greedy
. Fractional Knapsack . . . .
. Minimum Spanning Tree . .
.. Prim's Algorithm . .
.. Kruskal's Algorithm
. . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Dynamic Programming
. . . . . . . . . . . .
. Coin Change . . . . . . . . . . . .
.. Variant 1 . . . . . . . . . .
.. Variant 2 . . . . . . . . . .
.. Variant 3 . . . . . . . . . .
.. Variant 4 . . . . . . . . . .
.. Variant 5 . . . . . . . . . .
. Travelling Salesman Problem . .
. Longest Increasing Subsequence
. Longest Common Subsequence
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. n = 3
. . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. c = ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
.
.
.
. . . . . . . .
Heap . . . . . . . . . .
Heap array numbering
Segment Tree Build .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. math.h . . . . . . . . . . . . . . . . . . . .
, ,
,
!
,
,
- " ?"
- " ?" - " ,
, " !
,
, , , , , , ,
, , ,
,
,
,
, efficient
ACM
,
,
ACM Style Informatics Olympiad
Style. ACM
, Number Theory, Calculus, Graph Theory,
Game Theory, Dynamic Programming
Informatics Olympiad
Algorithmic Individual
Google, Facebook,
Microsoft ,
(
?) ,
Google, Facebook, Microsoft
? Google
"
uva.onlinejudge.org popular
icpcarchive.ecs.baylor.edu uva
OJ acm.pku.edu.cn, acm.zju.edu.cn,
acm.tju.edu.cn pku
analysis pku zju
tju ,
projecteuler.net mathematical
,
mathematical skill.
mathematical skill
uva uhunt.felix-halim.net uvatoolkit.com , userid
userid
comparison , Felix
Halim Steven Halim
www.e-maxx.ru
article Google Translator Bing Translator
!
infoarena.ro article
OJ
,
internet , net
preview suite
. ?
ACM
C, C++, Java Informatics Olympiad
C, C++ Pascal
.% C/C++ , C
C++ C C++ C++
C++ Object Oriented Programming
C
C
C
C C
basic if-else ,
loop , function, array ,
code
internet !
C
.
# i n c l u d e <s t d i o . h>
i n t ma in ( )
{
p r i n t f ( "%d\n " , 6 + 2 ) ;
r e t u r n 0;
}
?
! ,
Line 1 stdio.h header file include header file
stdio standard
input output.
line 2 empty line. space tab
line 3 main function
run function
function integer return
line 5
printf("%d %d\n", 6 + 2, 6 - 2)
line 6 main function 0 return
( .1) ,
run user
scanf ( .2)
# i n c l u d e <s t d i o . h>
i n t mai n ( )
{
int a , b;
s c a n f ( "%d %d " , a , b ) ;
p r i n t f ( "%d\n " , a + b ) ;
r e t u r n 0;
}
a b variable.
x, y, a, b, p , C variable
a b variable
declare scanf ,
a b &a &b ?
6 + 2 a + b
( - ), ( * ), ( / ) ( % )
, ? !
practice
hints
Online Judge OJ
Timus 1000 Timus 1264 Timus 1293 Timus 1409
math.h
experiment ( .2)
(a b) run 100000 100000
( )! ,
( python , python
!) a b variable declare int int
variable 231 231 range
263 263 1 int %d
long long %lld
3 2
1.5 ? 1? ? ?
, ?
, a b int a/b integer
a%b
a b
231 2 109 .
int long long
long long int64 %I64d
1.5 ?
double float int long
long float range , double range
, float precision
int long long int long long
slow. signed unsigned
(stdio.h).
, math.h math
( sin, cos, tan, square
root, square, cube ) math.h
. math.h
.: math.h
sqrt(x)
fabs(x)
sin(x), cos(x), tan(x)
asin(x), acos(x), atan(x)
atan(x), atan2(y, x)
pow(x, y)
exp(x)
log(x), log10(x)
floor(x), ceil(x)
x square root x
Run Time Error (RTE)
x
x sin, cos, tan x radian
x sin1 , cos1 , tan1 x [1, 1]
range
y = 1, x = 0 tan1 atan
, atan2
xy
ex
log natural logarithm log10 10 based logarithm.
floor ceiling
.3
, cos = 1
acos(-1) .
Listing .3 : circle area.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
# i n c l u d e <s t d i o . h>
# i n c l u d e <m a t h . h>
i n t ma in ( )
{
double r , area , pi ;
s c a n f ( "% l f " , &r ) ;
p i = a c o s ( 1.) ;
area = pi r r ;
p r i n t f ( "% l f \n " , a r e a ) ;
double
float %lf %f
double, float precision http://community.topcoder.
com/tc?module=Static&d1=tutorials&d2=integersReals article
= 22 , approximation
7
14
15
16
r e t u r n 0;
2D co-ordinate
,
,
,
integer
vertex co-ordinate ,
if - else if - else
leap year
leap year
leap year
leap year
if-else if-else. .4
, syntax
Listing .4 : simple if
1
2
3
4
5
6
7
8
9
10
11
12
13
if ( condition1 )
{
/ / if condition1 is true
}
else if ( condition2 )
{
/ / otherwise if condition2 is true
}
...
else
{
/ / i f no c o n d i t i o n s a r e t r u e
}
condition ? +, -, *, / (
arithmetic operator ) comparison operator <
, >, <=, >=, ==(equal), ! =(not equal).
( .5
syntax
syntax.
# i n c l u d e <s t d i o . h>
i n t ma in ( )
{
int a;
s c a n f ( "%d " , &a ) ;
i f ( a % 2 == 0 )
{
p r i n t f ( "%d i s e v e n \n " , a ) ;
}
else
{
p r i n t f ( "%d i s odd \n " , a ) ;
}
}
r e t u r n 0;
leap year
,
, .6
Listing .6 : leap year.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# i n c l u d e <s t d i o . h>
i n t ma in ( )
{
i n t year ;
s c a n f ( "%d " , &y e a r ) ;
i f ( y e a r % 400 == 0 )
{
p r i n t f ( "%d i s Leap Y e a r \n " , y e a r ) ;
}
e l s e i f ( y e a r % 100 == 0 )
{
p r i n t f ( "%d i s n o t Leap Y e a r \n " , y e a r ) ;
}
e l s e i f ( y e a r % 4 == 0 )
{
p r i n t f ( "%d i s Leap Y e a r \n " , y e a r ) ;
}
else
{
p r i n t f ( "%d i s n o t Leap Y e a r \n " , y e a r ) ;
}
}
r e t u r n 0;
# i n c l u d e <s t d i o . h>
i n t mai n ( )
{
i n t year ;
s c a n f ( "%d " , &y e a r ) ;
i f ( y e a r % 400 == 0 | | ( y e a r % 100 != 0 && y e a r % 4 == 0 ) )
p r i n t f ( "%d i s Leap Y e a r \n " , y e a r ) ;
else
p r i n t f ( "%d i s n o t Leap Y e a r \n " , y e a r ) ;
}
r e t u r n 0;
Palindrome ,
Palindrome number 1, 2, 3, . . . 9, 11, 22, 33, . . . 99, 101, 111, 121, . . ..
n Palindrome Number (n < 100)
n
n , i=1 i (n i + 1) = 1 n + 2 (n 1) + . . . n 1
( if-else !)
co-ordinate , quadrant
Timus 1068
Loop
Loop
a + b ( .2) 1 100
, 1 , 2 , 3 100
loop C loop For loop, While loop, DoWhile loop. ,
,
if-else curly brace
.8 for loop while loop outline
main
faunction ,
Listing .8 : simple loop.cpp
1
2
3
4
5
6
7
8
9
10
11
loop
keyword break continue.
loop
loop loop iteration
break continue .10
i++ i = i + 1 i += 2 i = i + 2. double slash comment
comment
/ / p r i n t s odd n u m b e r s f r o m 1 t o 10
f o r ( i = 1 ; i <= 1 0 ; i ++)
{
i f ( i % 2 == 0 ) c o n t i n u e ;
p r i n t f ( "%d\n " , i ) ;
}
/ / p r i n t s o n l y 1 , 2 and 3
f o r ( i = 1 ; i <= 1 0 ; i ++)
{
i f ( i > 3) break ;
p r i n t f ( "%d\n " , i ) ;
}
/ / takes input u n t i l the input is 0
/ / s o m e t i m e s i t i s n e e d e d f o r OJs .
/ / EOF = End Of F i l e .
w h i l e ( s c a n f ( "%d " , &a ) ! = EOF )
{
i f ( a == 0 ) b r e a k ;
p r i n t f ( "%d\n " , a ) ;
}
/ / in short
w h i l e ( s c a n f ( "%d " , &a ) ! = EOF && a )
{
p r i n t f ( "%d\n " , a ) ;
}
loop loop ,
n 1 + (1 + 2) + (1 + 2 + 3) + . . . + (1 +
2 + . . . + n). , (1 + 2 + . . . + n)
for loop 1 n
1 1 ,
2 n for loop
upper bound for loop
.11
Listing .11 : simple loop4.cpp
1
2
3
4
. 1 + 2 + 3 + . . . + n
. 12 + 22 + 32 + . . . + n2
loop formula , formula
:)
. 11 + 22 + 33 + . . . + nn
. 1 + (2 + 3) + (4 + 5 + 6) + . . . + nth term
. 1 2 + 3 4 + 5 . . . nth term
. 1 + (2 + 3 4) + (5 + 6 7 + 8 9 10) + . . . + nth term
. 1 n + 2 (n 1) + . . . + n 1
n
.: n = 3
Palindrome ,
Palindrome number 1, 2, 3, . . . 9, 11, 22, 33, . . . 99, 101, 111, 121, . . ..
n Palindrome Number (n < 109 ) (
)
n Prime 1 1 ba n n Prime Prime
n!
n r ,
(n)
r
n!
r!(nr)!
quadratic equation
A B answer 0 B answer 0 A 1 answer
pattern
Array String
// initialization
f o r ( i = 0 ; i < 1 0 ; i ++ ) a [ i ] = 0 ;
f o r ( i = 0 ; i < 1 0 0 ; i ++)
{
s c a n f ( "%d " , &i d ) ; / / t h e p l a y e r g i v i n g c o r r e c t a n s w e r
a [ id 1]++; / / increment p l a y e r s p o i n t
}
m a x i m u m s c o r e = 0 ; / / i n i t i a l i z i n g max s c o r e
f o r ( i = 0 ; i < 1 0 ; i ++ )
i f ( m a x i m u m s c o r e < a [ i ] ) / / i f i t h p l a y e r s s c o r e i s more t h a n
t h e max
m a x i m u m s c o r e = a [ i ] ; / / s e t max s c o r e t o t h i s v a l u e
p r i n t f ( " Winners a r e :\ n " ) ;
f o r ( i = 0 ; i < 1 0 ; i ++ )
i f ( m a x i m u m s c o r e == a [ i ] )
// if
i t h p l a y e r s s c o r e i s maximum
solution 2d ,
intersection
, x
x
intersect
co-ordinate
formula internet !
0-indexing 1-indexing
18
p r i n t f ( "%d\n " , i + 1 ) ; / / p r i n t h i s i d
space,
new line, tab white character
new line
dummy gets , scanf
gets
, n sentence
sentence ? , sentence array
n sentence ? sentence1[100], sentence2[100]
100 array declare ? , array array! ,
sentence[20][100] sentence[0] sentence
20 sentence , string
, int, double dimension , multidimension
array , matrix 2 dimension array
string.h- string
strlen - string length
, strcmp - string dictionary ,
lexicographical order , strcat - string concatenation , strcpy - string
copy , memset - memory fill
strtok, strstr
intuitive. memset critical
a integer array , element
0 initialize memset(a, 0, sizeof(a)). a
array , 0 er fill
,
array 0 1 initialize , memset
, 1 initialize ,
convert
array ,
array
sorting
array 1 0 1
array number.
array i j ?
string length (library function )
Topcoder http://community.topcoder.com/tc?module=
Static&d1=tutorials&d2=integersReals
for loop sort array
, ,
,
swap
! i j for loop ! , ,
!
(a, b, . . . z) (A, B, . . . Z)
string A B , B A
A = bangladesh B = desh B, A B
A aa aaa
string A B , B A subsequence B A
subsequence A letter B
A = bangladesh B = bash B, A subsequence B =
dash subsequence
term n term , n n2
term. n2 term , n term
2
n2 /2. constant term
( )n .
Time Complexity. , algorithm O n2 . n = 1000
( )
, O n2 = 106 1s , n = 106 ?
( )
n O n2 algorithm
Time Limit Exceed (TLE) optimize ?
, i for loop 1 n 1 + 2 + . . . + i
2
for loop formula ( i 2+i )
( )
O n n ? ,
n = 101 2?
algorithm order
1 + (1 + 2) + (1 + 2 + 3) + . . . + (1 + 2 + . . . + n)
=
n
i
i=1 j=1
n
2
i=1
1
=
2
1
=
2
(
(
i +i
2
i=1
i +
)
i
i=1
n(n + 1)(2n + 1) n2 + n
+
6
2
formula (
loop
)
, O 1 algorithm.
Memory Complexity (Fibonacci
Number) , n Fn
0
Fn = 1
Fn1 + Fn2
n=0
n=1
n2
order n2
= 0
Time Complexity Time
Complexity
n
a = 0;
b = 1;
f o r ( i = 2 ; i <= n ; i ++)
{
c = a + b;
a = b;
b = c;
}
p r i n t f ( " n t h F i b o n a c c i = %d\n " , b ) ;
. Function Recursion
, ,
, ,
, ,
,
!
! , sqrt
,
C 4 , parameter, , return type
, parameter
processing processing return Grade ,
grade function
parameter marks if-else grade
( .14)
Listing .14 : grade.cpp
1
2
3
4
5
6
7
8
9
i n t gr ade ( i n t marks )
{
i f ( m a r k s >= 8 0 ) r e t u r n 5 ;
e l s e i f ( m a r k s >= 6 0 ) r e t u r n
e l s e i f ( m a r k s >= 5 0 ) r e t u r n
e l s e i f ( m a r k s >= 4 0 ) r e t u r n
e l s e i f ( m a r k s >= 3 3 ) r e t u r n
else r e t u r n 0;
}
4;
3;
2;
1;
LightOJ 1136
"A B answer 0 B answer 0 A 1
answer "
f parameter n
0 n answer f (B)f (A1).
!
Recursion recursion !
Mr Edsger Dijkstra
I learned a second lesson in the 60s, when I taught a course on
programming to sophomores and discovered to my surprise that
10% of my audience had the greatest difficulty in coping with the
concept of recursive procedures. I was surprised because I knew
that the concept of recursion was not difficult. Walking with my
five-year old son through Eindhover, he suddenly said "Dad, not
every boat has a life-boat, has it?" "How come?" I said. "Well, the
life-boat could have a smaller life-boat, but then that would be
without one." It turned out.
Recursion , processing
, , Fn = Fn1 +Fn2 .
n ,
n1 n2
call recursion recursion call
, call , n = 3
, n 1 = 2 n 2 = 1 ,
?
definition
n=0
0
Fn = 1
n=1
Fn1 + Fn2 n 2
, n 1 n1 n2
, recursion
?? , recursive function
n ( )
loop ?
Time Complexity , algorithm Time Complexity
,
,
challenging. array
array recursion
Timus 1005 Timus 1082 Timus 1149
LightOJ 1042 LightOJ 1189
File Structure
,
problem sample test data
case case
case OJ
file file
File , :)
input.txt output.txt
,
freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);.
fopen
save array
save ,
information. , , , ,
information information
array. maintain
structure.
.15
Listing .15 : structure.cpp
1
2
3
4
5
6
7
8
9
10
11
s t r u c t Student
{
c h a r name [ 3 0 ] , f a t h e r [ 3 0 ] , a d d r e s s [ 5 0 ] ;
int birth date , birth month , birth year ;
i n t phone ;
};
Student s , student [50];
s c a n f ( "%s " , s . name ) ;
p r i n t f ( "%d\n " , s t u d e n t [ 5 ] . b i r t h d a t e ) ;
. bitwise operation
Decimal Number
System 10 0, 1, 2, . . . 9.
0 1. Number System Binary Binary
bit variable 6 0, 1
bitwise operation operation bit
bitwise operator & (bitwise and), | (bitwise or),
^ (bitwise xor), (1's complement), << (shift left), >> (shift right).
Mathematics
. Number Theory
.. Prime Number
Prime Number n
1 1 n
n Prime ?
n n
2 n 1 n n Prime
Idea Primality
.1
Listing .1 : isPrime1.cpp
1
2
3
4
5
6
7
8
9
10
/ / r e t u r n s 1 i f prime , o t h e r w i s e 0
int isPrime ( int n)
{
i f ( n <= 1 ) r e t u r n 0 ;
f o r ( i n t i = 2 ; i < n ; i + +)
i f ( n % i == 0 )
r e t u r n 0;
}
r e t u r n 1;
(
) Prime for loop n 2 , Time Complexity
O n . , , 2 Prime
for loop (
) ! run
time ? O n/2 constant term
( )
run time O n , order
notation , ?
, d n
n n/d. divisor ( )
n = 24 divisor 1, 2, 3, 4, 6, 8, 12, 24
4 (1, 24), (2, 12), (3, 8), (4, 6).
n ? direct , Proof
by Contradiction n ,
! n
n n ? n
(
) ( .2) run time
O n . for loop condition i i n
, i sqrt(n) , sqrt costly
, double precision loss sqrt(9) = 3
2.9999999 3.0000001 ii !
loop
limit = sqrt(n + 1)
loop sqrt
Listing .2 : isPrime2.cpp
1
2
3
4
5
6
7
8
9
10
/ / r e t u r n s 1 i f prime , o t h e r w i s e 0
int isPrime ( int n)
{
i f ( n <= 1 ) r e t u r n 0 ;
f o r ( i n t i = 2 ; i i <= n ; i ++ )
i f ( n % i == 0 )
r e t u r n 0;
}
r e t u r n 1;
(
)
run time? , O log n !
internet
Sieve of Eratosthenes
Prime
generate
( Number
)
O n algorithm number
, prime
?
, pair
Sieve algorithm
1 n prime ,
prime Algorithm
! 2 n , ,
multiple !
prime
prime ! n !
! n = 10 . algorithm simulate
.3 algorithm
( implementation
)
run time O n log log n . prime number
mark array prime
double represent sqrt integer
!
.: n = 10
initial
uncut number = 2. 2 multiple
uncut number
= 3. 3 multiple
, 5 > 10
2, 3, 4, 5, 6, 7, 8, 9, 10
2, 3, 4, 5, 6, 7, 8, 9, 10
2, 3, 4, 5, 6, 7, 8, 9, 10
2, 3, 4, 5, 6, 7, 8, 9, 10
Listing .3 : sieve.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
i f ( i <= l i m i t )
{
f o r ( j = i i ; j <= n ; j += i 2 )
{
mark [ j ] = 1 ;
}
}
sieve variation
Memory Efficient Sieve n , array mark 2 mark 1
memory requirement
mark array 0 1
, int 32 bit variable 32
information memory requirement 32
efficient 2 b )
prime factorize prime
prime power
..
Divisor
() divisor .2
O n divisor sieve algorithm
modify 1 (n ) divisor ? ,
runtime O n log n . .4
, multiple list insert mark memory
! , n divisor n log n STL vector vector Dynamic
Linked List ,
Listing .4 : all divisors.cpp
1
2
3
4
5
6
7
8
9
10
i n t mark [ 1 0 0 0 0 0 2 ] ;
v e c t o r <i n t > d i v i s o r s [ 1 0 0 0 0 0 2 ] ;
void Divisors ( i n t n )
{
int i , j ;
f o r ( i = 1 ; i <= n ; i ++)
f o r ( j = i ; j <= n ; j += i )
d i v i s o r s [ j ] . push back ( i ) ;
}
divisor , divisor
sum !
divisor problem method
, n = pa1 1 pa2 2 . . . pakk pi prime
prime factorization , d n divisor
, d pi prime divisor
, pi power ai d = pb11 pb22 . . . pbkk
0 bi ai . equation n divisor
(NOD = Number of Divisor) divisor (SOD = Sum of Divisor)!
N OD(n) = (a1 + 1)(a2 + 1) . . . (ak + 1)
SOD(n) = (1 + p1 + p21 + . . . + pa1 1 )(1 + p2 + p22 + . . . + pa2 2 ) . . . (1 + pk + p2k + . . . + pakk )
=
..
pak +1 1
p1a1 +1 1 p2a2 +1 1
... k
p1 1
p2 1
pk 1
GCD LCM
a b g l a b = g l.
? a b (
)
1 , run time O n .
, euclid
a b , , a
b , b b
b ( a ) ,
c a = k b + c. c b ! (a < b
!) a b c
b c a b
c
!
exact run time
long long 100 150
recursive .5
Listing .5 : gcd.cpp
1
2
3
4
5
i n t gcd ( i n t a , i n t b )
{
i f ( b == 0 ) r e t u r n a ;
r e t u r n gcd ( b , a % b ) ;
}
i n t p h i [ 1 0 0 0 0 0 6 ] , mark [ 1 0 0 0 0 0 6 ] ;
void sievephi ( i n t n )
wiki runtime
!
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int i , j ;
f o r ( i = 1 ; i <= n ; i ++) p h i [ i ] = i ;
phi [1] = 1;
mark [ 1 ] = 1 ;
f o r ( i = 2 ; i <= n ; i += 2 )
{
i f ( i != 2 ) mark [ i ] = 1 ;
phi [ i ] = phi [ i ] / 2;
}
f o r ( i = 3 ; i <=n ; i += 2 )
i f ( ! mark [ i ] )
{
phi [ i ] = phi [ i ] 1;
..
f o r ( j = 2 i ; j <= n ; j += i )
{
mark [ j ] = 1 ;
phi [ j ] = phi [ j ] / i ( i 1) ;
}
BigMod
BigMod
Method. bowler
n ,
? 2 , 2n
n
i n t bigmod ( i n t a , i n t b , i n t M)
{
i f ( b == 0 ) r e t u r n 1 % M;
i n t x = bigmod ( a , b / 2 , M) ;
x = ( x x ) % M;
i f ( b % 2 == 1 ) x = ( x a ) % M;
return x;
}
1 + a + a2 + a3 + a4 = 1 + a(1 + a + a2 + a3 )
1 + 2a + 3a2 + 4a3 + 5a4 + . . . + bab1 mod M
..
Modular Inverse
exact
mod
, , ab modM amodM
bmodM
b b1 M
b M prime , b1 bM 2 mod M .
, b1 bM 1 mod M M b coprime
bigmod
..
Extended GCD
a b g x y ax + by = g
. a = 10 b = 6 x y
euclid
x y x = 1 y = 2.
.: a = 10 b = 6
10
6
4
2
x
1
0
1
-1
10x + 6y
10
6
4
2
i n t e g c d ( i n t a , i n t b , i n t &x , i n t &y )
{
i f ( a == 0 )
{
x = 0; y = 1;
return b;
}
i n t x1 , y1 ;
i n t d = e g c d ( b%a , a , x1 , y1 ) ;
x = y1 ( b / a ) x1 ;
y = x1 ;
}
return d;
, bx = 1 + yM y integer. , bx yM = 1. b M
coprime x y , bx yM = 1 , bx 1 mod M
egcd x ,
x M mod
. Combinatorics
.. Factorial 0
100! ? - common
, 100!
10
, 5! = 120 10 , 0
? 5 2 10
2 5 2
, 2 5 ,
5 , 5 1
100 100/5 = 20 5 5
25 5 , 125
125 100
5 power 5
100/5 + 100/25 = 20 + 4 = 24. 100! 24
n! prime number p
n/p + n/p2 + n/p3 + . . .
.. Factorial Digit
n! 0 , n!
? calculator 50! 3.04140932
106 4 3 64
10 power
? , log. calculator log
64.4830 . . . floor
number of digits digit
, log
50! log! , log
log (a b) = log a + log b log 50! = log 1 + log 2 + . . . log 50.
.. Combination:
(n )
r
( )
n!
n r nr = (nr)!r!
.
(n)
n r r
factorial overflow. n = 50, r = 1 50!
x
= (x mod M + M) mod M
10x
ceiling
( )
overflow 50
1 = 50. double , double
approximation , exact , (n r)!
r! n! ,
50 1 50. method overflow
( ) overflow
, nr array
array , gcd
1 (
)
overflow nr
, , overflow, time complexity,
memory complexity, implementation complexity
exact mod
mod prime
n! mod p, ModuloInverse(r! mod p, p) ModuloInverse((n-r)! mod
p, p)
p>
( n
) facotiral mod precalculate
O log n mod prime
Lucas' Theorem. theorem
( )
)
k (
m
mi
(modp)
n
ni
i=0
, m = mk pk +( .). . + m1 p1 + m0 p0 n = nk pk + . . . + n1 p1 + n0 p0 .
ab a, b < p precalculate
( ) ( )
prime (O 1 ) nr
( )
nr precalculate nn array
( 2)
( ) (
) (n1)
O n nr = n1
.9
r (+) r1
n
limncr r generate
Listing .9 : ncr.cpp
1
2
3
4
5
6
7
8
9
ncr [ 0 ] [ 0 ] = 1;
i n t limncr = 10;
f o r ( i = 1 ; i <= l i m n c r ; i ++)
f o r ( j = 0 ; j <= l i m n c r ; j ++ )
{
i f ( j > i ) ncr [ i ][ j ] = 0;
e l s e i f ( j == i | | j == 0 ) n c r [ i ] [ j ] = 1 ;
e l s e n c r [ i ] [ j ] = n c r [ i 1 ] [ j 1] + n c r [ i 1 ] [ j ] ;
}
2 ? ,
approximation
base case
.. special number
special number
internet
Derangement Number
n
! n = 3
2 BCA CAB (
A, B C) inclusion exclusion principle
recurrance
Dn n Derangement Number n
n 1
X X
n 2 Dn2
(n 1)Dn2 X
X
n 1 n 1
(n 1)Dn1 ,
Dn = (n 1)Dn2 + (n 1)Dn1
Catalan Number
2n Dyck Word ? 2n Dyck Word n X n Y
prefix Y X n = 3
Dyck Word XXXYYY, XYXXYY, XYXYXY, XXYYXY XXYXYY.
n opening bracket n closing bracket paranthese
expression ? n = 3 ((())), ()(()), ()()(), (())() (()()).
n leaf complete binary tree ?
n polygon triangulate ?
Catalan Number.
Cn
Cn =
n Catalon Number
( ) ( ) (
)
2n
2n
2n
1
=
n+1 n
n
n+1
http://en.wikipedia.org/wiki/Catalan_number interpretation
.. Fibonacci Number
n 106
, n 101 8
? ( mod )
method
matrix matrix matrix general method method problem
Matrix
[ ] [
F2
1
=
F1
1
[ ] [
F3
1
=
F2
1
[
1
=
1
[
1
=
1
][ ]
F1
F0
][ ]
1 F2
0 F1
][
][ ]
1 1 1 F1
0 1 0 F0
]2 [ ]
1
F1
0
F0
1
0
,
[
] [
]3 [ ]
F4
1 1
F1
=
F3
1 0
F0
,
[
] [
]n1 [
]
Fn
1 1
Fn1
=
Fn1
1 0
Fn2
matrix power ,
BigMod ,
matrix. matrix
Stirling Number
, k k matrix
k n
,
,
,
(
)
time complexity O 2n .
bitmask
n
n bit , bit 1 ,
0 loop -
details
.. Probability
Head Tail
? ! chance 50-50.
, 5 6
?
! 5 mathematical
5 , 6 1, 2, 3, 4 1, 2, 3, 4
, common sense
?
? !
=
r
4r 2 = 4 . experiment n
randomly b , experiment
nb nb 4 , 4b
n.
n
.. Expectation
coin head 0
tail 100 ? 100
, , 50% 0
,
mathematician
50 ? 0
100 , 50 ? , 10
5 head 5 tail. 10
500 , 50 expectation 50
,
?
expected number of move
move expectation
probability , coin
head tail. head probability 0.5
0 0.5 probability tail 100
expectation 0.5 0 + 0.5 100 = 50.
.:
1 5
3 1 6
3 5
Expected number of move ?
, Ti i expected number of
move. T1 T5 = 0 5
move
4 T4 move.
, 1 4 , T4
move , 4
T4 move T4 move
? 1 T5 move. 1/6 probability T5
move 5/6 probability T4 move.
, T4 = 1 + 16 T5 + 56 T4 , T4 = 6.
, 6
expectation 6. T3 ,
, 2 1/6 probability 2
T4 move, 1/6 probability 3 T5 move , 4/6
probability 2 T2 move ,
T2 = 1 + 16 T4 + 16 T5 + 46 T2 T2 = 6. T1
, T1 = 1 + 16 T2 + 16 T4 + 61 T5 + 36 T1 T1 = 6. expected number of
move 6.
.. Base Conversion
base 10. base 2
- (base 8), (base 16)
Decimal
10
voltage up down
0 1.
0, 1, . . . 9, 10, 11, 12, . . . 19 . . . digit
0, 1, 10, 11, 100, 101, 110, 111, 1000 . . . number system
number system 481
4 102 + 8 101 + 1 100 1010
1 23 + 0 22 + 1 21 + 0 20 10.
number system
number system i
basei
number system
? b base
an bn + . . . + a1 b1 + a0 b0 b
a0 power 1 ,
b a1
.. BigInteger
mod ,
BigInteger Java
advantage Java BigInteger library
Slow TLE C BigInteger
function
, ,
,
, array
100 digit 50 digit
string input align
, ,
, align
,
digit result array 0 initialize
? ,
? 10 ,
, ?
,
Sorting Searching
. Sorting
Sort
1 60
sorting sort
, string, co-ordinate sort
sorting algorithm
.. Insertion Sort
real life sorting 60 , sorted
sorting
implementation
1 . . . i 1 sorted , i
, i 1 ?
position i 1 i
i 2 .
( ) algorithm time
complexity O n2 . sorting Insertion
Sort .1
Listing .1 : insertion sort.cpp
1
2
3
4
5
6
7
8
9
f o r ( i = 1 ; i <= n ; i ++)
{
x = num [ i ] ;
f o r ( j = i 1 ; j >= 1 ; j )
i f ( num [ j ] > x )
num [ j + 1 ] = num [ j ] ;
}
num [ j + 1 ] = x ;
5, 8,
5, 8, 6,
5, 6, 8,
5, 6, 8, 1,
5, 6, 1, 8,
5, 1, 6, 8,
1, 5, 6, 8,
1, 5, 6, 8, 7,
1, 5, 6, 7, 8,
1, 5, 6, 7, 8, 9
1, 5, 6, 7, 8, 9
6, 1, 7, 9
1, 7, 9
1, 7, 9
7, 9
7, 9
7, 9
7, 9
9
9
..
Bubble Sort
( )
O n2 sorting algorithm Insertion Sort
bubble sort algorithm
(
)
swap n algorithm O n2
,
n
.2 optimization
, n array sorted
loop pair
i i
optimization
( ) optimization algorithm worst
case O n2 worst case ?
Listing .2 : bubble sort.cpp
1
2
3
4
5
6
7
8
9
10
f o r ( i = 1 ; i <= n ; i ++ )
{
f o r ( j = 1 ; j < n ; j ++)
i f ( num [ j + 1 ] > num [ j ] )
{
te mp = num [ j ] ;
num [ j ] = num [ j + 1 ] ;
num [ j + 1 ] = t e m p ;
}
}
( )
array O n2
.. Merge Sort
algorithm practical life
sorting 60
sort
sorted ,
?
,
sort ?
,
recursive function function array
function call sort
merge sorted return
merge sort .3 , mergesort
variable parameter , lo hi. variable array
sort
Listing .3 : merge sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
i n t num [ 1 0 0 0 0 0 ] , te mp [ 1 0 0 0 0 0 ] ;
/ / c a l l m e r g e s o r t ( a , b ) i s you w a n t t o s o r t num [ a . . . b ]
void m e r g e s o r t ( i n t lo , i n t h i )
{
i f ( l o == h i ) r e t u r n ;
i n t mid = ( l o + h i ) / 2 ;
m e r g e s o r t ( l o , mid ) ;
m e r g e s o r t ( mid + 1 , h i ) ;
int i , j , k;
f o r ( i = l o , j = mid + 1 , k = l o ; k <= h i ; k + + )
{
i f ( i == mid + 1 )
temp [ k ] =
num [ j + + ] ;
e l s e i f ( j == h i + 1 )
te m p [ k ] = num [ i + + ] ;
e l s e i f ( num [ i ] < num [ j ] )
te m p [ k ] = num [ i + + ] ;
else
temp
[ k ] = num [ j + + ] ;
}
16
17
18
19
20
21
22
f o r ( k = l o ; k <= h i ; k ++ ) num [ k ] = te m p [ k ] ;
mergesort call
call merge
temp array ,
temp array temp array
array array sorted
base case
2T ( n2 ).
merge n/2 n/2
temp
n n
n
( )
O n ,
n
T (n) = 2T ( ) + n
2
n
n
= 2[2T ( ) + ] + n
4
2
n
= 4T ( ) + 2n
4
n
= 8T ( ) + 3n
8
n
log n
2
T ( ) + n log n
n
nT (1) + n log n
n log n
(
)
time complexity O n log n .
..
Counting Sort
..
STL sort
(
)
, sorting O n log n algortihm
sort non negative
integer
(
) N counting sort time complexity
O N . algorithm auxiliary array count auxiliary array
array 1 N loop i i
output array output array sorted
sort
STL algorithm header file
include num array 0 n 1 sort
, sort(num, num + n). 1 n sort
sort(num + 1, num + n + 1). a b
sort sort(num + a, num + b + 1).
sort vector V sort
, sort(V.begin(), V.end()).
2 dimension point
point x y co-ordinate
x , x y
point x y structure
structure array , sort
structure Point array point.
b o o l cmp ( P o i n t A , P o i n t B )
{
i f (A . x < B . x ) r e t u r n 1 ;
i f (A . x > B . x ) r e t u r n 0 ;
i f (A . y < B . y ) r e t u r n 1 ;
i f (A . y > B . y ) r e t u r n 0 ;
}
r e t u r n 0;
??
Listing .5 : improved cmp.cpp
1
2
3
4
5
b o o l cmp ( P o i n t A , P o i n t B )
{
i f (A . x != B . x ) r e t u r n A . x < B . x ;
r e t u r n A. y < B. y ;
}
st ruc t Point
{
int x, y;
}point [100];
b o o l o p e r a t o r <( P o i n t A , P o i n t B )
{
i f (A . x != B . x ) r e t u r n A . x < B . x ;
r e t u r n A. y < B. y ;
}
integer array
?
declare functional
sort(num, num + n, greater<int>).
# i n c l u d e <s t d i o . h>
# i n c l u d e <s t r i n g >
# i n c l u d e <a l g o r i t h m >
# i n c l u d e <v e c t o r >
us ing namespace s t d ;
i n t mai n ( )
{
int n , i ;
char s [100];
v e c t o r <s t r i n g > V ;
s c a n f ( "%d " , &n ) ;
f o r ( i = 0 ; i < n ; i ++)
{
s c a n f ( "%s " , s ) ;
V. push back ( s ) ;
}
s o r t (V . b e g i n ( ) , V . e n d ( ) ) ;
}
r e t u r n 0;
. Binary Search
Game Show 100
,
1986
1986
,
1986 1986
1986
, 100 50
1986
? method
binary search bisection method
, array 0 1 0 1
1 binary search
0 1, 0
, 1
Binary Search
, binary search ,
! . w
7 :)
,
a b. c
a, b c , w =?.
a
b
c
w
.: c = ?
w
w c
?
( )
1
p q.
, c = 1 +
1 .
p
w c
c w . w w
guess , c ,
w w guess c
w w w binary
search c w
range
. Backtracking
Backtracking algorithm , method.
Backtracking.
.. Permutation Generate
1 n permutation n = 3
(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2) (3, 2, 1)
for-loop , n
, n 10. n = 3 n = 4
3, 4 nested loop , n
n
loop
loop
?
systematically n
systematic ? n = 3 ,
, (1)
(2)
(3). (1, 2, 3) immediate ,
3 next
3 ,
2 2
(3) ( )
(2)
permutation (1, 3, 2) immediate
(2). ,
3 3
1 next 2 1
3 (2, 1, 3)
permutation
for loop ,
,
loop
,
permutation
next permutation
, black box permutation
black box black box next
black box call
black box recursive function. recursive function Fibonacci
Factorial
, ?
? - , ?-
, ? - fix , permute
permutation
black box
black box ,
. order .
base case number
sequence integer
double array standard
pointer pointer
vector slow. global
array array array
(0 , 1
i n t used [ 2 0 ] , number [ 2 0 ] ;
/ / c a l l with : permutation (1 , n )
/ / make s u r e , a l l t h e e n t r i e s i n u s e d [ ] i s 0
void p e r m u t a t i o n ( i n t at , i n t n )
{
i f ( a t == n + 1 )
{
f o r ( i = 1 ; i <= n ; i + +) p r i n t f ( "%d " , n u m b e r [ i ] ) ;
p r i n t f ( " \n " ) ;
return ;
}
f o r ( i = 1 ; i <= n ; i ++) i f ( ! u s e d [ i ] )
{
used [ i ] = 1;
number [ a t ] = i ;
permutation ( at + 1, n) ;
used [ i ] = 0;
}
.. Combination Generate
n k combination
n = 3 k = 2 (1, 2), (1, 3) (2, 3).
systemetic
, 1 n
k
,
n
(n) (n
) 2
k k ?
decision k
call
( .9 7
( )
(O n)
O 2n )
k
Listing .9 : combination1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
i n t number [ 2 0 ] ;
int n , k;
/ / c a l l with : permutation (1 , k )
void combination ( i n t at , i n t l e f t )
{
i f ( l e f t > n a t + 1) r e t u r n ;
/ / you c a n u s e l e f t == 0 t o make i t a l i t t l e b i t more f a s t e r
/ / i n s u c h c a s e you d o n t n e e d f o l l o w i n g i f ( l e f t ) c o n d i t i o n
i f ( a t == n + 1 )
{
f o r ( i = 1 ; i <= k ; i + + ) p r i n t f ( "%d " , n u m b e r [ i ] ) ;
p r i n t f ( " \n " ) ;
return ;
}
if ( left )
{
}
}
number [ k l e f t + 1] = a t ;
c o m b i n a t i o n ( a t + 1 , l e f t 1) ;
combination ( at + 1 , l e f t ) ;
,
k
number combination (1, 2) (2, 1)
n k permutation
combination
,
parameter
loop 1
better
, worst case recursion n depth ,
k depth .10
14 (
( )
(O n)
)
if O 2n
k
condition ,
for loop upper bound
,
i n k + at condition ?
i at n i
k at , k at n i i n k + at.
i n t number [ 2 0 ] ;
int n , k;
/ / c a l l with : permutat ion (1 , 0)
void combination ( i n t at , i n t l a s t )
{
i f ( a t == k + 1 )
{
f o r ( i = 1 ; i <= k ; i + +) p r i n t f ( "%d " , n u m b e r [ i ] ) ;
p r i n t f ( " \n " ) ;
return ;
}
f o r ( i = l a s t + 1 ; i <= n k + a t ; i ++ )
{
number [ a t ] = i ;
combination ( at + 1 , i ) ;
}
.. Eight Queen
( 8 8 ) 8 Queen (
) Queen
Queen attack Queen Queen attack
Row Column Diagonal
row queen
, row queen queen
queen attack row queen
queen row column
diagonal column
, diagonal tricky.
diagonal diagonal
diagonal
row 1 8 column
1 8 ( . diagonal
row column
diagonal row column
row queen queen
column diagonal ,
queen column 6 queen
, valid placement
queen
queen attacking position
, queen pair queen
queen
queen ,
array column diagonal queen
1 2 3 4 5 6 7 8
1
2
3
4
5
6
7
8
.:
queen array column,
diagonal queen queen
column diagonal queen
loop , if-else
optimized
improvement
optimization performance
8 8 optimization
9 9, 10 10
optimization .11
n = 8 8 8 ,
Listing .11 : nqueen.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
i n t q u e e n [ 2 0 ] ; / / q u e e n [ i ] = c o l u m n n u m b e r o f q u e e n a t i t h row
i n t c o l u m n [ 2 0 ] , d i a g o n a l 1 [ 4 0 ] , d i a g o n a l 2 [ 4 0 ] ; / / a r r a y s t o mark i f
t h e r e i s queen or not
/ / c a l l with nqueen (1 , 8) f o r 8 queen problem
/ / make s u r e column , d i a g o n a l 1 , d i a g o n a l 2 a r e a l l 0 i n i t i a l l y
void nqueen ( i n t at , i n t n )
{
i f ( a t == n + 1 )
{
p r i n t f ( " ( row , c o l u m n ) = " ) ;
f o r ( i = 1 ; i <= n ; i + + ) p r i n t f ( " (%d , %d ) " , i , q u e e n
[ i ]) ;
p r i n t f ( " \n " ) ;
return ;
}
f o r ( i = 1 ; i <= n ; i ++)
{
i f ( column [ i ] | | d i a g o n a l 1 [ i + a t ] | | d i a g o n a l 2 [ n + i
at ]) continue ;
queen [ a t ] = i ;
/ / n o t e t h a t , i a t c a n be n e g a t i v e a n d we c a n t h a v e
array index negative
/ / s o we a r e a d d i n g o f f s e t n w i t h t h i s .
22
23
24
25
26
column [ i ] = d i a g o n a l 1 [ i + a t ] = d i a g o n a l 2 [ n + i a t
] = 1;
nqueen ( a t + 1 , n ) ;
column [ i ] = d i a g o n a l 1 [ i + a t ] = d i a g o n a l 2 [ n + i a t
] = 0;
optimization ,
optimization run time
optimization ! optimization
Backtracking optimization
optimization
! array queen
.. Knapsack
W
n
wi vi
W ? limit
. Linked List
n
? ,
n n 0 1 matrix i j
matrix ( [i][j]
) 1 0
memory O n2
( )
update O 1 .
adjacency matrix
n n matrix i row i
array
[i][1] [i][f riend[i]] i
, friend[i] (i ) friend
memory O n2
(
)
O f riend[i]
( )
O 1
friend[i] matrix [i][f riend[i]]
adjacency list array implementation
n nn
declare dynamically memory
adjacency list linked list implementation.
method memory complexity
freindship memory
array array dynamic memory
allocation ,
element
declare
array , 106
, 104 , array
104 104 declare
linked list 106 declare
dynamically memory allocate define array array
linked list , dynamically
point
terminal terminal
node point
terminal 1 0
3 - Insert, Delete Search.
Search
terminal
data
Insert
terminal node
next point id
node ( . A B D)
, , D next A next A
next point D
Data A
Head
Data B
Next
Data C
Next
Data D
Next
.:
Delete
node delete node next
point point node (
B) A next B next point
structure data next
i n t h e a d [ 1 0 0 0 0 ] ; / / t o t a l n o d e = 1 0 0 0 0 , 0 t o 9 9 9 9 . I n i t i l i z e d t o 1
i n t d a t a [ 1 0 0 0 0 0 ] , n e x t [ 1 0 0 0 0 0 ] ; / / t o t a l e d g e = 100000
i n t id ;
/ / add node y i n t h e l i s t o f x
void i n s e r t ( i n t x , i n t y )
{
data [ id ] = y ;
next [ id ] = head [ x ] ;
head [ x ] = id ;
}
/ / e r a s e f i r s t node from head o f x
void erase ( i n t x )
{
head [ x ] = next [ head [ x ] ] ;
}
/ / s e a r c h node y i n x ' s l i s t
int search ( int x , int y)
{
f o r ( p = h e a d [ x ] ; p != 1; p = n e x t [ p ] )
i f ( d a t a [ p ] == y )
r e t u r n 1; / / found
r e t u r n 0; / / not found
Next
26
Stack
Stack
?
? ,
Stack stack
push pop LIFO Last In First
Out array
pointer stack
array declare
linked list STL stack stack
implementation .2
Listing .2 : stack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/ array implementation /
sz = 0
// initialization
s [ s z ++] = d a t a ; / / p u s h
r e t u r n s[s z ] ; / / pop a n d r e t u r n
i f ( sz )
/ / check whether t h e r e i s something in s t a c k
/ linked l i s t implementation /
h e a d = 1, s z = 0 ;
// initialization
node [ sz ] = d a t a ; n e x t [ sz ] = head ; head = sz ++;
/ / push
r e t = n o d e [ h e a d ] ; h e a d = n e x t [ h e a d ] ; r e t u r n r e t ; / / pop & r e t u r n
i f ( h e a d != 1)
/ / check
/ STL /
# i n c l u d e <s t a c k >
us ing namespace s t d ;
s t a c k <i n t > S ;
t h e t y p e you w a n t
w h i l e ( ! S . e m p t y ( ) ) S . pop ( ) ;
S . push ( 5 ) ;
S . top () ;
, b u t d o e s n t pop
S . pop ( ) ;
return
S. size () ;
S . empty ( ) ;
/ / d e c l a r e , r e p l a c e i n t by
// initialization
a f t e r used
/ / push
/ / r e t u r n top element
/ / pop b u t d o e s n t
/ / size of the stack
/ / r e t u r n s 1 i f empty
..
0 1 matrix 1
n n 0 1 matrix
. Queue
queue queue,
queue. ? queue
FIFO First In First Out
queue
stack implementation array ,
linked list STL queue
queue implementation .3
Listing .3 : queue.cpp
1
2
3
4
5
6
7
8
/ ar r a y implementation /
head = t a i l = 0;
// initialization
q [ t a i l ++] = d a t a ; / / p u s h
r e t u r n s [ h e a d + + ] ; / / pop a n d r e t u r n
i f ( h e a d == t a i l )
/ / check whether t h e r e i s something in s t a c k
/ STL /
# i n c l u d e <q u e u e>
9
10
11
12
13
14
15
16
17
us ing namespace s t d ;
q u e u e<i n t > Q ;
/ / d e c l a r e , r e p l a c e i n t by
t h e t y p e you w a n t
w h i l e ( ! Q . e m p t y ( ) ) Q . pop ( ) ;
/ / i n i t i a l i z a t i o n a f t e r used
Q. push ( 5 ) ;
/ / push
Q. f r o n t ( ) ;
// return front
e l e m e n t , b u t d o e s n t pop
Q . pop ( ) ;
/ / pop b u t d o e s n t
return
Q. s i z e ( ) ;
/ / s i z e of t h e queue
Q. empty ( ) ;
/ / r e t u r n s 1 i f empty
Graph representation
Tree
edge node
node node uniquely
( )
special node root. tree edge directed
edge direction root node edge
root tree
edge edge node parent ,
node parent child node parent child
node sibling node root
node ancestor node
node descendant tree level
, node root
root level 0 , level 1
level depth tree node
h 1 depth tree height h
tree adjacency matrix list
represent tree
Child List directed graph adjacency list node
child node
representation root
tree
binary
(
)search
O log n binary search
? , binary search insert
delete BST insert delete
BST
( ), 1 2, 2 3 n
O n BST balance
tree height AVL
Tree, Red Black Tree, Treap internet
binary tree.
complete binary tree.
tree level level node
, node ??
heap
.: Heap
Heap , Max Heap, Min Heap. Max Heap
node descendant root heap
, left child left subtree
Min Heap heap n node
heap height log n
??
100 , 36
heap ?
link list link
( drawback !) left child link right child
link dynamically memory assign
array declare array declare
?? heap array indexing
, node index i left
# i n c l u d e <p r i o r i t y q u e u e >
us ing namespace s t d ;
p r i o r i t y q u e u e <i n t > PQ ; / / d e c l a r e a max h e a p
PQ . p u s h ( 4 ) ;
// insert
PQ . t o p ( ) ;
/ / maximum e l e m e n t
PQ . pop ( ) ;
/ / pop max
PQ . s i z e ( ) ;
/ / r e t u r n s s i z e of heap
PQ . e m p t y ( ) ;
/ / r e t u r n s 1 i f heap i s empty
, ?
?
Disjoin Set Union
Union Find
array p. p[i] i
p[i] i p[i] = i.
a ? p[a] a
p[] ,
, p[] array (
) , p[1] = 2, p[2] = 3, . . . p[n1] = n
a = 1 O n 1
n p[1] = n ? ,
1 2, 3, . . . n 1
n n
, chain
chain Find Find
.5
Listing .5 : union find.cpp
1
2
3
4
5
6
7
8
9
10
11
12
int p [100]; / / i n i t i a l l y p[ i ] = i ;
i n t Find ( i n t x )
{
i f ( p [ x ] == x ) r e t u r n x ;
r e t u r n p [ x ] = Find ( p [ x ] ) ;
}
v o i d Union ( i n t a , i n t b )
{
p [ Find ( b ) ] = Find ( a ) ;
}
, a b ?
, p[b] = a b b ?
F ind(b). , p[F ind(b)] = a
b a p[F ind(b)] = F ind(a)
Union .5
0 n1 n
0 i t i j efficiently
? i
amount[i]+ =(t
) query i j amount
update O 1 query worst
( )
case O n query update
? 0 x total[x]
total[j] total[i 1] i j
( (i
) =0
), query O 1 .
total[x] i t update i (n ) total
t update O n .
,
update
, query ,
, 0
x
k. , k (0 k 1
) sum[0] , k (k 2k 1
) sum[1] k
i sum[i/k]
update amount[i] sum[i/k] ( )
update O 1 query
i j i x = i/k j y = j/k
, x = y i j loop ,
range , i x range , j range
j
x + 1 y 1 sum x range
kx
k(x + 1) 1. 2k ,
sum n/k , range
k (
range n/k. update
)
, O k + n/k . inequality
(
) ( ) k =(n ) query O n O n O n !
Square Root Segmentation
, update i t
i j t ?
range
variable range amount
update
range () variable
! update O n
. Static Query
query , update update
? , array query
sum query
, 1 i ,
i ( j) ? 1 j 1 i 1
O( 1 ) query preprocessing
O n .
query sum max min ?
Square Root Segmentation preprocessing
( )
( )
O n query O n . Tarjan research
( )
( )
, preprocessing O n query O 1 ,
method complex. internet
)
(
method preprocessing O n log n
( )
query O 1 . max min method
max
.
Segment Tree
1
1
3 4 5
6 7 8
2
1 2
8
1
3
3
5 6
7 8
1 2
3 4
5 6
7 8
9
2
10
3
11
4
12
5
13
6
14
7
15
8
1
2
3
4
5
6
7
8
9
10
11
12
13
void b u i l d ( i n t at , i n t L , i n t R)
{
/ / do i n i t i a l i z a t i o n l i k e : sum [ a t ] = 0
i f ( L == R )
{
/ / m i g h t n e e d t o do , s o m e t h i n g l i k e : sum [ a t ] = num [ L ]
return ;
}
i n t mid = ( L + R ) / 2 ;
b u i l d ( a t 2 , L , mid ) ;
b u i l d ( a t 2 + 1 , mid + 1 , R ) ;
/ / do i n i t i a l i z a t i o n l i k e : sum [ a t ] = sum [ a t 2 ] + sum [ a t 2
+ 1] e t c .
}
v o i d u p d a t e ( i n t a t , i n t L , i n t R , i n t pos , i n t u )
{
/ / s o m e t i m e s i n s t e a d o f u s i n g i f e l s e i n l i n e 11 a n d 12
/ / you c a n u s e : i f ( a t < L | | R < a t ) r e t u r n ;
i f ( L == R )
{
sum [ a t ] += u ;
return ;
}
i n t mid = ( L + R ) / 2 ;
i f ( p o s <= mid ) u p d a t e ( a t 2 , L , mid , pos , u ) ;
e l s e u p d a t e ( a t 2 + 1 , mid + 1 , R , pos , u ) ;
}
i n t query ( i n t at , i n t L , i n t R, i n t l , i n t r )
{
i f ( r < L | | R < l ) r e t u r n 0;
i f ( l <= L && R <= r ) r e t u r n sum [ a t ] ;
i n t mid = ( L + R ) / 2 ;
i n t x = q u e r y ( a t 2 , L , mid , l , r ) ;
i n t y = q u e r y ( a t 2 + 1 , mid + 1 , R , l , r ) ;
}
return x + y;
time complexity !
( ) time complexity
! tree O n node
( )
time complexity O n . ! [1, 1] [2, 2] query
range [1, 2]
range cover range
complexity ? ,
? ? node range
query range partially overlap , tree
level partially overlap node , ?
partial overlap
level partial overlap
(
) 2 level log n
time complexity O log n .
, time complexity
tree structure
Link Cut Tree
amazing !
on off off on
j toggle update ,
update n = 8 1
4 update Segment Tree [1, 4]
segment toggle ( .
) 1 3 toggle , [1, 2]
[3, 3] update update
toggle ? 3 ? , root
[3, 3] (
) toggle
query O log n
..
, update? (
)
update O log n . .9 Query
Update
update , Lazy
Lazy , Without Propagation
Listing .9 : lazyWithoutPropagation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void update ( i n t at , i n t L , i n t R, i n t l , i n t r )
{
if ( r < L || R < l ) return ;
i f ( l <= L && R <= r ) { t o g g l e [ a t ] = 1 ; r e t u r n ; }
i n t mid = ( L + R ) / 2 ;
u p d a t e ( a t 2 , L , mid , l , r ) ;
u p d a t e ( a t 2 + 1 , mid + 1 , R , l , r ) ;
/ / r e t u r n s 1 i f ON, 0 i f OFF
i n t q u r e r y ( i n t at , i n t L , i n t R , i n t pos )
{
i f ( pos < L | | R < pos ) r e t u r n 0;
i f ( L <= p o s && p o s <= R ) r e t u r n t o g g l e [ a t ] ;
i n t mid = ( L + R ) / 2 ;
i f ( p o s <= mid ) r e t u r n q u e r y ( a t 2 , L , mid , p o s ) t o g g l e [ a t
];
e l s e r e t u r n q u e r y ( a t 2 + 1 , mid + 1 , R , p o s ) t o g g l e [ a t ] ;
( ) ,
toggle= 1 , on = R L + 1 on
?
[1, 4] update [1, 2] update
? node update ?
query [1, 4] on , ?
[1, 2] , [1, 4] , [1, 2]
[1, 4] ? !
[1, 4] update
node on update
time complexity ? ,
Lazy , Lazy
, Lazy
Lazy Propagation. [1, 4] update
[1, 2] update [1, 4]
Lazy , Propagate
, Lazy , Propagate
Query node
, Lazy
Lazy ? , Lazy
? node toggle on, left right child
toggle on. Lazy toggle = 1. , Left Right
child toggle= 1 on node
toggle = 0 , on ( toggle
on ) , [1, 4]
toggle propagation
, toggle= 1 on = R L + 1 on
Lazy update cancel
lazy cancel cancel
, toggle = 1 lazy , !
.10
Listing .10 : lazyWithPropagation.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void Propagate ( i n t at , i n t L , i n t R)
{
i n t mid = ( L + R ) / 2 ;
i n t l e f t a t = a t 2 , l e f t L = L , l e f t R = mid ;
i n t r i g h t a t = a t 2 + 1 , r i g h t L = mid + 1 , r i g h t R = R ;
toggle [ at ] = 0;
t o g g l e [ l e f t a t ] = 1 ;
t o g g l e [ r i g h t a t ] = 1 ;
on [ l e f t a t ] = l e f t R l e f t L + 1 on [ l e f t a t ] ;
on [ r i g h t a t ] = r i g h t R r i g h t L + 1 on [ r i g h t a t ] ;
void update ( i n t at , i n t L , i n t R, i n t l , i n t r )
{
without propagation
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
i n t qurery ( i n t at , i n t L , i n t R, i n t l , i n t r )
{
if ( r < L || R < l ) return ;
i f ( l <= L && R <= r ) r e t u r n on [ a t ] ;
i f ( t o g g l e [ a t ] ) Propagate ( at , L , R) ;
i n t mid = ( L + R ) / 2 ;
i n t x = q u e r y ( a t 2 , L , mid , l , r ) ;
i n t y = q u e r y ( a t 2 + 1 , mid + 1 , l , r ) ;
return x + y;
idx v update(idx, v)
idx
read(idx)
operation topcoder
tutorial
.11 read update MaxVal n
array !
Listing .11 : bit.cpp
1
2
3
4
5
i n t read ( i n t idx )
{
i n t sum = 0 ;
while ( idx > 0)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
}
}
sum += t r e e [ i d x ] ;
i d x = ( i d x & i d x ) ;
r e t u r n sum ;
Greedy
Greedy ? buffet
?
?
!
? buffet ,
?
Greedy
! ?
factor ! , Greedy
. Fractional Knapsack
Greedy algorithm common
, , ,
20 kg. ?
,
kg 1 kg 100 , 500g
60 , kg 120 !
electronics
tv ? tv laptop
mobile greedy
, 1 tv 15000 15kg, monitor
10kg 9000 20 kg
? tv kg
monitor Greedy
""
Fractional Knapsack 0-1
knapsack ( )
..
Prim's Algorithm
(
)
( )
complexity O n2 + m O n2 m < n2 ?
improve n vertex
cost ( Min-Heap
) (C++
priority queue set) algorithm O m log n
m n2
heap complexity interested
internet
.. Kruskal's Algorithm
algorithm. MST Kruskal's
algorithm implement ! algorithm
, weight edge , vertex
tree component , edge
!
vertex tree !
Disjoint Set Union. vertex set.
edge set , vertex set ( !) time complexity ? , edge weight
sort O m log m edge find set
( )
(
)
union
) complexity O 1 O m log m + m =
(
O m log m .
algorithm greedily vertex
edge algorithm greedy edge
.
?
i ai
bi optimal order
i j. i j
? ai + max(bi , aj ) + bj j
aj + max(bj , ai ) + bi ai + max(bi , aj ) +
bj aj + max(bj , ai ) + bi . k aj + max(bj , ak ) +
bk ak + max(bk , aj ) + bj k j
ai + max(bi , ak ) + bk ak + max(bk , ai ) + bi i
k ( proof by contradiction
) ? order
optimal order
,
Dynamic Programming
Dynamic Programming
practice
!
.
, array 1 2
n n = 4 5 array 1, 1, 1, 1, 1, 1, 2,
1, 2, 1, 2, 1, 1 2, 2. ! ,
array 1 2. 1 n 1
array 2 n 2
, n way(n) , way(n) = way(n
1) + way(n 2).
1 2
n = 0
1 , n = 0 1
2
n > 1 way(2) = way(1)+way(0).
way(1) way(0)
n > 1
way(1) 1 , 1.
way(1) = 1. , way(0)
way(0) = 1. 0 0
array 0 ?
way(2) ? 2 ? 2 1, 1
n = 2 , way(2) = way(1) + way(0)
way(2) = 2 way(1) = 1 way(0) = 1 ? ? ,
n = 2 1 2 1 = 1
way(1) = 1 1. 2 ,
!!! way(0) = 1.
( recursive function )
base case. DP
Iteratively Recursively. Iterative .1
recursively .2
Dynamic
Programming DP
Listing .1 : fibIterative.cpp
1
2
3
way [ 0 ] = way [ 1 ] = 1 ;
f o r ( i = 2 ; i <= n ; i ++ )
way [ i ] = way [ i 1 ] + way [ i 2 ] ;
Listing .2 : fibRecursive.cpp
1
2
3
4
5
i n t way ( i n t n )
{
i f ( n == 0 | | n == 1 ) r e t u r n 1 ;
r e t u r n way ( n 1 ) + way ( n 2 ) ;
}
Coin Change
, 1 , 2 8
50
? ?
..
Variant 1
coin[1 . . . k].
n ?
possible[i] i 1
0. possible[n].
n ? ,
n coin[1] n coin[2] ... n coin[k]
n
DP! 1 . . . n k
( ) time
complexity O nk .
Listing .3 : variant1.cpp
1
2
3
4
5
possible [0] = 1
f o r ( i = 1 ; i <= n ; i ++ )
f o r ( j = 1 ; j <= k ; j ++ )
i f ( i >= c o i n [ j ] )
p o s s i b l e [ i ] |= p o s s i b l e [ i coin [ j ] ] ;
..
Variant 2
n order
1 + 3 3 + 1 1 2
4 5 1 + 1 + 1 + 1, 1 + 1 + 2, 1 + 2 + 1,
2 + 1 + 1 2 + 2.
way[n] n n coin[1]
coin[2] k coin[1]
n coin[1] way[n coint[1]]
( )
! time complexity O nk .
Listing .4 : variant2.cpp
1
2
3
4
5
way [ 0 ] = 1
f o r ( i = 1 ; i <= n ; i ++)
f o r ( j = 1 ; j <= k ; j ++)
i f ( i >= c o i n [ j ] )
way [ i ] += way [ i c o i n [ j ] ] ;
.. Variant 3
variant 1
?
n
10 2 8 10
2 !
n i , n coin[i]
i 1
,
, n i
n i 1
n coin[i] i 1
DP parameter. 2D array
( )
time space complexity O nk .
( )
space complexity O n
,
i
i 1
row ( row
column )
row ,
.. Variant 4
Variant 3
2
! variant
.. Variant 5
variant 2 1 + 2 + 1 2 + 1 + 1
? way[n][i] i n
n coin[i]
way[n coin[i]][i] way[n][i 1] :)
n
1 1
? Travelling
Salesman Problem. DP
, 1 2 3 4
5 . . . n
1 3 2 4
,
state
4
state (1, 2, 3, 4) (4)
DP
state array parameter
? , n ,
1 0 n
0 1 array
dimension n ?
tricks 0 1 binary
1, 2, 4 0000 . . . 1011 = 7.
? 2n state
? n 2n state ( ) (n )
time complexity O n2 2n .
Listing .5 : tsp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
return ret ;
sequence subsequence.
order
algorithm stl
simple stl
stl
stl
,
,
, edge
already
vertex
V
edge
(
)
E O V + E .
edge
.1
Listing .1 : bfs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# i n c l u d e <v e c t o r >
# i n c l u d e <q u e u e>
us ing namespace s t d ;
v e c t o r <i n t > a d j [ 1 0 0 ] ; / / a d j [ a ] . p u s h b a c k ( b ) ; f o r a n e d g e f r o m a t o
b.
i n t v i s i t e d [100]; / / 0 i f not visited , 1 i f v i s i t e d
/ / s is the s t a r t i n g vertex
/ / n i s t h e number o f v e r t i c e s (0 . . . n 1)
void bfs ( i n t s , i n t n )
{
f o r ( i n t i = 0 ; i < n ; i + +) v i s [ i ] = 0 ;
q u e u e<i n t > Q ;
Q. push ( s ) ;
v i s i t e d [ s ] = 1;
18
19
20
21
22
23
24
25
26
27
28
29
30
31
w h i l e ( !Q. empty ( ) )
{
i n t u = Q. f r o n t ( ) ;
Q . pop ( ) ;
f o r ( i n t i = 0 ; i < a d j [ u ] . s i z e ( ) ; i ++)
i f ( v i s i t e d [ a d j [ u ] [ i ] ] == 0 )
{
int v = adj [u ][ i ];
v i s i t e d [ v ] = 1;
Q. push ( v ) ;
}
,
edge
, recursive ,
edge
recursively .2
, dfs call
dfs call
cost ( state )
Listing .2 : dfs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# i n c l u d e <v e c t o r >
us ing namespace s t d ;
v e c t o r <i n t > a d j [ 1 0 0 ] ;
int vis [100];
/ / c a l l i t by d f s ( s )
/ / b e f o r e c a l l i n g , make v i s [ ] a l l z e r o .
void dfs ( i n t at )
{
if ( vis [ at ]) return ; / / if previously visited .
v i s [ a t ] = 1;
f o r ( i n t i = 0 ; i < v i s [ a t ] . s i z e ( ) ; i ++ )
dfs ( vis [ at ][ i ]) ;
(
)
complexity O V +E V
recursive call compiler default stack size
stack overflow online judge
manually recursive
stack stack DFS ??
Listing .3 : dfsStack.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# i n c l u d e <v e c t o r >
# i n c l u d e <s t a c k >
us ing namespace s t d ;
v e c t o r <i n t > a d j [ 1 0 0 ] ;
int edge id [100];
int vis [100];
// s is starting vertex
/ / n i s number o f v e r t i c e s
void dfs ( i n t s , i n t n )
{
f o r ( i n t i = 0 ; i < n ; i + +) e d g e i d [ i ] = v i s [ i ] = 0 ;
s t a c k <i n t > S ;
S . push ( s ) ;
while (1)
{
i n t u = S . top () ;
S . pop ( ) ;
25
26
27
28
29
30
31
32
33
34
35
36
37
. DFS BFS
..
node
edge ? BFS
, BFS
shortest path
BFS
i n t d r [ ] = {1, 0 , 1 , 0 } ;
i n t dc [ ] = { 0 , 1 , 0 , 1};
int valid ( int r , int c)
{
r e t u r n r >= 0 && r < R && c >=0 && c < C ;
/ / a l s o may be c h e c k i f ( r , c ) i s e m p t y .
8
9
/ / you may a l s o c h e c k i f t h e c e l l i s v i s i t e d by b f s .
.. Dijkstra's Algorithm
algorithm edge cost (non-negative)
(
) implement time complexity
O n2
,
, u edge update
directed undirected algorithm
( m ) m heap priority queue ,
complexity O m log m .
optimization
priority queue
cost complexity
efficient heap
heap
STL set priority queue
set complexity
( !
) set remove
, complexity O m log n
, set internal algorithm
definitely ,
priority queue heap set red black tree. Red black
tree internal structure
(
)
complexity O log n set constant factor
, priority queue, set dijkstra algorithm perform
dense m n2 priority
queue set performance
algorithm edge cost
edge cost algorithm
visited cost algorithm
visited negative
cycle algorithm negative edge cost
complexity
(
) , complexity
, O m2 logm2 negative edge cost
shortest path
.. BellmanFord Algorithm
single source shortest path algorithm dijkstra
edge
( cost
) dijkstra ? complexity O mn dijkstra
negative cycle algorithm negative cycle
cycle edge cost sum
edge
edge cost
sum ? , negative
cycle
negative cycle minimum
cost undefined negative infinity
negative cycle
negative cycle
BellmanFord algorithm , negative cycle
(
)
dijkstra algorithm complexity O m log n
f o r ( k = 1 ; k <= n ; k ++ )
f o r ( i = 1 ; i <= n ; i + +)
f o r ( j = 1 ; j <= n ; j ++)
i f (w[ i ] [ j ] > w[ i ] [ k ] + w[ k ] [ j ] )
w[ i ] [ j ] = w[ i ] [ k ] + w[ k ] [ j ] ;
, k i j.
? , i j cost k cost
cost w
array , array initial infinity.
i j edge cost w[i][j]
edge undirected
w[j][i]
( )
complexity ? O n3 .
, edge cost floyd warshall ?
, negative cycle
dijkstra
n 1 n
, k !
value value
articulation vertex articulation edge u,
articulation vertex . root child .
root low[u] df sStartT ime[u]
condition articulation vertex
articulation vertex condition
condition uv edge articulation
edge condition , u v parent
low[v] > df sStartT ime[u] , back edge articulation
edge dfs tree edge check
vertex
edge visited vertex print
vertex visit
directed euler path cycle
paragraph
internet directed euler path
cycle undirected
, outgoing edge outgoing edge
print ,
dfs euler path cycle order
! , path print outdegree
indegree indegree outdegree
indegree, outdegree
outdegree, indegree path
in out degree
connected
,
. (Topological sort)
directed , u v
directed edge u, v
directed cycle cycle cycle
? directed
cycle
topological sort BFS DFS
BFS , stack overflow
DFS -
BFS
indegree indegree
queue indegree queue
edge
indegree
indegree
queue queue queue order topological sort
, queue indegree
cycle intuitive
DFS T
, visited initial 0.
visited 2 DFS
DFS visited 1
directed edge
visited
1 cycle topological
order visited 2 0
DFS
visited 2 T DFS return
directed u v v u
SCC ,
u v SCC v w SCC u w
SCC w v v u ,
u v w u w SCC
SCC SCC ,
edge (u, v), (v, w), (w, u) SCC: u, v, w.
edge (u, v), (w, v) SCC: u, v, w.
(u, v), (v, u), (w, u), (w, v) SCC: u, v, w.
SCC
Kosaraju's algoritm (2-dfs ) Tarjan's
algorithm. ,
visited
unvisited , unvisited
dfs dfs , visited
unvisited dfs
adjacent visited dfs return (
L) visited
L edge
(
adjacency list
) L
DFS unvisited L
visited dfs
, dfs dfs
visited SCC . SCC
Tarjjan SCC
Articulation Bridge Vertex
directed visited
unvisited dfs dfs
low startTime ,
neighbor
(low startTime )
, stack
SCC.
dfs number SCC visited
, parameter visited
. 2-satisfiability (2-sat)
(a or b) and (!b or c) and (!a or !c) equation a = 1, b =
0, c = 0. , (a or b) and (a or !b) and
(!a or b) and (!a or !b). Formally a, b, c variable
variable not or pair clause
clause and equation statement
, variable assign statement
clause term 2-sat
3-sat NP
3-sat
statement n variable 2n
directed x variable x
!x (!x or y) clause,
x y !y !x. (!x or y) interpret
!x y , y !x
directed edge (!x or y) edge x y
!y !x x y , !y
!x clause
edge
edge , x !x ( x variable,
n variable ) x !x !x
x path 2-sat
variable
? SCC!
SCC x !x component
,
component ? , x y
, x y x !x
x !x x
!x x x x
2-sat
2-sat ? , scc component contract ( ) DAG (DAG = Directed
Acyclic Graph) directed cycle cycle
topological order ,
component true component
variable assing
true conflict false
greedy assign
implication sign
, a b (a = 1, b = 0) false
true. a b , a b