You are on page 1of 109

}

Dawn of Programming Contest


.
. . . . . . . . .
.
? .
. ? . . . . . . . .
.
? . . . . .
. ? . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

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

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

. Breadth First Search (BFS) . . . . . . . . . . . . . . .


. Depth First Search (DFS) . . . . . . . . . . . . . . . .
. DFS BFS . . . . . . . . . . . . . . . . .
..
node . . . . . . . . . . . . . . . .
. Single Source Shortest Path . . . . . . . . . . . . . .
.. Dijkstra's Algorithm . . . . . . . . . . . . . .
.. BellmanFord Algorithm . . . . . . . . . . . .
. All pair shortest path Floyd Warshall Algorithm .
. Dijkstra, BellmanFord, Floyd Warshall ? . .
. Articulation vertex Articulation edge . . . . . . .
. Euler path euler cycle . . . . . . . . . . . . . . .
. (Topological sort) . . . . . . . . . . . .
. Strongly Connected Component (SCC) . . . . . . .
. 2-satisfiability (2-sat) . . . . . . . . . . . . . . . . . .

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

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

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

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

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

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

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

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.

.
.
.
.
.
.
.
.
.
.


. n = 3

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

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

. c = ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.


. . . . . . . .
Heap . . . . . . . . . .
Heap array numbering
Segment Tree Build .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.


. math.h . . . . . . . . . . . . . . . . . . . .

. n = 10 sieve algorithm simulation . . . . . . . . . . .


. a = 10 b = 6 Extended GCD simulation . . . . . . .

. Insertion Sort simulation . . . . . . . . . . . . . . . . . . . .

, ,
,


!
,
,
- " ?"
- " ?" - " ,
, " !
,



, , , , , , ,

, , ,



,


,




,
, 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

Internet ( ... internet


, )
internet ! Youtube
translator


website Contest
main ,


?
,

,

! ,
, !
website

"

"

uva.onlinejudge.org popular


icpcarchive.ecs.baylor.edu uva

ICPC Regional Programming Contest ACM ICPC


World Finals
acm.sgu.ru ,
!
acm.timus.ru
recently
Beginners Problem

,
www.codechef.com ,
ACM IOI

www.codeforces.com Division
Division 2 Beginner , Division 1
Advanced
Rating
!
www.topcoder.com/tc codeforces Rating system

acm.hust.edu.cn/vjudge host host
www.lightoj.com Online Judge (Practice
Online Judge OJ )
Dhaka University ACM ICPC World Finals

www.z-trening.com down Informatics Olympiad


ipsc.ksp.sk IPSC

Encryption, Music, New Language, Game


www.spoj.com Polish
Informatics Olympiad


ace.delos.com/usacogate USA Informatics Olympiad IOI offline Catagorywise , analysis
offline

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

http://www.hsin.hr/coci/ Croatian Informatics Olympiad


Practice Contest

Introduction to Algorithms Thomas H. Cormen, Charles E. Leserson, Ronald
L. Rivest Clifford Stein
Programming Challenges Steven S Skiena Miguel A Revilla
The Algorithm Design Manual Steven S Skiena
Algorithm Design Jon Kleinberg Eva Tardos
Computational Geometry: Algorithms and Applications Mard de Berg,
Otfried Cheong, Marc van Kreveld Mark Overmars
Computational Geometry in C Joseph O'Rourke
Art of Programming Contest Ahmed Shamsul Arefin
Data Structures and Algorithms in C++ Michael T. Goodrich, Roberto Tamassia
David M. Mount
Competitive Programming Felix Halim Steven Halim
,

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
.

simple ( .1) run


6 2 8
, 4, 12 3
Listing .1 : simple code.cpp
1
2
3
4
5
6
7

# 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)

Listing .2 : simple input.cpp


1
2
3
4
5
6
7
8
9

# 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.

Listing .5 : odd even.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 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;

curly brace () if / else


if / else curly brace
, variable

leap year
logical operator logical operator

|| (or), && (and), ! (not). condition ||


, && !
condition condition .7
logical operator leap year
bracket
5 (2 + 1) 5 2 + 1 5 + 2 1
, sure bracket

Listing .7 : leap year2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 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

/ / prototype ( not s y n t a c t i c a l l y valid l i n e )


f o r ( i n i t i a l i z a t i o n ; c o n d i t i o n ; i n c r e m e n t / d e c r e m e n t ) {}
w h i l e ( c o n d i t i o n i s t r u e ) {}
/ / Examples
f o r ( i = 1 ; i <= 1 0 ; i ++) p r i n t f ( "%d\n " , i ) ; / / p r i n t s f r o m 1 t o 10
f o r ( i = 1 0 ; i >= 1 ; i ) p r i n t f ( "%d\n " , i ) ; / / p r i n t s f r o m 10 t o 1
f o r ( i = 1 ; i <= 1 0 ; i += 2 ) p r i n t f ( "%d\n " , i ) ; / / p r i n t s odd n u m b e r s
f r o m 1 t o 10
i = 5;
w h i l e ( i <= 7 ) { p r i n t f ( "%d\n " , i 2 ) ; i + + ; } / / p r i n t s 1 0 , 1 2 , 14

for loop initialization condition


loop loop
increment/decrement condition loop
while loop condition
,
.8 loop i ? ,
for loop i 11, for loop 0, for loop 11 while
loop 8. loop .9
Listing .9 : simple loop2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

/ / c o u n t s how many 2 d i v i d e s 100


x = 100;
cnt = 0;
w h i l e ( x % 2 == 0 )
{
x = x / 2;
c n t ++;
}
/ / f i n d s o u t t h e h i g h e s t number which i s power o f 2 and l e s s t h a n
1000
x = 1;
w h i l e ( x 2 < 1 0 0 0 ) x = 2 ;
/ / same t h i n g u s i n g f o r l o o p . N o t e a s e m i c o l o n i s a f t e r t h e f o r l o o p .
f o r ( x = 1 ; x 2 < 1 0 0 0 ; x = 2 ) ;

loop
keyword break continue.
loop
loop loop iteration
break continue .10
i++ i = i + 1 i += 2 i = i + 2. double slash comment
comment

Listing .10 : simple loop3.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
27
28

/ / 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

sum = 0 ; / / v e r y i m p o r t a n t . many o f you f o r g e t s t o i n i t i a l i z e


variable
f o r ( i = 1 ; i <= n ; i ++ )
f o r ( j = 1 ; j <= n ; j ++)
sum += j ;



. 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)!

x n , cos x maclaurine series


2
cos x series 1 x2! + x4 4! + . . . + nth term
OJ Timus 1083 Timus 1086 Timus 1209
LightOJ 1001 LightOJ 1008 LightOJ 1010 LightOJ 1015 LightOJ
1022 LightOJ 1053 LightOJ 1069 LightOJ 1072 LightOJ 1107
LightOJ 1116 LightOJ 1136 LightOJ 1182 LightOJ 1202 LightOJ
formula

quadratic equation

A B answer 0 B answer 0 A 1 answer

pattern

1211 LightOJ 1216 LightOJ 1294 LightOJ 1305 LightOJ 1311


LightOJ 1331 LightOJ 1433
Last but not the least UVa 100

Array String

Game Show 10 Host


,
answer answer 1 Game

?
10 variable , variable a, b, . . . j
a ,
, 10
if-else variable game
if-else (
, 20 if-else )
?
Array Array
, variable int a[10] int
10 variable a[0], a[1], . . . a[9].
id = 1 a[id 1] + +
variable maximum
, for loop maximum
10 100 .12
Listing .12 : simple array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// 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

int double variable ,


variable type
char. char character
character , Rajshahi 8 character
string char array ,
char city[10] array declare , Rajshahi
city[0] = R, city[1] = a, . . . city[7] = i.
null. city[8] null null
city[0]
city array
city[0]
city[8] null
city array printf("%s", city)
scanf("%s",
city). &
null , for loop string length
3 (city[3] = 0; printf("%s", city);).
city[0] R city[0] 82.
character value , ASCII value. www.lookuptables.com
ascii value A Z ascii value
65 90, a z 97 122
0 9 48 57. ascii value
character %d
character ascii value.
ascii value , A Z, a z 0 9

character ch , if('a' <=
ch && ch <= 'z'). (single quotation character ascii value
) condition
, , ch
ch = ch - 'a' + 'A'. ch digit int variable
, d = ch - '0'. ascii value relative
order
String scanf
space string
, sentence "Facebook is a popular web media"
scanf %s array Facebook
, scanf
non whitespace
character , white character
space sentence gets(s). s
char array gets
new line
, scanf gets
, n
n sentence n scanf
sentence gets , sentence
, scanf n n
new line white character gets
copyright

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 string water


string melon string- watermelon

string A B , B A
A = bangladesh B = desh B, A B
A aa aaa

sentence word word space


string lexicographically smaller. (library


function )

21/9/2013 format string ,


int variable

string A B , B A subsequence B A
subsequence A letter B
A = bangladesh B = bash B, A subsequence B =
dash subsequence

OJ Timus 1001 Timus 1014 Timus 1020 Timus 1025


Timus 1044 Timus 1079 Timus 1197 Timus 1313 Timus 1319
LightOJ 1006 LightOJ 1045 LightOJ 1109 LightOJ 1113 LightOJ
1133 LightOJ 1214 LightOJ 1225 LightOJ 1227 LightOJ 1241
LightOJ 1249 LightOJ 1261 LightOJ 1338 LightOJ 1354 LightOJ
1387 LightOJ 1414

. Time Memory Complexity


Time Memory Complexity
Time Memory Time
Complexity Memory Complexity Time Memory second
Byte ?
computer
computer 10s
5s ,
Memory ! n = 100

Memory Time n = 1000
Memory Time solution Time Memory
problem parameter
exactly Time Memory ,
solution

loop 1 + (1 + 2) + (1 + 2 +
3) + . . . + (1 + 2 + . . . + n). for loop ,
2
1 + 2 + . . . n = n 2+n n

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

array F[0] = 0, F[1] = 1


for loop F[i] = F[i - 1] + F[i - 2].
( n
)
array declare Memory Complexity O n .
array Fn .13 ()
3 variable , Memory Complexity O 1 .
( )
( )
Time Complexity O n Memory Complexity O 1

order n2
= 0
Time Complexity Time
Complexity
n

Listing .13 : fibonacci.cpp


1
2
3
4
5
6
7
8
9
10

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 ) ;

Student structure declare


variable declare Student
data type variable s
Student array student variable dot
variable access

. 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;

Time Complexity ? Worst case

(
) 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

sieve algorithm simulation

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 n t Prime [300000] , nPrime ;


i n t mark [ 1 0 0 0 0 0 2 ] ;
void sieve ( i n t n )
{
i n t i , j , l i m i t = s q r t ( n 1.) + 2;
mark [ 1 ] = 1 ;
f o r ( i = 4 ; i <= n ; i += 2 ) mark [ i ] = 1 ;
Prime [ nPrime ++]=2;
f o r ( i = 3 ; i <= n ; i += 2 )
i f ( ! mark [ i ] )
{
P r i m e [ n P r i m e ++] = i ;

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

Segmented Sieve 1 n , a b prime


a, b 1012 1014 range
, b a
106 . [a, b] range sieve
b prime
(prime

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

GCD Greatest Common Divisor ( )


LCM Least Common Multiple ( )

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 ) ;
}

.. Euler Totient Function ( )


Totient Function
(n) = n n coprime
coprime factor , (12) = 4 2, 3, 4, 6, 8, 9, 10, 12
12 factor 1, 5, 7, 11
common factor n = pa1 1 pa2 2 . . . pakk
(
)(
)
(
)
1
1
1
(n) = n 1
1
... 1
p1
p2
pk
prime factorize
prime divisor 1 n
? , prime p multiple
p p 1 1 n prime
( .6)
Listing .6 : sieve phi.cpp
1
2
3

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

exact mod 107


mod result , 2100 mod 7
? ? 2100 7 ? , 2100 long
long ? mod ,
int ! 100 ,
1018 ? ? idea
2100 mod 7 , 250 mod 7
, a, 2100 mod 7 (a a) mod 7.
for loop 100 2 , 50 2
result 50
, 25
? ?
! 224 2 power
power 2
power 0
20 = 1

? Black
Box a, b, M ab mod M b
Black Box a, b/2, M
Black Box a, b 1, M
? , b = 0 Black

Box function function function


recursive function .7
b
( ) ,
algorithm run time O log n .
Listing .7 : bigmod.cpp
1
2
3
4
5
6
7
8

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;
}

solving method divide and conquer


combine
BigMod ,
1 + a + a2 + . . . + ab1 mod M b
term
b = 6
!
1 + a + a2 + a3 + a4 + a5 = (1 + a + a2 ) + a3 (1 + a + a2 )
bigmod(a, b/2, M )
log n
bigmod log n ,
(
)
run time O log n2 . cost
(
)
O log n equation
1 + a + a2 + a3 + a4 + a5 = (1 + a2 + a4 ) + a(1 + a2 + a4 )
= (1 + (a2 ) + (a2 )2 ) + a(1 + (a2 ) + (a2 )2 )
bigsum bigsum(a, b, M )
bigsum(a2 , b/2, M ) a overflow
a2 mod M b ?

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

Extended GCD simulation


y
0
1
-1
2

10x + 6y
10
6
4
2

Extended GCD egcd .8


egcd call variable reference
x y return
Listing .8 : egcd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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;

egcd Modular Inverse ( b M coprime


) b x , bx 1 mod M .

, 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

Stirling Number of Second Kind


n
{ } k Stirling Number of Second
Kind. nk n = 3 k = 2 3,
(AB, C), (AC, B), (BC, A). recurrence Derangement
Number n
n 1 k
{ 1
}
( , ) n1
k1
, n1 k {
}
k k n1
,
k
{ } {
}
{
}
n
n1
n1
=
+k
k
k1
k
recurrance base case k = 1
? ? k = n ? n n
? base case
{ } { }
n
n
=
=1
1
n
Stirling Number of First Kind
n
[ ]k cycle Stirling Number of
First Kind. nk n = 4 k = 2 11,
(AB, CD), (AD, BC), (AC, BD), (A, BCD), (A, BDC), (B, ACD), (B, ADC),
(C, ABD), (C, ADB), (D, ABC), (D, ACB)). recurrence
n
cycle n 1 k 1[ cycle
] (
, ) n1
k1 ,
n 1 k cycle [ ] n 1
(n 1) n1
,
k
[ ] [
]
[
]
n
n1
n1
=
+ (n 1)
k
k1
k
recurrance base case k = 1 cycle
? common (n 1)! k = n ?
n n cycle ? base case
[ ]
[ ]
n
n
= (n 1)!,
=1
1
n

.. 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

.. Inclusion Exclusion Principle


Counting
method Inclusion Exclusion Principle.
, 1 100 2 3 ?
, , 2 , 3
, 2 3 , 2
, 100/2 = 50 3
100/3 = 33.
, 6, 12, 18 . . .
double count
double count , double count
2 3 6 6
100/6 = 16 50+ 3316 = 67.
count method inclusion exclusion principle. 2
2, 3, 5, 7

,
,
,
(
)
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
?
? !

=

, , Head Tail probability 12 coin Head Tail Head Tail.


5 probability , 60 = 0.
5 ! 1, 2, 3 4 probability 61 6 probability
2

6 . 6
method method

( n )
, b 4b
n
? ? radius r
r2
4r2 . randomly
2

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 ,



, ?
,

.. Cycle Finding Algorithm


UVa 11036 idea x , f (x) = x (x + 1)mod11, n
f (n), f (f (n)), f (f (f (n))) . . . period length
repeat n = 1 2, 6, 9, 2, 6, 9, 2, 6, 9 . . .
, period 3. ,
2 ,
repeatation array
array
array
position , array ,
period array
( )
( )
memory complexity O n time complexity O n
(
)
, O + =
cycle

( )
= cycle length. memory complexity O 1 time complexity method
Floyd's Cycle Finding Algorithm.
algorithm




period .


.

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 ;

.: Insertion Sort simulation


5, 8, 6, 1, 7, 9

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

algorithm time complexity ? , n


array sort T (n).
n algorithm

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.

sort(point, point + n) Point



Point Point ,
cmp. Point ,
Point Point true return
false return ,
, cmp cmp(A, B) cmp(B, A) true .4

Listing .4 : cmp.cpp
1
2
3
4
5
6
7
8
9
10

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 ;
}

sort sort(point, point +


n, cmp). overload ,
overload sort
.6 overload
sort(point, point + n)
Listing .6 : operator overload.cpp
1
2
3
4
5
6
7
8
9
10

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>).

string sort , STL string


.7 string sort
Listing .7 : string sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 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

) array black box


1 n

black box ,
,

permutation
black box ?
,

array parameter
n
, global permutation
- ?
? permutation
.8
Listing .8 : permutation.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 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.

Listing .10 : combination2.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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

n 50, wi 1012 vi 1012 . ?


1 n , ,
W ,

(
) !
run time ? O 2n . n 50
W ,
,
optimization ?
W
,
W
optimization optimization ? ,

V
V
optimization
run time

Algorithm Data Structure


efficiency

1 n
? number array
array array
array

array 0 1
(

)
m O m memory
( )
( )
O m O n
memory
( ) n
O 1 algorithm ,
,
representation runtime memory requirement
n m ,

. 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

array .1 adjacency list


edge insert delete search

( node delete node insert search
) head
array 1 initialize
Listing .1 : linkedlist.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 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

variation doubly linked list


next previous pointer , circular
next terminal
point
linked list , STL vector
,
( ) insert delete linked list
O 1 dynamically memory allocation

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

row loop row




1

row 1 count
n sub-range
sub range
maximize stack array

stack
stack push
stack stack element stack

stack , stack element
,


stack pop push

? , stack
, height 1
stack height height height
height

element

. 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

Graph entity graph


facebook
graph
:P
node vertex node
vertex
edge map

vertex edge


, vertex number
vertex adjacency list
adjacency matrix
!
facebook friendship mutual bidirectional
A B B A bidirectional
directional facebook follower. A B follow
B A follow
undirected graph directed graph. A
B undirected edge A B B A
directed edge A B A
edge B

Tree

Tree special n vertex n 1 edge


connected connected node
node edge node
edge ,
properties cycle , node

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

top down representation


Parent link node parent representation
node
bottom up representation
Child list Parent link
node child tree binary tree
child left child right child
tree term

. Binary Search Tree (BST)


binary tree node
left subtree node right subtree
link list
node link , left child right
child parent link Binary Search
Tree node

,
insert delete
delete node flag delete
flag off
, array tree
? , node

subtree

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

Heap Priority Queye

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

child index 2i right child index 2i + 1.



level by level index node i parent
i/2 , integer division

.: Heap array numbering


Heap insert heap n
n + 1 parent root , parent
swap , parent
height log n insertion
(
)
O log n . Max Heap root remove
root
left child right child.
(
)
swap O log n
remove node
modify remove ,
node
worst case
Heap priority queue queue
, ,
priority
queue. priority
heap. STL priority queue .4
STL int structure priority queue
operator overload
Listing .4 : priority queue.cpp
1
2
3
4
5
6
7
8
9

# 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

Disjoint set Union



, ?
?

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

Square Root segmentation


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
.

1 segment max [1, 1], [2, 2], [3, 3], . . .

. 2 segment max [1, 2], [2, 3], [3, 4], [4, 5] . . .


. 4 segment max [1, 4], [2, 5], [3, 6], [4, 7] . . .
. 8 segment max [1, 8], [2, 9], [3, 10], [4, 11] . . .
. i 2i segment max [1, 2i ], [2, 2i +
1] . . ..
2i n i log n. x
2i max ? , x
2i max x
2i1 max x + 2i1
2i1 max
max ,
= max(table[i (1][x], table[i
1][x + (1 << i)].
( table[i][x]
)
)
O n O log n
(
)
O n log n . i j max ?
x
x
( ) 2 j i+1 loop
O log n , array

( ) , array
O 1 x max(table[x][i], table[x][j (1 <<
x) + 1])

Segment Tree

Binary Search Tree Segment


Tree BST insert, delete, update
1 n
insert delete , index
range query index
1 2
? range query
, , ;
; range update
Segment Tree
Square Root Segmentation
(

) Square Root Segmentation


(
) complexity
O n Segment Tree O log n Square Root Segmentation
, update array
query array range
(
) update query Segment Tree
O log n

.. Segment Tree Build

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

.: Segment Tree Build


n = 8 Segment Tree .
8 [1, 8]
[1, 4] [5, 8]. [L, R] range
[L, mid] [mid + 1, R] mid = (L + R)/2
( integer division ) range
segment , L = R.
segment tree n 2 power
n = 3 segment [1, 3] [1, 2] [3, 3]
[1, 2] [1, 1] [2, 2] ,

?
segment
, x (left child) 2x
2x + 1 (parent) x/2
segment tree .6 Segment Tree

segment 0 initialize
, segment
(sum[at] = sum[at * 2] + sum[at *
2 + 1]). tree level 1 node,
level 2 , 4 ,
(
) 8, 16 . . . n node,
2n. time complexity O n .
Listing .6 : segmentTreeBuild.cpp

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 .
}

Segment Tree Time Complexity important Space


Complexity. array declare Run Time Error
, n 4 array declare
n 2 power 2 power
2 power memory
x 2x 2 power
2 power , 4 declare
n 2 power declare ,

.. Segment Tree Update


update
root
root [1, 8] 3 update
, root [1, 4] ,
[3, 4] [3, 3] build sum array
populate sum array update
update .7 (
) tree height log n
update time complexity O log n
Listing .7 : segmentTreeQuery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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 ) ;
}

sum [ a t ] = sum [ a t 2 ] + sum [ a t 2 + 1 ] ;

.. Segment Tree Query


query [l, r] range
tree root

node range query range
, ?
range 0. node
query range ,
node sum return case
query range node child
sum return
.8
Listing .8 : segmentTreeQuery.cpp
1
2
3
4
5
6
7
8
9
10
11

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 !

.. Lazy without Propagation


n
off.
i j toggle
(q ) on off?
Segment Tree O log n idea i
toggle

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 ] ;

.. Lazy With Propagation



l r on !
Without Propagation
with propagation
tree node ! Lazy
, node toggle
range er on off , on
off build
node toggle = 0 on = 0. update
node query range
, partially

( ) ,
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

if ( r < L || R < l ) return ;


i f ( l <= L && R <= r ) { t o g g l e [ a t ] = 1 ; on [ a t ] = R L + 1
on ; r e t u r n ; }
i f ( t o g g l e [ a t ] ) Propagate ( at , L , R) ;
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 ) ;
on [ a t ] = on [ a t 2 ] + on [ a t 2 + 1 ] ;

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;

Binary Indexed Tree

BIT Segment Tree


,

BIT Segment Tree
, Segment Tree
BIT BIT , ,
n fast.
article
, BIT operation
.
.

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 ;

void update ( i n t idx , i n t val )


{
w h i l e ( i d x <= MaxVal )
{
t r e e [ i d x ] += v a l ;
i d x += ( i d x & i d x ) ;
}
}

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 ( )

Minimum Spanning Tree

Tree , Minimum Spanning Tree


weighted graph (weight ) vertex,
edge edge weight. edge
weight vertex connected
n vertex connected
n 1 edge edge weight
n 1 edge n vertex
n 1 edge connected graph tree. vertex
connected edge weight
graph Minimum Spanning Tree ( MST).
Minimum Tree ? Spanning connected
MST
algorithm

algorithm Greedy
represent ! !

n vertex m edge

..

Prim's Algorithm

vertex connected vertex

, vertex edge weight edge


vertex edge , vertex edge
weight
vertex weight edge
edge tree
vertex
tree ! connected,
edge weight ?
algorithm time complexity ! n
vertex
() edge
(
)
complexity O nm . O n2 ,
a vertex process a
edge ?
vertex tree edge ,
edge tree update ,
a vertex b 10 cost ,
c b !
b cost update , vertex
vertex
? n , vertex
, edge
vertex , cost update
n complexity ? n n
vertex check 2m edge ,

(
)
( )
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] :)

Travelling Salesman Problem

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

i n t dp [1 < <20][20]; / / Assume t h a t t h e r e a r e 20 f r i e n d s


/ / mask = f r i e n d s i v i s i t e d , a t = l a s t v i s i t e d f r i e n d
i n t DP ( i n t mask , i n t a t )
{
i n t & r e t = dp [ mask ] [ a t ] ;
/ / Assume t h a t we i n i t i a l i z e d dp w i t h 1
i f ( r e t != 1) r e t u r n r e t ;
r e t = 1000000000; / / i n i t i a l i z e r e t with i n f i n i t y
/ / d i s t c o n t a i n s d i s t a n c e b e t w e e n e v e r y two n o d e s
f o r ( i n t i = 0 ; i < n ; i ++) / / n = n u m b e r o f f r i e n d
i f ( ! ( mask & (1<< i ) ) )
r e t = MIN ( r e t , DP ( mask | (1<< i ) , i ) + d i s t [
at ][ i ]) ;
}

return ret ;

. Longest Increasing Subsequence


sequence sequence ( ) increasing order
increasing subsequence DP n
LIS (Longest Increasing Subsequence) n 1 LIS ? n
? n a[i] (a
sequence i < n). a[i] a[i] < a[n]
? ? , 1, 2, 3, 4 5
? 1 4 5 4
4 LIS n
LIS (LIS[n]) , LIS[i]
( ) + 1 a[i] < a[n]
time complexity O n2 . Segment Tree
(
)
O n log n n 1 . . . a[n] 1 query a[n]

. Longest Common Subsequence


string: S T , string S T
subsequence longest state
S T S s T t letter
Longest Common Subsequence (LCS) ? S[s] = T[t] (1
indexing ) S s 1 T t 1
S[s] = T [t] S s 1 T t letter
S s T t 1 letter
string
dp table table string
character
dp string character ,
, string
string
character reverse
recursively dp
dp string while
, (
generally path printing. dp
, path printing ) ,
path print

sequence subsequence.
order

algorithm stl
simple stl
stl
stl

. Breadth First Search (BFS)


(traverse) s

,

,

, 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 ) ;
}

Depth First Search (DFS)

,
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

while ( edge id [ u ] < adj [ u ] . size () )


{
/ / s t a r t l o o k i n g i n t o edges , from t h e p l a c e
we l e f t
int v = adj [u ][ edge id [u ]] ;
e d g e i d [ u ]++; / / u p d a t e edge p o i n t e r t o
check next time
i f ( v i s [ v ] == 0 ) / / i f t h e v e r t e x i s n o t
already visited
{
v i s [ v ] = 1;
S . push ( u ) ; / / o r d e r of push
important for dfs
S . p u s h ( v ) ; / / f i r s t we w i l l c h e c k v ,
t h e n we w i l l come b a c k t o u
/ / note , s t a c k i s l a s t in f i r s t out .
So v w i l l be p o p p e d b e f o r e u
break ;
}
}

. DFS BFS
..

node


edge ? BFS
, BFS

shortest path

BFS

DFS DFS shortest path A, B C


A DFS
B C
, A C DFS
shortest path ? path
printing
BFS


, 3 5 8
4

DFS ?
BFS BFS
edge ? BFS vertex edge

DP state
represent - state
1-dimensional array visited
3-dimensional array visited queue
structure (structure queue). BFS

, state represent 8 optimization
run time memory
queue 8
visited
memory computation
queue visited memorization
visited matrix
UVa 10653




1, 2, . . . RC
(r, c) represent .4 matrix
Listing .4 : cellbfs.cpp
1
2
3
4
5
6
7

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 .

(r, c) cell (r + dr[i], c + dc[i]) (i


0 3 ) cell valid .4
valid call
UVa 10651
BFS DFS
peeble game configuration
0 1 cost
weighted edge cost 0 1.
shortest path BFS
0 queue
add , 1
queue add queue ,
deque. STL deque built-in
deque n m
dist
2n

. Single Source Shortest Path


Shortest Path , weighted graph
cost Shortest Path Single source shortest path All pair shortest path. Single
source shortest path cost All Pair Shortest Path
cost Single
Source Single Destination Shortest Path ?
, Single Source Shortest Path Single Destination variation
, Single Destination variation
simpler algorithm simpler
Single Source Shortest Path , Single
Source Shortest Path
algorithm , Single Destination
efficient algorithm , optimization worst case time complexity
, algorithm
optimization , Single
Destination variation Single Source Shortest Path algorithm

Single Source Shortest Path
algorithm
Dijkstra's Algorithm
BellmanFord Algorithm.
! ,

.. Dijkstra's Algorithm
algorithm edge cost (non-negative)

(
) implement time complexity
O n2

n array , dist (distance


)
element cost
1 000 000 000 1

Single Source Shortest Path ,


source
s
array s 0 , s
cost 0.
n array visited 0
initialize

visited 0 , cost, dist array
select u. visited array u
1 u ? , u v
edge cost c. dist[v]
dist[u] + c? v already
u u > v edge
dist[u]+c dist[v] update
u edge
visited ( visited array 1 )

dist array s distance
n
( )
u n n O n2 .
u edge ,
) edge
(
( )
2 complexity O n2 + m O n2
( m n2 ).
(
)
complexity O m log m
unvisited
STL priority queue ,
structure priority queue cost
cost priority queue
cost priority queue cost strcut
object visited visited
method
edge
update

,
, 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

negative infinity cost !!


algorithm
shortest path n dist
element infinity source 0.
n , edge , edge a
b cost c ( bidirectional edge

consider ) , dist[b] dist[a] + c


n shortest path
, (
n edge m
)
complexity O mn . optimization
mincost maxflow
bellman-ford optimization , n
edge edge , n break
, , bellman ford edge order randomize
bellman ford case , edge order

negative cycle
, n n + 1 edge cost
negative cycle

All pair shortest path Floyd Warshall Algorithm

(
)
dijkstra algorithm complexity O m log n

all pair shortest path


( dijkstra
)
O nm log n dense (m n2 ) n dijkstra
floyd warchall dijkstra
floyd warshall ?
for-loop
algorithm
Listing .5 : apsp.cpp
1
2
3
4
5

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

w[i][i] 0 floyd warshall w[i][i]


negative negative cycle


dijkstra

! mincost maxflow negative cost edge

. Dijkstra, BellmanFord, Floyd Warshall ?


Dijkstra cost
vertex visited edge cost
visited
BellmanFord ,
n shortest ! , s shortest
path n edge
, edge order important.
edge order
shortest path , n
Floyd warshall k
? k Bellman Ford
n
,
i j
k ,
k , i j 1, 2, . . . k cost
w[i][j] n shortest
path

. Articulation vertex Articulation edge


undirected disconnected
articulation vertex edge
disconnected articulation edge articulation bridge
DFS articulation vertex edge DFS
powerful
dfsStartTime, dfsEndTime low. Articulation vertex edge
,
Informatics Olympia
2006 IOI , dfsStartTime
dfsEndTime dfsTime variable initial
0. dfs unvisited
dfsStartTime dfsTime child
visit time dfsEndTime
vertex visit dfsTime dfsStartTime
dfsEndTime. low dfs tree
unvisited adjacent vertex
visit ( ) unvisited adjacent vertex
(parent ) visited
ancestor root path ( )
subtree ancestor edge
back edge low[u] u u subtree
(root ) index.

n 1 n
, k !

low[u] v u adjacent vertex.


v visited v u parent parent (ancestor)
ancestor dfsStartTime low[u] update
parent parent edge u
edge , edge
update multi edge
v visited
dfs recursively low[v] low[u] update
update minimum value low[]
dfsStartTime, time root

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

Euler path euler cycle

undirected graph Euler path


vertex
edge, exactly vertex
euler path
vertex
euler cycle euler circuit euler path cycle
connected
degree euler cycle (euler cycle
euler path , ) odd
degree euler path

,

edge
vertex degree
cycle
degree
cycle path
vertex
degree euler path cyle
property property euler path cycle
induction

euler path cycle ? ,
dfs vertex
vertex
visited , edge edge
visit vertex
edge visited , edge
Euler

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

DFS T topological sort

Strongly Connected Component (SCC)

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

startTime low time time


stack
visited
low startTime (minimum )
unvisited dfs neighbor

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

You might also like