Upload
kamrul-hasan
View
93
Download
38
Embed Size (px)
DESCRIPTION
Programming Book
Citation preview
g
Dawn of Programming Contestg
,
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ? . . . . . . . . . . . . . . . . . . . . . . . . . . . .
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 . . . . . . . . . . . . . . . . . . . .. Gaussian elimination . . . . . . . . . . . . . . . . . . . . . .. Matrix Inverse . . . . . . . . . . . . . . . . . . . . . . . .
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 1matrix 1 . . . . . . . . . Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Graph representation . . . . . . . . . . . . . . . . . . . . . . . Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Binary Search Tree (BST) . . . . . . . . . . . . . . . . . . . . . . . . Heap Priority Queue . . . . . . . . . . . . . . . . . . . . . . . . . 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 . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . Huffman Coding . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Coin Change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. Variant 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. Variant 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. Variant 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. Variant 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. Variant 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. Travelling Salesman Problem . . . . . . . . . . . . . . . . . . . . . Longest Increasing Subsequence . . . . . . . . . . . . . . . . . . . Longest Common Subsequence . . . . . . . . . . . . . . . . . . . Matrix Chain Multiplication . . . . . . . . . . . . . . . . . . . . . . Optimal Binary Search Tree . . . . . . . . . . . . . . . . . . . . .
. Breadth First Search (BFS) . . . . . . . . . . . . . . . . . . . . . . . Depth First Search (DFS) . . . . . . . . . . . . . . . . . . . . . . . . DFS BFS . . . . . . . . . . . . . . . . . . . . . . . .
.. node . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . .. UVa 10653 . . . . . . . . . . . . . . . . . . . . . . . . . . . .. UVa 10651 . . . . . . . . . . . . . . . . . . . . . . . . . . . .. 0 1 cost . . . . . . . . . . . . . . . . . . . . . . .
. 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) . . . . . . . . . . . . . . . . . . . . . . . . . . Biconnected component . . . . . . . . . . . . . . . . . . . . . . . . Flow . . . . . . . . . . . . . . . . . . . . . . . .
.. Maximum flow . . . . . . . . . . . . . . . . . . . . . . . . .. Minimum cut . . . . . . . . . . . . . . . . . . . . . . . . . .. Minimum cost maximum flow . . . . . . . . . . . . . . . .. Maximum Bipartite Matching . . . . . . . . . . . . . . . .. Vertex cover Independent set . . . . . . . . . . . . . . .. Weighted maximum bipartite matching . . . . . . . . .
Adhoc . Cumulative sum . . . . . . . . . . . . . . . . . . . . . . . . Maximum sum . . . . . . . . . . . . . . . . . . . . . . . .
.. One dimensional Maximum sum problem . . . . . . . . .. Two dimensional Maximum sum problem . . . . . . . .
. Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. LightOJ 1008 . . . . . . . . . . . . . . . . . . . . . . . . . .. Josephus Problem . . . . . . . . . . . . . . . . . . . . . .
. Maximum element . . . . . . . . . . . . . . . . .. 1 dimension . . . . . . . . . . . . . . . . . . . . . . . . . . .. 2 dimension . . . . . . . . . . . . . . . . . . . . . . . . . .
. Least Common Ancestor . . . . . . . . . . . . . . . . . . . . . . . Geometry Computational Geometry
. Basic Geometry Trigonometry . . . . . . . . . . . . . . . . . . . Coordinate Geometry Vector . . . . . . . . . . . . . . . . . . Computational Geometry . . . . . . . . . . .
.. Convex Hull . . . . . . . . . . . . . . . . . . . . . . . . . . .. Closest pair of points . . . . . . . . . . . . . . . . . . . . .. Line segment intersection . . . . . . . . . . . . . . . . . .. Pick's theorem . . . . . . . . . . . . . . . . . . . . . . . . .. Polygon . . . . . . . . . . . . . . . . . . . .. Line sweep Rotating Calipers . . . . . . . . . . . . . .. coordinate counting . . . . . . . . . . . . . .
String . Hashing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Knuth Morris Pratt KMP . . . . . . . . . . . . . . .
.. KMP . . . . . . . . . . . . . . . . . . . . . Z algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. Z algorithm . . . . . . . . . . . . . . . . . Trie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Aho corasick . . . . . . . . . . . . . . . . . . . . . . . . Suffix Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.. Suffix array . . . . . . . . . . . . . . . .
. n = 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . w = ? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Heap array numbering . . . . . . . . . . . . . . . . . . . . . . . . . Segment Tree Build . . . . . . . . . . . . . . . . . . . . . . . . . . Prim's algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . Kruskal's algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . Fibonacci Recursive Call Tree . . . . . . . . . . . . . . . . . . . . . Biconnected algorithm . . . . . . . . . . . . . . . . . . . . . . . . . Biconnected algorithm . . . . . . . . . . . . . . . . . . . . . . . . . Maximum flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Maximum flow: local maxima maximum . . . . . . . . . . Maximum flow: representation initial . . . . . . . . Maximum flow: maxflow . . . . . . . . . . . . . . . Minimum cut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Bipartite matching, Vertex cover Independent set . . . . . . . euler representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Pick's theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . fa, and, ant, art, on, onto, owl, tableg trie . . . . . fhers, hi, his, sheg aho corasick trie . . . . . . . .
. math.h . . . . . . . . . . . . . . . . . . . . . n = 10 sieve algorithm simulation . . . . . . . . . . . . a = 10 b = 6 Extended GCD simulation . . . . . . . . Insertion Sort simulation . . . . . . . . . . . . . . . . . . . . . LightOJ 1008 . . . . . . . . . . . . . . . . . . . . . . . Josephus problem n last man standing index . maximum element h = 4 A B
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string prefix function . . . . . . . .
. , , , ! , , - " ?" - " ?" - " , , " ! ,
. ? , , , , , , , , , , , , , ,
efficient ACM , ,
ACMStyle InformaticsOlympiadStyle. 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 - , - ? , , ! , , !
" " !
website
uva.onlinejudge.org popular
icpcarchive.ecs.baylor.edu uva ICPC Regional Programming Contest ACM ICPCWorld Finals
acm.sgu.ru , !
acm.timus.ru recently BeginnersProblem ,
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 InformaticsOlympiad
ipsc.ksp.sk IPSC Encryption, Music, New Language, Game
www.spoj.com Polish - informatics olympiad - profile
ace.delos.com/usacogate USA informatics olympiad - - IOIoffline categorywise- , analysis
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 , user id user id comparison , FelixHalim StevenHalim
www.e-maxx.ru article Google Translator Bing Translator !
infoarena.ro article
www.hsin.hr/coci/ Croatian Informatics Olympiad practice contest
Introduction to Algorithms ThomasH.Cormen, Charles E. Leserson, Ronald
L. Rivest Clifford SteinProgramming Challenges Steven S Skiena Miguel A RevillaThe Algorithm Design Manual Steven S SkienaAlgorithm Design Jon Kleinberg Eva TardosComputational Geometry: Algorithms and Applications Mark de Berg,
Otfried Cheong, Marc van Kreveld Mark OvermarsComputational Geometry in C Joseph O'RourkeArt of Programming Contest Ahmed Shamsul ArefinData Structures and Algorithms in C++ Michael T. Goodrich, RobertoTamassia
David M. Mountoffline
Competitive Programming Felix Halim Steven Halim
, OJ , internet , net preview suit
. ? ACMC, 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 ( .) run 6 2 8 , 4, 12 3
.: simple code.cpp #include int main() f printf("%dnn", 6 + 2); return 0; g
- ? ! , Line 1 stdio.h header file include header file
stdio standardinput output.
line 2 empty line. space tab
line 3 main function run function function integer return
line 5 printf("%d %dnn", 6 + 2, 6 - 2)
line 6 main function 0 return ( .) ,
run user
scanf ( .)
.: simple input.cpp #include int main() f int a, b; scanf("%d %d", &a, &b); printf("%dnn", a + b); return 0; g
a b variable. x; y; a; b; p , C variable a b variable declare scanf , a b &a &b ? 6 + 2 a + b ( - ), ( * ), ( / ) ( % )
, ? ! - practice Online Judge OJ
Timus 1000 Timus 1264 Timus 1293 Timus 1409
. math.h experiment ( .) (a b) run 100000 100000 ( )! , ( python , python !) a b variable declare int int variable 231 231 1 int long long range 263 263 1 int %d long long %lld
a%b a b 231 2 109. compiler long long int64 %I64d
3 2 1:5 ? 1? ? ? , ? , a b int a/b integer 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, squareroot, square, cube ) math.h . math.h
.: math.h
sqrt(x) x square root x Run Time Error (RTE)
fabs(x) x sin(x), cos(x), tan(x) x sin; cos; tan x radian asin(x), acos(x), atan(x) x sin1; cos1; tan1 sin1 cos1
x [1; 1] range atan(x), atan2(y, x) y = 1;x = 0 tan1 atan
, atan2 pow(x, y) xy exp(x) ex log(x), log10(x) log natural logarithm log10 10 based logarithm.floor(x), ceil(x) floor ceiling
. , cos = 1 acos(-1) .
.: circle area.cpp #include #include int main() f double r, area, pi;
double float %lf %f double, float precision http://community.topcoder.
com/tc?module=Static&d1=tutorials&d2=integersReals article = 22
7, approximation
scanf("%lf", &r); pi = acos(1.); area = pi r r; printf("%lfnn", area); return 0; g
2D co-ordinate , , , integer vertex co-ordinate ,
. if - else if - else - leap year leap year - leap year leap year if-else if-else. . , syntax
.: simple if if( condition1 ) f //if condition1 is true g else if( condition2 ) f //otherwise if condition2 is true
syntax syntax.
g ... else f //if no conditions are true g
condition ? +, -, *, / (arithmetic operator ) comparison operator ;=, ==(equal), ! =(not equal). ( .)
.: odd even.cpp #include int main() f int a; scanf("%d", &a); if(a % 2 == 0) f printf("%d is evennn", a); g else f printf("%d is oddnn", a); g return 0; g
leap year , , .
.: leap year.cpp #include int main() f int year; scanf("%d", &year); if(year % 400 == 0) f printf("%d is Leap Yearnn", year); g
else if(year % 100 == 0) f printf("%d is not Leap Yearnn", year); g else if(year % 4 == 0) f printf("%d is Leap Yearnn", year); g else f printf("%d is not Leap Yearnn", year); g return 0; g
curly brace (fg) if / elseif / else curly brace , variable
leap year logical operator logical operator || (or), && (and), ! (not). condition || , && ! condition condition condition ! . logicaloperator leap year bracket 5 (2 + 1)5 2 + 1 5 + 2 1 , sure bracket
.: leap year2.cpp #include int main() f int year; scanf("%d", &year); if(year % 400 == 0 j j (year % 100 != 0 && year % 4 -
== 0))
printf("%d is Leap Yearnn", year); else printf("%d is not Leap Yearnn", year); return 0; g
-
Palindrome , Palindrome number 1; 2; 3; : : : 9; 11; 22; 33; : : : 99; 101; 111; 121; : : :. n Palindrome Number (n < 100)
n , Pni=1 i (n i+ 1) = 1n+2(n1)+ : : : n1 ( if-else !) co-ordinate , quadrant Timus 1068
. LoopLoop a + b ( .) 1 100 , 1 , 2 , 3 100 - loop C loop For loop, While loop,Do-While loop. , , if-else curly brace . for loop while loop outline - mainfunction ,
.: simple loop.cpp //prototype(not syntactically valid line) for(initialization ; condition ; increment/decrement) -
fg while(condition is true) fg //Examples for(i = 1; i = 1; i) printf("%dnn", i); //prints -from 10 to 1
for(i = 1; i
for(i = 1; i 3) break; printf("%dnn", i); g //takes input until the input is 0 //sometimes it is needed for OJs. //EOF = End Of File. while(scanf("%d", &a) != EOF) f if(a == 0) break; printf("%dnn", a); g //in short while(scanf("%d", &a) != EOF && a) f printf("%dnn", a); g
loop loop , n 1+ (1+2)+ (1+2+3)+ : : :+(1+2 + : : : + n). , (1 + 2 + : : : + n) for loop 1 n 1 1 , 2 n forloop upper bound for loop .
.: simple loop4.cpp sum = 0; //very important. many of you forget to -
initialize variable
for(i = 1; i
. 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 n - n Prime Prime
n! (n factorial) n r , nr = n!r!(nr)! x n , cosx maclaurine series cosx series 1 x22! + x44! + : : :+ nth term
OJ { Timus 1083 { Timus 1086 { Timus 1209{LightOJ1001 {LightOJ1008 {LightOJ1010 {LightOJ1015 {LightOJ1022 { LightOJ 1053 { LightOJ 1069 { LightOJ 1072 { LightOJ 1107{LightOJ1116 {LightOJ1136 {LightOJ1182 {LightOJ1202 {LightOJ1211 { LightOJ 1216 { LightOJ 1294 { LightOJ 1305 { LightOJ 1311{ LightOJ 1331 { LightOJ 1433
formula quadratic equation pattern A B answer 0 B answer 0 A 1 answer
solution 2d ,
intersection x x intersect co-ordinate
formula internet !
{ Last but not the least UVa 100
. Array String Game Show 10 Host , answer answer 1 Game ? 10 variable , variable a; b; : : : j a , , 10if-else variable game if-else ?
programming languagearray 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 .
.: simple array.cpp //initialization for(i = 0; i < 10; i++) a[i] = 0; for(i = 0; i < 100; i++) f scanf("%d", &id); //the player giving correct -
answer
a[id 1]++; //increment players point g maximum score = 0; //initializing max score for(i = 0; i < 10; i++) if(maximum score < a[i]) //if ith players score is -
more than the max
maximum score = a[i]; //set max score to this -value
printf("Winners are:nn"); for(i = 0; i < 10; i++) if(maximum score == a[i]) //if ith players score is -
maximum
printf("%dnn", i + 1); //print his id0-indexing 1-indexing
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 asciivalue 65 90, a z 97 122 0 9 48 57. ascii value character %d ascii value asciivalue , A Z, a z 0 9 character ch , if('a'
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 , multidimensionarray , matrix 2 dimension array
string.h- string - strlen - string length, strcmp - string dictionary , lexicographical order , strcat - string concatenation , strcpy - stringcopy , memset - memory fill strtok, strstr
intuitive. memset critical a integer array , element 0 initialize memset(a, 0, sizeof(a)). a array , 0 fill , array 0 1 initialize , memset , 1 initialize ,
convert array , array sorting
array 1 0 1
array array i j ?
string length (library function ) (a; b; : : : z) (A;B; : : : Z)
Topcoder http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=integersReals
for loop sort array , , , swap
! i j for loop ! , , !
string string water string melon string-watermelon
stringA B , B A A = bangladesh B = desh B, A BA aa aaa
sentenceword 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 { LightOJ1133 { LightOJ 1214 { LightOJ 1225 { LightOJ 1227 { LightOJ 1241{ LightOJ 1249 { LightOJ 1261 { LightOJ 1338 { LightOJ 1354 { LightOJ1387 { LightOJ 1414
. Time Memory Complexity Time Memory Complexity time memory TimeComplexity Memory Complexity time memory second Byte ?
computer computer 10s 5s , memory ! n = 100 memory time n = 1000 memory time , 10 n 2d n2 n = 100 n = 1000 10 100 solution time memory problem parameter exactly time memory , solution complexity
loop 1+(1+2)+(1+2+3)+: : :+(1+2+ : : :+n). for loop , 1+2+: : : n = n
2+n2 n
term n term , n n2 term. n2 term , n term n2/2. constant coefficient n2. Time Complexity. , algorithm On2 . n = 1000 , On2 = 106 1s , n = 106 ? n On2 algorithm Time Limit Exceed (TLE) optimize ? , i for loop 1 n 1 + 2 + : : : + i for loop formula ( i2+i2 ) On n ? ,n = 1012? algorithm order
1 + (1 + 2) + (1 + 2 + 3) + : : :+ (1 + 2 + : : :+ n)
=nXi=1
iXj=1
j
=nXi=1
i2 + i
2
=1
2
nXi=1
i2 +nXi=1
i
!
=1
2
n(n+ 1)(2n+ 1)
6+n2 + n
2
formula loop
, O1 algorithm. Memory Complexity (Fibonacci
Number) , n Fn
Fn =
8>:0 n = 0
1 n = 1
Fn1 + Fn2 n 2
array F[0] = 0, F[1] = 1 for loop F[i] = F[i - 1] + F[i - 2]. n array declare Memory Complexity On. array Fn . 3 variable , Memory Complexity O1. Time Complexity On Memory ComplexityO1
order of n2.n = 0 Time Complexity Time
Complexity
.: fibonacci.cpp a = 0; b = 1; for(i = 2; i = 80) return 5; else if(marks >= 60) return 4; else if(marks >= 50) return 3; else if(marks >= 40) return 2; else if(marks >= 33) return 1; else return 0; g
LightOJ 1136 "A B answer 0 B answer 0 A 1 answer " f parameter n 0 n answer f(B) f(A 1). !
Recursion recursion !Mr Edsger Dijkstra
I learned a second lesson in the 60s, when I taught a courseon programming to sophomores and discovered to my surprise that10% of my audience had the greatest difficulty in coping with theconcept of recursive procedures. I was surprised because I knew thatthe concept of recursion was not difficult. Walking with my five-yearold son through Eindhover, he suddenly said Dad, not every boathas a life-boat, has it? How come? I said. Well, the life-boatcould have a smaller life-boat, but then that would be without one.It turned out.
Recursion , processing , , Fn = Fn1 + Fn2. n , n 1 n 2 call recursion recursion call , call , n = 3 , n 1 = 2 n 2 = 1 , ? definition
Fn =
8>:0 n = 0
1 n = 1
Fn1 + Fn2 n 2 , n 2 n1n2
, recursion . , recursive function n ( ) loop ? Time Complexity , algorithm Time Complexity , ,
.: recursive fibonacci.cpp int fibonacci(int n) f if(n == 0) return 0; if(n == 1) return 1; return fibonacci(n 1) + fibonacci(n 2); g
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
structure save array save , information. , ,, , information information array. maintain structure. .
.: structure.cpp struct Student f char name[30], father[30], address[50]; int birth date, birth month, birth year; int phone; g; Student s, student[50]; scanf("%s", s.name); printf("%dnn", student[5].birth date);
Student structure declare variable declare Student datatype variable s Student array student variable dot
variable access
. bitwise operation Decimal NumberSystem 10 0; 1; 2; : : : 9. 0 1. Number System Binary Binary bit variable 6 0; 1
bitwise operation operation bit - bitwise operator & (bitwise and), | (bitwiseor), ^ (bitwise xor), (1's complement), > (shift right). net
Mathematics. Number Theory.. Prime NumberPrime Number n 1 1 n n Prime - ? n n 2 n 1 n nPrime Idea Primality .
.: isPrime1.cpp //returns 1 if prime, otherwise 0 int isPrime(int n) f if(n
() n = 24 divisor 1; 2; 3; 4; 6; 8; 12; 24 4 (1; 24); (2; 12); (3; 8); (4; 6). pn ? direct , Proof by Contradiction pn , ! n pn n ? pn (.) run time Opn. forloop condition i i n , i sqrt(n) , sqrt costly , double precisionloss sqrt(9) = 3 2.9999999 3.0000001 i i ! loop limit = sqrt(n + 1) loop sqrt
.: isPrime2.cpp //returns 1 if prime, otherwise 0 int isPrime(int n) f if(n
! n = 10 . algorithm simulate
.: n = 10 sieve algorithm simulation
initial 2; 3; 4; 5; 6; 7; 8; 9; 10 uncut number = 2. 2 multiple 2, 3, 4, 5, 6, 7, 8, 9, 10 uncut number = 3. 3 multiple 2, 3, 4, 5, 6, 7, 8, 9, 10 , 5 > p10 2, 3, 4, 5, 6, 7, 8, 9, 10
implementation . algorithm run time On log logn. prime number mark array prime
.: sieve.cpp int Prime[300000], nPrime; int mark[1000002]; void sieve(int n) f int i, j, limit = sqrt(n 1.) + 2; mark[1] = 1; for(i = 4; i
, 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 pb prime (prime efficient 2 pb )
prime factorize prime prime power
.. Divisor divisor . Op
n divisor sieve algorithm
modify 1 n divisor ? ! runtimeOn logn. . , multiple list insert - mark memory ! , n divisor n logn STL vector vector Dynamic Linked List ,
.: all divisors.cpp int mark[1000002]; vector divisors[1000002]; void Divisors(int n) f int i, j; for(i = 1; i
NOD(n) = (a1 + 1)(a2 + 1) : : : (ak + 1)
SOD(n) = (1 + p1 + p21 + : : :+ p
a11 )(1 + p2 + p
22 + : : :+ p
a22 ) : : : (1 + pk + p
2k + : : :+ p
akk )
=pa1+11 1p1 1
pa2+12 1p2 1 : : :
pak+1k 1pk 1
.. GCD LCMGCD Greatest Common Divisor () LCM Least CommonMultiple () a b g l a b = g l. ? a b 1 , a b run time On. , 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 .
.: gcd.cpp int gcd(int a, int b) f if(b == 0) return a; return gcd(b, a % b); g
.. Euler Totient Function ( ) Totient Function
(n) = n n coprime wiki runtime
!
coprime factor ,(12) = 4 2; 3; 4; 6; 8; 9; 10; 12 12 factor 1; 5; 7; 11 common factor n = pa11 pa22 : : : pakk
(n) = n
1 1
p1
1 1
p2
: : :
1 1
pk
prime factorize
prime divisor 1 n ? , prime p multiple p p1 1 n prime ( .)
.: sieve phi.cpp int phi[1000006], mark[1000006]; void sievephi(int n) f int i,j; for(i = 1; i
? 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
? BlackBox a; b;M ab modM b Black Box a; b/2;M Black Box a; b1;M ? , b = 0 BlackBox function function function recursive function . b , algorithm run time Ologn.
.: bigmod.cpp int bigmod(int a, int b, int M) f if(b == 0) return 1 % M; int x = bigmod(a, b / 2, M); x = (x x) % M; if(b % 2 == 1) x = (x a) % M; return x; g
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) logn bigmod logn , run time O(logn)2. cost Ologn
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 modM
.. Modular Inverse exact mod , , abmodM amodMbmodM b b1modM b M prime , b1 bM2 modM . , b1 b(M)1 modM 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.
Extended GCD egcd . x y egcd call variable reference x y return
.: a = 10 b = 6 Extended GCD simulation
x y 10x + 6y10 1 0 106 0 1 64 1 -1 42 -1 2 2
.: egcd.cpp int egcd (int a, int b, int &x, int &y) f if (a == 0) f x = 0; y = 1; return b; g int x1, y1; int d = egcd (b%a, a, x1, y1); x = y1 (b / a) x1; y = x1; return d; g
egcd Modular Inverse ( bM coprime ) b x , bx 1modM ., bx = 1+yM y integer. , bxyM = 1. b Mcoprime x y , bx yM = 1 , bx 1modM egcd x , x M mod
. Combinatorics.. Factorial 0100! ? - common , 100! 10 , 5! = 120. 10 , 0 ? 5 2 , 10 2 5 2 , 2 5 , 5 , 5 1 100 b100/5c = 20 5 5
x = (x mod M + M) mod M
25 5 , 125 125 100 5 power 5 b100/5c+ b100/25c = 20+4 = 24. 100! 24 n! prime number p
bn/pc+ bn/p2c+ bn/p3c+ : : :
.. Factorial Digit n! 0 , n! ? calculator 50! 3:04140932 1064 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: nr
n r nr = n!(nr)!r! . n r nr factorial - overflow. n = 50; r = 1 50! overflow 501 = 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
ceiling 10x p2 ? ,
approximation
n! mod p, ModuloInverse(r! mod p, p) ModuloInverse((n-r)! mod p,p) p > n facotiral mod precalculate Ologn
mod prime Lucas' Theorem. theorem
m
n
kYi=0
mini
(modp)
,m = mkpk + : : :+m1p1 +m0p0 n = nkpk + : : :+ n1p1 + n0p0. ab a; b < p precalculate prime (O1) nr
nr precalculate n n array On2 nr = n1r + n1r1 . limncr nr generate
.: ncr.cpp ncr[0][0] = 1; int limncr = 10; for(i = 1; i
Dn n Derangement Number n n 1 X X n 2 Dn2 (n 1)Dn2 X X n 1 n 1 (n 1)Dn1 n 1 X n 1 Dn recurrence ,
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 openingbracketn closingbracket parenthesesexpression ? n = 3 ((())), ()(()), ()()(), (())() (()()).
n leaf complete binary tree ? n polygon triangulate ? Catalan Number. n Catalon Number
Cn
Cn =1
n+ 1
2n
n
=
2n
n
2n
n+ 1
recurrence ,
discrete math
Stirling Number of Second Kindn k Stirling Number of SecondKind. nk n = 3 k = 2 3,(AB;C); (AC;B); (BC;A). recurrence DerangementNumber n n 1 k 1 ( , ) n1k1 , n1 k k kn1k ,
n
k
=
n 1k 1
+ k
n 1k
http://en.wikipedia.org/wiki/Catalan_number interpretation
recurrancebase case k = 1 ? ? k = n ? n n ? base case
n
1
=
n
n
= 1
Stirling Number of First Kind
n k cycle Stirling Number ofFirst 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)). , AB BA cycle , cycle BA (AB;CD) (CD;AB) cycle , stirling number of first kind recurrence n cycle n1 k1 cycle ( , ) n1k1 , n 1 k cycle n 1 (n 1)n1k ,
n
k
=
n 1k 1
+ (n 1)
n 1k
recurrance base case k = 1 cycle ? common (n 1)! k = n ? n n cycle ? base case
n
1
= (n 1)!;
n
n
= 1
.. Fibonacci Number
n 106 , n 1018 ( mod )? method matrix matrix matrix matrix general method, method problem Matrix
F2F1
=
1 11 0
F1F0
F3F2
=
1 11 0
F2F1
=
1 11 0
1 11 0
F1F0
=
1 11 0
2 F1F0
, F4F3
=
1 11 0
3 F1F0
, FnFn1
=
1 11 0
n1 F1F0
matrix power , BigMod , , matrix. matrix Stirling Number , kkmatrix k n
.. Inclusion Exclusion PrincipleCounting method Inclusion Exclusion Principle. , 1 100 2 3 ? , 2 , 3 , 2 3 , 2 , b100/2c = 50. 3 b100/3c = 33. , 6; 12; 18 : : : double count double count , double count 2 3 6 6 b100/6c = 16 50 + 33 16 = 67. count method inclusion exclusion principle. 2 2; 3; 5; 7
, , , time complexity O2n. bitmask n n bit , bit 1 , 0 loop -
. details
.. Probability Head Tail ? ! chance 50-50. , 5 6 ? mathematical 5 , 6 1; 2; 3; 4 1; 2; 3; 4 , common sense ? ?
= , , Head probability 12
coin Head Tail Head. - 5 probability , 06 = 0. 5 ! 1; 2; 3 4 probability 16 6 probability 26 . 6
method method , n randomly , b 4bn ? ? radius r r2 4r2. randomly r24r2 = 4 . experiment n randomly b , experiment bn
bn 4 , 4bn . n experiment accurate
.. 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 2 3 4 5 .:
1 5 3 1 6 3 5 5 Expected number of move ?
, Ti i expected number ofmove. T1 T5 = 0 5 move 4 T4 move. , 1 4 , T4 move , 4 T4 move T4 move ? 1 T5 move. 1/6 probability T5move 5/6 probability T4 move. , T4 = 1 + 16T5 + 56T4 , T4 = 6. , 6 expectation 6. T3 ,
, 2 1/6 probability 2 T4 move, 1/6 probability 3 T5 move , 4/6probability 2 T2move ,T2 = 1 +
16T4 +
16T5 +
46T2 T2 = 6. T1
, T1 = 1 + 16T2 + 16T4 + 16T5 + 36T1 ) T1 = 6. expected number ofmove 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 4102+8101+1100 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 , , ? , BigInteger , , common sense
.. Cycle Finding AlgorithmUVa 11036 idea x , f(x) = x (x + 1) mod 11, 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 ON N time complexity On - , O + = cycle = cycle length. memory complexity O1 time complexity method Floyd'sCycle Finding Algorithm.
algorithm cycle ( f(f(x)) f(x)) period . , .
.. Gaussian elimination x+2y = 5 3x+2y = 7. x y variable ? n variablen equation ? BUET practice BUETworld finalist team, , 4 5 ! 4 variable 4 equation ? variable x0; x1; x2 x3. x0 , ? 3 equation 3 variable equation variable , variable equation. equation idea. special case
n equation variable constant n nmatrixA n B x+ 2y = 5 3x+ 2y = 7 A B
A =
1 23 2
; B =
57
counter e. n i (i = 0 : : : (n 1)) e row A[j][i] e j < n j A[j][i] A[j][i] 0 i continue 0 B A e row j row swap matrix e row A[e][i] A[e][i] 1 0 j < n j 6= i row A[e] row A[j][i] A[j] A row B variable eliminate row i variable eliminate e i continue i e n unique A row 0 row B row B 0 equation A row B row 0 e = n unique variable B Gaussian elemination time complexity On3.
.. Matrix Inverse Gaussian elimination matrix inverse A matrix inverse matrix B identity matrix main diagonal 1 0. operation (row swap, , ) A identity A operation operation B A identity matrix B A1. A identity (0 row) A inverse ?
Sorting Searching. SortingSort 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 timecomplexityOn2. sorting InsertionSort .
.: insertion sort.cpp for(i = 1; i = 1 && num[j] > x) f num[j + 1] = num[j]; j; g
.: Insertion Sort simulation
5, 8, 6, 1, 7, 95, 8, 6, 1, 7, 95, 8, 6, 1, 7, 95, 6,8, 1, 7, 95, 6, 8, 1, 7, 95, 6, 1,8, 7, 95, 1,6, 8, 7, 91,5, 6, 8, 7, 91, 5, 6, 8, 7, 91, 5, 6, 7,8, 91, 5, 6, 7, 8, 91, 5, 6, 7, 8, 9
num[j + 1] = x; g
.. Bubble SortOn2 sorting algorithm Insertion Sort
bubble sort algorithm swap n algorithm On2
, n . optimization , n array sorted loop pair i i optimization optimization algorithm worst case On2 worst case ?
.: bubble sort.cpp for(i = 1; i num[j]) f
array On2
temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; g g
.. Merge Sort algorithm practical life sorting 60 sort sorted , ? , - sort ? , recursive function function array function call sort merge sorted return merge sort . ,mergesort variable parameter , lo hi (, , low high ). variable array sort ( )
.: merge sort.cpp int num[100000], temp[100000]; //call mergesort(a, b) is you want to sort num[a...b] void mergesort(int lo, int hi) f if(lo == hi) return; int mid = (lo + hi)/2; mergesort(lo, mid); mergesort(mid + 1, hi); int i, j, k; for(i = lo, j = mid + 1, k = lo; k
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 Run Time Error .
.: cmp.cpp bool cmp(Point A, Point B) f if(A.x < B.x) return 1; if(A.x > B.x) return 0; if(A.y < B.y) return 1; if(A.y > B.y) return 0; return 0; g
.
.: improved cmp.cpp bool cmp(Point A, Point B) f if(A.x != B.x) return A.x < B.x; return A.y < B.y; g
sort sort(point, point +n, cmp). overload , overload sort . overload sort(point, point + n)
. Binary Search Game Show 100 , 1986 , 1986 1986 1986 , 100 50 1986 ? method binarysearch bisection method
, array 0 1 0 1 1 binary search 0 1, 0 , 1
Binary Search , binary search , ! . w , a b. c a; b c , w =?.
c
w
a
b
.: w = ? w
w c ? ( ) p q. , c = 11
p+1q
. 7 :)
w c c w0. w w0 guess , c , w w0 guess c w w0 w binary search c w range
. BacktrackingBacktracking algorithm , method. Backtracking.
.. Permutation Generate 1 npermutation 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 ? 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 , systematic process
, npermutation generate
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 numbersequence integer double array standard pointer pointer vector slow. globalarray array array (0 , 1 ) array black box 1 n - black box , , permutation black box ? , array parameter n , global permutation - ? ? permutation .
.: permutation.cpp int used[20], number[20]; //call with: permutation(1, n) //make sure, all the entries in used[] is 0 void permutation(int at, int n) f
87
6
5
4
3
2
1
1 2 3 4 5 6 7 8
8+1=7+2=: :: 9
61=7
2=: : : =
5
.:
improvement optimization performance 88 optimization 9 9; 10 10 optimization . n = 8 8 8 ,
.: nqueen.cpp int queen[20]; //queen[i] = column number of queen at -
ith row
int column[20], diagonal1[40], diagonal2[40]; //arrays -to mark if there is queen or not
//call with nqueen(1, 8) for 8 queen problem //make sure column, diagonal1, diagonal2 are all 0 -
initially
void nqueen(int at, int n) f if(at == n + 1) f printf("(row, column) = "); for(i = 1; i
queen[i]);
printf("nn"); return; g for(i = 1; i
optimization optimization ? , V V optimization run time
Algorithm Data Structure efficiency 1 n , ? number array array array array array 0 1 m Ommemory Om Onmemory n O1 algorithm , , representation runtime memory requirement n m ,
. Linked List n ? ,
n n 0 1matrix i j matrix [i][j] 1 0 memory On2 update O1. adjacency matrix
n n matrix i row i array
[i][1] [i][friend[i]] i - , friend[i] i friend memory On2 Ofriend[i] O1 friend[i] matrix [i][friend[i]] adjacency list array implementation
n nn - declare dynamically memory adjacency list linked list implementation.method memory complexity freindship memory
array array - dynamic memoryallocation 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
InsertLinked list insert node next point point node ( .ABD) , , D next A next A nextpoint D
Head Data Anext
Data Bnext
Data Cnext
Deletion of B
Data D
insertion of Dnext
.:
Delete node delete node next point point node ( . B) A next B next point
structure data next array . adjacency list edge insert delete search node delete node insert - search headarray 1( terminal ) initialize
.: linkedlist.cpp int head[10000]; //total node = 10000, 0 to 9999. -
Initilized to 1 int data[100000], next[100000]; //total edge = 100000 int id; //add node y in the list of x void insert(int x, int y) f data[id] = y; next[id] = head[x]; head[x] = id; id++; g //erase first node from head of x void erase(int x)
f // if you are not sure if the linked // list is empty, check head[x] == 1? head[x] = next[head[x]]; g //search node y in list of x int search(int x, int y) f for(int p = head[x]; p != 1; p = next[p]) if(data[p] == y) return 1; //found return 0; //not found g
variation doubly linked list next , previous pointer , circular next terminal point linked list , STL vector , vector insert delete linkedlist O1 dynamically memory allocation vector linked list insert delete stl list list link list insert delete stl list
. Stack Stack ? ? , Stack Stack push pop Stack LIFO Last InFirst Out array pointer stack array declare linked list STL stack stack implementation .
.: stack.cpp / array implementation / sz = 0 //initialization s[sz++] = data; //push return s[sz]; //pop and return if(sz) //check whether there is something in -
stack
/ linked list implementation / head = 1, sz = 0; // -
initialization
node[sz] = data; next[sz] = head; head = sz++; //push ret = node[head]; head = next[head]; return ret; //pop -
& return
if(head != 1) // -check
/ STL / #include using namespace std; stack S; //declare, replace int by -
the type you want
while(!S.empty()) S.pop(); //initialization after -using
S.push(5); //push S.top(); //return top element, but -
doesnt pop
S.pop(); //pop but doesnt return S.size(); //size of the stack S.empty(); //returns true if empty
?
.. 0 1matrix 1 n m 0 1 matrix 1
row loop row row , 1 row 1 count m sub-range sub range maximum stack array stack index, stack push stack stack element (index) stack , stack element , stack index index
(index) stack pop (index) push
? , stack , height 1 stack height height height , height element , stack 5; 8; 9. 6. 8 9 continue continue 8 9 ? 8 9 index index difference 6 8 index 8 6
. Queue queue queue, queue. ? queue FIFO First In First Out queue Stack queue implementation array , linked list STL queue queue implementation .
.: queue.cpp / array implementation / head = tail = 0; //initialization q[tail++] = data; //push return s[head++]; //pop and return if(head == tail) //check whether there is something in -
stack
/ STL / #include using namespace std; queue Q; //declare, replace int by -
the type you want
while(!Q.empty()) Q.pop(); //initialization after -using
Q.push(5); //push Q.front(); //return front element, but -
doesnt pop
Q.pop(); //pop but doesnt return
Q.size(); //size of the queue Q.empty(); //returns true if empty
. Graph representationGraph entity graph facebook graph ! 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 follower directed graph. A B undirected edge A B B A directed edge A B A B edge
. TreeTree special n vertex n 1 edge connected Connected node node edge node edge , properties cycle , node edge node node node uniquely ( ) tree 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 , level1 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 rightchild parent link Binary SearchTree node , insert delete delete node flag delete flag off
, array tree ? , node binary search Ologn binary search ? , binary search insert delete BST insert delete BST , 1 2, 2 3 n On BST balance
subtree tree tree.
tree height AVLTree, RedBlack Tree, Treap internet STL Map Set BST
. Heap Priority Queue binary tree. complete binary tree. tree level level node , node . heap
100
36
125
19
317
72 .: Heap
Heap , Max Heap, Min Heap. Max Heap node descendant root heap , left child left subtree heap 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
13
76
2
54 .: Heap array numbering
Heap insert heap n n + 1 parent root , parent swap , parent height log (n) insertion Ologn. Max Heap root remove root left child right child. swap Ologn remove node modify remove , node worst case
Heap priority queue queue , , priorityqueue. priority heap. STL priority queue . STL int , structure priorityqueue operator overload
.: priority queue.cpp #include using namespace std; priority queue PQ; //declare a max heap PQ.push(4); //insert PQ.top(); //maximum element PQ.pop(); //pop max PQ.size(); //returns size of heap PQ.empty(); //returns 1 if heap is 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[n 1] = n a = 1 On 1 n p[1] = n ? , 1 2; 3; : : : n 1 n n , chain chain Find Find .
.: union find.cpp int p[100]; //initially p[i] = i; int Find(int x) f if(p[x] == x) return x; return p[x] = Find(p[x]); g void Union(int a, int b) f p[Find(b)] = Find(a); g
, a b ? , p[b] = a b b ? Find(b). , p[Find(b)] = a b a p[Find(b)] = Find(a) Union . p[] total max union-find update
. Square Root segmentation
0 n 1 n - 0 i t i j efficiently ? i amount[i]+ = t query i j amount update O1 query worst case On query update ? 0 x total[x] total[j] total[i 1] i j (i = 0 ), query O1. total[x] i t update i n total t update On. ,
update , query - , , 0 x k. , k (0 k 1 ) sum[0] , k (k 2k1 - ) sum[1] k i sum[i/k] update amount[i] sum[i/k] update O1 query i j i x = i/k j y = j/k , x = y i j loop , ,i x range , j range j x + 1 y 1 sum range p kp k(p+1) 1. 2k , sum n/k , range k range n/k. query Ok+ n/k. inequality k = pn query Opn On Opn ! Square Root Segmentation
, update i t i j t ? range variable range amount update range variable ! update Opn
. Static Query query , update update ? information , query sum query , i 1 i (1-indexing ), i j ? 1 j 1 i 1 O1 query preprocessing On.
query sum maximum minimum ? Square Root Segmentation preprocessing On query Opn. Tarjan research , preprocessingOn queryO1 - , method complex. internet method preprocessing On logn
query O1. maximum minimum method maximum . 1 segmentmaximum [1; 1]; [2; 2]; [3; 3]; : : :. 2 segmentmaximum [1; 2]; [2; 3]; [3; 4]; [4; 5] : : :. 4 segmentmaximum [1; 4]; [2; 5]; [3; 6]; [4; 7] : : :. 8 segmentmaximum [1; 8]; [2; 9]; [3; 10]; [4; 11] : : :. i 2i segmentmaximum [1; 2i]; [2; 2i+
1] : : :. 2i n i log (n). preprocessing
x 2i maximum ? , x 2i segment maximum x 2i1 segment maximum x + 2i1 2i1 segment maximum- maximum , table[i][x] = max(table[i 1][x]; table[i 1][x+ (1
index 1 2 ? range query , , ; ; range update Segment Tree Square RootSegmentation Square Root Segmentation complexity Opn Segment Tree Ologn SquareRoot Segmentation update array query array range update query Segment Tree Ologn .. Segment Tree Build
1 2 3 4 5 6 7 8
1 2 3 4
1 2
1 2
3 4
3 4
5 6 7 8
5 6
5 6
7 8
7 8
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
.: 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 . 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 complexityOn.
.: segmentTreeBuild.cpp void build(int at, int L, int R) f //do initialization like: sum[at] = 0 if(L == R) f //might need to do, something like: sum[at] = -
num[L]
return; g int mid = (L + R)/2; build(at 2, L, mid); build(at 2 + 1, mid + 1, R); //do initialization like: sum[at] = sum[at 2] + -
sum[at 2 + 1] etc. g
Segment Tree Time Complexity important SpaceComplexity. array declareRunTimeError , n 4 array declare n 2 power 2 power 2 power memory accurately x 2x 2 power 2 power , 4 declare n 2 power declare , 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 . tree height log (n) update time complexity Ologn
.: segmentTreeQuery.cpp void update(int at, int L, int R, int pos, int u) f
//sometimes instead of using ifelse in line 11 and -12
//you can use: if(at < L j j R < at) return; if(L == R) f sum[at] += u; return; g int mid = (L + R)/2; if(pos
complexity ? , ? ? node range query range partially overlap , tree level partially overlap node , ? partially overlap level partially overlap 2 level logn time complexity Ologn. , time complexity tree structure Link Cut Tree amazing !
.. Lazy without Propagation n off. i j toggle q on off? Segment Tree Ologn idea i 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 Ologn , update? .. update Ologn. . query update update , lazy lazy , without propagation
.: lazyWithoutPropagation.cpp void update(int at, int L, int R, int l, int r) f if(r < L j j R < l) return; if(l
toggle on. Lazy toggle = 1. , left rightchild toggle = toggle ^ 1 on node toggle = 0 , on ( toggle on ) , [1; 4] toggle propagation , toggle = toggle^ 1 on = RL+1 on lazy update cancel lazy cancel cancel , toggle = 1 lazy ,! .
.: lazyWithPropagation.cpp void Propagate(int at, int L, int R) f int mid = (L + R)/2; int left at = at 2, left L = L, left R = mid; int right at = at 2 + 1, right L = mid + 1, -
right R = R;
toggle[at] = 0; toggle[left at] ^= 1; toggle[right at] ^= 1; on[left at] = left R left L + 1 on[left at]; on[right at] = right R right L + 1 on[right at -
];
g void update(int at, int L, int R, int l, int r) f if(r < L j j R < l) return; if(l
if(toggle[at]) Propagate(at, L, R); int mid = (L + R)/2; int x = query(at 2, L, mid, l, r); int y = query(at 2 + 1, mid + 1, l, r); return x + y; g
. Binary Indexed Tree BIT Segment Tree , , BIT SegmentTree , Segment Tree BIT BIT , , n fast. article
, BIT operation . idx v update(idx, v). idx read(idx) operation topcoder
tutorial . read update MaxVal n
array ! BIT 1-indexing
.: bit.cpp int read(int idx) f int sum = 0; while (idx > 0) f sum += tree[idx]; idx = (idx & idx); g return sum; g void update(int idx ,int val) f while (idx
tree[idx] += val; idx += (idx & idx); g g
Greedy Greedy ? buffet ? ? ! ! buffet , ? Greedy ! ? factor ! , Greedy
. Fractional KnapsackGreedy 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 ?
. 1 prim algorithm 1 5 edge , 1 2, 2 3. edge ? state edge edge 3 6,3 4 5 4. weight edge 3 6. 6.
algorithm time complexity ! n vertex edge complexity Onm. On2 a vertex process a edge ? vertex tree edge ,
12 3
45
6
1
2
3
14
5
6
7 8 9
.: Prim's algorithm
edge tree update tree . , 4 9 6 2. 6. edge 6 edge 6 4 weight 3. 4 cost9 3 , 3 4 9 cost , 6 4 ! 4 cost update , n , vertex vertex ? n , vertex , edge vertex , cost update complexity ? n n vertex check 2m edge , complexity On2 +m On2 m < n2 ?
improve n vertex cost Min-Heap (C++ priority queue set) algorithmOm logn m n2 heap complexity interested internet
.. Kruskal's Algorithm algorithm. MST Kruskal'salgorithm implement ! algorithm , - algorithm weight edge , vertex tree component , edge
! vertex tree ! Disjoint Set Union. vertex set edge set , vertex set !
1
2 3
45
6
1
2
3
14
4
6
7 8 5
.: Kruskal's algorithm
. 2 3 3 6,64, 15. edge 34 tree edge edge 1 2 tree edge tree edge cost increasing order edge consider
algorithm time complexity ? , edge weight sort Om logm edge find set union complexity O1 Om logm+m =Om logm
. 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
,
. Huffman CodingHuffmancoding prefix free coding Coding alphabet character - english alphabet character 0 1 a 001 , b 110 Prefix free coding prefix Prefix 01 0110 prefix. code 0 1 coding binary tree edge label 0 edge label 1. root 0 1 coding binary tree representation. prefix free coding representation ? ancestor predecessor code prefix free ? space decode , a = 01; b = 0; c = 1. prefix free 01 decode ?bc a? prefix free , decode decode , tree root traverse character root traverse decode
character character text text prefix free coding text encoded , 3 character frequency (a; 10); (b; 4); (c; 8), (a; 01); (b; 1); (c; 00) - encoded text 102+41+82 = 40. ? character character frequency cost cost merge merge , child cost cost merge
character code algorithm heap priority queue set On logn
Dynamic ProgrammingDynamic Programming practice !
. , array 1 2 n n = 4 5 array f1; 1; 1; 1g, f1; 1; 2g,f1; 2; 1g, f2; 1; 1g f2; 2g. ! , 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 , f1g. way(1) = 1. , way(0) way(0) = 1. 0 0 fg array 0 ? way(2) ? 2 ? f2g f1; 1g n = 2 ,way(2) = way(1) + way(0) way(2) = 2 way(1) = 1 way(0) = 1 ? ? , n = 2 1 21 = 1 way(1) = 1 f1g. 2 , !!! way(0) = 1. ( recursive function) base case. DP Iteratively Recursively.
Dynamic Programming DP
Iterative . recursively .
.: fibIterative.cpp way[0] = way[1] = 1; for(i = 2; i
int dp[1000]; // initialize to 1. int way(int n) f if(n == 0 j j n == 1) return 1; if(dp[n] != 1) return dp[n]; return dp[n] = way(n 1) + way(n 2); g
, 1 1 initialize visited 0 1 visited 0 initialize mark variablemarker dp marker markmarker return dp function , test case
. Coin Change , 1 , 2 , 8 50 ? ?
.. Variant 1 coin[1 : : : k]. n ?
possible[i] i 1 0. possible[n]. n ? ,ncoin[1] ncoin[2] ... ncoin[k] n DP! 1 : : : n k time complexity Onk. .
.: variant1.cpp possible[0] = 1 for(i = 1; i
.. 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 Onk. .
.: variant2.cpp way[0] = 1 for(i = 1; i
.. 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 On22n. .
.: tsp.cpp int dp[1
algorithm time complexity ? n b n binary search Ologn runtime On logn. , insertion sort binary search runtime ? , insertion sort insert replace O1 insert worst case On linked list insert O1 , linked list binary search binary search index linked list
. 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] 6= T [t] S s 1 T t letter S s T t 1 letter string dptable table string character dp string character , string string character reverse recursively dp dp string while , , path print
. Matrix Chain Multiplication matrix A(pq)B(rs) matrix q = r A B A B (BAAB matrix ) matrix A1; A2; : : : An. dimension A1(p1 p2); A2(p2 p3); A3(p3 p4) : : : An(pn pn+1). matrixA(p q) B(q r) cost p q r. ? matrix p; q r
dp , , path printing
A1 (A2 A3) cost (A1 A2) A3 cost A1 = 2 3, A2 = 3 5 A3 = 5 4. A1(A2A3) cost 354+234 = 60+24 = 84 (A1A2)A3 cost 235+254 = 30+40 = 70. n matrix ( catalan ) n , 100, ? A1 A5 optimal matrix matrix (A1A2 : : : Ai) (Ai+1 : : : An). matrix "" , matrix matrix dimension p1 pi+1 matrix dimension pi+1 pn. cost p1 pi+1 pn. cost. DP. 1 n cost range cost recursive Ai Aj matrix cost Ai Ak Ak+1 Aj cost recursively matrix cost i k < j cost cost Ai Aj optimally cost. base case ? , , matrix cost , matrix i = j i k < j k cost ? ? 0, ? base case. time complexity ? DP parameter ? ,i j On2 i; j parameter i k < j k On3. n n3 On3. memoization Memoize algorithm On3 backtrack. backtrack state memoize DP state memoize
, recursively Iteratively i; j length l i. j = i + l 1. k ? , i; j k dp[i][k] dp[k + 1][j] i k ! Idea ? length. length
, Ai Aj dimension pi pj+1
. Optimal Binary Search TreeBinary search tree query root , , query , query equi-probable balanced binarysearch tree query ? query ? huffman tree sorted tree n 1 n i query pi. cost expected cost query depth algorithm optimal binary search tree theme , n ? 0. ? root, i j k root i k j. cost ? k cost 0. [i; k 1] left [k + 1; j] right configuration cost dp[i; k 1] + dp[k + 1; j] + (pi + pi+1 + : : : + pk1) + (pk+1 + : : : pj). root cost probablity probability 1 cost matrix chainmultiplication time complexity On3 optimization On2 optimization
special properties special properties optimization Optimization [i; j] optimal k P [i; j]. P [i+1; j] P [i; j] P [i; j1]. [i; j] k i j P [i + 1; j] P [i; j 1] runtime On2
sorted ? in-order traversal sorted
algorithm stl simple stl stl stl
. Breadth First Search (BFS) (traverse) s , , , edge - already vertex V edge E OV + E. edge .
.: bfs.cpp #include #include using namespace std; vector adj[100]; // adj[a].push back(b); for an -
edge from a to b.
int visited[100]; // 0 if not visited, 1 if visited // s is the starting vertex // n is the number of vertices (0 ... n 1) void bfs(int s, int n) f for(int i = 0; i < n; i++) vis[i] = 0;
queue Q; Q.push(s); visited[s] = 1; while(!Q.empty()) f int u = Q.front(); Q.pop(); for(int i = 0; i < adj[u].size(); i++) if(visited[adj[u][i]] == 0) f int v = adj[u][i]; visited[v] = 1; Q.push(v); g g g
. Depth First Search (DFS) s , edge , recursive , edge recursively . , dfs call dfs call cost ( state )
.: dfs.cpp #include using namespace std; vector adj[100]; int vis[100]; // call it by dfs(s) // before calling, make vis[] all zero. void dfs(int at) f if(vis[at]) return; // if previously visited. vis[at] = 1; for(int i = 0; i < vis[at].size(); i++)
dfs(vis[at][i]); g
complexity OV +E V recursive call compiler default stack size stack overflow online judge manually recursive stack stack DFS .
.: dfsStack.cpp #include #include using namespace std; vector adj[100]; int edge id[100]; int vis[100]; // s is starting vertex // n is number of vertices void dfs(int s, int n) f for(int i = 0; i < n; i++) edge id[i] = vis[i] = 0; stack S; S.push(s); while(1) f int u = S.top(); S.pop(); while(edge id[u] < adj[u].size()) f // start looking into edges, from the place -
we left
int v = adj[u][edge id[u]]; edge id[u]++; // update edge pointer to -
check next time
if(vis[v] == 0) // if the vertex is not -already visited
f vis[v] = 1; S.push(u); // order of push important -
for dfs
S.push(v); // first we will check v, -then we will come back to u
// note, stack is last in first out. So -v will be popped before u
break;
g g g g
. DFS BFS .. node edge ? BFS , BFS shortest path BFS
DFS DFS - shortest path A;B C A DFS