├── solved ├── problem-set-volumes │ ├── 10 │ │ └── 10140-Prime_Distance │ │ │ ├── 10140 │ │ │ ├── test.dat │ │ │ ├── 10140.dat │ │ │ ├── A │ │ │ ├── test │ │ │ ├── tmp │ │ │ ├── A.dat │ │ │ ├── A.diff │ │ │ ├── out.c │ │ │ ├── A.c │ │ │ ├── tmp.cc │ │ │ ├── 10140.cpp │ │ │ └── test.cc │ ├── 11 │ │ └── 1124-Celebrity_Jeopardy │ │ │ ├── 1124.cpp │ │ │ └── Main.java │ ├── 12 │ │ ├── 1226-Numerical_Surprises │ │ │ ├── 1226.dat │ │ │ └── Main.java │ │ ├── 1203-Argus │ │ │ ├── 1203.dat │ │ │ └── 1203.cpp │ │ ├── 1215-String_Cutting │ │ │ ├── 1215.dat │ │ │ └── 1215.cpp │ │ ├── 1260-Sales │ │ │ ├── 1260.dat │ │ │ └── 1260.cpp │ │ └── 1219-Team_Arrangement │ │ │ └── 1219.dat │ ├── 01 │ │ └── 100-3n+1 │ │ │ ├── 100.dat │ │ │ └── 100.cpp │ ├── 02 │ │ └── 200-Rare_Order │ │ │ └── 200.dat │ ├── 04 │ │ └── 441-Lotto │ │ │ ├── 441.dat │ │ │ └── 441.cpp │ ├── 07 │ │ └── 740-Baudot_Data_Communication_Code │ │ │ ├── 740.dat │ │ │ ├── 740_.cpp │ │ │ └── 740.cpp │ └── 03 │ │ └── 386-Perfect_Cubes │ │ └── 386.cpp └── contest-volumes │ ├── ECNA2012-practice │ ├── B │ │ ├── B.in │ │ ├── README.md │ │ └── B.cpp │ └── C │ │ ├── C.in │ │ ├── README.md │ │ └── C.cpp │ └── C │ ├── 10008.dat │ ├── 10050.dat │ └── 10050.cpp ├── tryouts ├── 2011 │ ├── bh08ti │ │ ├── 1205 │ │ │ └── Main.java │ │ └── 1226 │ │ │ ├── in1226.dat │ │ │ └── Main.java │ ├── jt11li │ │ ├── Node.java │ │ └── ColorTree.java │ ├── km07ok │ │ └── Main.java │ ├── mc08il │ │ └── 1205.cpp │ └── mm08sj │ │ └── 1205.cpp └── 2012 │ ├── 441.pdf │ ├── 10140.pdf │ ├── 1124.pdf │ ├── 1215.pdf │ └── 1260.pdf ├── practice-problems ├── ECNA-2011 │ └── practice-set │ │ ├── C.in │ │ ├── C │ │ ├── C-iter.cc │ │ └── C-recur.cc ├── GreaterNewYork2009 │ ├── A │ │ ├── a │ │ ├── a.dat │ │ ├── a.cpp │ │ └── a_judge.cpp │ └── problems.zip ├── ECNA-2010 │ ├── problem-set-2010.pdf │ ├── D │ │ ├── outD.dat │ │ ├── D1.cc │ │ └── D.cc │ ├── H │ │ ├── outH.dat │ │ └── inH.dat │ ├── B │ │ ├── B.cc │ │ ├── B.java │ │ └── outB.dat │ ├── E │ │ ├── E.cc │ │ └── outE.dat │ ├── F │ │ └── F.cc │ └── C │ │ └── outC.dat ├── ACM2008 WorldFinalsProblemSet.pdf └── ACM_ICPC_2009-South_America(North).pdf └── resources ├── ACM-2011-Waterloo.pdf ├── Dynamic Programming.pdf ├── common_graph_algorithms.pdf ├── programming_challenges.pdf ├── c++_and_stl ├── cpp_tutorial.pdf ├── snu_cheatsheet.pdf ├── ch1-Intro │ ├── ch1_02_scanf_input.txt │ ├── ch1_01_factorial.java │ └── ch1_02_scanf.cpp ├── bitwise operations.odt ├── stanford_cheatsheet_2012.pdf ├── ch4-Graph │ ├── IntegerPair.java │ ├── ch4_07_floyd_warshall.cpp │ ├── ch4_07_floyd_warshall.java │ ├── ch4_02_UVa469.cpp │ ├── ch4_09_spoj101.cpp │ ├── ch4_06_bellman_ford.cpp │ ├── ch4_05_dijkstra.cpp │ ├── ch4_02_UVa469.java │ ├── ch4_10_mcbm.cpp │ ├── ch4_09_spoj101.java │ ├── ch4_06_bellman_ford.java │ └── ch4_03_kruskal_prim.java ├── ch5-Mathematics │ ├── ch5_03_UVa1230_LA4104.java │ ├── ch5_04_UVa10551.java │ ├── ch5_02_UVa10814.java │ ├── ch5_01_UVa10925.java │ ├── ch5_06_UVa350.cpp │ ├── ch5_06_UVa350.java │ ├── ch5_07_UVa10229.java │ └── ch5_07_UVa10229.cpp ├── sample_input.cpp ├── ch3-Problem_Solving_Methods │ ├── ch3_08_UVa674.cpp │ ├── ch3_10_UVa10003.cpp │ ├── ch3_05_UVa231.cpp │ ├── ch3_08_UVa674.java │ ├── ch3_10_UVa10003.java │ ├── ch3_11_UVa10943.java │ ├── ch3_06_UVa108.java │ ├── ch3_07_UVa10130.java │ ├── ch3_05_UVa231.java │ ├── ch3_03_UVa11450_td.cpp │ ├── ch3_09_UVa10496.cpp │ ├── ch3_01_UVa750.cpp │ ├── ch3_11_UVa10943.cpp │ ├── ch3_04_UVa11450_bu.java │ ├── ch3_03_UVa11450_td.java │ ├── ch3_01_UVa750.java │ ├── ch3_09_UVa10496.java │ └── ch3_07_UVa10130.cpp ├── insertionSort.cpp ├── ch2-Data_Structures │ ├── ch2_01_staticarray_stl_vector.cpp │ ├── ch2_01_staticarray_Vector.java │ ├── ch2_02_Collections.java │ ├── ch2_03_Stack_Queue.java │ ├── ch2_03_stl_stack_queue.cpp │ ├── ch2_08_unionfind_ds.java │ ├── ch2_06_stl_priority_queue.cpp │ ├── ch2_08_unionfind_ds.cpp │ ├── ch2_10_fenwicktree_ds.cpp │ ├── ch2_05_stl_map_set.cpp │ ├── ch2_06_PriorityQueue.java │ ├── ch2_10_fenwicktree_ds.java │ ├── ch2_05_TreeMap_TreeSet.java │ └── ch2_07_graph_ds.cpp ├── ch8-Advanced │ ├── ch8_04_LA4106.cpp │ ├── ch8_03_UVa10911.cpp │ └── ch8_03_UVa10911.java ├── ch6-String_Processing │ ├── ch6_02_str_align.cpp │ ├── ch6_02_str_align.java │ ├── ch6_01_kmp.cpp │ └── ch6_01_kmp.java ├── ch7-Computational_Geometry │ ├── ch7_04_UVa11817.cpp │ ├── ch7_04_UVa11817.java │ └── ch7_02_circles.cpp ├── test-compgeo.cpp ├── string_tokenizer.cc ├── priority_queue.cc ├── next_permutation.cc └── competition.h ├── EligibilityDecisionTree-2011.pdf ├── Algorithms for ICPC (espanol).pdf ├── 4P03Week5 - Ranking,Unranking,LexNext.doc ├── arithmetic ├── fast_exp_mod.c ├── fast_exp.c ├── solve_quad.c ├── simpsons.c ├── solve_cubic.c ├── discrete_log.cc └── t_func.c └── java └── io.java /solved/problem-set-volumes/10/10140-Prime_Distance/test.dat: -------------------------------------------------------------------------------- 1 | 1 2 2 | -------------------------------------------------------------------------------- /tryouts/2011/bh08ti/1226/in1226.dat: -------------------------------------------------------------------------------- 1 | 2 2 | 4 3 | 11 4 | 5 5 | 111 6 | -------------------------------------------------------------------------------- /solved/contest-volumes/ECNA2012-practice/B/B.in: -------------------------------------------------------------------------------- 1 | 51 2 | 8 3 | 52 4 | 3 5 | 0 6 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/10140.dat: -------------------------------------------------------------------------------- 1 | 2 17 2 | 14 17 3 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2011/practice-set/C.in: -------------------------------------------------------------------------------- 1 | 2 2 | ab.d.P..n.dd 3 | hrWHhrWHhrWH 4 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/01/100-3n+1/100.dat: -------------------------------------------------------------------------------- 1 | 1 10 2 | 100 200 3 | 201 210 4 | 900 1000 5 | -------------------------------------------------------------------------------- /tryouts/2012/441.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/tryouts/2012/441.pdf -------------------------------------------------------------------------------- /solved/problem-set-volumes/02/200-Rare_Order/200.dat: -------------------------------------------------------------------------------- 1 | XWY 2 | ZX 3 | ZXY 4 | ZXW 5 | YWWX 6 | # 7 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/04/441-Lotto/441.dat: -------------------------------------------------------------------------------- 1 | 7 1 2 3 4 5 6 7 2 | 8 1 2 3 5 8 13 21 34 3 | 0 4 | -------------------------------------------------------------------------------- /tryouts/2012/10140.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/tryouts/2012/10140.pdf -------------------------------------------------------------------------------- /tryouts/2012/1124.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/tryouts/2012/1124.pdf -------------------------------------------------------------------------------- /tryouts/2012/1215.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/tryouts/2012/1215.pdf -------------------------------------------------------------------------------- /tryouts/2012/1260.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/tryouts/2012/1260.pdf -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1226-Numerical_Surprises/1226.dat: -------------------------------------------------------------------------------- 1 | 2 2 | 4 3 | 11 4 | 5 5 | 111 6 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1203-Argus/1203.dat: -------------------------------------------------------------------------------- 1 | Register 2004 200 2 | Register 2005 300 3 | # 4 | 5 5 | -------------------------------------------------------------------------------- /resources/ACM-2011-Waterloo.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/ACM-2011-Waterloo.pdf -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1215-String_Cutting/1215.dat: -------------------------------------------------------------------------------- 1 | 2 2 | 3 3 | 5 3 6 4 | ababccd 5 | 2 6 | 4 2 7 | ababcd 8 | -------------------------------------------------------------------------------- /resources/Dynamic Programming.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/Dynamic Programming.pdf -------------------------------------------------------------------------------- /solved/contest-volumes/C/10008.dat: -------------------------------------------------------------------------------- 1 | 3 2 | This is a test. 3 | Count me 1 2 3 4 5. 4 | Wow!!!! Is this question easy? 5 | -------------------------------------------------------------------------------- /resources/common_graph_algorithms.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/common_graph_algorithms.pdf -------------------------------------------------------------------------------- /resources/programming_challenges.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/programming_challenges.pdf -------------------------------------------------------------------------------- /solved/contest-volumes/C/10050.dat: -------------------------------------------------------------------------------- 1 | 2 2 | 14 3 | 3 4 | 3 5 | 4 6 | 8 7 | 100 8 | 4 9 | 12 10 | 15 11 | 25 12 | 40 13 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1260-Sales/1260.dat: -------------------------------------------------------------------------------- 1 | 2 2 | 5 3 | 38 111 102 111 177 4 | 8 5 | 276 284 103 439 452 276 452 398 6 | -------------------------------------------------------------------------------- /practice-problems/GreaterNewYork2009/A/a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/practice-problems/GreaterNewYork2009/A/a -------------------------------------------------------------------------------- /resources/c++_and_stl/cpp_tutorial.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/c++_and_stl/cpp_tutorial.pdf -------------------------------------------------------------------------------- /resources/c++_and_stl/snu_cheatsheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/c++_and_stl/snu_cheatsheet.pdf -------------------------------------------------------------------------------- /practice-problems/ECNA-2011/practice-set/C: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/practice-problems/ECNA-2011/practice-set/C -------------------------------------------------------------------------------- /resources/EligibilityDecisionTree-2011.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/EligibilityDecisionTree-2011.pdf -------------------------------------------------------------------------------- /resources/c++_and_stl/ch1-Intro/ch1_02_scanf_input.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 0.1227... 3 | 0.517611738... 4 | 0.7341231223444344389923899277... 5 | -------------------------------------------------------------------------------- /resources/Algorithms for ICPC (espanol).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/Algorithms for ICPC (espanol).pdf -------------------------------------------------------------------------------- /resources/c++_and_stl/bitwise operations.odt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/c++_and_stl/bitwise operations.odt -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/problem-set-2010.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/practice-problems/ECNA-2010/problem-set-2010.pdf -------------------------------------------------------------------------------- /practice-problems/GreaterNewYork2009/problems.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/practice-problems/GreaterNewYork2009/problems.zip -------------------------------------------------------------------------------- /resources/c++_and_stl/stanford_cheatsheet_2012.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/c++_and_stl/stanford_cheatsheet_2012.pdf -------------------------------------------------------------------------------- /practice-problems/ACM2008 WorldFinalsProblemSet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/practice-problems/ACM2008 WorldFinalsProblemSet.pdf -------------------------------------------------------------------------------- /resources/4P03Week5 - Ranking,Unranking,LexNext.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/resources/4P03Week5 - Ranking,Unranking,LexNext.doc -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/A: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/solved/problem-set-volumes/10/10140-Prime_Distance/A -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/test: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/solved/problem-set-volumes/10/10140-Prime_Distance/test -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/tmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/solved/problem-set-volumes/10/10140-Prime_Distance/tmp -------------------------------------------------------------------------------- /practice-problems/ACM_ICPC_2009-South_America(North).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/practice-problems/ACM_ICPC_2009-South_America(North).pdf -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/10140: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BrockCSC/acm-icpc/HEAD/solved/problem-set-volumes/10/10140-Prime_Distance/10140 -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/A.dat: -------------------------------------------------------------------------------- 1 | 1 100 2 | 1000000000 1001000000 3 | 1000000000 1000000008 4 | 2147483587 2147483647 5 | 2147481000 2147483646 6 | 1 2 7 | 2 3 8 | -------------------------------------------------------------------------------- /practice-problems/GreaterNewYork2009/A/a.dat: -------------------------------------------------------------------------------- 1 | 4 2 | 1 1 2 3 4 5 6 7 8 9 1000 3 | 2 338 304 619 95 343 496 489 116 98 127 4 | 3 931 240 986 894 826 640 965 833 136 138 5 | 4 940 955 364 188 133 254 501 122 768 408 6 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/11/1124-Celebrity_Jeopardy/1124.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | main() 4 | { 5 | std::string line; 6 | while(getline(std::cin, line)) std::cout << line << std::endl; 7 | } 8 | -------------------------------------------------------------------------------- /tryouts/2011/jt11li/Node.java: -------------------------------------------------------------------------------- 1 | public class Node 2 | { 3 | public int number, colorCost; 4 | public Node fatherNode; 5 | public Node[] childNodes; 6 | //this is if they have all son nodes are colored 7 | public boolean isActive = true, isColored = false; 8 | } -------------------------------------------------------------------------------- /solved/contest-volumes/ECNA2012-practice/C/C.in: -------------------------------------------------------------------------------- 1 | 8 2 | Ford 61 3 | Depp 69 4 | DiCaprio 63 5 | Hanks 71 6 | Pitt 70 7 | Statham 62 8 | Smith 72 9 | Chan 67 10 | 4 11 | Nicholson 70 12 | Willis 64 13 | Crowe 66 14 | McGregor 68 15 | 3 16 | Bale 50 17 | Stallone 56 18 | Freeman 59 19 | 0 20 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/11/1124-Celebrity_Jeopardy/Main.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Main 4 | { 5 | public static void main(String[] args) 6 | { 7 | Scanner in = new Scanner(System.in); 8 | while (in.hasNext()) 9 | { 10 | String line = in.nextLine(); 11 | System.out.println(line); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/D/outD.dat: -------------------------------------------------------------------------------- 1 | Case 1: 2 2 | Case 2: 3 3 | Case 3: 1 4 | Case 4: 2 5 | Case 5: 6 6 | Case 6: 4 7 | Case 7: 3 8 | Case 8: 7 9 | Case 9: 6 10 | Case 10: 6 11 | Case 11: 10 12 | Case 12: 3 13 | Case 13: 1 14 | Case 14: 7 15 | Case 15: 7 16 | Case 16: 5 17 | Case 17: 6 18 | Case 18: 5 19 | Case 19: 4 20 | Case 20: 3 21 | Case 21: 3 22 | Case 22: 3 23 | Case 23: 2 24 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/07/740-Baudot_Data_Communication_Code/740.dat: -------------------------------------------------------------------------------- 1 | 5@9 %,.+)4&80:;3"$?#6!/-2' 71( 3 | 100100110011000010011111101110000111110111101 4 | 001100001101111001001111100001001100010001100110111100000111 5 | 100100110011000010011111101110000111110111101 6 | 001100001101111001001111100001001100010001100110111100000111 7 | 111110000000100110101101111100 8 | 1100101001010110100110101101 9 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/A.diff: -------------------------------------------------------------------------------- 1 | 2,3 are closest, 89,97 are most distant. 2 | 1000000007,1000000009 are closest, 1000097621,1000097797 are most distant. 3 | There are no adjacent primes. 4 | 2147483629,2147483647 are closest, 2147483587,2147483629 are most distant. 5 | 2147481899,2147481901 are closest, 2147481673,2147481793 are most distant. 6 | There are no adjacent primes. 7 | 2,3 are closest, 2,3 are most distant. 8 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/03/386-Perfect_Cubes/386.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | for(int a=6; a <= 200; a++) 7 | for(int b=2; b < a; b++) // must be greater than 1, thus start at 2 8 | for(int c=b; c < a; c++) 9 | for(int d=c; d < a; d++) 10 | if( (a*a*a) == (b*b*b) + (c*c*c) + (d*d*d) ) 11 | cout << "Cube = " << a << ", Triple = (" << b << "," << c << "," << d << ")" << endl; 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch1-Intro/ch1_01_factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.math.BigInteger; 3 | 4 | class Main { // standard Java class name in UVa OJ 5 | public static void main(String[] args) { 6 | BigInteger fac = BigInteger.ONE; // :) 7 | for (int i = 2; i <= 25; i++) 8 | fac = fac.multiply(BigInteger.valueOf(i)); // wow :) 9 | System.out.println(fac); 10 | } } 11 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/IntegerPair.java: -------------------------------------------------------------------------------- 1 | class IntegerPair implements Comparable { 2 | Integer _first, _second; 3 | 4 | public IntegerPair(Integer f, Integer s) { 5 | _first = f; 6 | _second = s; 7 | } 8 | 9 | public int compareTo(Object o) { 10 | if (this.first() != ((IntegerPair )o).first()) 11 | return this.first() - ((IntegerPair )o).first(); 12 | else 13 | return this.second() - ((IntegerPair )o).second(); 14 | } 15 | 16 | Integer first() { return _first; } 17 | Integer second() { return _second; } 18 | } 19 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/out.c: -------------------------------------------------------------------------------- 1 | #include 2 | main() 3 | { 4 | printf("2,3 are closest, 89,97 are most distant.\n" 5 | "1000000007,1000000009 are closest, 1000097621,1000097797 are most distant.\n" 6 | "There are no adjacent primes.\n" 7 | "2147483629,2147483647 are closest, 2147483587,2147483629 are most distant.\n" 8 | "2147481899,2147481901 are closest, 2147481673,2147481793 are most distant.\n" 9 | "There are no adjacent primes.\n" 10 | "2,3 are closest, 2,3 are most distant.\n"); 11 | } 12 | -------------------------------------------------------------------------------- /practice-problems/GreaterNewYork2009/A/a.cpp: -------------------------------------------------------------------------------- 1 | // http://www.acmgnyr.org/year2009/problems.shtml 2 | // Nth largest value 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | #define REP(i,a) for(i=0;i> p; 12 | int setNum; // dataset number 13 | int dataSet[p]; 14 | int i; 15 | REP(i,p) 16 | { 17 | cin >> setNum; 18 | int j; 19 | REP(j,10) 20 | { 21 | cin >> dataSet[j]; 22 | } 23 | sort(dataSet, dataSet+10); 24 | cout << setNum << " " << dataSet[7] << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_03_UVa1230_LA4104.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.math.BigInteger; 3 | 4 | class Main { /* LA 4104 - MODEX */ 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | int c = sc.nextInt(); 8 | while (c-- > 0) { 9 | BigInteger x = BigInteger.valueOf(sc.nextInt()); // valueOf converts 10 | BigInteger y = BigInteger.valueOf(sc.nextInt()); // simple integer 11 | BigInteger n = BigInteger.valueOf(sc.nextInt()); // into BigInteger 12 | System.out.println(x.modPow(y, n)); // look ma, it's in the library ;) 13 | } } } 14 | -------------------------------------------------------------------------------- /tryouts/2011/bh08ti/1226/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | 7 | public class Main { 8 | public Main () { 9 | 10 | } 11 | 12 | 13 | public void work (){ 14 | Scanner scan = new Scanner(System.in); 15 | 16 | int numCases = scan.nextInt(); 17 | BigInteger P; 18 | BigInteger N; 19 | 20 | for (int i = numCases; i > 0 ;i--) { 21 | N = scan.nextBigInteger(); 22 | P = scan.nextBigInteger(); 23 | 24 | System.out.println(P.mod(N)); 25 | } 26 | 27 | scan.close(); 28 | 29 | } 30 | 31 | public static void main(String[] args) { new Main().work(); } 32 | } 33 | -------------------------------------------------------------------------------- /tryouts/2011/bh08ti/1205/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | 7 | public class Main { 8 | public Main () { 9 | 10 | } 11 | 12 | public void work (){ 13 | int N; 14 | int R; 15 | int tree[]; 16 | 17 | Scanner scan = new Scanner(System.in); 18 | 19 | N = scan.nextInt(); 20 | R = scan.nextInt(); 21 | 22 | tree = new int[N]; 23 | for (int i = 0; i 6 | #include 7 | using namespace std; 8 | 9 | int main(void) 10 | { 11 | 12 | /* sample input/output for subtracting the higher number with the lower number and outputting the result */ 13 | /* 14 | long long a,b,c; 15 | 16 | while(cin >> a >> b) 17 | { 18 | if(b > a) c = b-a; 19 | else c = a-b; 20 | cout << c << endl; 21 | } 22 | */ 23 | 24 | /* prints out the input you feed it */ 25 | string str; 26 | 27 | while(cin >> str) 28 | { 29 | cout << str << endl; 30 | } 31 | 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_02_UVa10814.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | import java.math.BigInteger; 3 | 4 | class Main { /* UVa 10814 - Simplifying Fractions */ 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | int N = sc.nextInt(); 8 | while (N-- > 0) { // unlike in C/C++, we have to supply > 0 in (N-- > 0) 9 | BigInteger p = sc.nextBigInteger(); 10 | String ch = sc.next(); // we ignore the division sign in input 11 | BigInteger q = sc.nextBigInteger(); 12 | BigInteger gcd_pq = p.gcd(q); // wow :) 13 | System.out.println(p.divide(gcd_pq) + " / " + q.divide(gcd_pq)); 14 | } } } 15 | -------------------------------------------------------------------------------- /tryouts/2011/km07ok/Main.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.lang.*; 3 | import java.math.BigInteger; 4 | import java.util.Scanner; 5 | 6 | public class Main { 7 | 8 | public Main(){ 9 | Scanner in = new Scanner(System.in); 10 | int times = in.nextInt(); 11 | for(int i = 0; i < times; i++){ 12 | BigInteger N = in.nextBigInteger(); 13 | BigInteger P = in.nextBigInteger(); 14 | System.out.println(P.mod(N)); 15 | } 16 | } 17 | 18 | public static void main(String[] args){ 19 | new Main(); 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch1-Intro/ch1_02_scanf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int N; // using global variables in contests can be a good strategy 5 | char x[110]; // make it a habit to set array size slightly larger than needed 6 | 7 | int main() { 8 | freopen("ch1_02_scanf_input.txt", "r", stdin); 9 | 10 | scanf("%d\n", &N); 11 | while (N--) { // we simply loop from N, N-1, N-2, ... 0 12 | scanf("0.%[0-9]...\n", &x); // if you are surprised with this line, 13 | // check scanf details in www.cppreference.com 14 | printf("the digits are 0.%s\n", x); 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1260-Sales/1260.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | main() 5 | { 6 | int T; 7 | cin >> T; 8 | for (int t = 0; t < T; ++t) // for each test case 9 | { 10 | int n; 11 | cin >> n; 12 | vector A; 13 | vector B; 14 | for (int i = 0; i < n; ++i) // for each daily sale 15 | { 16 | int sale; 17 | cin >> sale; 18 | A.push_back(sale); 19 | } 20 | // calculate B list 21 | int b = 0; 22 | if (A.size() > 1) for (int i = 1; i < A.size(); ++i) 23 | { 24 | for (int j = 0; j < i; ++j) 25 | { 26 | if (A[j] <= A[i]) b++; 27 | } 28 | } 29 | cout << b << endl; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /resources/arithmetic/fast_exp_mod.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Fast Exponentiation mod m 3 | * 4 | * Author: Howard Cheng 5 | * 6 | * Given b, n, and m, computes b^n mod m quickly. 7 | * 8 | */ 9 | 10 | #include 11 | #include 12 | 13 | int fast_exp(int b, int n, int m) 14 | { 15 | int res = 1; 16 | int x = b; 17 | 18 | while (n > 0) { 19 | if (n & 0x01) { 20 | n--; 21 | res = (res * x) % m; 22 | } else { 23 | n >>= 1; 24 | x = (x * x) % m; 25 | } 26 | } 27 | 28 | return res; 29 | } 30 | 31 | int main(void) 32 | { 33 | int b, n, m; 34 | 35 | while (scanf("%d %d %d", &b, &n, &m) == 3) { 36 | printf("%d^%d mod %d = %d\n", b, n, m, fast_exp(b, n, m)); 37 | } 38 | return 0; 39 | 40 | } 41 | -------------------------------------------------------------------------------- /solved/contest-volumes/ECNA2012-practice/B/README.md: -------------------------------------------------------------------------------- 1 | B - It All Adds Up 2 | ================== 3 | 4 | **Note:** This solution has not been submitted, so it's not guaranteed to be an "Accepted Answer". 5 | 6 | Plan of attack: 7 | 8 | Brute force it with some slight optimizations. 9 | Use a "two finger" scan. Don't need to scan the whole range 10 | because there is a threshold where the sum will always exceed 11 | *n*. While the first finger is on the starting point, the second 12 | finger starts sequentially adding the remaining integers 13 | while the sum is still less than *n*. If the sum equals *n*, 14 | a valid partition has been found so we can advance the first 15 | finger. If the counting sum exceeds *n*, we also advance the 16 | first finger. 17 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_08_UVa674.cpp: -------------------------------------------------------------------------------- 1 | /* Coin Change */ 2 | 3 | // O(NV) DP solution 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | int N = 5, V, coinValue[5] = {1, 5, 10, 25, 50}, memo[6][7500]; 10 | // N and coinValue are fixed for this problem, max V is 7489 11 | 12 | int ways(int type, int value) { 13 | if (value == 0) return 1; 14 | if (value < 0 || type == N) return 0; 15 | if (memo[type][value] != -1) return memo[type][value]; 16 | return memo[type][value] = ways(type + 1, value) + ways(type, value - coinValue[type]); 17 | } 18 | 19 | int main() { 20 | memset(memo, -1, sizeof memo); // we only need to initialize this once 21 | while (scanf("%d", &V) != EOF) 22 | printf("%d\n", ways(0, V)); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /resources/c++_and_stl/insertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define ELEMENTS 6 5 | 6 | void insertion_sort(int x[], int length) 7 | { 8 | int key, i, j; 9 | for(j=1; j < length; j++) 10 | { 11 | key = x[j]; 12 | i = j-1; 13 | while(x[i] > key && i >= 0) // if the next element is smaller 14 | { 15 | x[i+1] = x[i]; // move larger element up 16 | i--; 17 | } 18 | x[i+1] = key; 19 | } 20 | } 21 | 22 | int main() 23 | { 24 | int A[ELEMENTS]={5,2,4,6,1,3}; 25 | int i; 26 | 27 | cout << "NON SORTED LIST:" << endl; 28 | for(i=0; i < ELEMENTS; i++) 29 | cout << A[i] << " "; 30 | 31 | insertion_sort(A,ELEMENTS); 32 | 33 | cout << "\n\nSORTED LIST" << endl; 34 | for(i=0; i < ELEMENTS; i++) 35 | cout << A[i] << " "; 36 | cout << endl; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/H/outH.dat: -------------------------------------------------------------------------------- 1 | Case 1: 4 3 2 2 | Case 2: 1 12 2 3 3 | Case 3: No 4 | Case 4: 2 7 4 6 5 | Case 5: 1 2 1 1 6 | Case 6: 1 5 4 3 7 | Case 7: 1 2 2 1 8 | Case 8: 1 2 2 1 9 | Case 9: 2 2 1 1 1 2 1 10 | Case 10: 5 4 25 4 13 15 11 | Case 11: 2 5 3 15 2 2 10 10 12 | Case 12: No 13 | Case 13: No 14 | Case 14: 18156 6593 20292 15 | Case 15: 20292 6593 18156 16 | Case 16: No 17 | Case 17: 1 1 1 1 18 | Case 18: 2 8 40 2 1 5 19 | Case 19: No 20 | Case 20: 11 12 200 29 11 1 21 | Case 21: 1 11 12 29 200 11 22 | Case 22: 1 1 23 | Case 23: 2 1 24 | Case 24: No 25 | Case 25: No 26 | Case 26: No 27 | Case 27: 2 2 1 1 28 | Case 28: No 29 | Case 29: No 30 | Case 30: No 31 | Case 31: 9 1 1 1 1 1 1 1 1 1 9 1 1 1 1 1 1 1 1 1 32 | Case 32: 76 175 116 90 90 58 44 3 2 33 | Case 33: 131 171 59 146 60 11 2 3 34 | Case 34: 65 195 132 78 5 1 35 | Case 35: 23 33 13 14 25 25 20 13 4 1 36 | Case 36: 39 6 2 12 3 5 3 2 37 | -------------------------------------------------------------------------------- /solved/contest-volumes/ECNA2012-practice/B/B.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | main() 7 | { 8 | unsigned n; // max 100,000 9 | unsigned tc = 0; 10 | vector v; 11 | vector< vector< int > > partitions; 12 | while (cin >> n) 13 | { 14 | if (n == 0) break; 15 | int m = 0; 16 | for (int i = 1; i < (n/2)+1; ++i) 17 | { 18 | int sum = 0; 19 | v.clear(); 20 | for (int j = i; sum < n; ++j) 21 | { 22 | sum += j; 23 | v.push_back(j); 24 | if (sum == n) 25 | { 26 | m++; 27 | partitions.push_back(v); 28 | break; 29 | } 30 | } 31 | } 32 | cout << "Case " << ++tc << ": " << m << endl; 33 | for (int i = 0; i < m; ++i) 34 | cout << partitions[i][0] << " " << partitions[i][partitions[i].size()-1] << endl; 35 | partitions.clear(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_01_staticarray_stl_vector.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main() { 6 | int arr[5] = {7,7,7}; // initial size (5) and initial value {7,7,7,0,0} 7 | vector v(5, 5); // initial size (5) and initial value {5,5,5,5,5} 8 | 9 | printf("arr[2] = %d and v[2] = %d\n", arr[2], v[2]); // 7 and 5 10 | 11 | for (int i = 0; i < 5; i++) { 12 | arr[i] = i; 13 | v[i] = i; 14 | } 15 | 16 | printf("arr[2] = %d and v[2] = %d\n", arr[2], v[2]); // 2 and 2 17 | 18 | // arr[5] = 5; // static array will generate index out of bound error 19 | // uncomment the line above to see the error 20 | 21 | v.push_back(5); // but vector will resize itself 22 | printf("v[5] = %d\n", v[5]); // 5 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /resources/java/io.java: -------------------------------------------------------------------------------- 1 | // Basic input & output with the Scanner class. 2 | // You may also use the BufferedReader class, but it's more complicated. 3 | 4 | import java.util.Scanner; 5 | 6 | public class Main // Source file must contain a class named 'Main' 7 | { 8 | public static void main(String[] args) 9 | { 10 | Scanner in = new Scanner(System.in); // Read from System.in 11 | 12 | while (in.hasNext()) 13 | { 14 | int i = in.nextInt(); 15 | double d = in.nextDouble(); 16 | String s = in.next(); 17 | char c = s.charAt(2); // There is no nextChar(). Use next() and charAt(). 18 | String line = in.nextLine(); // Read whole line (or rest of the line past '\n') 19 | 20 | // Use print(), println(), or printf() for output. 21 | System.out.println(i + " " + d + " " + s " " + " " + c + " " + line); 22 | System.out.printf("%4d, %6.2f, %s, %c\n", i, d, s, c); // Don't forget '\n' 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /solved/contest-volumes/ECNA2012-practice/C/README.md: -------------------------------------------------------------------------------- 1 | C - You've Got Nothing to Hit but the Heights 2 | ============================================= 3 | 4 | **Note:** This solution has not been submitted, 5 | so it's not guaranteed to be an "Accepted Answer". 6 | 7 | Plan of attack: 8 | 9 | We want a list of actors so we can sort them in descending order. 10 | To do so, you'll need an Actor class/struct. Once the list of 11 | actors has been sorted, use a "two finger" scan to find a 12 | potential cast. The first finger points at the potential father, 13 | while the second finger is used to find a potential son and 14 | grandson. We know the required heights, so we first search for a 15 | an actor that matches the height of the son role. Once he's been 16 | found, we search for an actor that matches the height of the 17 | grandson role. If all roles have been filled, we can print the 18 | cast. In either case, we advance the search for a new cast 19 | by moving the first finger to the next potential father. 20 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1226-Numerical_Surprises/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 1226 - Numerical Surprises 3 | * Simple modulus that requires BigInt 4 | * @author Dennis Ideler 5 | * javac Main.java && java Main < 1226.dat 6 | */ 7 | 8 | import java.util.Scanner; 9 | import java.math.BigInteger; 10 | 11 | class Main 12 | { 13 | public static void main(String[] args) 14 | { 15 | Scanner in = new Scanner(System.in); 16 | 17 | int cases = in.nextInt(); // read # of test cases 18 | 19 | for (int i = 0; i < cases; ++i) 20 | { 21 | // String n_str = in.next(); // read n 22 | // String p_str = in.next(); // read p 23 | // BigInteger n = new BigInteger(n_str); // convert to bigint 24 | // BigInteger p = new BigInteger(p_str); // convert to bigint 25 | BigInteger n = new BigInteger.valueOf(in.nextInt()); // read and convert n 26 | BigInteger p = new BigInteger.valueOf(in.nextInt()); // read and convert p 27 | 28 | System.out.println(p.mod(n)); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_10_UVa10003.cpp: -------------------------------------------------------------------------------- 1 | /* Cutting Sticks */ 2 | 3 | // Top-Down DP 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int arr[55], memo[55][55]; 11 | 12 | int cut(int left, int right) { 13 | if (left + 1 == right) return 0; 14 | if (memo[left][right] != -1) return memo[left][right]; 15 | 16 | int ans = 2000000000; 17 | for (int i = left + 1; i < right; i++) 18 | ans = min(ans, cut(left, i) + cut(i, right) + (arr[right] - arr[left])); 19 | return memo[left][right] = ans; 20 | } 21 | 22 | int main() { 23 | int l, n; 24 | 25 | while (scanf("%d", &l), l) { 26 | arr[0] = 0; 27 | scanf("%d", &n); 28 | for (int i = 1; i <= n; i++) 29 | scanf("%d", &arr[i]); 30 | arr[n + 1] = l; 31 | 32 | memset(memo, -1, sizeof memo); 33 | printf("The minimum cutting is %d.\n", cut(0, n + 1)); // start with left = 0 and right = n + 1 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_05_UVa231.cpp: -------------------------------------------------------------------------------- 1 | /* What Goes Up */ 2 | 3 | // O(n log k) LNIS DP (longest NON-increasing sequence) 4 | 5 | #include 6 | #include 7 | #include // greater() is here 8 | using namespace std; 9 | 10 | #define MAX_N 200000 11 | 12 | int main() { 13 | int i, lnis, n, X[MAX_N], A[MAX_N], caseNo = 1; 14 | bool first = true; 15 | 16 | while (1) { 17 | for (n = 0; scanf("%d", &X[n]), X[n] != -1; n++); // read this test case 18 | if (X[0] == -1) break; // end of input 19 | 20 | // O(n log k) algorithm 21 | for (A[0] = X[0], i = lnis = 1; i < n; i++) { // O(n) 22 | int *l = upper_bound(A, A + lnis, X[i], greater()); // find insertion point, O(log k) 23 | lnis = max(lnis, (int)(l - A) + 1); 24 | *l = X[i]; 25 | } 26 | 27 | if (!first) printf("\n"); 28 | first = false; 29 | printf("Test #%d:\n", caseNo++); 30 | printf(" maximum possible interceptions: %d\n", lnis); 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /solved/contest-volumes/C/10050.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(void) 5 | { 6 | int t; // number of test cases 7 | int n; // number of days (7 <= n <= 3650) 8 | int p; // number of political parties (1 <= p <= 100) 9 | int hi; // hartel parameter 10 | int strikedays; 11 | int * harteldays; // days of strike (Fri and Sat not included) 12 | 13 | cin >> t; 14 | if (t <= 0) exit(0); 15 | 16 | for (int i = 0; i < t; i++) 17 | { 18 | cin >> n; 19 | cin >> p; 20 | harteldays = new int[n]; 21 | for (int j = 0; j < p; j++) 22 | { 23 | cin >> hi; 24 | for (int k = 0; k < n; k++) 25 | { 26 | if ((k+1) % hi == 0) 27 | { 28 | if ((k+1) % 7 != 0 && (k+2) % 7 != 0) 29 | harteldays[k] = 1; 30 | else 31 | harteldays[k] = 0; 32 | } 33 | } 34 | } 35 | strikedays = 0; 36 | for (int l = 0; l < n; l++) 37 | strikedays += harteldays[l]; 38 | cout << strikedays << endl; 39 | } 40 | return(0); 41 | } 42 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_01_UVa10925.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; // Scanner class is inside package java.util 2 | import java.math.BigInteger; // BigInteger class is inside package java.math 3 | 4 | class Main { /* UVa 10925 - Krakovia */ 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | int caseNo = 1; 8 | while (true) { 9 | int N = sc.nextInt(), F = sc.nextInt(); // N bills, F friends 10 | if (N == 0 && F == 0) break; 11 | BigInteger sum = BigInteger.ZERO; // BigInteger has this constant ZERO 12 | for (int i = 0; i < N; i++) { // sum the N large bills 13 | BigInteger V = sc.nextBigInteger(); // for reading next BigInteger! 14 | sum = sum.add(V); // this is BigInteger addition 15 | } 16 | System.out.println("Bill #" + (caseNo++) + " costs " + 17 | sum + ": each friend should pay " + sum.divide(BigInteger.valueOf(F))); 18 | System.out.println(); // the line above is BigInteger division 19 | } } } // divide the large sum to F friends 20 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_08_UVa674.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* Coin Change */ 4 | // O(NV) DP solution 5 | 6 | // N and coinValue are fixed for this problem, max V is 7489 7 | private static int N = 5, V; 8 | private static int[] coinValue = new int[] {1, 5, 10, 25, 50}; 9 | private static int[][] memo = new int[6][7500]; 10 | 11 | private static int ways(int type, int value) { 12 | if (value == 0) return 1; 13 | if (value < 0 || type == N) return 0; 14 | if (memo[type][value] != -1) return memo[type][value]; 15 | return memo[type][value] = ways(type + 1, value) + ways(type, value - coinValue[type]); 16 | } 17 | 18 | public static void main(String[] args) { 19 | Scanner sc = new Scanner(System.in); 20 | 21 | for (int i = 0; i < 6; i++) 22 | for (int j = 0; j < 7500; j++) 23 | memo[i][j] = -1; // we only need to initialize this once 24 | 25 | while (sc.hasNext()) { 26 | V = sc.nextInt(); 27 | System.out.printf("%d\n", ways(0, V)); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_01_staticarray_Vector.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch2_01_staticarray_Vector { 4 | public static void main(String[] args) { 5 | // initial value {7,7,7,0,0} and thus initial size (5) 6 | int[] arr = new int[] {7,7,7,0,0}; 7 | // initial size (5) and initial value {5,5,5,5,5} 8 | Vector v = new Vector(Collections.nCopies(5, 5)); 9 | 10 | // 7 and 5, for Java Vector, we must use 'get' 11 | System.out.println("arr[2] = " + arr[2] + " and v[2] = " + v.get(2)); 12 | 13 | for (int i = 0; i <= 4; i++) { 14 | arr[i] = i; 15 | v.set(i, i); // for Java Vector, we must use 'set' 16 | } 17 | 18 | // 2 and 2 19 | System.out.println("arr[2] = " + arr[2] + " and v[2] = " + v.get(2)); 20 | 21 | // arr[5] = 5; // static array will generate index out of bound error 22 | // uncomment the line above to see the error 23 | 24 | v.add(5); // but vector will resize itself (use method add in Java Vector) 25 | System.out.println("v[5] = " + v.get(5)); // 5 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /resources/arithmetic/fast_exp.c: -------------------------------------------------------------------------------- 1 | /* Arithmetic: Fast Exponentition 2 | ================================================================= 3 | Description: Given integer x and nonnegative number N, computes 4 | x^N quickly 5 | 6 | Complexity: O(lg N) 7 | ----------------------------------------------------------------- 8 | Author: Gilbert Lee 9 | Date: Sept 17, 2002 10 | References: 11 | ----------------------------------------------------------------- 12 | Reliability: 0 13 | Notes: x can be negative. 14 | N >= 0 otherwise routine will infinitely loop 15 | The limit for the results is: 16 | [-9223372036854775808 = -2^63, to 17 | +9223372036854775807 = +2^63 - 1] 18 | */ 19 | 20 | #include 21 | 22 | #define LL long long 23 | 24 | LL fast_exp(int b, int n){ 25 | LL res = 1, x = b, p; 26 | 27 | for(p = n; p; p >>= 1, x *= x) 28 | if(p & 1) res *= x; 29 | 30 | return res; 31 | } 32 | 33 | int main(){ 34 | int b, n; 35 | 36 | while(scanf("%d %d", &b, &n) == 2){ 37 | printf("%d^%d = %Ld\n", b, n, fast_exp(b,n)); 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_07_floyd_warshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define INF 1000000000 6 | 7 | int main() { 8 | int V, E, u, v, w, AdjMatrix[200][200]; 9 | 10 | /* 11 | // Graph in Figure 4.19 12 | 5 9 13 | 0 1 2 14 | 0 2 1 15 | 0 4 3 16 | 1 3 4 17 | 2 1 1 18 | 2 4 1 19 | 3 0 1 20 | 3 2 3 21 | 3 4 5 22 | */ 23 | 24 | scanf("%d %d", &V, &E); 25 | for (int i = 0; i < V; i++) { 26 | for (int j = 0; j < V; j++) 27 | AdjMatrix[i][j] = INF; 28 | AdjMatrix[i][i] = 0; 29 | } 30 | 31 | for (int i = 0; i < E; i++) { 32 | scanf("%d %d %d", &u, &v, &w); 33 | AdjMatrix[u][v] = w; // directed graph 34 | } 35 | 36 | for (int k = 0; k < V; k++) // common error: remember that loop order is k->i->j 37 | for (int i = 0; i < V; i++) 38 | for (int j = 0; j < V; j++) 39 | AdjMatrix[i][j] = min(AdjMatrix[i][j], AdjMatrix[i][k] + AdjMatrix[k][j]); 40 | 41 | for (int i = 0; i < V; i++) 42 | for (int j = 0; j < V; j++) 43 | printf("APSP(%d, %d) = %d\n", i, j, AdjMatrix[i][j]); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_06_UVa350.cpp: -------------------------------------------------------------------------------- 1 | /* Pseudo-Random Numbers */ 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | typedef pair ii; 8 | 9 | int caseNo = 1, Z, I, M, L; 10 | 11 | int f(int x) { return (Z * x + I) % M; } 12 | 13 | ii floydCycleFinding(int x0) { // function "int f(int x)" must be defined earlier 14 | // 1st part: finding v, hare's speed is 2x tortoise's 15 | int tortoise = f(x0), hare = f(f(x0)); // f(x0) is the element/node next to x0 16 | while (tortoise != hare) { tortoise = f(tortoise); hare = f(f(hare)); } 17 | // 2nd part: finding mu, hare and tortoise move at the same speed 18 | int mu = 0; hare = x0; 19 | while (tortoise != hare) { tortoise = f(tortoise); hare = f(hare); mu++; } 20 | // 3rd part: finding lambda, hare moves, tortoise stays 21 | int lambda = 1; hare = f(tortoise); 22 | while (tortoise != hare) { hare = f(hare); lambda++; } 23 | return ii(mu, lambda); 24 | } 25 | 26 | int main() { 27 | while (scanf("%d %d %d %d", &Z, &I, &M, &L), (Z || I || M || L)) { 28 | ii result = floydCycleFinding(L); 29 | printf("Case %d: %d\n", caseNo++, result.second); 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch8-Advanced/ch8_04_LA4106.cpp: -------------------------------------------------------------------------------- 1 | /* ACORN */ 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int main() { 9 | int i, j, c, t, h, f, a, n, acorn[2010][2010], dp[2010]; 10 | 11 | scanf("%d", &c); 12 | while (c--) { 13 | scanf("%d %d %d", &t, &h, &f); 14 | memset(acorn, 0, sizeof acorn); 15 | for (i = 0; i < t; i++) { 16 | scanf("%d", &a); 17 | for (j = 0; j < a; j++) { 18 | scanf("%d", &n); 19 | acorn[i][n]++; // there is an acorn here 20 | } 21 | } 22 | 23 | for (int tree = 0; tree < t; tree++) // initialization 24 | dp[h] = max(dp[h], acorn[tree][h]); 25 | for (int height = h - 1; height >= 0; height--) 26 | for (int tree = 0; tree < t; tree++) { 27 | acorn[tree][height] += 28 | max(acorn[tree][height + 1], // from this tree, +1 above 29 | ((height + f <= h) ? dp[height + f] : 0)); // best from tree at height + f 30 | dp[height] = max(dp[height], acorn[tree][height]); // update this too 31 | } 32 | printf("%d\n", dp[0]); // solution will be here 33 | } 34 | // ignore the last number 0 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch6-String_Processing/ch6_02_str_align.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | char A[20] = "ACAATCC", B[20] = "AGCATGC"; 8 | int n = (int)strlen(A), m = (int)strlen(B); 9 | int i, j, table[20][20]; // Needleman Wunsnch's algorithm 10 | 11 | memset(table, 0, sizeof table); 12 | // insert/delete = -1 point 13 | for (i = 1; i <= n; i++) 14 | table[i][0] = i * -1; 15 | for (j = 1; j <= m; j++) 16 | table[0][j] = j * -1; 17 | 18 | for (i = 1; i <= n; i++) 19 | for (j = 1; j <= m; j++) { 20 | // match = 2 points, mismatch = -1 point 21 | table[i][j] = table[i - 1][j - 1] + (A[i - 1] == B[j - 1] ? 2 : -1); // cost for match or mismatches 22 | // insert/delete = -1 point 23 | table[i][j] = max(table[i][j], table[i - 1][j] - 1); // delete 24 | table[i][j] = max(table[i][j], table[i][j - 1] - 1); // insert 25 | } 26 | 27 | printf("DP table:\n"); 28 | for (i = 0; i <= n; i++) { 29 | for (j = 0; j <= m; j++) 30 | printf("%3d", table[i][j]); 31 | printf("\n"); 32 | } 33 | printf("Maximum Alignment Score: %d\n", table[n][m]); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2011/practice-set/C-iter.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define FOR(i,a,b) for(int i=a;i> n; 11 | 12 | string line; 13 | FOR(i,0,n) // for each test case 14 | { 15 | cin >> line; 16 | int longest_interval = -1; 17 | string winning_birds = ""; 18 | FOR(j,0,line.size()) // for each sighting 19 | { 20 | char bird = line[j]; 21 | if (bird == '.') continue; 22 | FOR(k,j+1,line.size()) // search later sightings to calculate interval; 23 | { 24 | if (bird == line[k]) // if bird is sighted again, check interval 25 | { 26 | int interval = k - j; 27 | if (interval > longest_interval) // wipe previous winners, record new winner 28 | { 29 | winning_birds = bird; 30 | longest_interval = interval; 31 | } 32 | else if (interval == longest_interval) // add additional winning bird 33 | { 34 | winning_birds += bird; 35 | } 36 | break; // don't check any further 37 | } 38 | } 39 | } 40 | cout << winning_birds << ": " << longest_interval << endl; 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch6-String_Processing/ch6_02_str_align.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch6_02_str_align { 4 | public static void main(String[] args){ 5 | char[] A = "ACAATCC".toCharArray(), B = "AGCATGC".toCharArray(); 6 | int[][] table = new int[20][20]; // Needleman Wunsnch's algorithm 7 | int i, j, n = A.length, m = B.length; 8 | 9 | // insert/delete = -1 point 10 | for (i = 1; i <= n; i++) 11 | table[i][0] = i * -1; 12 | for (j = 1; j <= m; j++) 13 | table[0][j] = j * -1; 14 | 15 | for (i = 1; i <= n; i++) 16 | for (j = 1; j <= m; j++) { 17 | // match = 2 points, mismatch = -1 point 18 | table[i][j] = table[i - 1][j - 1] + (A[i - 1] == B[j - 1] ? 2 : -1); // cost for match or mismatches 19 | // insert/delete = -1 point 20 | table[i][j] = Math.max(table[i][j], table[i - 1][j] - 1); // delete 21 | table[i][j] = Math.max(table[i][j], table[i][j - 1] - 1); // insert 22 | } 23 | 24 | System.out.printf("DP table:\n"); 25 | for (i = 0; i <= n; i++) { 26 | for (j = 0; j <= m; j++) 27 | System.out.printf("%3d", table[i][j]); 28 | System.out.printf("\n"); 29 | } 30 | System.out.printf("Maximum Alignment Score: %d\n", table[n][m]); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_10_UVa10003.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* Cutting Sticks */ 4 | // Top-Down DP 5 | 6 | private static int[] arr = new int[55]; 7 | private static int[][] memo = new int[55][55]; 8 | 9 | private static int cut(int left, int right) { 10 | if (left + 1 == right) return 0; 11 | if (memo[left][right] != -1) return memo[left][right]; 12 | 13 | int ans = 2000000000; 14 | for (int i = left + 1; i < right; i++) 15 | ans = Math.min(ans, cut(left, i) + cut(i, right) + (arr[right] - arr[left])); 16 | return memo[left][right] = ans; 17 | } 18 | 19 | public static void main(String[] args) { 20 | Scanner sc = new Scanner(System.in); 21 | int i, j, l, n; 22 | 23 | while (true) { 24 | l = sc.nextInt(); 25 | if (l == 0) 26 | break; 27 | 28 | arr[0] = 0; 29 | n = sc.nextInt(); 30 | for (i = 1; i <= n; i++) 31 | arr[i] = sc.nextInt(); 32 | arr[n + 1] = l; 33 | 34 | for (i = 0; i < 55; i++) 35 | for (j = 0; j < 55; j++) 36 | memo[i][j] = -1; 37 | 38 | // start with left = 0 and right = n + 1 39 | System.out.printf("The minimum cutting is %d.\n", cut(0, n + 1)); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tryouts/2011/mc08il/1205.cpp: -------------------------------------------------------------------------------- 1 | using namespace std; 2 | #include 3 | #include 4 | 5 | int main(void) 6 | { 7 | int N,R; 8 | cin >>N; 9 | cin>>R; 10 | vector hold[N+1]; 11 | int i; 12 | for(i=1; i<=N;i++) 13 | { 14 | int x; 15 | cin >> x; 16 | hold[i].push_back(x); 17 | } 18 | for(i=0; i> x; 22 | cin >>y; 23 | hold[x].push_back(y); 24 | } 25 | 26 | vector temp; 27 | int c1=hold[R].at(0); 28 | int Fi=1; 29 | for(i=1; i 1, we can choose one number from [0..N] to be one of the number 16 | // and recursively compute the rest 17 | int total_ways = 0; 18 | for (int split = 0; split <= N; split++) 19 | total_ways = (total_ways + ways(N - split, K - 1)) % 1000000; // we just need the modulo 1M 20 | return memo[N][K] = total_ways; // memoize them 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner sc = new Scanner(System.in); 25 | 26 | for (int i = 0; i < 110; i++) 27 | for (int j = 0; j < 110; j++) 28 | memo[i][j] = -1; 29 | 30 | while (true) { 31 | N = sc.nextInt(); 32 | K = sc.nextInt(); 33 | if (N == 0 && K == 0) 34 | break; 35 | System.out.printf("%d\n", ways(N, K)); // some recursion formula + top down DP 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/01/100-3n+1/100.cpp: -------------------------------------------------------------------------------- 1 | /* problem #: 100 2 | * 3n+1 3 | * 4 | * for all the integers between i and j (i,j inclusive) 5 | * calculate the hillstone sequence and find the longest 6 | * sequence, keep track of its length. 7 | * 8 | * "All integers will be less than 1,000,000 and greater than 0" */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | int main() 14 | { 15 | int i, j, k, seqLength, maxLength, n, iCpy, jCpy; // seqLength is sequence length 16 | 17 | while (cin >> i) 18 | { 19 | cin >> j; 20 | maxLength = 0; // reset max length for every i,j-set 21 | 22 | // need to make sure it computes the sequences even if i and j are given in descending order 23 | if (i > j) 24 | { 25 | iCpy = j; 26 | jCpy = i; 27 | } 28 | else 29 | { 30 | iCpy = i; 31 | jCpy = j; 32 | } 33 | 34 | for (k = iCpy; k <= jCpy; k++) 35 | { 36 | n = k; // cannot use n in loop condition, since value of n changes here 37 | seqLength = 1; // integers are always greater than 0, thus start at 1 38 | 39 | while(n > 1) 40 | { 41 | if (n%2 == 0) n = n / 2; 42 | else n = n * 3 + 1; 43 | seqLength++; 44 | } 45 | 46 | if (seqLength > maxLength) maxLength = seqLength; 47 | } 48 | cout << i << " " << j << " " << maxLength << endl; 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_06_UVa350.java: -------------------------------------------------------------------------------- 1 | /* Pseudo-Random Numbers */ 2 | 3 | import java.util.*; 4 | 5 | class ch5_06_UVa530 { 6 | static int Z, I, M, L, mu, lambda; 7 | 8 | static int f(int x) { return (Z * x + I) % M; } 9 | 10 | static void floydCycleFinding(int x0) { // function "int f(int x)" must be defined earlier 11 | // 1st part: finding v, hare's speed is 2x tortoise's 12 | int tortoise = f(x0), hare = f(f(x0)); // f(x0) is the element/node next to x0 13 | while (tortoise != hare) { tortoise = f(tortoise); hare = f(f(hare)); } 14 | // 2nd part: finding mu, hare and tortoise move at the same speed 15 | mu = 0; hare = x0; 16 | while (tortoise != hare) { tortoise = f(tortoise); hare = f(hare); mu++; } 17 | // 3rd part: finding lambda, hare moves, tortoise stays 18 | lambda = 1; hare = f(tortoise); 19 | while (tortoise != hare) { hare = f(hare); lambda++; } 20 | } 21 | 22 | public static void main(String[] args) { 23 | Scanner scan = new Scanner(System.in); 24 | for (int caseNo = 1; ; caseNo++) { 25 | Z = scan.nextInt(); 26 | I = scan.nextInt(); 27 | M = scan.nextInt(); 28 | L = scan.nextInt(); 29 | if (Z==0 && I==0 && M==0 && L==0) break; 30 | floydCycleFinding(L); 31 | System.out.printf("Case %d: %d\n", caseNo, lambda); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/07/740-Baudot_Data_Communication_Code/740_.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | #define GI ({int _t; scanf("%d", &_t); _t;}) 10 | #define FOR(i, a, b) for (int i=a; i string toString(T n){ostringstream ost;ost<>r;return r;} 14 | #define DBGV(_v) { REP(_i, _v.size()) { cout << _v[_i] << "\t";} cout << endl;} // DeBuG Vector 15 | 16 | int binary2decimal( string bin) 17 | { 18 | int res = 0; 19 | for (int i=bin.size()-1, j=0; i>=0; i--, j++) 20 | res += (bin[i]-'0')*((int)pow((double)2, (double)j)); 21 | return res; 22 | } 23 | 24 | int main() 25 | { 26 | string down, up, line; 27 | getline (cin, down); 28 | getline (cin, up); 29 | while (getline(cin, line)) 30 | { 31 | bool down_status = true; 32 | for (int i =0; i 0) matrix[i][j] += matrix[i][j - 1]; // pre-processing 14 | } 15 | 16 | // O(n^3) greedy solution (Kadane's algorithm) 17 | for (left = 0; left < n; left++) 18 | for (right = left; right < n; right++) { 19 | possibleMax = 0; 20 | for (row = 0; row < n; row++) { 21 | if (left > 0) 22 | possibleMax += matrix[row][right] - matrix[row][left - 1]; 23 | else 24 | possibleMax += matrix[row][right]; 25 | 26 | // crucial part, immediately reset if running sum is negative 27 | if (possibleMax < 0) possibleMax = 0; 28 | 29 | if (unCounted == 1 || possibleMax > currentMax) { 30 | currentMax = possibleMax; 31 | unCounted = 0; 32 | } 33 | } 34 | } 35 | 36 | System.out.printf("%d\n", currentMax); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1219-Team_Arrangement/1219.dat: -------------------------------------------------------------------------------- 1 | 9 PlayerA M 2000-2001 2003-2006 2 | 2 PlayerB M 2004-2006 3 | 10 PlayerC D 2001-2005 4 | 1 PlayerD D 2000-2001 2002-2004 5 | 11 PlayerE S 2003-2006 6 | 8 PlayerF M 2005-2006 7 | 22 PlayerG S 2005-2006 8 | 25 PlayerH G 2000-2001 2002-2003 2005-2006 9 | 6 PlayerI D 2003-2006 10 | 26 PlayerJ D 2003-2004 2000-2001 11 | 18 PlayerK M 2003-2004 12 | 19 PlayerL M 2000-2001 2003-2006 13 | 7 PlayerM S 2003-2006 1999-2001 14 | 21 PlayerN S 2003-2006 15 | 13 PlayerO S 2005-2006 16 | 15 PlayerP G 2001-2006 17 | 14 PlayerQ D 2003-2004 18 | 5 PlayerR S 2000-2005 19 | 20 PlayerS G 2000-2002 2003-2003 20 | 12 PlayerT M 2004-2005 21 | 3 PlayerU D 2000-2005 22 | 4 PlayerV M 2001-2004 23 | 4-4-2 24 | 9 PlayerA M 2000-2001 2003-2006 25 | 2 PlayerB G 2004-2006 26 | 10 PlayerC D 2001-2005 27 | 1 PlayerD D 2000-2001 2002-2004 28 | 11 PlayerE S 2003-2006 29 | 8 PlayerF M 2005-2006 30 | 22 PlayerG S 2005-2006 31 | 25 PlayerH G 2000-2001 2002-2003 2005-2006 32 | 6 PlayerI D 2003-2006 33 | 26 PlayerJ D 2003-2004 2000-2001 34 | 18 PlayerK G 2003-2004 35 | 19 PlayerL M 2000-2001 2003-2006 36 | 7 PlayerM S 2003-2006 1999-2001 37 | 21 PlayerN S 2003-2006 38 | 13 PlayerO S 2005-2006 39 | 15 PlayerP G 2001-2006 40 | 14 PlayerQ D 2003-2004 41 | 5 PlayerR S 2000-2005 42 | 20 PlayerS G 2000-2002 2003-2003 43 | 12 PlayerT D 2004-2005 44 | 3 PlayerU D 2000-2005 45 | 4 PlayerV S 2001-2004 46 | 4-4-2 47 | 0 48 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/04/441-Lotto/441.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | main() 6 | { 7 | int k; 8 | cin >> k; 9 | while (true) 10 | { 11 | vector S; 12 | for (int i = 0; i < k; ++i) 13 | { 14 | int s; 15 | cin >> s; 16 | S.push_back(s); 17 | } 18 | // Note that the complete search has been pruned. 19 | for (int i = 0; i < S.size()-5; ++i) // 1 20 | { 21 | for (int j = 1; j < S.size()-4; ++j) // 2 22 | { 23 | if (j <= i) continue; // These conditions guarantee the ascending order. 24 | for (int k = 2; k < S.size()-3; ++k) // 3 25 | { 26 | if (k <= j) continue; 27 | for (int l = 3; l < S.size()-2; ++l) // 4 28 | { 29 | if (l <= k) continue; 30 | for (int m = 4; m < S.size()-1; ++m) // 5 31 | { 32 | if (m <= l) continue; 33 | for (int n = 5; n < S.size(); ++n) // 6 34 | { 35 | if (n <= m) continue; 36 | cout << S[i] << " " << S[j] << " " << S[k] << " " << S[l] << " " 37 | << S[m] << " " << S[n] << "\n"; 38 | } 39 | } 40 | } 41 | } 42 | } 43 | } 44 | cin >> k; // Read k at the end so we can break before printing a newline. 45 | if (k == 0) break; 46 | cout << endl; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_07_floyd_warshall.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ch4_07_floyd_warshall { 4 | public static void main(String[] args) { 5 | int i, j, k, V, E, a, b, weight; 6 | 7 | /* 8 | // Graph in Figure 4.19 9 | 5 9 10 | 0 1 2 11 | 0 2 1 12 | 0 4 3 13 | 1 3 4 14 | 2 1 1 15 | 2 4 1 16 | 3 0 1 17 | 3 2 3 18 | 3 4 5 19 | */ 20 | 21 | Scanner sc = new Scanner(System.in); 22 | V = sc.nextInt(); 23 | E = sc.nextInt(); 24 | 25 | int[][] AdjMat = new int[V][]; 26 | for (i = 0; i < V; i++) { 27 | AdjMat[i] = new int[V]; 28 | for (j = 0; j < V; j++) 29 | AdjMat[i][j] = 1000000000; // use 1.10^9 to avoid overflow 30 | AdjMat[i][i] = 0; 31 | } 32 | 33 | for (i = 0; i < E; i++) { 34 | a = sc.nextInt(); 35 | b = sc.nextInt(); 36 | weight = sc.nextInt(); 37 | AdjMat[a][b] = weight; // directed graph 38 | } 39 | 40 | for (k = 0; k < V; k++) // O(v^3) Floyd Warshall's code is here 41 | for (i = 0; i < V; i++) 42 | for (j = 0; j < V; j++) 43 | AdjMat[i][j] = Math.min(AdjMat[i][j], 44 | AdjMat[i][k] + AdjMat[k][j]); 45 | 46 | for (i = 0; i < V; i++) 47 | for (j = 0; j < V; j++) 48 | System.out.printf("APSP(%d, %d) = %d\n", i, j, AdjMat[i][j]); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_07_UVa10130.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* SuperSale */ 4 | // 0-1 Knapsack DP (Top-Down) - faster as not all states are visited 5 | 6 | private static final int MAX_N = 1010; 7 | private static final int MAX_W = 40; 8 | private static int N, MW; 9 | private static int[] V = new int[MAX_N], W = new int[MAX_N]; 10 | private static int[][] memo = new int[MAX_N][MAX_W]; 11 | 12 | private static int value(int id, int w) { 13 | if (id == N || w == 0) return 0; 14 | if (memo[id][w] != -1) return memo[id][w]; 15 | if (W[id] > w) return memo[id][w] = value(id + 1, w); 16 | return memo[id][w] = Math.max(value(id + 1, w), V[id] + value(id + 1, w - W[id])); 17 | } 18 | 19 | public static void main(String[] args) { 20 | Scanner sc = new Scanner(System.in); 21 | int i, j, T, G, ans; 22 | 23 | T = sc.nextInt(); 24 | while (T-- > 0) { 25 | for (i = 0; i < MAX_N; i++) 26 | for (j = 0; j < MAX_W; j++) 27 | memo[i][j] = -1; 28 | 29 | N = sc.nextInt(); 30 | for (i = 0; i < N; i++) { 31 | V[i] = sc.nextInt(); 32 | W[i] = sc.nextInt(); 33 | } 34 | 35 | ans = 0; 36 | G = sc.nextInt(); 37 | while (G-- > 0) { 38 | MW = sc.nextInt(); 39 | ans += value(0, MW); 40 | } 41 | 42 | System.out.printf("%d\n", ans); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_02_Collections.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch2_02_Collections { 4 | public static void main(String[] args) { 5 | Vector v = new Vector(); 6 | 7 | v.add(10); 8 | v.add(5); 9 | v.add(2); 10 | v.add(7); 11 | v.add(1); 12 | 13 | System.out.println("Before sorting:"); 14 | System.out.println(v); 15 | 16 | Collections.sort(v); 17 | // if we want to modify comparison function, use the overloaded method: Collections.sort(List list, Comparator c); 18 | 19 | System.out.println("After sorting:"); 20 | System.out.println(v); 21 | 22 | int pos = Collections.binarySearch(v, 7); 23 | System.out.println("Trying to search for 7 in v, found at index = " + pos); 24 | 25 | pos = Collections.binarySearch(v, 8); 26 | System.out.println("Trying to search for 8 in v, found at index = " + pos); // output is -5 (explanation below) 27 | 28 | /* 29 | binarySearch will returns: 30 | 31 | index of the search key, if it is contained in the list; 32 | otherwise, (-(insertion point) - 1). 33 | The insertion point is defined as the point at which the key would be inserted into the list: 34 | the index of the first element greater than the key, 35 | or list.size(), if all elements in the list are less than the specified key. 36 | Note that this guarantees that the return value will be >= 0 if and only if the key is found. 37 | */ 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/A.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char seive[10000001]; 5 | 6 | main(){ 7 | unsigned a,b; 8 | while (2 == scanf("%u %u ",&a,&b)){ 9 | unsigned i,j,k,m; 10 | unsigned min=3000000000,max=0,prev,maxprev,minprev,maxi,mini; 11 | for (i=a;i<=b;i++) seive[i-a] = 0; 12 | if (a <= 2) {prev = 2;a = 3;} else prev = 0; 13 | m = sqrt((double)b); 14 | for (i=3;i<=m;i+=2){ 15 | k = sqrt((double)i); 16 | for (j=3;j<=k;j+=2) if (i%j == 0ul) goto composite1; 17 | k = a % i; 18 | if (k == 0) k = i; 19 | for (k=i-k;k+a<=b;k+=i) { 20 | if (a+k == i) continue; 21 | seive[k] = 1; 22 | } 23 | continue; 24 | composite1:; 25 | } 26 | 27 | for (i=a%2==1ul?a:a+1ul;i<=b;i+=2ul){ 28 | if (seive[i-a]) continue; 29 | if (prev) { 30 | if (i-prev > max) { 31 | max = i-prev; 32 | maxprev = prev; 33 | maxi = i; 34 | } 35 | if (i-prev < min) { 36 | min = i-prev; 37 | minprev = prev; 38 | mini = i; 39 | } 40 | } 41 | prev = i; 42 | } 43 | if (max){ 44 | printf("%d,%d are closest, %d,%d are most distant.\n",minprev, 45 | mini,maxprev,maxi); 46 | }else{ 47 | printf("There are no adjacent primes.\n"); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_05_UVa231.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* What Goes Up */ 4 | // O(nk) LNIS DP (longest NON-increasing sequence) 5 | 6 | private static int upperbound(int[] A, int len, int key) { 7 | // please convert this code to binary search to achieve 8 | // O(log k) instead of O(k) performance :) 9 | 10 | int i; 11 | for (i = 0; i < len; i++) // O(k) 12 | if (A[i] < key) 13 | break; 14 | return i; 15 | } 16 | 17 | public static void main(String[] args) { 18 | final int MAX_N = 200000; 19 | int i, lnis = 0, n, caseNo = 1; 20 | int[] X = new int[MAX_N], A = new int[MAX_N]; 21 | Boolean first = true; 22 | 23 | Scanner sc = new Scanner(System.in); 24 | while (true) { 25 | n = 0; 26 | while (true) { // read this test case 27 | X[n] = sc.nextInt(); 28 | if (X[n] == -1) break; 29 | n++; 30 | } 31 | 32 | if (X[0] == -1) break; // end of input 33 | 34 | // O(n log k) algorithm 35 | for (A[0] = X[0], i = lnis = 1; i < n; i++) { // O(n) 36 | int l = upperbound(A, lnis, X[i]); // find insertion point, O(k) 37 | lnis = Math.max(lnis, l + 1); 38 | A[l] = X[i]; 39 | } 40 | 41 | if (!first) System.out.printf("\n"); 42 | first = false; 43 | System.out.printf("Test #%d:\n", caseNo++); 44 | System.out.printf(" maximum possible interceptions: %d\n", lnis); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /resources/arithmetic/solve_quad.c: -------------------------------------------------------------------------------- 1 | /* Arithmetic: Quadratic equation solver 2 | ================================================================= 3 | Description: Finds solutions to the quadratic equation: 4 | ax^2+bx+c = 0 5 | 6 | Complexity: O(1) 7 | ----------------------------------------------------------------- 8 | Author: Gilbert Lee 9 | Date: Sept 8, 2002 10 | References: 11 | ----------------------------------------------------------------- 12 | Reliability: 1 Successful use (Sept 2002) 13 | (Spain - 10357) 14 | Notes: When there are two solutions for x, r.x[0] is not 15 | necessarily smaller than r.x[1] 16 | */ 17 | 18 | #include 19 | #include 20 | 21 | typedef struct{ 22 | int n; /* Number of solutions */ 23 | double x[2]; /* Solutions */ 24 | } Result; 25 | 26 | Result solve_quad(double a, double b, double c){ 27 | Result r; 28 | double z = b*b-4*a*c; 29 | 30 | if(z < 0){ 31 | r.n = 0; 32 | } else if(z == 0){ 33 | r.n = 1; 34 | r.x[0] = -b/(2*a); 35 | } else { 36 | r.n = 2; 37 | r.x[0] = (-b+sqrt(z))/(2*a); 38 | r.x[1] = (-b-sqrt(z))/(2*a); 39 | } 40 | return r; 41 | } 42 | 43 | int main(){ 44 | double a,b,c; 45 | Result r; 46 | int i; 47 | 48 | while(scanf("%lf %lf %lf", &a, &b, &c) == 3){ 49 | r = solve_quad(a,b,c); 50 | printf("%d solution(s)\n", r.n); 51 | for(i = 0; i < r.n; i++){ 52 | printf("x = %f\n", r.x[i]); 53 | } 54 | } 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_03_UVa11450_td.cpp: -------------------------------------------------------------------------------- 1 | /* UVa 11450 - Wedding Shopping - Top Down */ 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int M, C, K, price[25][25]; // price[g (<= 20)][model (<= 20)] 8 | int memo[210][25]; // dp table memo[money (<= 200)][g (<= 20)] 9 | 10 | int shop(int money, int g) { 11 | if (money < 0) return -1000000000; // fail, return a large negative number (1B) 12 | if (g == C) return M - money; // we have bought last garment, done 13 | if (memo[money][g] != -1) return memo[money][g]; // this state has been visited before 14 | int ans = -1000000000; 15 | for (int model = 1; model <= price[g][0]; model++) // try all possible models 16 | ans = max(ans, shop(money - price[g][model], g + 1)); 17 | return memo[money][g] = ans; // assign ans to dp table + return it! 18 | } 19 | 20 | int main() { // easy to code if you are already familiar with it 21 | int i, j, TC, score; 22 | 23 | scanf("%d", &TC); 24 | while (TC--) { 25 | scanf("%d %d", &M, &C); 26 | for (i = 0; i < C; i++) { 27 | scanf("%d", &K); 28 | price[i][0] = K; // to simplify coding, we store K in price[i][0] 29 | for (j = 1; j <= K; j++) 30 | scanf("%d", &price[i][j]); 31 | } 32 | 33 | memset(memo, -1, sizeof memo); // initialize DP memo table 34 | score = shop(M, 0); // start the top-down DP 35 | if (score < 0) printf("no solution\n"); 36 | else printf("%d\n", score); 37 | } } // return 0; -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_09_UVa10496.cpp: -------------------------------------------------------------------------------- 1 | /* Collecting Beepers */ 2 | 3 | // DP TSP 4 | 5 | #include 6 | #include 7 | #include 8 | #include 9 | using namespace std; 10 | 11 | int i, j, TC, xsize, ysize, n, x[11], y[11], dist[11][11], memo[11][1 << 11]; // Karel + max 10 beepers 12 | 13 | int tsp(int pos, int bitmask) { // bitmask stores the visited coordinates 14 | if (bitmask == (1 << (n + 1)) - 1) 15 | return dist[pos][0]; // return trip to close the loop 16 | if (memo[pos][bitmask] != -1) 17 | return memo[pos][bitmask]; 18 | 19 | int ans = 2000000000; 20 | for (int nxt = 0; nxt <= n; nxt++) // O(n) here 21 | if (nxt != pos && !(bitmask & (1 << nxt))) // if coordinate nxt is not visited yet 22 | ans = min(ans, dist[pos][nxt] + tsp(nxt, bitmask | (1 << nxt))); 23 | return memo[pos][bitmask] = ans; 24 | } 25 | 26 | int main() { 27 | scanf("%d", &TC); 28 | while (TC--) { 29 | scanf("%d %d", &xsize, &ysize); // these two values are not used 30 | scanf("%d %d", &x[0], &y[0]); 31 | scanf("%d", &n); 32 | for (i = 1; i <= n; i++) // karel's position is at index 0 33 | scanf("%d %d", &x[i], &y[i]); 34 | 35 | for (i = 0; i <= n; i++) // build distance table 36 | for (j = 0; j <= n; j++) 37 | dist[i][j] = abs(x[i] - x[j]) + abs(y[i] - y[j]); // Manhattan distance 38 | 39 | memset(memo, -1, sizeof memo); 40 | printf("The shortest path has length %d\n", tsp(0, 1)); // DP-TSP 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_01_UVa750.cpp: -------------------------------------------------------------------------------- 1 | /* 8 Queens Chess Problem */ 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int row[9], TC, a, b, lineCounter; // it is ok to use global variables in competitive programming 8 | 9 | bool place(int col, int tryrow) { 10 | for (int prev = 1; prev < col; prev++) // check previously placed queens 11 | if (row[prev] == tryrow || (abs(row[prev] - tryrow) == abs(prev - col))) 12 | return false; // an infeasible solution if share same row or same diagonal 13 | return true; 14 | } 15 | 16 | void backtrack(int col) { 17 | for (int tryrow = 1; tryrow <= 8; tryrow++) // try all possible row 18 | if (place(col, tryrow)) { // if can place a queen at this col and row... 19 | row[col] = tryrow; // put this queen in this col and row 20 | if (col == 8 && row[b] == a) { // a candidate solution & (a, b) has 1 queen 21 | printf("%2d %d", ++lineCounter, row[1]); 22 | for (int j = 2; j <= 8; j++) printf(" %d", row[j]); 23 | printf("\n"); 24 | } 25 | else 26 | backtrack(col + 1); // recursively try next column 27 | } } 28 | 29 | int main() { 30 | scanf("%d", &TC); 31 | while (TC--) { 32 | scanf("%d %d", &a, &b); 33 | memset(row, 0, sizeof row); lineCounter = 0; 34 | printf("SOLN COLUMN\n"); 35 | printf(" # 1 2 3 4 5 6 7 8\n\n"); 36 | backtrack(1); // generate all possible 8! candidate solutions 37 | if (TC) printf("\n"); 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/07/740-Baudot_Data_Communication_Code/740.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // for (c++) string conversions 4 | #include 5 | #include // for binary to decimal 6 | using namespace std; 7 | 8 | #define REP(i,a) for(i=0;i> n; 18 | return n; 19 | } 20 | 21 | string int2str(int n) 22 | { 23 | stringstream ss; 24 | ss << n; 25 | return ss.str(); 26 | } 27 | 28 | int bin2dec(string bin) 29 | { 30 | int res = 0; 31 | for (int i=bin.size()-1, j=0; i>=0; i--, j++) 32 | res += (bin[i]-'0') * ((int) pow( (double) 2, (double) j)); // raise bits to appropriate power of 2 33 | return res; 34 | } 35 | 36 | int main() 37 | { 38 | string down, up, line; 39 | getline(cin, down); 40 | getline(cin, up); 41 | while(getline(cin, line)) 42 | { 43 | bool downshift = true; 44 | for(int i=0; i < line.length(); i+=5) 45 | { 46 | string code = line.substr(i, 5); 47 | int index = bin2dec(code); 48 | // unsigned long index = bitset<32>(codeStr).to_ulong(); // Alternate binary to decimal conversion 49 | if(code == "11111") downshift = false; 50 | else if(code == "11011") downshift = true; 51 | else if(downshift) putchar(down[index]); 52 | else putchar(up[index]); 53 | } 54 | putchar('\n'); 55 | } 56 | return 0; 57 | } 58 | 59 | -------------------------------------------------------------------------------- /resources/arithmetic/simpsons.c: -------------------------------------------------------------------------------- 1 | /* Arithmatic: Simpson's Rule for Numerical Intergration 2 | ================================================================= 3 | Description: Numerical integration of the function f from a to b 4 | Splits the interval [a,b] into 2k pieces. 5 | The error is <= (b-a)/180.0 * M * h^4 6 | where: 7 | M = max( abs(f''''(x))) for x in [a,b] 8 | h = (b-a)/2k 9 | Note that this means the integrals for low degree 10 | polynomials are computed exactly 11 | 12 | Complexity: O(k) 13 | ----------------------------------------------------------------- 14 | Author: Adam Beacham, Brian Lau 15 | Date: Oct 4, 2002 16 | References: Any Calculus book. 17 | ----------------------------------------------------------------- 18 | Reliability: 0/0 19 | Notes: 20 | */ 21 | 22 | #include 23 | #include 24 | 25 | 26 | double Simpson(double a, double b, int k, double (*f)(double)){ 27 | double dx, x, t; 28 | int i; 29 | 30 | /* assert( (a - b) != 0 && k > 0); */ 31 | 32 | dx = (b-a)/(2.0*k); 33 | t = 0; 34 | 35 | for( i=0; i 14 | #include 15 | 16 | using namespace std; 17 | 18 | int main(void) 19 | { 20 | // Read number of data sets to process 21 | int num, nprob; 22 | cin >> num; 23 | 24 | // Process each data set identically 25 | for (int i = 1; i <= num; ++i) 26 | { 27 | cin >> nprob; 28 | // (Dynamic) Array containing the three largest elements. 29 | // We want a[0] > a[1] > a[2]. Then after processing all 30 | // ten elements a[2] is the answer. We initialize the array 31 | // to all -1's because we know the inputs are all positive. 32 | vector a(3, -1); 33 | for (int j = 0; j < 10; ++j) 34 | { 35 | int x; 36 | cin >> x; 37 | // Put x in its appropriate location in the array a. 38 | // Bubble it down to its right location. 39 | for (int k = 0; k < 3; ++k) 40 | { 41 | if (x > a[k]) 42 | { 43 | const int temp = a[k]; 44 | a[k] = x; 45 | x = temp; 46 | } 47 | } 48 | // Notice that x falls off the array a and is lost. 49 | } 50 | cout << nprob << " " << a[2] << endl; 51 | } 52 | 53 | // We're done 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_03_Stack_Queue.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch2_03_Stack_Queue { 4 | public static void main(String[] args) { 5 | Stack s = new Stack(); 6 | 7 | // Queue is abstract, must be instantiated with LinkedList 8 | // (special case for Java Queue) 9 | Queue q = new LinkedList(); 10 | 11 | System.out.println(s.isEmpty()); // currently s is empty, true 12 | System.out.println("=================="); 13 | s.push('a'); 14 | s.push('b'); 15 | s.push('c'); 16 | // stack is LIFO, thus the content of s is currently like this: 17 | // c <- top 18 | // b 19 | // a 20 | System.out.println(s.peek()); // output 'c' 21 | s.pop(); // pop topmost 22 | System.out.println(s.peek()); // output 'b' 23 | System.out.println(s.empty()); // currently s is not empty, false 24 | System.out.println("=================="); 25 | 26 | System.out.println(q.isEmpty()); // currently q is empty, true 27 | System.out.println("=================="); 28 | while (!s.isEmpty()) { // stack s still has 2 more items 29 | q.offer(s.peek()); // enqueue 'b', and then 'a' (the method name in Java Queue for push/enqueue operation is 'offer') 30 | s.pop(); 31 | } 32 | 33 | System.out.println(q.peek()); // prints 'b' 34 | // in Java, it is harder to see the back of the queue... 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2011/practice-set/C-recur.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define FOR(i,a,b) for(int i=a;i> n; 19 | 20 | string line; 21 | FOR(i,0,n) // for each test case 22 | { 23 | cin >> line; 24 | int longest_interval = -1; 25 | string winning_birds = ""; 26 | // recursively check for sightings 27 | FOR(j,0,line.size()) // for each sighting 28 | { 29 | char bird = line[j]; 30 | if (bird == '.') continue; 31 | int interval = get_sighting(bird, line.substr(j,line.size(), 0)); 32 | cout << interval << endl; 33 | /* 34 | FOR(k,j+1,line.size()) // search later sightings to calculate interval; 35 | { 36 | if (bird == line[k]) // if bird is sighted again, check interval 37 | { 38 | int interval = k - j; 39 | if (interval > longest_interval) // wipe previous winners, record new winner 40 | { 41 | winning_birds = bird; 42 | longest_interval = interval; 43 | } 44 | else if (interval == longest_interval) // add additional winning bird 45 | { 46 | winning_birds += bird; 47 | } 48 | break; // don't check any further 49 | } 50 | } 51 | */ 52 | } 53 | cout << winning_birds << ": " << longest_interval << endl; 54 | } 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1203-Argus/1203.cpp: -------------------------------------------------------------------------------- 1 | /* 1203 - Argus */ 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | struct Query 10 | { 11 | int qnum; 12 | int period; 13 | }; 14 | 15 | // comparison function for sort 16 | bool compare_queries(Query a, Query b) 17 | { 18 | if (a.period == b.period) 19 | return a.qnum < b.qnum; 20 | else 21 | return a.period < b.period; 22 | } 23 | 24 | int main() 25 | { 26 | vector queries; 27 | 28 | string command; 29 | 30 | // read in register commands (stop when # encountered) 31 | while (cin >> command) 32 | { 33 | if (command[0] == '#') 34 | break; 35 | 36 | // else it's a register command 37 | Query q; 38 | cin >> q.qnum; 39 | cin >> q.period; 40 | 41 | queries.push_back(q); 42 | } 43 | 44 | // read in k 45 | int k; 46 | cin >> k; 47 | 48 | // calculate the return times of first k queries... 49 | 50 | // place each query (with their updated frequences) k times into the same vector 51 | vector sorted_queries; 52 | 53 | for (int i = 0; i < queries.size(); ++i) 54 | { 55 | int frequency = queries[i].period; 56 | int qnum = queries[i].qnum; 57 | 58 | for (int j = 0; j < k; ++j) 59 | { 60 | Query q; 61 | q.qnum = qnum; 62 | q.period = frequency + (j * frequency); 63 | 64 | sorted_queries.push_back(q); 65 | } 66 | } 67 | 68 | // then sort that vector 69 | sort(sorted_queries.begin(), sorted_queries.end(), compare_queries); 70 | 71 | // print first k queries 72 | for (int i = 0; i < k; ++i) 73 | cout << sorted_queries.at(i).qnum << endl; 74 | 75 | return 0; 76 | } 77 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_11_UVa10943.cpp: -------------------------------------------------------------------------------- 1 | /* How do you add? */ 2 | 3 | // top-down 4 | 5 | /* 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int N, K, memo[110][110]; 11 | 12 | int ways(int N, int K) { 13 | if (K == 1) // only can use 1 number to add up to N 14 | return 1; // the answer is definitely 1, that number itself 15 | else if (memo[N][K] != -1) 16 | return memo[N][K]; 17 | 18 | // if K > 1, we can choose one number from [0..N] to be one of the number and recursively compute the rest 19 | int total_ways = 0; 20 | for (int split = 0; split <= N; split++) 21 | total_ways = (total_ways + ways(N - split, K - 1)) % 1000000; // we just need the modulo 1M 22 | return memo[N][K] = total_ways; // memoize them 23 | } 24 | 25 | int main() { 26 | memset(memo, -1, sizeof memo); 27 | while (scanf("%d %d", &N, &K), (N || K)) // some recursion formula + top down DP 28 | printf("%d\n", ways(N, K)); 29 | return 0; 30 | } 31 | */ 32 | 33 | 34 | // bottom-up 35 | 36 | #include 37 | #include 38 | using namespace std; 39 | 40 | int main() { 41 | int i, j, split, dp[110][110], N, K; 42 | 43 | memset(dp, 0, sizeof dp); 44 | 45 | for (i = 0; i <= 100; i++) // these are the base cases 46 | dp[i][1] = 1; 47 | 48 | for (j = 1; j < 100; j++) // these three nested loops form the correct topological order 49 | for (i = 0; i <= 100; i++) 50 | for (split = 0; split <= 100 - i; split++) { 51 | dp[i + split][j + 1] += dp[i][j]; 52 | dp[i + split][j + 1] %= 1000000; 53 | } 54 | 55 | while (scanf("%d %d", &N, &K), (N || K)) 56 | printf("%d\n", dp[N][K]); 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/D/D1.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | const int MAX = 1000; 6 | const double PI = 4.0*atan(1.0); 7 | 8 | struct loc 9 | { 10 | double x, y; 11 | double angle; 12 | } locs[MAX]; 13 | 14 | int numCovered[MAX]; // numCovered[i] = # of people in frame if edge of 15 | // view starts at loc[i] 16 | 17 | double getAngle(int x, int y) 18 | { 19 | double angle = atan2(y, x) * 180.0/PI; 20 | if (angle < 0.0) 21 | angle += 360.0; 22 | return angle; 23 | } 24 | 25 | double angleDiff(int i, int j, int n) 26 | { 27 | if (i >= n) 28 | i -= n; 29 | double angle = locs[i].angle - locs[j].angle; 30 | if (angle < 0.0) 31 | angle += 360.0; 32 | return angle; 33 | } 34 | 35 | int main() 36 | { 37 | int n, x, y, f, icase=0; 38 | cin >> n >> x >> y >> f; 39 | while (n > 0) { 40 | icase++; 41 | for(int i=0; i> l.x >> l.y; 44 | l.x -= x; 45 | l.y -= y; 46 | l.angle = getAngle(l.x, l.y); 47 | int j=i; 48 | while (j > 0 && locs[j-1].angle > l.angle) { 49 | locs[j] = locs[j-1]; 50 | j--; 51 | } 52 | locs[j] = l; 53 | } 54 | int last=0; 55 | for(int i=0; i= n) 69 | next -= n; 70 | sum += numCovered[next]; 71 | next += numCovered[next]; 72 | count++; 73 | } 74 | if (count < best) 75 | best = count; 76 | } 77 | cout << "Case " << icase << ": " << best << endl; 78 | cin >> n >> x >> y >> f; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch8-Advanced/ch8_03_UVa10911.cpp: -------------------------------------------------------------------------------- 1 | /* Forming Quiz Teams */ 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | #define MAX_BITMASK 65536 // this is 2^16, max N = 8 10 | 11 | char line[1000], name[1000]; 12 | int i, j, N, x[20], y[20], caseNo = 1; 13 | double dist[20][20], memo[65536]; 14 | 15 | double matching(int bitmask) { 16 | if (memo[bitmask] > -0.1) // we initialize the array with -1 17 | return memo[bitmask]; 18 | 19 | if (bitmask == (int)(pow(2.0, 2.0 * N) - 1)) // all are matched 20 | return memo[bitmask] = 0; 21 | 22 | double matching_value = 32767 * 32767; 23 | for (int p1 = 0; p1 < 2 * N; p1++) 24 | if (!(bitmask & (1 << p1))) { // if this bit is off 25 | for (int p2 = p1 + 1; p2 < 2 * N; p2++) 26 | if (!(bitmask & (1 << p2))) // if this different bit is also off 27 | matching_value = min(matching_value, 28 | dist[p1][p2] + matching(bitmask | (1 << p1) | (1 << p2))); 29 | break; // to improve the complexity from O(16^2 * 2^N) to O(16 * 2^N) 30 | } 31 | 32 | return memo[bitmask] = matching_value; 33 | } 34 | 35 | int main() { 36 | while (sscanf(gets(line), "%d", &N), N) { 37 | for (i = 0; i < 2 * N; i++) 38 | sscanf(gets(line), "%s %d %d", &name, &x[i], &y[i]); 39 | 40 | for (i = 0; i < 2 * N; i++) 41 | for (j = 0; j < 2 * N; j++) 42 | dist[i][j] = sqrt((double)(x[i] - x[j]) * (x[i] - x[j]) + 43 | (y[i] - y[j]) * (y[i] - y[j])); 44 | 45 | // using DP to solve matching on general graph 46 | memset(memo, -1, sizeof memo); 47 | printf("Case %d: %.2lf\n", caseNo++, matching(0)); 48 | } 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /solved/contest-volumes/ECNA2012-practice/C/C.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | struct Actor 8 | { 9 | string name; 10 | int height; 11 | }; 12 | 13 | bool compare_actors(Actor a, Actor b) 14 | { 15 | return a.height > b.height; 16 | } 17 | 18 | main() 19 | { 20 | int n; 21 | int num_case = 1; 22 | while (cin >> n) 23 | { 24 | if (n == 0) break; 25 | cout << "Case " << num_case++ << ":" << endl; 26 | vector actors; 27 | for (int i = 0; i < n; ++i) 28 | { 29 | Actor a; 30 | cin >> a.name >> a.height; 31 | actors.push_back(a); 32 | } 33 | sort(actors.begin(), actors.end(), compare_actors); 34 | vector cast; 35 | // for each actor, check the remaining actors for possible cast 36 | for (int i = 0; i < actors.size(); ++i) 37 | { 38 | bool son_found = false, grandson_found = false; 39 | int son_h = actors[i].height - 3; 40 | int grandson_h = actors[i].height - 9; 41 | for (int j = i+1; j < actors.size(); ++j) 42 | { 43 | if (!son_found && actors[j].height == son_h) 44 | { 45 | son_found = true; 46 | cast.push_back(actors[i]); 47 | cast.push_back(actors[j]); 48 | } 49 | if (son_found && !grandson_found && actors[j].height == grandson_h) 50 | { 51 | grandson_found = true; 52 | cast.push_back(actors[j]); 53 | break; 54 | } 55 | } 56 | if (son_found && grandson_found) 57 | { 58 | for (int idx = 0; idx < 3; ++idx) 59 | cout << cast[idx].name << " "; 60 | cout << endl; 61 | } 62 | cast.clear(); 63 | son_found = false; grandson_found = false; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/H/inH.dat: -------------------------------------------------------------------------------- 1 | 2 1 Al O2 Al2O3 2 | 2 2 Fe2(SO4)3 KSCN K3Fe(SCN)6 K2SO4 3 | 1 1 CO2 CO 4 | 2 2 C2H6 O2 CO2 H2O 5 | 1 3 (NH4)2CO3 NH3 CO2 H2O 6 | 2 2 C3H8 O2 H2O CO2 7 | 2 2 CaCl2 AgNO3 AgCl Ca(NO3)2 8 | 2 2 I2 Na2S2O3 NaI Na2S4O6 9 | 3 4 NaCl H2SO4 MnO2 Na2SO4 MnSO4 H2O Cl2 10 | 3 3 HIO3 FeI2 HCl FeCl3 ICl H2O 11 | 4 4 Fe(NH4)2(SO4)6 H2O2 K2C2O4 H2C2O4 K3Fe(C2O4)9 (NH4)2SO4 H2SO4 H2O 12 | 4 4 FeN2S6H2O H2O2 K2C2O4 H2C2O4 K3FeC18H2O (NH4)2SO4 H2SO4 H2O 13 | 3 2 AD B C AD B 14 | 2 1 Al323 O1068 Al289O347 15 | 1 2 Al289O347 O1068 Al323 16 | 2 2 ABCDEFGHIJ KLMNOPQRST TRPNLJHFDB S2QOMKIGECA 17 | 2 2 ABCDEFGHIJ KLMNOPQRST TRPNLJHFDB SQOMKIGECA 18 | 1 5 (((AB)2C)3D)4E BCD AB ACE AC9 AC 19 | 1 5 (((AB)2C)3D)4E BCD AD ACE AC9 AC 20 | 1 5 ((AB2)3(CD2)4)5EF((GH2)3(IJ2)2)7 (A2B3)5((I2J)2G)2 CD2GH2J AB5D(HIJ)2 ACDEF (AB)5C9G7H4J2 21 | 5 1 (AB)5C9G7H4J2 ACDEF (A2B3)5((I2J)2G)2 AB5D(HIJ)2 CD2GH2J ((AB2)3(CD2)4)5EF((GH2)3(IJ2)2)7 22 | 1 1 A A 23 | 1 1 A A2 24 | 1 1 A B 25 | 2 2 AB B A B 26 | 2 2 AB CD A2B2 C2D2 27 | 2 2 AB CD A2C2 B2D2 28 | 10 10 AB CD EF GH IJ KL MN OP QR ST B ACD AEF AGH AIJ AKL AMN AOP AQR AST 29 | 10 10 AB CD EF GH IJ KL MN OP QR ST B ACF AEH AGD AIL AKN AMJ AOR AQT ASP 30 | 10 10 AB CD EF GH IJ KL MN OP QR ST B ACR AED AGF AIH AKJ AML AOM AQP AST 31 | 10 10 AB CD EF GH IJ KL MN OP QR ST B ACT AED AGF AIH AKJ AML AON AQP ASR 32 | 4 5 A(BC2)3H (BC)2D DEA2 FG AC2F A3(BC2)5E2HG AC(BD)6 (BG)8D9 CH9G4 33 | 4 4 AB(CD2)3 B(EF3)4 HGE2D3 ADG (DF3)10(GC2)3A4B5E13 (AC)3(EG)2D46F22H5 (AH)2BF5 DG 34 | 3 3 (A2B3)4C5 C(DE2)4FG2 AC3H (BCDE2)10(FA4)2G4H (AH2)5C27F7G15 (AG)3C(FH)4 35 | 5 5 AB3(CDE2)2 BE(FG2)3H2 (DI3J2)2KL3 (AB2M4)2N FJO A2(B2IJ)3E5O (DHF2G3)3C2M5 GKNL3 CFGHB2D3M3 AGN(CHJ)2I3 36 | 5 3 AFIJKLMNC3D2 (ABM)2KN (ABDEJ)2(CFK)3HLO2 I3(AHK)2BDGJO3 A2CDF2G2L2M2NO (C8G(IK)5(LN)3)3A17B5D19F8H4(JM)11O8 BFGNOH2 D(EF2)2LMC3 37 | 0 0 38 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_04_UVa11450_bu.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* UVa 11450 - Wedding Shopping - Bottom Up */ 4 | public static void main(String[] args) { 5 | Scanner sc = new Scanner(System.in); 6 | int i, j, l, TC, M, C, K; 7 | int[][] price = new int[25][25]; // price[g (<= 20)][model (<= 20)] 8 | Boolean[][] can_reach = new Boolean[210][25]; // can_reach table[money (<= 200)][g (<= 20)] 9 | 10 | TC = sc.nextInt(); 11 | while (TC-- > 0) { 12 | M = sc.nextInt(); C = sc.nextInt(); 13 | for (i = 0; i < C; i++) { 14 | K = sc.nextInt(); 15 | price[i][0] = K; // to simplify coding, we store K in price[i][0] 16 | for (j = 1; j <= K; j++) 17 | price[i][j] = sc.nextInt(); 18 | } 19 | 20 | for (i = 0; i < 210; i++) 21 | for (j = 0; j < 25; j++) 22 | can_reach[i][j] = false; // clear everything 23 | 24 | for (i = 1; i <= price[0][0]; i++) // initial values 25 | if (M - price[0][i] >= 0) 26 | can_reach[M - price[0][i]][0] = true; // if only using first garment g = 0 27 | 28 | for (j = 1; j < C; j++) // for each remaining garment (note: this is written in column major) 29 | for (i = 0; i < M; i++) if (can_reach[i][j - 1]) // if can reach this state 30 | for (l = 1; l <= price[j][0]; l++) if (i - price[j][l] >= 0) // flag the rest 31 | can_reach[i - price[j][l]][j] = true; // as long as it is feasible 32 | 33 | for (i = 0; i <= M && !can_reach[i][C - 1]; i++); // the answer is in the last column 34 | 35 | if (i == M + 1) 36 | System.out.printf("no solution\n"); // nothing in this last column has its bit turned on 37 | else 38 | System.out.printf("%d\n", M - i); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch7-Computational_Geometry/ch7_04_UVa11817.cpp: -------------------------------------------------------------------------------- 1 | /* Tunnelling the Earth */ 2 | 3 | // Great Circle distance + Euclidean distance 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | #define PI acos(-1.0) 10 | #define EARTH_RAD (6371009) // in meters 11 | 12 | double gcDistance(double pLat, double pLong, 13 | double qLat, double qLong, double radius) { 14 | pLat *= PI / 180; pLong *= PI / 180; 15 | qLat *= PI / 180; qLong *= PI / 180; 16 | return radius * acos(cos(pLat)*cos(pLong)*cos(qLat)*cos(qLong) + 17 | cos(pLat)*sin(pLong)*cos(qLat)*sin(qLong) + 18 | sin(pLat)*sin(qLat)); 19 | } 20 | 21 | double EucledianDistance(double pLat, double pLong, // 3D version 22 | double qLat, double qLong, double radius) { 23 | double phi1 = (90 - pLat) * PI / 180; 24 | double theta1 = (360 - pLong) * PI / 180; 25 | double x1 = radius * sin(phi1) * cos(theta1); 26 | double y1 = radius * sin(phi1) * sin(theta1); 27 | double z1 = radius * cos(phi1); 28 | 29 | double phi2 = (90 - qLat) * PI / 180; 30 | double theta2 = (360 - qLong) * PI / 180; 31 | double x2 = radius * sin(phi2) * cos(theta2); 32 | double y2 = radius * sin(phi2) * sin(theta2); 33 | double z2 = radius * cos(phi2); 34 | 35 | double dx = x1 - x2, dy = y1 - y2, dz = z1 - z2; 36 | return sqrt(dx * dx + dy * dy + dz * dz); 37 | } 38 | 39 | int main() { 40 | int TC; 41 | double lat1, lon1, lat2, lon2; 42 | 43 | scanf("%d", &TC); 44 | while (TC--) { 45 | scanf("%lf %lf %lf %lf", &lat1, &lon1, &lat2, &lon2); 46 | printf("%.0lf\n", gcDistance(lat1, lon1, lat2, lon2, EARTH_RAD) - 47 | EucledianDistance(lat1, lon1, lat2, lon2, EARTH_RAD)); 48 | } 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_03_stl_stack_queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int main() { 7 | stack s; 8 | queue q; 9 | 10 | printf("%d\n", s.empty()); // currently s is empty, true (1) 11 | printf("==================\n"); 12 | s.push('a'); 13 | s.push('b'); 14 | s.push('c'); 15 | // stack is LIFO, thus the content of s is currently like this: 16 | // c <- top 17 | // b 18 | // a 19 | printf("%c\n", s.top()); // output 'c' 20 | s.pop(); // pop topmost 21 | printf("%c\n", s.top()); // output 'b' 22 | printf("%d\n", s.empty()); // currently s is not empty, false (0) 23 | printf("==================\n"); 24 | 25 | printf("%d\n", q.empty()); // currently q is empty, true (1) 26 | printf("==================\n"); 27 | while (!s.empty()) { // stack s still has 2 more items 28 | q.push(s.top()); // enqueue 'b', and then 'a' 29 | s.pop(); 30 | } 31 | q.push('z'); // add one more item 32 | printf("%c\n", q.front()); // prints 'b' 33 | printf("%c\n", q.back()); // prints 'z' 34 | 35 | // output 'b', 'a', then 'z' (until queue is empty), according to the insertion order above 36 | printf("==================\n"); 37 | while (!q.empty()) { 38 | printf("%c\n", q.front()); // take the front first 39 | q.pop(); // before popping (dequeue-ing) it 40 | } 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_03_UVa11450_td.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* UVa 11450 - Wedding Shopping - Top Down */ 4 | private static int M, C, K; 5 | private static int[][] price = new int[25][25]; // price[g (<= 20)][model (<= 20)] 6 | private static int[][] memo = new int[210][25]; // dp table memo[money (<= 200)][g (<= 20)] 7 | 8 | private static int shop(int money, int g) { 9 | if (money < 0) return -1000000000; // fail, return a large negative number (1B) 10 | if (g == C) return M - money; // we have bought last garment, done 11 | if (memo[money][g] != -1) return memo[money][g]; // this state has been visited before 12 | int ans = -1000000000; 13 | for (int model = 1; model <= price[g][0]; model++) // try all possible models 14 | ans = Math.max(ans, shop(money - price[g][model], g + 1)); 15 | return memo[money][g] = ans; // assign ans to dp table + return it! 16 | } 17 | 18 | public static void main(String[] args) { // easy to code if you are already familiar with it 19 | Scanner sc = new Scanner(System.in); 20 | int i, j, TC, score; 21 | 22 | TC = sc.nextInt(); 23 | while (TC-- > 0) { 24 | M = sc.nextInt(); C = sc.nextInt(); 25 | for (i = 0; i < C; i++) { 26 | K = sc.nextInt(); 27 | price[i][0] = K; // to simplify coding, we store K in price[i][0] 28 | for (j = 1; j <= K; j++) 29 | price[i][j] = sc.nextInt(); 30 | } 31 | 32 | for (i = 0; i < 210; i++) 33 | for (j = 0; j < 25; j++) 34 | memo[i][j] = -1; // initialize DP memo table 35 | 36 | score = shop(M, 0); // start the top-down DP 37 | if (score < 0) System.out.printf("no solution\n"); 38 | else System.out.printf("%d\n", score); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_01_UVa750.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* 8 Queens Chess Problem */ 4 | private static int[] row = new int[9]; 5 | private static int TC, a, b, lineCounter; // it is ok to use global variables in competitive programming 6 | 7 | private static boolean place(int col, int tryrow) { 8 | for (int prev = 1; prev < col; prev++) // check previously placed queens 9 | if (row[prev] == tryrow || (Math.abs(row[prev] - tryrow) == Math.abs(prev - col))) 10 | return false; // an infeasible solution if share same row or same diagonal 11 | return true; 12 | } 13 | 14 | private static void backtrack(int col) { 15 | for (int tryrow = 1; tryrow <= 8; tryrow++) // try all possible row 16 | if (place(col, tryrow)) { // if can place a queen at this col and row... 17 | row[col] = tryrow; // put this queen in this col and row 18 | if (col == 8 && row[b] == a) { // a candidate solution & (a, b) has 1 queen 19 | System.out.printf("%2d %d", ++lineCounter, row[1]); 20 | for (int j = 2; j <= 8; j++) System.out.printf(" %d", row[j]); 21 | System.out.printf("\n"); 22 | } 23 | else 24 | backtrack(col + 1); // recursively try next column 25 | } } 26 | 27 | public static void main(String[] args) { 28 | Scanner sc = new Scanner(System.in); 29 | TC = sc.nextInt(); 30 | while (TC-- > 0) { 31 | a = sc.nextInt(); 32 | b = sc.nextInt(); 33 | for (int i = 0; i < 9; i++) row[i] = 0; 34 | lineCounter = 0; 35 | System.out.printf("SOLN COLUMN\n"); 36 | System.out.printf(" # 1 2 3 4 5 6 7 8\n\n"); 37 | backtrack(1); // generate all possible 8! candidate solutions 38 | if (TC > 0) System.out.printf("\n"); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /resources/arithmetic/solve_cubic.c: -------------------------------------------------------------------------------- 1 | /* Arithmetic: Cubic equation solver 2 | ================================================================= 3 | Description: Finds solutions to the cubic equation: 4 | ax^3+bx^2+cx+d = 0 5 | 6 | Complexity: O(1) 7 | ----------------------------------------------------------------- 8 | Author: Gilbert Lee 9 | Date: Sept 8, 2002 10 | References: www.snippets.org/snippets/portable/CUBIC+C.php3 11 | ----------------------------------------------------------------- 12 | Reliability: 0 13 | Notes: 14 | */ 15 | 16 | #include 17 | #include 18 | 19 | typedef struct{ 20 | int n; /* Number of solutions */ 21 | double x[3]; /* Solutions */ 22 | } Result; 23 | 24 | double PI; 25 | 26 | Result solve_cubic(double a, double b, double c, double d){ 27 | Result s; 28 | long double a1 = b/a, a2 = c/a, a3 = d/a; 29 | long double q = (a1*a1 - 3*a2)/9.0, sq = -2*sqrt(q); 30 | long double r = (2*a1*a1*a1 - 9*a1*a2 + 27*a3)/54.0; 31 | double z = r*r-q*q*q; 32 | double theta; 33 | 34 | if(z <= 0){ 35 | s.n = 3; 36 | theta = acos(r/sqrt(q*q*q)); 37 | s.x[0] = sq*cos(theta/3.0) - a1/3.0; 38 | s.x[1] = sq*cos((theta+2.0*PI)/3.0) - a1/3.0; 39 | s.x[2] = sq*cos((theta+4.0*PI)/3.0) - a1/3.0; 40 | } else { 41 | s.n = 1; 42 | s.x[0] = pow(sqrt(z)+fabs(r),1/3.0); 43 | s.x[0] += q/s.x[0]; 44 | s.x[0] *= (r < 0) ? 1 : -1; 45 | s.x[0] -= a1/3.0; 46 | } 47 | return s; 48 | } 49 | 50 | int main(){ 51 | double a,b,c,d; 52 | Result r; 53 | int i; 54 | 55 | PI = acos(-1); 56 | while(scanf("%lf %lf %lf %lf", &a, &b, &c, &d) == 4){ 57 | r = solve_cubic(a,b,c,d); 58 | printf("%d solution(s)\n", r.n); 59 | for(i = 0; i < r.n; i++){ 60 | printf("x = %f\n", r.x[i]); 61 | } 62 | } 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /resources/arithmetic/discrete_log.cc: -------------------------------------------------------------------------------- 1 | /* Arithmetic: Discrete Logarithm solver 2 | ================================================================= 3 | Description: Given prime P, B, and N, finds the smallest 4 | exponent L such that B^L == N (mod P) 5 | 6 | Complexity: O(sqrt(P)) 7 | ----------------------------------------------------------------- 8 | Author: Gilbert Lee 9 | Date: Sept 13, 2002 10 | References: http://plg.uwaterloo.ca/~acm00/020126/data/B.cpp 11 | ----------------------------------------------------------------- 12 | Reliability: 1 successful use (Spain Problem 10225) Sept 2002 13 | Notes: The function either returns the exponent L, or 14 | -1 if no solution is found 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | using namespace std; 22 | 23 | #define UI unsigned 24 | #define UL unsigned long 25 | #define ULL unsigned long long 26 | 27 | map M; 28 | 29 | UL times (UL a, UL b, UL m){ 30 | return (ULL) a * b % m; 31 | } 32 | 33 | UL power(UL val, UL power, UL m){ 34 | UL res = 1, p; 35 | 36 | for(p = power; p; p=p>>1){ 37 | if(p & 1) res = times(res, val, m); 38 | val = times(val, val, m); 39 | } 40 | return res; 41 | } 42 | 43 | int discrete_log(UI p, UI b, UI n){ 44 | UL i, j, jump; 45 | 46 | M.clear(); 47 | jump = (int)sqrt(p); 48 | for (i = 0; i < jump && i < p-1; i++){ 49 | M[power(b,i,p)] = i+1; 50 | } 51 | for (i = 0; i < p-1; i+= jump){ 52 | if (j = M[times(n,power(b,p-1-i,p),p)]) { 53 | j--; 54 | return (i+j)%(p-1); 55 | } 56 | } 57 | return -1; 58 | } 59 | 60 | int main(){ 61 | UI p, b, n; 62 | int x; 63 | 64 | while(scanf("%d %d %d", &p, &b, &n) == 3){ 65 | x = discrete_log(p,b,n); 66 | if(x < 0) printf("no solution\n"); 67 | else printf("%d\n", x); 68 | } 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_09_UVa10496.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Main { /* Collecting Beepers */ 4 | // DP TSP 5 | 6 | private static int i, j, TC, xsize, ysize, n; 7 | private static int[] x = new int[11], y = new int[11]; 8 | private static int[][] dist = new int[11][11], memo = new int[11][1 << 11]; // Karel + max 10 beepers 9 | 10 | private static int tsp(int pos, int bitmask) { // bitmask stores the visited coordinates 11 | if (bitmask == (1 << (n + 1)) - 1) 12 | return dist[pos][0]; // return trip to close the loop 13 | if (memo[pos][bitmask] != -1) 14 | return memo[pos][bitmask]; 15 | 16 | int ans = 2000000000; 17 | for (int nxt = 0; nxt <= n; nxt++) // O(n) here 18 | if (nxt != pos && (bitmask & (1 << nxt)) == 0) // if coordinate nxt is not visited yet 19 | ans = Math.min(ans, dist[pos][nxt] + tsp(nxt, bitmask | (1 << nxt))); 20 | return memo[pos][bitmask] = ans; 21 | } 22 | 23 | public static void main(String[] args) { 24 | Scanner sc = new Scanner(System.in); 25 | 26 | TC = sc.nextInt(); 27 | while (TC-- > 0) { 28 | xsize = sc.nextInt(); ysize = sc.nextInt(); // these two values are not used 29 | x[0] = sc.nextInt(); y[0] = sc.nextInt(); 30 | n = sc.nextInt(); 31 | for (i = 1; i <= n; i++) { // karel's position is at index 0 32 | x[i] = sc.nextInt(); 33 | y[i] = sc.nextInt(); 34 | } 35 | 36 | for (i = 0; i <= n; i++) // build distance table 37 | for (j = 0; j <= n; j++) 38 | dist[i][j] = Math.abs(x[i] - x[j]) + Math.abs(y[i] - y[j]); // Manhattan distance 39 | 40 | for (i = 0; i < 11; i++) 41 | for (j = 0; j < (1 << 11); j++) 42 | memo[i][j] = -1; 43 | 44 | System.out.printf("The shortest path has length %d\n", tsp(0, 1)); // DP-TSP 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_08_unionfind_ds.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch2_08_unionfind_ds { 4 | private static Vector pset; 5 | private static void initSet(int _size) { 6 | pset = new Vector(_size); for (int i = 0; i < _size; i++) pset.add(i); } 7 | private static int findSet(int i) { 8 | if (pset.get(i) == i) return i; 9 | else { 10 | int ret = findSet(pset.get(i)); pset.set(i, ret); 11 | return ret; } 12 | private static void unionSet(int i, int j) { pset.set(findSet(i), findSet(j)); } 13 | private static boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } 14 | 15 | public static void main(String[] args) { 16 | System.out.println("Assume that there are 5 disjoint sets initially"); 17 | initSet(5); // create 5 disjoint sets 18 | unionSet('A' - 'A', 'B' - 'A'); // unionSet(A, B) 19 | unionSet('A' - 'A', 'C' - 'A'); // unionSet(A, C) 20 | unionSet('D' - 'A', 'B' - 'A'); // unionSet(D, B) 21 | System.out.println("findSet(A) = " + findSet('A' - 'A')); // will return 1 (lazy update) 22 | System.out.println("findSet(A) = " + findSet('A' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 23 | System.out.println("findSet(B) = " + findSet('B' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 24 | System.out.println("findSet(C) = " + findSet('C' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 25 | System.out.println("findSet(D) = " + findSet('D' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 26 | System.out.println("findSet(E) = " + findSet('E' - 'A')); // will return 4 (the parent ID of 'E') 27 | System.out.println("isSameSet(A, E) = " + isSameSet('A' - 'A', 'E' - 'A')); // will return false 28 | System.out.println("isSameSet(A, B) = " + isSameSet('A' - 'A', 'B' - 'A')); // will return true 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_06_stl_priority_queue.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() { 8 | int money; 9 | char name[20]; 10 | priority_queue< pair > pq; // introducing 'pair' 11 | pair result; 12 | 13 | // suppose we enter these 7 money-name pairs via keyboard 14 | /* 15 | 100 john 16 | 10 billy 17 | 20 andy 18 | 100 steven 19 | 70 felix 20 | 2000 grace 21 | 70 martin 22 | */ 23 | for (int i = 0; i < 7; i++) { 24 | scanf("%d %s", &money, &name); 25 | pq.push(make_pair(money, name)); // inserting a pair in O(log n) 26 | // priority queue will arrange items in 'heap' based 27 | // on the first key in pair, which is money (integer), largest first 28 | // if first keys tied, use second key, which is name, largest first 29 | } 30 | 31 | // the internal content of pq heap MAY be something like this: 32 | // re-read (max) heap concept if you do not understand this diagram 33 | // the primary keys are money (integer), secondary keys are names (string)! 34 | // (2000,grace) 35 | // (100,steven) (70,martin) 36 | // (100,john) (10,billy) (20,andy) (70,felix) 37 | 38 | // let's print out the top 3 person with most money 39 | result = pq.top(); // O(1) to access the top / max element 40 | pq.pop(); // O(log n) to delete the top and repair the structure 41 | printf("%s has %d $\n", ((string)result.second).c_str(), result.first); 42 | result = pq.top(); pq.pop(); 43 | printf("%s has %d $\n", ((string)result.second).c_str(), result.first); 44 | result = pq.top(); pq.pop(); 45 | printf("%s has %d $\n", ((string)result.second).c_str(), result.first); 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_02_UVa469.cpp: -------------------------------------------------------------------------------- 1 | /* Wetlands of Florida */ 2 | 3 | // classic DFS flood fill 4 | 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | #define REP(i, a, b) \ 10 | for (int i = int(a); i <= int(b); i++) 11 | 12 | char line[150], grid[150][150]; 13 | int TC, R, C, row, col; 14 | 15 | int dr[] = {1,1,0,-1,-1,-1, 0, 1}; // S,SE,E,NE,N,NW,W,SW 16 | int dc[] = {0,1,1, 1, 0,-1,-1,-1}; // neighbors 17 | int floodfill(int r, int c, char c1, char c2) { 18 | if (r<0 || r>=R || c<0 || c>=C) return 0; // outside 19 | if (grid[r][c] != c1) return 0; // we want only c1 20 | grid[r][c] = c2; // important step to avoid cycling! 21 | int ans = 1; // coloring c1 -> c2, add 1 to answer 22 | REP (d, 0, 7) // recurse to neighbors 23 | ans += floodfill(r + dr[d], c + dc[d], c1, c2); 24 | return ans; 25 | } 26 | 27 | // inside the int main() of the solution for UVa 469 - Wetlands of Florida 28 | int main() { 29 | // read the implicit graph as global 2D array 'grid'/R/C and (row, col) query coordinate 30 | sscanf(gets(line), "%d", &TC); 31 | gets(line); // remove dummy line 32 | 33 | while (TC--) { 34 | R = 0; 35 | while (1) { 36 | gets(grid[R]); 37 | if (grid[R][0] != 'L' && grid[R][0] != 'W') // start of query 38 | break; 39 | R++; 40 | } 41 | C = (int)strlen(grid[0]); 42 | 43 | strcpy(line, grid[R]); 44 | while (1) { 45 | sscanf(line, "%d %d", &row, &col); row--; col--; // index starts from 0! 46 | printf("%d\n", floodfill(row, col, 'W', '.')); // change water 'W' to '.'; count size of this lake 47 | floodfill(row, col, '.', 'W'); // restore for next query 48 | gets(line); 49 | if (strcmp(line, "") == 0 || feof(stdin)) // next test case or last test case 50 | break; 51 | } 52 | 53 | if (TC) 54 | printf("\n"); 55 | } 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch6-String_Processing/ch6_01_kmp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define MAX_N 100010 6 | 7 | char T[MAX_N], P[MAX_N]; // T = text, P = pattern 8 | int b[MAX_N], n, m; // b = back table, n = length of T, m = length of P 9 | 10 | void naiveMatching() { 11 | for (int i = 0; i < n; i++) { // try all potential starting indices 12 | bool found = true; 13 | for (int j = 0; j < m && found; j++) // use boolean flag `found' 14 | if (P[j] != T[i + j]) // if mismatch found 15 | found = false; // abort this, shift starting index i by +1 16 | if (found) // if P[0 .. m - 1] == T[i .. i + m - 1] 17 | printf("P is found at index %d in T\n", i); 18 | } } 19 | 20 | void kmpPreprocess() { // call this before calling kmpSearch() 21 | int i = 0, j = -1; b[0] = -1; // starting values 22 | while (i < m) { // pre-process the pattern string P 23 | while (j >= 0 && P[i] != P[j]) j = b[j]; // if different, reset j using b 24 | i++; j++; // if same, advance both pointers 25 | b[i] = j; // observe i = 8, 9, 10, 11, 12 with j = 0, 1, 2, 3, 4 26 | } } // in the example of P = "SEVENTY SEVEN" above 27 | 28 | void kmpSearch() { // this is similar as kmpPreprocess(), but on string T 29 | int i = 0, j = 0; // starting values 30 | while (i < n) { // search through string T 31 | while (j >= 0 && T[i] != P[j]) j = b[j]; // if different, reset j using b 32 | i++; j++; // if same, advance both pointers 33 | if (j == m) { // a match found when j == m 34 | printf("P is found at index %d in T\n", i - j); 35 | j = b[j]; // prepare j for the next possible match 36 | } } } 37 | 38 | int main() { 39 | n = (int)strlen(gets(T)); 40 | m = (int)strlen(gets(P)); 41 | 42 | printf("Naive\n"); 43 | naiveMatching(); 44 | 45 | printf("KMP\n"); 46 | kmpPreprocess(); 47 | kmpSearch(); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_09_spoj101.cpp: -------------------------------------------------------------------------------- 1 | /* SPOJ 101 - Fishmonger */ 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | typedef pair ii; 8 | #define MAX_N 55 9 | #define MAX_T 1005 10 | #define INF 2000000000 11 | 12 | int i, j, n, t, toll[MAX_N][MAX_N], travelTime[MAX_N][MAX_N]; 13 | ii memo[MAX_N][MAX_T]; 14 | 15 | ii go(int cur, int t_left) { // top-down DP, returns a pair 16 | if (t_left < 0) return ii(INF, INF); // invalid state 17 | if (cur == n - 1) return ii(0, 0); // at last city, no need to pay toll and time needed is 0 18 | if (memo[cur][t_left] != ii(-1, -1)) return memo[cur][t_left]; // visited before 19 | ii ans = ii(INF, INF); 20 | for (int nxt = 0; nxt < n; nxt++) if (cur != nxt) { // try to go to another city 21 | ii nextCity = go(nxt, t_left - travelTime[cur][nxt]); // recursive step 22 | if (nextCity.first + toll[cur][nxt] < ans.first) { // pick the one that has min cost 23 | ans.first = nextCity.first + toll[cur][nxt]; 24 | ans.second = nextCity.second + travelTime[cur][nxt]; 25 | } } 26 | return memo[cur][t_left] = ans; 27 | } // store the answer to memo table as well as returning the answer to the caller 28 | 29 | int main() { 30 | /* 31 | // sample input 32 | 4 7 33 | 0 5 2 3 34 | 5 0 2 3 35 | 3 1 0 2 36 | 3 3 2 0 37 | 38 | 0 2 2 7 39 | 2 0 1 2 40 | 2 2 0 5 41 | 7 2 5 0 42 | 43 | 0 0 44 | 45 | // sample output 46 | 6 6 47 | */ 48 | 49 | while (scanf("%d %d", &n, &t), (n || t)) { 50 | for (i = 0; i < n; i++) 51 | for (j = 0; j < n; j++) 52 | scanf("%d", &travelTime[i][j]); 53 | for (i = 0; i < n; i++) 54 | for (j = 0; j < n; j++) 55 | scanf("%d", &toll[i][j]); 56 | 57 | for (i = 0; i <= n; i++) 58 | for (j = 0; j <= t; j++) 59 | memo[i][j] = ii(-1, -1); 60 | ii res = go(0, t); 61 | printf("%d %d\n", res.first, res.second); 62 | } 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/B/B.cc: -------------------------------------------------------------------------------- 1 | // FlipIt.cc 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | #define FOR(i,a,b) for(int i=a;i A[20][20]; 13 | 14 | void init(){ 15 | Left=Top=0; 16 | Bottom = n-1; 17 | Right = m-1; 18 | } 19 | 20 | void GetArray(){ 21 | int x; 22 | FOR(i,0,n) 23 | FOR(j,0,m) 24 | A[i][j].clear(); 25 | FOR(i,0,n) 26 | FOR(j,0,m){ 27 | cin>>x; 28 | A[i][j].push_back(x); 29 | } 30 | } 31 | 32 | void MakeFlip(char c){ 33 | if(c=='L'){ //A[*][Left] -> A[*][Left+1] 34 | FOR(j,Top,Bottom+1){ 35 | for(int k=A[j][Left].size()-1; k>=0; k--){ 36 | A[j][Left+1].push_back(A[j][Left][k] * -1); 37 | } 38 | } 39 | Left++; 40 | return; 41 | } 42 | if(c=='R'){ //A[*][Right] -> A[*][Right-1] 43 | FOR(j,Top,Bottom+1){ 44 | for(int k=A[j][Right].size()-1; k>=0; k--){ 45 | A[j][Right-1].push_back(A[j][Right][k] * -1); 46 | } 47 | } 48 | Right--; 49 | return; 50 | } 51 | if(c=='B'){ //A[Bottom][*] -> A[Bottom-1][*] 52 | FOR(i,Left,Right+1){ 53 | for(int k=A[Bottom][i].size()-1; k>=0;k--){ 54 | A[Bottom-1][i].push_back(A[Bottom][i][k] * -1); 55 | } 56 | } 57 | Bottom--; 58 | return; 59 | } 60 | if(c=='T'){ //A[Top][*] -> A[Top+1][*] 61 | FOR(i,Left,Right+1){ 62 | for(int k=A[Top][i].size()-1; k>=0;k--){ 63 | A[Top+1][i].push_back(A[Top][i][k] * -1); 64 | } 65 | } 66 | Top++; 67 | return; 68 | } 69 | } 70 | 71 | int main(){ 72 | char c; 73 | 74 | cin>>n>>m; 75 | while(n>0){ 76 | GetArray(); 77 | init(); 78 | 79 | FOR(i,0,n+m-2){ 80 | cin>>c; 81 | MakeFlip(c); 82 | } 83 | cout<<"Case "<0) 86 | cout<<' '<>n>>m; 90 | } 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_08_unionfind_ds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | typedef vector vi; 6 | 7 | // Union-Find Disjoint Sets Library 8 | // PS: This library code does not include the `union by rank' heuristic yet 9 | // 1000 is just a rough number, adjustable by user 10 | vi pset(1000), setSize(1000); int _numDisjointSets; 11 | void initSet(int N) { setSize.assign(N, 1); _numDisjointSets = N; 12 | pset.assign(N, 0); for (int i = 0; i < N; i++) pset[i] = i; } 13 | int findSet(int i) { return (pset[i] == i) ? i : (pset[i] = findSet(pset[i])); } 14 | bool isSameSet(int i, int j) { return findSet(i) == findSet(j); } 15 | void unionSet(int i, int j) { 16 | if (!isSameSet(i, j)) { 17 | _numDisjointSets--; 18 | setSize[findSet(j)] += setSize[findSet(i)]; 19 | pset[findSet(i)] = findSet(j); } } 20 | int numDisjointSets() { return _numDisjointSets; } 21 | int sizeOfSet(int i) { return setSize[findSet(i)]; } 22 | 23 | int main() { 24 | printf("Assume that there are 5 disjoint sets initially\n"); 25 | initSet(5); // create 5 disjoint sets 26 | unionSet('A' - 'A', 'B' - 'A'); // unionSet(A, B) 27 | unionSet('A' - 'A', 'C' - 'A'); // unionSet(A, C) 28 | unionSet('D' - 'A', 'B' - 'A'); // unionSet(D, B) 29 | printf("findSet(A) = %d\n", findSet('A' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 30 | printf("findSet(B) = %d\n", findSet('B' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 31 | printf("findSet(C) = %d\n", findSet('C' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 32 | printf("findSet(D) = %d\n", findSet('D' - 'A')); // will return 2 (the parent ID of 'A', 'B', 'C', 'D') 33 | printf("findSet(E) = %d\n", findSet('E' - 'A')); // will return 4 (the parent ID of 'E') 34 | printf("isSameSet(A, E) = %d\n", isSameSet('A' - 'A', 'E' - 'A')); // will return 0 (false) 35 | printf("isSameSet(A, B) = %d\n", isSameSet('A' - 'A', 'B' - 'A')); // will return 1 (true) 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /tryouts/2011/mm08sj/1205.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | void search(int root, vector weights, map*> connections); 12 | 13 | int main() 14 | { 15 | string line; 16 | int nodes = 0; 17 | int root; 18 | cin >> nodes >> root; 19 | vector weights; 20 | map*> nodelist; 21 | for(int i =0; i> val; 25 | weights.push_back(val); 26 | nodelist[i+1] = new vector(); 27 | } 28 | while(true) 29 | { 30 | int input, output; 31 | cin >> input; 32 | cin >> output; 33 | if(input==0 || output==0) 34 | break; 35 | nodelist[input]->push_back(output); 36 | } 37 | search(root,weights,nodelist); 38 | return 0; 39 | } 40 | 41 | 42 | void search(int root, vector weights, map*> connections) 43 | { 44 | queue*> orders; 45 | vector* startvect = new vector(); 46 | startvect->push_back(root); 47 | orders.push(startvect); 48 | int bestvalue = 0; 49 | while(!orders.empty()) 50 | { 51 | vector* order = orders.front(); 52 | orders.pop(); 53 | if(order->size() next; 56 | for(int i = 0; isize(); i++) 57 | { 58 | vector* children = connections[(*order)[i]]; 59 | for(int i = 0; isize(); i++) 60 | { 61 | next.insert((*children)[i]); 62 | } 63 | set::iterator it; 64 | for(it = next.begin(); it!=next.end(); it++) 65 | { 66 | vector* nextvect = new vector(order->begin(),order->end()); 67 | nextvect->push_back(*it); 68 | orders.push(nextvect); 69 | } 70 | } 71 | } 72 | else 73 | { 74 | int value = 0; 75 | for(int i=0; isize(); i++) 76 | { 77 | value += (i+1) * weights[(*order)[i]]; 78 | } 79 | if(bestvalue==0 || value 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | typedef pair ii; 8 | typedef vector vi; 9 | typedef vector vii; 10 | #define INF 1000000000 11 | 12 | int main() { 13 | int V, E, s, u, v, w; 14 | vector AdjList; 15 | 16 | /* 17 | // Graph in Figure 4.17, has negative weight, but no negative cycle 18 | 5 5 0 19 | 0 1 1 20 | 0 2 10 21 | 1 3 2 22 | 2 3 -10 23 | 3 4 3 24 | 25 | // Graph in Figure 4.18, negative cycle exists 26 | 3 3 0 27 | 0 1 1000 28 | 1 2 15 29 | 2 1 -42 30 | */ 31 | 32 | scanf("%d %d %d", &V, &E, &s); 33 | 34 | AdjList.assign(V, vii()); // assign blank vectors of pairs to AdjList 35 | for (int i = 0; i < E; i++) { 36 | scanf("%d %d %d", &u, &v, &w); 37 | AdjList[u].push_back(ii(v, w)); 38 | } 39 | 40 | // Bellman Ford routine 41 | vi dist(V, INF); dist[s] = 0; 42 | for (int i = 0; i < V - 1; i++) // relax all E edges V-1 times, overall O(VE) 43 | for (int u = 0; u < V; u++) // these two loops = O(E) 44 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 45 | ii v = AdjList[u][j]; // we can record SP spanning here if needed 46 | dist[v.first] = min(dist[v.first], dist[u] + v.second); // relax 47 | } 48 | 49 | bool hasNegativeCycle = false; 50 | for (int u = 0; u < V; u++) // one more pass to check 51 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 52 | ii v = AdjList[u][j]; 53 | if (dist[v.first] > dist[u] + v.second) // should be false 54 | hasNegativeCycle = true; // but if true, then negative cycle exists! 55 | } 56 | printf("Negative Cycle Exist? %s\n", hasNegativeCycle ? "Yes" : "No"); 57 | 58 | if (!hasNegativeCycle) 59 | for (int i = 0; i < V; i++) 60 | printf("SSSP(%d, %d) = %d\n", s, i, dist[i]); 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /resources/c++_and_stl/test-compgeo.cpp: -------------------------------------------------------------------------------- 1 | #include "compgeo.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | std::cout << dist(point(2.0, 2.0), point(6.0, 5.0)) << std::endl; 11 | std::cout << dist(2.0, 2.0, 6.0, 5.0) << std::endl; 12 | std::cout << distR(2.0, 2.0, 6.0, 5.0) << std::endl; 13 | 14 | line l1(point(2.0,2.0), point(4.0,3.0)); 15 | line l2(2,2,2,5); 16 | printf("a = %f, b = %f, c = %f\n", l1.a, l1.b, l1.c); 17 | printf("a = %f, b = %f, c = %f\n", l2.a, l2.b, l2.c); 18 | std::cout << areSame(l1, l2) << std::endl; 19 | 20 | std::cout << cross(2,2,4,3,6,5) << std::endl; 21 | std::cout << cross(point(2,2),point(4,3),point(6,5)) << std::endl; 22 | std::cout << ccw(point(2,2),point(4,3),point(6,5)) << std::endl; 23 | std::cout << crossOper(2,2,4,3,6,5) << std::endl; 24 | 25 | vector P; 26 | P.push_back(point(2, 2)); 27 | P.push_back(point(4, 3)); 28 | P.push_back(point(2, 4)); 29 | P.push_back(point(6, 6)); 30 | P.push_back(point(2, 6)); 31 | P.push_back(point(6, 5)); 32 | 33 | // Sorting points demo. 34 | sort(P.begin(), P.end()); 35 | for (int i = 0; i < (int)P.size(); i++) 36 | printf("(%.2lf, %.2lf)\n", P[i].x, P[i].y); 37 | 38 | // Rearrange points. 39 | P.clear(); 40 | P.push_back(point(2, 2)); 41 | P.push_back(point(4, 3)); 42 | P.push_back(point(2, 4)); 43 | P.push_back(point(6, 6)); 44 | P.push_back(point(2, 6)); 45 | P.push_back(point(6, 5)); 46 | 47 | line l3(P[2], P[3]); 48 | point ans; 49 | closestPoint(l3, P[0], ans); 50 | printf("Closest point from P[0] to line V2 (P[2]-P[3]): (%.2lf, %.2lf), dist = %.2lf\n", ans.x, ans.y, dist(P[0], ans)); 51 | 52 | printf("P[0], P[2], P[3] are collinear? %d\n", collinear(P[0], P[2], P[3])); // no 53 | printf("P[0], P[2], P[4] are collinear? %d\n", collinear(P[0], P[2], P[4])); // yes 54 | 55 | printf("P[0], P[2], P[3] form A left turn? %d\n", ccw(P[0], P[2], P[3])); // no 56 | printf("P[0], P[3], P[2] form A left turn? %d\n", ccw(P[0], P[3], P[2])); // yes 57 | } 58 | -------------------------------------------------------------------------------- /resources/c++_and_stl/string_tokenizer.cc: -------------------------------------------------------------------------------- 1 | /* C++ - String Tokenizer 2 | ================================================================= 3 | Description: Takes a string and divides it into either substrings 4 | or ints 5 | Complexity: O(M) - M the length of the string 6 | ----------------------------------------------------------------- 7 | Author: Scott Crosswhite 8 | Date: Feb 10, 2003 9 | References: 10 | ----------------------------------------------------------------- 11 | Reliability: 0 12 | Notes: 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | using namespace std; 20 | 21 | /* Subdivide it into strings separated by the characters in div */ 22 | vector makeStringTokens (string s, string div) { 23 | vector items; 24 | int i=0, j; 25 | 26 | for (i=s.find_first_not_of(div, i); i!=-1; i=s.find_first_not_of(div, i=j)) { 27 | j = s.find_first_of(div, i); 28 | items.push_back(s.substr(i, j-i)); 29 | } 30 | return items; 31 | } 32 | 33 | /* Subdivide it into ints separated by the characters in div */ 34 | vector makeIntTokens (string s, string div) { 35 | vector items; 36 | int i=0, j; 37 | 38 | for (i=s.find_first_not_of(div, i); i!=-1; i=s.find_first_not_of(div, i=j)) { 39 | j = s.find_first_of(div, i); 40 | items.push_back(atoi(s.substr(i, j-i).c_str())); 41 | } 42 | return items; 43 | } 44 | 45 | 46 | int main () { 47 | string testString = "This is a test", testInt = "4:5:6:7:8"; 48 | unsigned int i; 49 | 50 | vector resString = makeStringTokens(testString, " "); 51 | vectorresInt = makeIntTokens(testInt, ":"); 52 | 53 | cout << "Result of tokenizing the string: \"" 54 | << testString 55 | << "\"" << endl; 56 | 57 | for (i=0; i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | typedef pair ii; 7 | typedef vector vi; 8 | typedef vector vii; 9 | #define INF 1000000000 10 | 11 | int main() { 12 | int V, E, s, u, v, w; 13 | vector AdjList; 14 | 15 | /* 16 | // Graph in Figure 4.16 17 | 5 7 2 18 | 2 1 2 19 | 2 3 7 20 | 2 0 6 21 | 1 3 3 22 | 1 4 6 23 | 3 4 5 24 | 0 4 1 25 | 26 | // Graph in Figure 4.17, has negative weight, but no negative cycle 27 | 5 5 0 28 | 0 1 1 29 | 0 2 10 30 | 1 3 2 31 | 2 3 -10 32 | 3 4 3 33 | */ 34 | 35 | scanf("%d %d %d", &V, &E, &s); 36 | 37 | AdjList.assign(V, vii()); // assign blank vectors of pairs to AdjList 38 | for (int i = 0; i < E; i++) { 39 | scanf("%d %d %d", &u, &v, &w); 40 | AdjList[u].push_back(ii(v, w)); // directed graph 41 | } 42 | 43 | // Dijkstra routine 44 | vi dist(V, INF); dist[s] = 0; // INF = 1B to avoid overflow 45 | priority_queue< ii, vector, greater > pq; pq.push(ii(0, s)); 46 | // ^to sort the pairs by increasing distance from s 47 | while (!pq.empty()) { // main loop 48 | ii front = pq.top(); pq.pop(); // greedy: pick shortest unvisited vertex 49 | int d = front.first, u = front.second; 50 | if (d == dist[u]) // this check is important, see the explanation 51 | for (int j = 0; j < (int)AdjList[u].size(); j++) { 52 | ii v = AdjList[u][j]; // all outgoing edges from u 53 | if (dist[u] + v.second < dist[v.first]) { 54 | dist[v.first] = dist[u] + v.second; // relax operation 55 | pq.push(ii(dist[v.first], v.first)); 56 | } } } // note: this variant can cause duplicate items in the priority queue 57 | 58 | for (int i = 0; i < V; i++) // index + 1 for final answer 59 | printf("SSSP(%d, %d) = %d\n", s, i, dist[i]); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch8-Advanced/ch8_03_UVa10911.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.text.*; 3 | 4 | class Main { /* UVa 10911 - Forming Quiz Teams */ 5 | private static int N, x[] = new int[20], y[] = new int[20], caseNo = 1; 6 | private static double dist[][] = new double[20][], memo[] = new double[65536]; // this is 2^16, max N = 8 7 | 8 | private static double matching(int bit_mask) { 9 | if (memo[bit_mask] > -0.1) // we initialize the array with -1 10 | return memo[bit_mask]; 11 | 12 | if (bit_mask == (1 << (2 * N)) - 1) // all are matched 13 | return memo[bit_mask] = 0; 14 | 15 | double matching_value = 32767 * 32767; 16 | for (int p1 = 0; p1 < 2 * N; p1++) 17 | if (1 - (bit_mask & (1 << p1)) == 1) { // if this bit is off 18 | for (int p2 = p1 + 1; p2 < 2 * N; p2++) 19 | if (1 - (bit_mask & (1 << p2)) == 1) // if this different bit is also off 20 | matching_value = Math.min(matching_value, 21 | dist[p1][p2] + matching(bit_mask | (1 << p1) | (1 << p2))); 22 | break; // to improve the complexity from O(16^2 * 2^N) to O(16 * 2^N) 23 | } 24 | 25 | return memo[bit_mask] = matching_value; 26 | } 27 | 28 | public static void main(String[] args) { 29 | Scanner sc = new Scanner(System.in); 30 | while (true) { 31 | N = sc.nextInt(); 32 | if (N == 0) 33 | break; 34 | 35 | for (int i = 0; i < 2 * N; i++) { 36 | String name = sc.next(); // dummy 37 | x[i] = sc.nextInt(); 38 | y[i] = sc.nextInt(); 39 | } 40 | 41 | for (int i = 0; i < 2 * N; i++) { 42 | dist[i] = new double[20]; 43 | for (int j = 0; j < 2 * N; j++) 44 | dist[i][j] = Math.sqrt((double)(x[i] - x[j]) * (x[i] - x[j]) + 45 | (y[i] - y[j]) * (y[i] - y[j])); 46 | } 47 | 48 | // using DP to solve matching on general graph 49 | for (int i = 0; i < 65536; i++) 50 | memo[i] = -1.0; 51 | System.out.println(String.format("Case %d: %.2f", caseNo++, matching(0))); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch7-Computational_Geometry/ch7_04_UVa11817.java: -------------------------------------------------------------------------------- 1 | /* Tunnelling the Earth */ 2 | 3 | // Great Circle distance + Euclidean distance 4 | 5 | import java.util.*; 6 | 7 | class ch7_04_UVa11817 { 8 | static final int EARTH_RAD = 6371009; // in meters 9 | 10 | static double gcDistance(double pLat, double pLong, 11 | double qLat, double qLong, double radius) { 12 | pLat *= Math.PI / 180; pLong *= Math.PI / 180; 13 | qLat *= Math.PI / 180; qLong *= Math.PI / 180; 14 | return radius * Math.acos(Math.cos(pLat)*Math.cos(pLong)*Math.cos(qLat)*Math.cos(qLong) + 15 | Math.cos(pLat)*Math.sin(pLong)*Math.cos(qLat)*Math.sin(qLong) + 16 | Math.sin(pLat)*Math.sin(qLat)); 17 | } 18 | 19 | static double EucledianDistance(double pLat, double pLong, // 3D version 20 | double qLat, double qLong, double radius) { 21 | double phi1 = (90 - pLat) * Math.PI / 180; 22 | double theta1 = (360 - pLong) * Math.PI / 180; 23 | double x1 = radius * Math.sin(phi1) * Math.cos(theta1); 24 | double y1 = radius * Math.sin(phi1) * Math.sin(theta1); 25 | double z1 = radius * Math.cos(phi1); 26 | 27 | double phi2 = (90 - qLat) * Math.PI / 180; 28 | double theta2 = (360 - qLong) * Math.PI / 180; 29 | double x2 = radius * Math.sin(phi2) * Math.cos(theta2); 30 | double y2 = radius * Math.sin(phi2) * Math.sin(theta2); 31 | double z2 = radius * Math.cos(phi2); 32 | 33 | double dx = x1 - x2, dy = y1 - y2, dz = z1 - z2; 34 | return Math.sqrt(dx * dx + dy * dy + dz * dz); 35 | } 36 | 37 | public static void main(String[] args) { 38 | Scanner scan = new Scanner(System.in); 39 | int TC = scan.nextInt(); 40 | while (TC-- > 0) { 41 | double lat1 = scan.nextDouble(); 42 | double lon1 = scan.nextDouble(); 43 | double lat2 = scan.nextDouble(); 44 | double lon2 = scan.nextDouble(); 45 | System.out.printf("%.0f\n", gcDistance(lat1, lon1, lat2, lon2, EARTH_RAD) - 46 | EucledianDistance(lat1, lon1, lat2, lon2, EARTH_RAD)); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch3-Problem_Solving_Methods/ch3_07_UVa10130.cpp: -------------------------------------------------------------------------------- 1 | /* SuperSale */ 2 | 3 | // 0-1 Knapsack DP (Top-Down) - faster as not all states are visited 4 | 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | #define MAX_N 1010 11 | #define MAX_W 40 12 | 13 | int N, MW, V[MAX_N], W[MAX_N], memo[MAX_N][MAX_W]; 14 | 15 | int value(int id, int w) { 16 | if (id == N || w == 0) return 0; 17 | if (memo[id][w] != -1) return memo[id][w]; 18 | if (W[id] > w) return memo[id][w] = value(id + 1, w); 19 | return memo[id][w] = max(value(id + 1, w), V[id] + value(id + 1, w - W[id])); 20 | } 21 | 22 | int main() { 23 | int i, T, G, ans; 24 | 25 | scanf("%d", &T); 26 | while (T--) { 27 | memset(memo, -1, sizeof memo); 28 | 29 | scanf("%d", &N); 30 | for (i = 0; i < N; i++) 31 | scanf("%d %d", &V[i], &W[i]); 32 | 33 | ans = 0; 34 | scanf("%d", &G); 35 | while (G--) { 36 | scanf("%d", &MW); 37 | ans += value(0, MW); 38 | } 39 | 40 | printf("%d\n", ans); 41 | } 42 | 43 | return 0; 44 | } 45 | 46 | /* 47 | 48 | // 0-1 Knapsack DP (Bottom-Up) 49 | 50 | #include 51 | #include 52 | using namespace std; 53 | 54 | #define MAX_N 1010 55 | #define MAX_W 40 56 | 57 | int main() { 58 | int i, w, T, N, G, MW, V[MAX_N], W[MAX_N], C[MAX_N][MAX_W], ans; 59 | 60 | scanf("%d", &T); 61 | while (T--) { 62 | scanf("%d", &N); 63 | for (i = 1; i<= N; i++) 64 | scanf("%d %d", &V[i], &W[i]); 65 | 66 | ans = 0; 67 | scanf("%d", &G); 68 | while (G--) { 69 | scanf("%d", &MW); 70 | 71 | for (i = 0; i <= N; i++) C[i][0] = 0; 72 | for (w = 0; w <= MW; w++) C[0][w] = 0; 73 | 74 | for (i = 1; i <= N; i++) 75 | for (w = 1; w <= MW; w++) { 76 | if (Wi[i] > w) C[i][w] = C[i - 1][w]; 77 | else C[i][w] = max(C[i - 1][w], V[i] + C[i - 1][w - W[i]]); 78 | } 79 | 80 | ans += C[N][MW]; 81 | } 82 | 83 | printf("%d\n", ans); 84 | } 85 | 86 | return 0; 87 | } 88 | 89 | */ 90 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/E/E.cc: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int MAXRINGS = 100; 5 | const int MAXSECTORS = 100; 6 | 7 | bool table[MAXRINGS][MAXSECTORS]; 8 | bool tmp[MAXRINGS][MAXSECTORS]; 9 | 10 | int getRowCount(int r, int s, int ns) 11 | { 12 | int count = table[r][s]; 13 | if (s>0) 14 | count += table[r][s-1]; 15 | else 16 | count += table[r][ns-1]; 17 | if (s> m >> n; 42 | while (m > 0) { 43 | icase++; 44 | for(int i=0; i> k; 48 | for(int i=0; i> r >> s; 51 | table[r][s] = true; 52 | } 53 | cin >> g; 54 | 55 | for(int ig=1; ig<=g; ig++) { 56 | for(int i=0; i> m >> n; 94 | } 95 | } 96 | 97 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch6-String_Processing/ch6_01_kmp.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch6_01_kmp { 4 | char[] T, P; // T = text, P = pattern 5 | int n, m; // n = length of T, m = length of P 6 | int [] b; // b = back table 7 | 8 | void naiveMatching() { 9 | for (int i = 0; i < n; i++) { // try all potential starting indices 10 | boolean found = true; 11 | for (int j = 0; j < m && found; j++) // use boolean flag `found' 12 | if (P[j] != T[i + j]) // if mismatch found 13 | found = false; // abort this, shift starting index i by +1 14 | if (found) // if P[0 .. m - 1] == T[i .. i + m - 1] 15 | System.out.printf("P is found at index %d in T\n", i); 16 | } } 17 | 18 | void kmpPreprocess() { // call this before calling kmpSearch() 19 | int i = 0, j = -1; b[0] = -1; // starting values 20 | while (i < m) { // pre-process the pattern string P 21 | while (j >= 0 && P[i] != P[j]) j = b[j]; // if different, reset j using b 22 | i++; j++; // if same, advance both pointers 23 | b[i] = j; // observe i = 8, 9, 10, 11, 12 with j = 0, 1, 2, 3, 4 24 | } } // in the example of P = "SEVENTY SEVEN" above 25 | 26 | void kmpSearch() { // this is similar as kmpPreprocess(), but on string T 27 | int i = 0, j = 0; // starting values 28 | while (i < n) { // search through string T 29 | while (j >= 0 && T[i] != P[j]) j = b[j]; // if different, reset j using b 30 | i++; j++; // if same, advance both pointers 31 | if (j == m) { // a match found when j == m 32 | System.out.printf("P is found at index %d in T\n", i - j); 33 | j = b[j]; // prepare j for the next possible match 34 | } } } 35 | 36 | void run() { 37 | Scanner scan = new Scanner(System.in); 38 | T = scan.nextLine().toCharArray(); 39 | P = scan.nextLine().toCharArray(); 40 | n = T.length; 41 | m = P.length; 42 | b = new int[100010]; 43 | 44 | System.out.printf("Naive\n"); 45 | naiveMatching(); 46 | 47 | System.out.printf("KMP\n"); 48 | kmpPreprocess(); 49 | kmpSearch(); 50 | } 51 | 52 | public static void main(String[] args){ 53 | new ch6_01_kmp().run(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /tryouts/2011/jt11li/ColorTree.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ColorTree 4 | { 5 | int time = 1, currentCost = 0; 6 | int numNodes = 0, firstNodeNum = 0; 7 | Node[] nodes; 8 | //stores the current node that is being processed 9 | Node currentNode = new Node(); 10 | 11 | public static void main (String[] args) 12 | { 13 | ColorTree colorTree = new ColorTree(); 14 | } 15 | 16 | public ColorTree() 17 | { 18 | //-----START----- 19 | 20 | //get input from user 21 | getInput(); 22 | 23 | nodes = new Node[numNodes]; 24 | currentNode = nodes[0]; 25 | 26 | color(); 27 | } 28 | 29 | public void getInput() 30 | { 31 | Scanner scanner = new Scanner(System.in); 32 | 33 | numNodes = scanner.nextInt(); 34 | firstNodeNum = scanner.nextInt(); 35 | //get node color costs 36 | for (int i = 0; i < numNodes; i ++) 37 | { 38 | //set variables for nodes 39 | nodes[i] = new Node(); 40 | nodes[i].colorCost = scanner.nextInt(); 41 | nodes[i].number = i + firstNodeNum; 42 | } 43 | 44 | } 45 | 46 | public void color() 47 | { 48 | int[] lowestCosts = new int[numNodes]; 49 | for (int i = 0; i < numNodes; i++) 50 | { 51 | if (nodes[i].isActive) 52 | { 53 | lowestCosts[i] = getLowestColorCost(currentNode); 54 | } 55 | } 56 | } 57 | 58 | //gets lowest child color cost 59 | public int getLowestColorCost(Node fatherNode) 60 | { 61 | //get the child nodes and the cost of each of those child nodes 62 | Node[] childNodes = currentNode.childNodes; 63 | int numChild = childNodes.length; 64 | 65 | int[] colorCost_child = new int[numChild]; 66 | for (int i = 0; i < numChild; i ++) 67 | { 68 | colorCost_child[i] = childNodes[i].colorCost; 69 | } 70 | 71 | //get lowest cost 72 | int lowest = 501; 73 | for (int i = 0; i < numChild; i++) 74 | { 75 | if (colorCost_child[i] < lowest) 76 | { 77 | lowest = colorCost_child[i]; 78 | } 79 | } 80 | 81 | return lowest; 82 | } 83 | } -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/F/F.cc: -------------------------------------------------------------------------------- 1 | // Voting.cc 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | 8 | #define FOR(i, low, hi) for(int i=low; i> Pop[n-1-i]>>Init_perc[n-1-i]>>Delta_perc[n-1-i]; 20 | Init_perc[n-1-i] *= 0.01; 21 | Delta_perc[n-1-i] *= 0.01; 22 | } 23 | } 24 | 25 | void init(){ 26 | FOR(i,0,n) 27 | FOR(j,0,m+1) 28 | V[j][i]=Spent[j][i]=0; 29 | 30 | V[0][0]=round(Pop[0]*Init_perc[0]); //no money spent 31 | 32 | //figure values for precinct 0 33 | FOR(j,1,m+1){ 34 | V[j][0] = round( Pop[0]*(Init_perc[0]+(Delta_perc[0]*j)/((double)(10.1+j)))); 35 | Spent[j][0] = j; 36 | } 37 | } 38 | 39 | void PrintPrecinctInfo(){ 40 | int money = m; 41 | FOR(i,0,n){ 42 | if(i>0) cout<<' '; 43 | cout<>m>>n; 53 | while(m>0){ 54 | //m /= 100; 55 | GetInfo(); 56 | init(); 57 | 58 | FOR(i,1,n){ 59 | FOR(j,0,m+1){ //j=money spent on precincts 0..i 60 | int MaxVotes=V[0][i]; //default is to spend no money 61 | int LocalSpent = 0; 62 | FOR(k,0,j+1){ //spend k (out of j) on prec i 63 | int Vo = //spend k on prec i and j-k on prec 0..i-1 64 | round (Pop[i]*(Init_perc[i]+(Delta_perc[i]*k)/((double) 10.1+k))) 65 | + V[j-k][i-1]; 66 | if(Vo >= MaxVotes){ 67 | LocalSpent = k; 68 | MaxVotes = Vo; 69 | } 70 | } 71 | V[j][i] = MaxVotes; 72 | Spent[j][i] = LocalSpent; 73 | } 74 | } 75 | 76 | //V[m][n-1] is the best we can do 77 | cout << "Case "<< CaseNo++<<": "<< V[m][n-1]<< endl; 78 | //PrintPrecinctInfo(n-1, m); 79 | PrintPrecinctInfo(); 80 | cout<>m>>n; 83 | } 84 | 85 | return 0; 86 | } 87 | 88 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_10_fenwicktree_ds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | typedef vector vi; 6 | #define LSOne(S) (S & (-S)) 7 | 8 | // initialization: n + 1 zeroes, ignoring index 0, just using index [1..n] 9 | void ft_create(vi &ft, int n) { ft.assign(n + 1, 0); } 10 | 11 | int ft_rsq(const vi &ft, int b) { // returns RSQ(1, b) 12 | int sum = 0; for (; b; b -= LSOne(b)) sum += ft[b]; 13 | return sum; } 14 | 15 | int ft_rsq(const vi &ft, int a, int b) { // returns RSQ(a, b) 16 | return ft_rsq(ft, b) - (a == 1 ? 0 : ft_rsq(ft, a - 1)); } 17 | 18 | // adjusts value of the k-th element by v (v can be +ve/inc or -ve/dec) 19 | void ft_adjust(vi &ft, int k, int v) { // note: n = ft.size() - 1 20 | for (; k < (int)ft.size(); k += LSOne(k)) ft[k] += v; } 21 | 22 | int main() { 23 | vi ft; // idx 0 1 2 3 4 5 6 7 8 9 10, no index 0! 24 | ft_create(ft, 10); // ft = {-,0,0,0,0,0,0,0, 0,0,0} 25 | ft_adjust(ft, 2, 1); // ft = {-,0,1,0,1,0,0,0, 1,0,0}, idx 2,4,8 => +1 26 | ft_adjust(ft, 4, 1); // ft = {-,0,1,0,2,0,0,0, 2,0,0}, idx 4,8 => +1 27 | ft_adjust(ft, 5, 2); // ft = {-,0,1,0,2,2,2,0, 4,0,0}, idx 5,6,8 => +2 28 | ft_adjust(ft, 6, 3); // ft = {-,0,1,0,2,2,5,0, 7,0,0}, idx 6,8 => +3 29 | ft_adjust(ft, 7, 2); // ft = {-,0,1,0,2,2,5,2, 9,0,0}, idx 7,8 => +2 30 | ft_adjust(ft, 8, 1); // ft = {-,0,1,0,2,2,5,2,10,0,0}, idx 8 => +1 31 | ft_adjust(ft, 9, 1); // ft = {-,0,1,0,2,2,5,2,10,1,1}, idx 9,10 => +1 32 | printf("%d\n", ft_rsq(ft, 1, 1)); // 0 => ft[1] = 0 33 | printf("%d\n", ft_rsq(ft, 1, 2)); // 1 => ft[2] = 1 34 | printf("%d\n", ft_rsq(ft, 1, 6)); // 7 => ft[6] + ft[4] = 5 + 2 = 7 35 | printf("%d\n", ft_rsq(ft, 1, 10)); // 11 => ft[10] + ft[8] = 1 + 10 = 11 36 | printf("%d\n", ft_rsq(ft, 3, 6)); // 6 => rsq(1, 6) - rsq(1, 2) = 7 - 1 37 | 38 | ft_adjust(ft, 5, 2); // update demo 39 | printf("Index: "); 40 | for (int i = 0; i < (int)ft.size(); i++) 41 | printf("%d ", i); 42 | printf("\n"); 43 | printf("FT : "); 44 | for (int i = 0; i < (int)ft.size(); i++) 45 | printf("%d ", ft[i]); 46 | printf("\n"); 47 | } // return 0; -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_05_stl_map_set.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() { 8 | char name[20]; 9 | int value; 10 | // note: there are many clever usages of this set/map 11 | // that you can learn by looking at top coder's codes 12 | // note, we don't have to use .clear() if we have just initialized the set/map 13 | set used_values; // used_values.clear(); 14 | map mapper; // mapper.clear(); 15 | 16 | // suppose we enter these 7 name-score pairs via keyboard 17 | /* 18 | john 78 19 | billy 69 20 | andy 80 21 | steven 77 22 | felix 82 23 | grace 75 24 | martin 81 25 | */ 26 | for (int i = 0; i < 7; i++) { 27 | scanf("%s %d", &name, &value); 28 | mapper[name] = value; // map example 29 | used_values.insert(value); // set example 30 | } 31 | 32 | // then the internal content of mapper MAY be something like this: 33 | // re-read balanced BST concept if you do not understand this diagram 34 | // the keys are names (string)! 35 | // (grace,75) 36 | // (billy,69) (martin,81) 37 | // (andy,80) (felix,82) (john,78) (steven,77) 38 | 39 | // iterating through the content of mapper will give a sorted output 40 | // based on keys (names) 41 | for (map::iterator it = mapper.begin(); it != mapper.end(); it++) 42 | printf("%s %d\n", ((string)it->first).c_str(), it->second); 43 | 44 | // map can also be used like this 45 | printf("steven's score is %d, grace's score is %d\n", 46 | mapper["steven"], mapper["grace"]); 47 | printf("==================\n"); 48 | 49 | // the internal content of used_values MAY be something like this 50 | // the keys are values (integers)! 51 | // (78) 52 | // (75) (81) 53 | // (69) (77) (80) (82) 54 | 55 | // O(log n) search, found 56 | printf("%d\n", *used_values.find(77)); 57 | // O(log n) search, not found 58 | if (used_values.find(79) == used_values.end()) 59 | printf("79 not found\n"); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /resources/arithmetic/t_func.c: -------------------------------------------------------------------------------- 1 | /* Miscellaneous: Coupons Problem 2 | ================================================================= 3 | Description: Coupons are given away in boxes of cereal. There are 4 | 'm' different kinds of coupons (with equiprobable 5 | distribution). How many boxes of cereal would you 6 | have to buy, on average, to collect them all? 7 | 8 | Complexity: O(N) 9 | ----------------------------------------------------------------- 10 | Author: Ashley Zinyk 11 | Date: March 19, 2003 12 | References: http://mathforum.org/library/drmath/view/56657.html 13 | ----------------------------------------------------------------- 14 | Reliability: 0 15 | Notes: 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | double ncoupons(int m) { 23 | double num = 0.0; 24 | int i; 25 | 26 | for (i = 1; i <= m; i++) num += m/(double) i; 27 | return num; 28 | } 29 | 30 | /* A related problem: If you buy 'n' boxes of cereal, what is the 31 | probability you get at least one of each of the 'm' coupons? 32 | This is solved by the T(n,m) function. The T(n,m) function is 33 | recursive, so this implementation creates a table using dynamic 34 | programming (only once) and queries it thereafter. Like most 35 | combinatoric problems, this one blows up very fast. This solution 36 | works for n < 100. */ 37 | 38 | double nways[100][100]; 39 | 40 | void make_coupon_table() { 41 | double fact = 1.0; 42 | int i, j; 43 | 44 | for (i = 1; i < 100; i++) { 45 | nways[i][1] = 1.0; 46 | for (j = 2; j < i; j++) 47 | nways[i][j] = j*(nways[i-1][j] + nways[i-1][j-1]); 48 | nways[i][i] = fact *= i; 49 | } 50 | } 51 | 52 | double query_table(int m, int n) { 53 | if (n < m) return 0.0; 54 | if (m == 0) return 1.0; 55 | if (n >= 100 || m >= 100) exit(1); 56 | return nways[n][m]/pow(m,n); 57 | } 58 | 59 | int main() { 60 | int i, j; 61 | 62 | for (i = 1; i < 34; i++) 63 | printf("On average, it takes %g boxes to collect all %d\n", 64 | ncoupons(i), i); 65 | make_coupon_table(); 66 | for (i = 0; i < 100; i++) { 67 | printf("With %d boxes, there is a ",i); 68 | printf("%g probability of collecting all 26\n", 69 | query_table(26,i)); 70 | } 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/E/outE.dat: -------------------------------------------------------------------------------- 1 | Case 1: 3 0 0 1 0 2 | Case 2: 0 -1 -1 -1 -1 3 | Case 3: 0 -1 -1 -1 -1 4 | Case 4: 5 3 3 5 4 5 | Case 5: 39 0 58 92 63 6 | Case 6: 0 -1 -1 -1 -1 7 | Case 7: 106 0 26 28 56 8 | Case 8: 0 -1 -1 -1 -1 9 | Case 9: 0 -1 -1 -1 -1 10 | Case 10: 0 -1 -1 -1 -1 11 | Case 11: 82 5 75 30 89 12 | Case 12: 239 2 41 52 61 13 | Case 13: 161 0 23 46 35 14 | Case 14: 78 3 8 38 16 15 | Case 15: 0 -1 -1 -1 -1 16 | Case 16: 0 -1 -1 -1 -1 17 | Case 17: 6232 0 0 99 99 18 | Case 18: 527 0 64 99 74 19 | Case 19: 97 0 6 20 40 20 | Case 20: 420 2 62 83 73 21 | Case 21: 0 -1 -1 -1 -1 22 | Case 22: 192 0 1 37 47 23 | Case 23: 51 6 17 56 25 24 | Case 24: 15 0 1 3 25 25 | Case 25: 113 2 9 81 2 26 | Case 26: 295 1 19 90 52 27 | Case 27: 252 6 31 85 31 28 | Case 28: 589 0 26 74 76 29 | Case 29: 20 28 5 49 2 30 | Case 30: 119 0 11 10 49 31 | Case 31: 0 -1 -1 -1 -1 32 | Case 32: 126 0 11 24 37 33 | Case 33: 38 3 2 86 5 34 | Case 34: 775 0 5 63 99 35 | Case 35: 293 1 4 91 23 36 | Case 36: 6 0 12 16 23 37 | Case 37: 331 1 33 60 78 38 | Case 38: 131 16 4 90 11 39 | Case 39: 460 0 3 95 51 40 | Case 40: 36 1 12 18 24 41 | Case 41: 50 1 16 49 17 42 | Case 42: 125 0 17 26 75 43 | Case 43: 0 -1 -1 -1 -1 44 | Case 44: 102 1 0 65 8 45 | Case 45: 0 -1 -1 -1 -1 46 | Case 46: 238 0 1 97 20 47 | Case 47: 0 -1 -1 -1 -1 48 | Case 48: 242 0 0 22 44 49 | Case 49: 0 -1 -1 -1 -1 50 | Case 50: 38 1 8 18 8 51 | Case 51: 146 9 49 88 3 52 | Case 52: 109 0 4 16 55 53 | Case 53: 42 0 4 32 30 54 | Case 54: 0 -1 -1 -1 -1 55 | Case 55: 0 -1 -1 -1 -1 56 | Case 56: 41 0 10 6 91 57 | Case 57: 26 3 0 69 17 58 | Case 58: 292 0 16 66 4 59 | Case 59: 0 -1 -1 -1 -1 60 | Case 60: 19 1 52 10 33 61 | Case 61: 66 0 28 17 58 62 | Case 62: 0 -1 -1 -1 -1 63 | Case 63: 0 -1 -1 -1 -1 64 | Case 64: 0 -1 -1 -1 -1 65 | Case 65: 23 6 12 55 6 66 | Case 66: 173 2 41 43 94 67 | Case 67: 66 6 47 48 41 68 | Case 68: 279 1 7 65 25 69 | Case 69: 6 0 8 1 23 70 | Case 70: 164 0 35 74 12 71 | Case 71: 4 21 3 22 4 72 | Case 72: 29 28 20 67 14 73 | Case 73: 0 -1 -1 -1 -1 74 | Case 74: 804 0 0 78 70 75 | Case 75: 0 -1 -1 -1 -1 76 | Case 76: 850 0 1 98 69 77 | Case 77: 3 19 21 19 23 78 | Case 78: 49 23 35 77 6 79 | Case 79: 7 0 1 2 5 80 | Case 80: 0 -1 -1 -1 -1 81 | Case 81: 230 0 0 2 99 82 | Case 82: 0 -1 -1 -1 -1 83 | Case 83: 461 0 0 99 5 84 | Case 84: 192 0 0 97 5 85 | Case 85: 2045 0 3 99 92 86 | Case 86: 301 0 18 99 97 87 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_02_UVa469.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.text.*; 3 | 4 | // classic DFS flood fill 5 | 6 | class Main { /* UVa 469 - Wetlands of Florida */ 7 | private static String line; 8 | private static char[][] grid = new char[150][]; 9 | private static int TC, R, C, row, col; 10 | 11 | private static int dr[] = {1,1,0,-1,-1,-1, 0, 1}; // S,SE,E,NE,N,NW,W,SW 12 | private static int dc[] = {0,1,1, 1, 0,-1,-1,-1}; // neighbors 13 | 14 | private static int floodfill(int r, int c, char c1, char c2) { 15 | if (r<0 || r>=R || c<0 || c>=C) return 0; // outside 16 | if (grid[r][c] != c1) return 0; // we want only c1 17 | grid[r][c] = c2; // important step to avoid cycling! 18 | int ans = 1; // coloring c1 -> c2, add 1 to answer 19 | for (int d = 0; d < 8; d++) // recurse to neighbors 20 | ans += floodfill(r + dr[d], c + dc[d], c1, c2); 21 | return ans; 22 | } 23 | 24 | // inside the void main(String[] args) of the solution for UVa 469 - Wetlands of Florida 25 | public static void main(String[] args) { 26 | Scanner sc = new Scanner(System.in); 27 | // read the implicit graph as global 2D array 'grid'/R/C and (row, col) query coordinate 28 | TC = sc.nextInt(); sc.nextLine(); 29 | sc.nextLine(); // remove dummy line 30 | 31 | while (TC-- > 0) { 32 | R = 0; 33 | while (true) { 34 | grid[R] = sc.nextLine().toCharArray(); 35 | if (grid[R][0] != 'L' && grid[R][0] != 'W') // start of query 36 | break; 37 | R++; 38 | } 39 | C = grid[0].length; 40 | 41 | 42 | line = new String(grid[R]); 43 | while (true) { 44 | StringTokenizer st = new StringTokenizer(line); 45 | row = Integer.parseInt(st.nextToken()); row--; // index starts from 0! 46 | col = Integer.parseInt(st.nextToken()); col--; 47 | System.out.println(floodfill(row, col, 'W', '.')); // change water 'W' to '.'; count size of this lake 48 | floodfill(row, col, '.', 'W'); // restore for next query 49 | if (sc.hasNext()) line = sc.nextLine(); 50 | else break; // last test case 51 | if (line.length() == 0) break; // next test case 52 | } 53 | 54 | if (TC > 0) 55 | System.out.println(); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/D/D.cc: -------------------------------------------------------------------------------- 1 | // Photo.cc 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | #define PI 3.14159265; 10 | #define FOR(i, a, b) for(int i=a; i Angles; 16 | 17 | void PrintAngles(){ 18 | FOR(i,0,n) 19 | cout<>a>>b; 30 | a -= x; 31 | b -= y; 32 | result = atan2(b,a) * 180 / PI; 33 | if (result<0) result += 360; // all angles >= 0 34 | Angles.push_back(result); 35 | } 36 | sort(Angles.begin(), Angles.end()); 37 | // for debugging: 38 | // check if angles distinct 39 | FOR(i,1,n) 40 | if(Angles[i-1]==Angles[i]) cout <<"two angles equal " <>n>>x>>y>>f; 91 | } 92 | 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_10_mcbm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | typedef pair ii; 6 | typedef vector vi; 7 | typedef vector vii; 8 | 9 | vector AdjList; 10 | vi owner, visited; // global variables 11 | 12 | int Aug(int left) { 13 | if (visited[left]) return 0; 14 | visited[left] = true; 15 | for (int j = 0; j < (int)AdjList[left].size(); j++) { 16 | int right = AdjList[left][j].first; 17 | // either greedy assignment or recurse 18 | if (owner[right] == -1 || Aug(owner[right])) { 19 | owner[right] = left; 20 | return 1; // we found one matching 21 | } 22 | } 23 | return 0; // no matching 24 | } 25 | 26 | bool isprime(int v) { 27 | int primes[10] = {2,3,5,7,11,13,17,19,23,29}; 28 | for (int i = 0; i < 10; i++) 29 | if (primes[i] == v) 30 | return true; 31 | return false; 32 | } 33 | 34 | int main() { 35 | int i, j; 36 | 37 | /* 38 | // Graph in Figure 4.34 can be built on the fly 39 | // we know there are 6 vertices in this bipartite graph, left side are numbered 0,1,2, right side 3,4,5 40 | //int V = 6, num_vertices_on_left = 3, set1[3] = {1,7,11}, set2[3] = {4,10,12}; 41 | 42 | // Graph in Figure 4.35 can be built on the fly 43 | // we know there are 5 vertices in this bipartite graph, left side are numbered 0,1, right side 3,4,5 44 | int V = 5, num_vertices_on_left = 2, set1[2] = {1,7}, set2[3] = {4,10,12}; 45 | 46 | // build the bipartite graph, only directed edge from left to right is needed 47 | AdjList.assign(V, vii()); 48 | for (i = 0; i < num_vertices_on_left; i++) 49 | for (j = 0; j < 3; j++) 50 | if (isprime(set1[i] + set2[j])) 51 | AdjList[i].push_back(ii(3 + j, 0)); 52 | */ 53 | 54 | 55 | // Graph in Figure 4.37, manual construction 56 | int V = 4, num_vertices_on_left = 2; 57 | AdjList.assign(V, vii()); 58 | AdjList[0].push_back(ii(2, 1)); 59 | AdjList[0].push_back(ii(3, 1)); 60 | AdjList[1].push_back(ii(2, 1)); 61 | 62 | 63 | // the MCBM routine 64 | int cardinality = 0; 65 | owner.assign(V, -1); 66 | for (int left = 0; left < num_vertices_on_left; left++) { 67 | visited.assign(num_vertices_on_left, 0); 68 | cardinality += Aug(left); 69 | } 70 | 71 | printf("Found %d matchings\n", cardinality); 72 | 73 | return 0; 74 | } -------------------------------------------------------------------------------- /resources/c++_and_stl/priority_queue.cc: -------------------------------------------------------------------------------- 1 | /* C++: Priority Queue template 2 | ================================================================= 3 | Description: Template for using C++ STL priority queues 4 | 5 | Given an adjacency matrix of a weighted graph, and 6 | a source vertex s, finds the shortest path from 7 | source to all other vertices and stores it in dist[] 8 | 9 | Complexity: lg(N) access time, where N is size of queue 10 | ----------------------------------------------------------------- 11 | Author: Gilbert Lee 12 | Date: Jan 31, 2003 13 | References: 14 | ----------------------------------------------------------------- 15 | Reliability: 0 16 | Notes: q.top() returns the LARGEST element in the queue, 17 | as defined by the < operator 18 | -> if X < Y, then Y is first on the queue 19 | q.pop() removes the largest element of the queue 20 | q.push(X) adds X onto the queue 21 | q.empty() returns 1 if queue is empty, 0 otherwise 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | using namespace std; 28 | 29 | #define MAXN 300 30 | int adj[MAXN][MAXN]; 31 | int dist[MAXN]; 32 | 33 | struct Node{ 34 | int node, cost; 35 | 36 | // i.e Node o is higher up in priority in the queue 37 | bool operator<(Node const &o) const { 38 | return cost > o.cost; 39 | } 40 | }; 41 | 42 | int main(){ 43 | int n, i, j; Node start, curr, next; 44 | 45 | while(scanf("%d", &n) == 1){ // Read # of vertices 46 | for(i = 0; i < n; i++) // Read adjacency matrix 47 | for(j = 0; j < n; j++) 48 | scanf("%d", &adj[i][j]); 49 | scanf("%d", &start.node); // Get source vertex 50 | start.cost = 0; 51 | memset(dist, -1, sizeof(dist)); // Initialize distance 52 | 53 | priority_queue q; // Initialize queue 54 | q.push(start); 55 | while(!q.empty()){ 56 | curr = q.top(); 57 | q.pop(); 58 | if(dist[curr.node] == -1){ 59 | dist[curr.node] = curr.cost; 60 | for(i = 0; i < n; i++){ 61 | if(dist[i] != -1 || adj[curr.node][i] == -1) continue; 62 | next.node = i; 63 | next.cost = curr.cost + adj[curr.node][i]; 64 | q.push(next); 65 | } 66 | } 67 | } 68 | for(i = 0; i < n; i++) 69 | printf("Distance from %d to %d: %d\n", start.node, i, dist[i]); 70 | } 71 | return 0; 72 | } 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_09_spoj101.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ch4_09_spoj101 { /* SPOJ 101 - Fishmonger */ 4 | static final int MAX_N = 55; 5 | static final int MAX_T = 1005; 6 | static final int INF = 2000000000; 7 | 8 | static int i, j, n, t; 9 | static int[][] toll = new int[MAX_N][MAX_N]; 10 | static int[][] travelTime = new int[MAX_N][MAX_N]; 11 | static IntegerPair[][] memo = new IntegerPair[MAX_N][MAX_T]; 12 | 13 | static IntegerPair go(int cur, int t_left) { // top-down DP, returns a pair 14 | if (t_left < 0) return new IntegerPair(INF, INF); // invalid state 15 | if (cur == n - 1) return new IntegerPair(0, 0); // at last city, no need to pay toll and time needed is 0 16 | if (memo[cur][t_left].first() != -1) return memo[cur][t_left]; // visited before 17 | IntegerPair ans = new IntegerPair(INF, INF); 18 | for (int nxt = 0; nxt < n; nxt++) if (cur != nxt) { // try to go to another city 19 | IntegerPair nextCity = go(nxt, t_left - travelTime[cur][nxt]); // recursive step 20 | if (nextCity.first() + toll[cur][nxt] < ans.first()) { // pick the one that has min cost 21 | ans = new IntegerPair(nextCity.first() + toll[cur][nxt], 22 | nextCity.second() + travelTime[cur][nxt]); 23 | } } 24 | return memo[cur][t_left] = ans; 25 | } // store the answer to memo table as well as returning the answer to the caller 26 | 27 | 28 | public static void main(String[] args) { 29 | /* 30 | // sample input 31 | 4 7 32 | 0 5 2 3 33 | 5 0 2 3 34 | 3 1 0 2 35 | 3 3 2 0 36 | 37 | 0 2 2 7 38 | 2 0 1 2 39 | 2 2 0 5 40 | 7 2 5 0 41 | 42 | 0 0 43 | 44 | // sample output 45 | 6 6 46 | */ 47 | 48 | Scanner sc = new Scanner(System.in); 49 | while (true) { 50 | n = sc.nextInt(); t = sc.nextInt(); 51 | if (n == 0 && t == 0) 52 | break; 53 | 54 | for (i = 0; i < n; i++) 55 | for (j = 0; j < n; j++) 56 | travelTime[i][j] = sc.nextInt(); 57 | 58 | for (i = 0; i < n; i++) 59 | for (j = 0; j < n; j++) 60 | toll[i][j] = sc.nextInt(); 61 | 62 | for (i = 0; i <= n; i++) 63 | for (j = 0; j <= t; j++) 64 | memo[i][j] = new IntegerPair(-1, -1); 65 | 66 | IntegerPair res = go(0, t); 67 | System.out.printf("%d %d\n", res.first(), res.second()); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/tmp.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char sieve[10000001]; // 10^7 is the typical limit for sieve of eratosthenes 5 | 6 | main() 7 | { 8 | unsigned l,u; // data type of int is assumed when keyword 'unsigned' is used on its own 9 | while (2 == scanf("%u %u ", &l, &u)) 10 | { 11 | unsigned mindist = 3000000000, maxdist = 0; 12 | unsigned prev, maxprev, minprev, maxi, mini; 13 | 14 | // for as many numbers in the range (inclusive), assume that many primes 15 | for (int i = l; i <= u; ++i) 16 | { 17 | sieve[i-l] = 0; // note that they reversed the true/false 18 | } 19 | 20 | // TODO: This cannot be removed (causes WA). Why is it needed? 21 | if (l <= 2) // if L is 1 or 2 22 | { 23 | prev = 2; // the first prime is 2, so that is the previous prime 24 | l = 3; // let L be 3, the prime after 2 25 | } 26 | else 27 | { 28 | prev = 0; 29 | } 30 | 31 | // sieve algorithm 32 | for (int i = 3; i <= sqrt(static_cast(u)); i += 2) 33 | { 34 | unsigned k = sqrt((double)i); 35 | for (int j = 3; j <= k; j += 2) 36 | { 37 | if (i % j == 0ul) goto composite1; // this code must be old 38 | } 39 | k = l % i; 40 | if (k == 0) k = i; 41 | for (k = i - k; k + l <= u; k += i) 42 | { 43 | if (l + k == i) continue; 44 | sieve[k] = 1; 45 | } 46 | continue; 47 | composite1:; 48 | } 49 | 50 | // some kind of linear scan 51 | for (int i = l % 2 == 1ul ? l : l + 1ul; i <= u; i += 2ul) 52 | { 53 | if (sieve[i-l]) continue; 54 | if (prev) 55 | { 56 | int dist = i - prev; 57 | if (dist > maxdist) 58 | { 59 | maxdist = dist; 60 | maxprev = prev; 61 | maxi = i; 62 | } 63 | if (dist < mindist) 64 | { 65 | mindist = dist; 66 | minprev = prev; 67 | mini = i; 68 | } 69 | } 70 | prev = i; 71 | } 72 | if (maxdist) 73 | { 74 | printf("%d,%d are closest, %d,%d are most distant.\n", minprev, mini, maxprev, maxi); 75 | } 76 | else 77 | { 78 | printf("There are no adjacent primes.\n"); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/10140.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | typedef long long ll; 9 | typedef vector vi; 10 | 11 | ll _sieve_size; 12 | bitset<10000010> bs; 13 | vi primes; 14 | vi _primes; 15 | 16 | void sieve(ll upperbound) 17 | { 18 | _sieve_size = upperbound + 1; 19 | bs.set(); // set all bits to 1 (assume all numbers are prime at first) 20 | bs[0] = bs[1] = 0; 21 | for (ll i = 2; i <= _sieve_size; ++i) 22 | { 23 | // cross out multiples of i, starting from i * i 24 | for (ll j = i * i; j <= _sieve_size; j += i) bs[j] = 0; 25 | primes.push_back(static_cast(i)); // push back every i? 26 | } 27 | } 28 | 29 | bool is_prime(ll N) 30 | { 31 | if (N <= _sieve_size) return bs[N]; // O(1) for small primes 32 | for (int i = 0; i < static_cast(primes.size()); ++i) 33 | if (N % primes[i] == 0) return false; 34 | return true; 35 | } 36 | 37 | int main(int argc, char** argv) 38 | { 39 | cin.sync_with_stdio(false); 40 | sieve(1000000); 41 | //sieve(10000000); 42 | int L, U; 43 | while (cin >> L >> U) 44 | { 45 | //cout << L << " " << U << endl; 46 | int min_dist = 1000000; 47 | int max_dist = -1; 48 | pair closest; 49 | pair furthest; 50 | 51 | for (int i = L; i <= U; ++i) // find all primes within range 52 | { 53 | if (is_prime(i)) 54 | { 55 | _primes.push_back(i); 56 | } 57 | } 58 | if (_primes.size() < 2) 59 | { 60 | cout << "There are no adjacent primes.\n"; 61 | } 62 | else 63 | { 64 | for (int i = 0; i < _primes.size()-1; ++i) // iterate through all primes 65 | { 66 | int dist = _primes.at(i+1) - _primes.at(i); 67 | //cout << "dist " << _primes[i] << " to " << _primes[i+1] << " = " << dist << endl; 68 | if (dist < min_dist) 69 | { 70 | closest.first = _primes[i]; 71 | closest.second = _primes[i+1]; 72 | min_dist = dist; 73 | } 74 | if (dist > max_dist) 75 | { 76 | furthest.first = _primes[i]; 77 | furthest.second = _primes[i+1]; 78 | max_dist = dist; 79 | } 80 | //cout << _primes[i] << " "; 81 | } 82 | cout << closest.first << "," << closest.second << " are closest, " 83 | << furthest.first << "," << furthest.second << " are most distant.\n"; 84 | } 85 | _primes.clear(); 86 | } 87 | return 0; 88 | } 89 | -------------------------------------------------------------------------------- /resources/c++_and_stl/next_permutation.cc: -------------------------------------------------------------------------------- 1 | /* C++: Next/Prev Permutation with STL 2 | ================================================================= 3 | Description: This routine shows how to use next/prev permutation 4 | with STL 5 | 6 | Complexity: O(N) 7 | ----------------------------------------------------------------- 8 | Author: Gilbert Lee 9 | Date: Oct 27, 2002 10 | References: http://www.sgi.com/tech/stl/next_permutation.html 11 | ----------------------------------------------------------------- 12 | Reliability: 0 13 | Notes: Any base type can be used, e.g. chars, strings 14 | -next_permutation returns 1 as long as a next 15 | permutation exists. It modifies the array/vector 16 | that it is fed to contain the next permutation 17 | 18 | 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | typedef struct{ 26 | int x, y; 27 | } Point; 28 | 29 | int cmp_strict_less_Point(Point a, Point b){ 30 | if(a.x < b.x) return 1; 31 | if(a.x == b.x && a.y < b.y) return 1; 32 | return 0; 33 | } 34 | 35 | int main(){ 36 | char buff[100]; 37 | int len; 38 | unsigned int i; 39 | 40 | /*----------------------------------------*/ 41 | /* For an array */ 42 | /*----------------------------------------*/ 43 | scanf(" %s", buff); 44 | len = strlen(buff); 45 | while(next_permutation(buff, buff+len)){ 46 | printf("%s\n", buff); 47 | } 48 | 49 | 50 | /*----------------------------------------*/ 51 | /* For a vector */ 52 | /*----------------------------------------*/ 53 | 54 | /* For a vector */ 55 | vector vec; 56 | for(i = 0; i < 3; i++) vec.push_back(3-i); 57 | 58 | while(prev_permutation(vec.begin(), vec.end())){ 59 | for(i = 0; i < vec.size(); i++) printf("%d ", vec[i]); 60 | printf("\n"); 61 | } 62 | printf("\n"); 63 | 64 | /*----------------------------------------*/ 65 | /* For an array of structs 66 | The comparision function must be written 67 | - a strictly less than function: 68 | 1 if a < b 69 | 0 otherwise 70 | /*----------------------------------------*/ 71 | Point p[5]; 72 | for(i = 0; i < 5; i++){ 73 | p[i].x = (3*i)%4; 74 | p[i].y = (2*i)%7; 75 | } 76 | while(next_permutation(p, p+5, cmp_strict_less_Point)){ 77 | for(i = 0; i < 5; i++){ 78 | printf("[%d,%d] ", p[i].x, p[i].y); 79 | } 80 | printf("\n"); 81 | } 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/10/10140-Prime_Distance/test.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char sieve[10000001]; // 10^7 is the typical limit for sieve of eratosthenes 5 | 6 | main() 7 | { 8 | unsigned l,u; // data type of int is assumed when keyword 'unsigned' is used on its own 9 | while (2 == scanf("%u %u ", &l, &u)) 10 | { 11 | unsigned mindist = 3000000000, maxdist = 0; 12 | unsigned prev, maxprev, minprev, maxi, mini; 13 | 14 | for (int i = 0, dist = u-l; i <= dist; ++i) // <= because inclusive range 15 | { 16 | sieve[i] = 0; 17 | } 18 | // TODO: This cannot be removed (causes WA). Why is it needed? 19 | // Seems like some kind of optimization (when l > 3 and prev = 0). 20 | if (l <= 2) // if L is 1 or 2 21 | { 22 | prev = 2; // the first prime is 2, so that is the previous prime 23 | l = 3; // let L be 3, the prime after 2 24 | } 25 | else 26 | { 27 | prev = 0; // when prev = 0, 1 is considered prime and 2 is not 28 | } 29 | 30 | // sieve algorithm 31 | for (int i = 3; i <= sqrt(static_cast(u)); i += 2) 32 | { 33 | unsigned k = sqrt((double)i); 34 | for (int j = 3; j <= k; j += 2) 35 | { 36 | if (i % j == 0ul) goto composite1; // this code must be old 37 | } 38 | k = l % i; 39 | if (k == 0) k = i; 40 | for (k = i - k; k + l <= u; k += i) 41 | { 42 | if (l + k == i) continue; 43 | sieve[k] = 1; 44 | } 45 | continue; 46 | composite1:; 47 | } 48 | 49 | // some kind of linear scan 50 | for (int i = (l % 2 == 1ul) ? l : l + 1ul; i <= u; i += 2ul) 51 | { 52 | if (sieve[i-l]) continue; // continue if not prime 53 | if (prev) 54 | { 55 | int dist = i - prev; 56 | if (dist > maxdist) 57 | { 58 | maxdist = dist; 59 | maxprev = prev; 60 | maxi = i; 61 | } 62 | if (dist < mindist) 63 | { 64 | mindist = dist; 65 | minprev = prev; 66 | mini = i; 67 | } 68 | } 69 | prev = i; 70 | } 71 | if (maxdist) 72 | { 73 | printf("%d,%d are closest, %d,%d are most distant.\n", minprev, mini, maxprev, maxi); 74 | } 75 | else 76 | { 77 | printf("There are no adjacent primes.\n"); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_06_PriorityQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class pair < X, Y > { // utilizing Java "Generics" 4 | X _first; 5 | Y _second; 6 | 7 | public pair(X f, Y s) { _first = f; _second = s; } 8 | 9 | X first() { return _first; } 10 | Y second() { return _second; } 11 | 12 | void setFirst(X f) { _first = f; } 13 | void setSecond(Y s) { _second = s; } 14 | } 15 | 16 | class ch2_06_PriorityQueue { 17 | public static void main(String[] args) { 18 | // introducing 'pair' 19 | PriorityQueue < pair < Integer, String > > pq = new PriorityQueue < pair < Integer, String > >(1, 20 | new Comparator< pair < Integer, String > >() { // overriding the compare method 21 | public int compare(pair < Integer, String > i, pair < Integer, String > j) { 22 | return j.first() - i.first(); // currently max heap, reverse these two to try produce min-heap 23 | } 24 | } 25 | ); 26 | 27 | // suppose we enter these 7 money-name pairs via keyboard 28 | /* 29 | 100 john 30 | 10 billy 31 | 20 andy 32 | 100 steven 33 | 70 felix 34 | 2000 grace 35 | 70 martin 36 | */ 37 | Scanner sc = new Scanner(System.in); 38 | for (int i = 0; i < 7; i++) { 39 | int money = sc.nextInt(); 40 | String name = sc.nextLine(); 41 | pq.offer(new pair < Integer, String > (money, name)); // this is how we use Java PriorityQueue 42 | // priority queue will arrange items in 'heap' based 43 | // on the first key in pair, which is money (integer), largest first 44 | // if first keys tied, use second key, which is name, largest first 45 | } 46 | 47 | // the internal content of pq heap MAY be something like this: 48 | // re-read (max) heap concept if you do not understand this diagram 49 | // the primary keys are money (integer), secondary keys are names (string)! 50 | // (2000,grace) 51 | // (100,steven) (70,martin) 52 | // (100,john) (10,billy) (20,andy) (70,felix) 53 | 54 | // let's print out the top 3 person with most money 55 | pair result = pq.poll(); // O(1) to access the top / max element + O(log n) removal of the top and repair the structure 56 | System.out.println(result.second() + " has " + result.first() + " $"); 57 | result = pq.poll(); 58 | System.out.println(result.second() + " has " + result.first() + " $"); 59 | result = pq.poll(); 60 | System.out.println(result.second() + " has " + result.first() + " $"); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_10_fenwicktree_ds.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch2_10_fenwicktree_ds { 4 | private static int LSOne(int S) { return (S & (-S)); } 5 | 6 | private static Vector ft_create(int n) { 7 | Vector v = new Vector(); 8 | // initialization: n + 1 zeroes, ignoring index 0, just using index [1..n] 9 | for (int i = 0; i <= n; i++) v.add(0); 10 | return v; 11 | } 12 | 13 | private static int ft_rsq(Vector ft, int b) { // returns RSQ(1, b) 14 | int sum = 0; for (; b > 0; b -= LSOne(b)) sum += ft.get(b); 15 | return sum; } 16 | 17 | private static int ft_rsq(Vector ft, int a, int b) { // returns RSQ(a, b) 18 | return ft_rsq(ft, b) - (a == 1 ? 0 : ft_rsq(ft, a - 1)); } 19 | 20 | // adjusts value of the k-th element by v (v can be +ve/inc or -ve/dec) 21 | private static void ft_adjust(Vector ft, int k, int v) { // note: n = ft.size() - 1 22 | for (; k < (int)ft.size(); k += LSOne(k)) ft.set(k, ft.get(k) + v); } 23 | 24 | public static void main(String[] args) { 25 | // idx 0 1 2 3 4 5 6 7 8 9 10, no index 0! 26 | Vector ft; 27 | ft = ft_create(10); // ft = {-,0,0,0,0,0,0,0, 0,0,0} 28 | ft_adjust(ft, 2, 1); // ft = {-,0,1,0,1,0,0,0, 1,0,0}, idx 2,4,8 => +1 29 | ft_adjust(ft, 4, 1); // ft = {-,0,1,0,2,0,0,0, 2,0,0}, idx 4,8 => +1 30 | ft_adjust(ft, 5, 2); // ft = {-,0,1,0,2,2,2,0, 4,0,0}, idx 5,6,8 => +2 31 | ft_adjust(ft, 6, 3); // ft = {-,0,1,0,2,2,5,0, 7,0,0}, idx 6,8 => +3 32 | ft_adjust(ft, 7, 2); // ft = {-,0,1,0,2,2,5,2, 9,0,0}, idx 7,8 => +2 33 | ft_adjust(ft, 8, 1); // ft = {-,0,1,0,2,2,5,2,10,0,0}, idx 8 => +1 34 | ft_adjust(ft, 9, 1); // ft = {-,0,1,0,2,2,5,2,10,1,1}, idx 9,10 => +1 35 | System.out.printf("%d\n", ft_rsq(ft, 1, 1)); // 0 => ft[1] = 0 36 | System.out.printf("%d\n", ft_rsq(ft, 1, 2)); // 1 => ft[2] = 1 37 | System.out.printf("%d\n", ft_rsq(ft, 1, 6)); // 7 => ft[6] + ft[4] = 5 + 2 = 7 38 | System.out.printf("%d\n", ft_rsq(ft, 1, 10)); // 11 => ft[10] + ft[8] = 1 + 10 = 11 39 | System.out.printf("%d\n", ft_rsq(ft, 3, 6)); // 6 => rsq(1, 6) - rsq(1, 2) = 7 - 1 40 | 41 | ft_adjust(ft, 5, 2); // update demo 42 | System.out.printf("Index: "); 43 | for (int i = 0; i < (int)ft.size(); i++) 44 | System.out.printf("%d ", i); 45 | System.out.printf("\n"); 46 | System.out.printf("FT : "); 47 | for (int i = 0; i < (int)ft.size(); i++) 48 | System.out.printf("%d ", ft.get(i)); 49 | System.out.printf("\n"); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/C/outC.dat: -------------------------------------------------------------------------------- 1 | UULLLLUUBBBB 2 | UULLLLUUBBBB 3 | LUB 4 | LBUUBULBL 5 | LLBBUUBUL 6 | LBLLBUUUB 7 | LBLLBUBUU 8 | ULBBULUBL 9 | ULBBULULB 10 | LLUUULBBB 11 | BBULLULUB 12 | LLLUUBUBB 13 | BUULBLLUB 14 | BBULLLBUU 15 | UBLLBUUULBBL 16 | UULUULBBRDBBULLL 17 | LUUUUBBRBBLLFLLB 18 | BUULUURBBLLLBL 19 | UULUULBBRBBLLL 20 | BULUBBLBLULU 21 | LBLUBLULUBUB 22 | LBBLUBLLBUUU 23 | ULBLBLDBLBLUURFRUFRFUUUBLBLBDDLLUBBU 24 | LLUUBUULUBULULLBLBDBDDFDFDRFDDBLBBRBUUBLUUUUU 25 | BLLULUBLBLUUUURUFURFRRRUFUUBBBBDLLDDDFDDBRBBRBBLDBBBDRDBDDBLLBBRRUUUBBLUULFUFFLLBUULBBUUULUUULLFFDFLFLULUBLUBBDLLUBULLL 26 | LBUBBBBLLFLFUUBRUULLB 27 | LLUBLLUULBUBBUB 28 | BLUBLLFUFLLBUBUUBRBBL 29 | LUBLUBUBBULBLUL 30 | UBBLLBUBURURFFFFLULLLLDBBBBUB 31 | LLLULBBBLDBBURUURUULL 32 | UUBLUBBBBBBULBUULLBUUUULBBBLLLLUULLL 33 | ULBLBDBLLFLUFFURRUUUBURRUFRUUULUBULBBLBBLLLDBDBBLLLFLFLLBBBBRBBRUULL 34 | LLULBUBLBULBLBUULUBLLULUUUBBULBLBUBB 35 | LLLBUBBURBRRUULULUBBLBLBBBULBULLBLLULUFLLFUUBB 36 | LBUUBBBUUFFLLBLLLLBBLBBLBBBUUBBUUUUFFUUBLLLB 37 | BLBUBURBBLUUULBLLLULUBBBBLUBUUBLLLLLUU 38 | LULBUULBBULUBUBBBLLLBDLLUURURUULUULLDBBUBBDLLU 39 | LULLBLULUFULLLDLLBBRBBDDBRBBLBBBLDLLBBRRURUURFUUFURFFURFFURRDDLFFFRRBBRBRRUUUUBBDLBBLBLDLBLLFUFURUULLLLDDLDLLUUUBB 40 | LLLBUBBLLBUUUBU 41 | LBBULBLBDLBBLBBUBBDLBLLFLLUULUBUUUFFUUBBUUU 42 | UBBBULLLLLBLBUUUUB 43 | LLBBBLUUBLBULBBLUUUBUBLLUUL 44 | LUUURUULLBLBUUULBLLBBBRBBLDLLU 45 | BLBUUFRFUUUBLLLBDLDBLLBBDLDDBBUURURRFURUFUUBLBLDLLU 46 | BBUBLLBUULUUURUUUFUFLFLUFLLUULULULUBLUBLBLDBBLBLBBLUBBBBLBBBLBB 47 | UBBLLLULULFFUURRDRRRUUULULLLDLBLLFLULLUUBLBBLBBBUUBRBBBBRUBBDLLULFFUUUBBULLBLLBBB 48 | BUBLLUBUUFUFUFUUULLBULUUUBLUBUBLLUBLUBLLBDDDFFDDFRFRDDLDBLDDDBLDDLDBLDDRBRRDBRRBUBBRUUURBRUULFLLBUBLLFUULULUUBUUUBBULBBULLL 49 | LLLLLBULBLLFULUUULUBBLBUULUUBUUULUBBDRBDRBRRDBDRBRDDDBBDBBRRUBRUUBURUUURRFUFULFFULULLBBDLLBLLFDDLLULLUBBULLLL 50 | ULBUBUBRUUUULBBBLUBBBLBBUUUBLLULUUUFLLLUULBLLFDFLLLBUBBBBLLBB 51 | BLLBLBULLDBBLBBLUBBUURBUUFLFFRDDLLUFLFFULLLDLBBLBUBLUUUUBBRBBUULUBUULBLUUBUBB 52 | UUBLLBULBULBLUUBUUBRRUBRURBBRBBBDBBUUBBDDDLBDDFLFDFFULFUUFFLLFLFLLDDRFFFFFRFFFLLUULUULBBLBLBLULBLBUBBLBBLUUUUBBDBBBUBBU 53 | LBUUFULLLULBLULUFULLULBBUURBRBDBRBBBBDBRBRRBURURRRBBBLLLUBUUBRBBUULLLBBRRRURUUURUUULLLLDLFFRURRFFUUBUBLLLUUBBRBBLBBLBBLDLLULFLLBDDDLDLFLFLUURFURURFRFFLLDLDLLULUBBLBLLBBBDDLLFFLLFULLUBBB 54 | UBUUBUUUFUUUUFLLLLLBDDDFLLLBLULLUBLLBUBBDLDLFFLUULBBLLDLLBBRRUBRBUBUBBDBDLBDBLBBDDDFDDFDDBDDFRFFRUFRRBRURBBLBDBLBBBBLBLDBBLBLUUUULBBLUULUFFUURRRRFFLDDFFUULLLFUUBRURRBUBURBBBRUURFUUBRUUBRURUFFDFLDLDDRFDFFRRRRUFFDFRFFFFLLBLBBLLDLLLLLULBLBUUUFUUUUBUUUFLFLLBBLBBLBDDFDDBBUBBUUBBU 55 | LBLUBUBRUUUBRUBUUUUUFULFUUUBUUFLULUUURRUUUBRBBBBLBUBBBURBBBBBBLDDRFFLDDDDDRDDBBUBUBBDDFLDDDDDLDDLBBLDDRFFFFLLFDDFLDLFLDDDLLDBBBDRRBBBRBRUBBULLBLBLDLBLLLLFULLFFDFFULFFUFLUUFULLLFLLULLUBLBBBBUUFFUUUUURRRUULLLBUUBRURUUURUUUULLLBBBBB 56 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch7-Computational_Geometry/ch7_02_circles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #define INF 1e9 6 | #define EPS 1e-9 7 | #define PI acos(-1.0) 8 | 9 | double DEG_to_RAD(double d) { return d * PI / 180.0; } 10 | 11 | double RAD_to_DEG(double r) { return r * 180.0 / PI; } 12 | 13 | struct point_i { int x, y; // whenever possible, work with point_i 14 | point_i(int _x, int _y) { x = _x, y = _y; } // constructor (optional) 15 | }; 16 | struct point { double x, y; // only used if more precision is needed 17 | point(double _x, double _y) { x = _x, y = _y; } // constructor 18 | }; 19 | 20 | int insideCircle(point_i p, point_i c, int r) { // all integer version 21 | int dx = p.x - c.x, dy = p.y - c.y; 22 | int Euc = dx * dx + dy * dy, rSq = r * r; // all integer 23 | return Euc < rSq ? 0 : Euc == rSq ? 1 : 2; } // inside/border/outside 24 | 25 | bool circle2PtsRad(point p1, point p2, double r, point *c) { 26 | double d2 = (p1.x - p2.x) * (p1.x - p2.x) + 27 | (p1.y - p2.y) * (p1.y - p2.y); 28 | double det = r * r / d2 - 0.25; 29 | if (det < 0.0) return false; 30 | double h = sqrt(det); 31 | c->x = (p1.x + p2.x) * 0.5 + (p1.y - p2.y) * h; 32 | c->y = (p1.y + p2.y) * 0.5 + (p2.x - p1.x) * h; 33 | return true; } 34 | 35 | int main() { 36 | // circle equation, inside, border, outside 37 | point_i pt(2, 2); 38 | int r = 7; 39 | point_i inside(8, 2); 40 | printf("%d\n", insideCircle(inside, pt, r)); // 0-inside 41 | point_i border(9, 2); 42 | printf("%d\n", insideCircle(border, pt, r)); // 1-at border 43 | point_i outside(10, 2); 44 | printf("%d\n", insideCircle(outside, pt, r)); // 2-outside 45 | 46 | double d = 2 * r; 47 | printf("Diameter = %.2lf\n", d); 48 | double c = PI * d; 49 | printf("Circumference / Perimeter = %.2lf\n", c); 50 | double A = PI * r * r; 51 | printf("Area of circle = %.2lf\n", A); 52 | 53 | printf("Length of arc (central angle = 30 degrees) = %.2lf\n", 30.0 / 360.0 * c); 54 | printf("Length of chord (central angle = 30 degrees) = %.2lf\n", sqrt((2 * r * r) * (1 - cos(DEG_to_RAD(30.0))))); 55 | printf("Area of sector (central angle = 30 degrees) = %.2lf\n", 30.0 / 360.0 * A); 56 | // printf("Area of segment (30 degrees) = %.2lf\n", 0.0); // subtract the area of the corresponding sector with the area of an Isosceles Triangle with sides: r, r, and Chord-length 57 | 58 | point p1(0.0, 1.0); 59 | point p2(0.0, -1.0); 60 | point ans(0.0, 0.0); 61 | circle2PtsRad(p1, p2, 2.0, &ans); 62 | printf("One of the center is (%.2lf, %.2lf)\n", ans.x, ans.y); 63 | circle2PtsRad(p2, p1, 2.0, &ans); 64 | printf("The other center is (%.2lf, %.2lf)\n", ans.x, ans.y); 65 | 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_05_TreeMap_TreeSet.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class ch2_05_TreeMap_TreeSet { 4 | public static void main(String[] args) { 5 | // note: there are many clever usages of this set/map 6 | // that you can learn by looking at top coder's codes 7 | TreeSet used_values = new TreeSet(); // must use TreeSet as Set is an abstract class 8 | used_values.clear(); 9 | TreeMap mapper = new TreeMap(); // must use TreeMap as Map is an abstract class 10 | mapper.clear(); 11 | 12 | // suppose we enter these 7 name-score pairs via keyboard 13 | /* 14 | john 78 15 | billy 69 16 | andy 80 17 | steven 77 18 | felix 82 19 | grace 75 20 | martin 81 21 | */ 22 | Scanner sc = new Scanner(System.in); // for reading input 23 | for (int i = 0; i < 7; i++) { // just need to repeat 7 times 24 | String name = sc.next(); 25 | int value = sc.nextInt(); 26 | sc.nextLine(); // to clear this line for reading the next name 27 | mapper.put(name, value); // map example 28 | used_values.add(value); // set example 29 | } 30 | 31 | // then the internal content of mapper MAY be something like this: 32 | // re-read balanced BST concept if you do not understand this diagram 33 | // the keys are names (string)! 34 | // (grace,75) 35 | // (billy,69) (martin,81) 36 | // (andy,80) (felix,82) (john,78) (steven,77) 37 | 38 | // iterating through the content of mapper will give a sorted output 39 | // based on keys (names) 40 | System.out.println(mapper.keySet()); 41 | System.out.println(mapper.values()); 42 | 43 | // map can also be used like this 44 | System.out.println("steven's score is " + mapper.get("steven") + ", grace's score is " + mapper.get("grace")); 45 | System.out.println("=================="); 46 | 47 | // the internal content of used_values MAY be something like this 48 | // the keys are values (integers)! 49 | // (78) 50 | // (75) (81) 51 | // (69) (77) (80) (82) 52 | 53 | // O(log n) search, found 54 | System.out.println(used_values.contains(77)); // returns true 55 | System.out.println(used_values.headSet(77)); // returns [69, 75] (these two are before 77 in the inorder traversal of this BST) 56 | System.out.println(used_values.tailSet(77)); // returns [77, 78, 80, 81, 82] (these five are equal or after 77 in the inorder traversal of this BST) 57 | // O(log n) search, not found 58 | if (!used_values.contains(79)) 59 | System.out.println("79 not found"); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /solved/problem-set-volumes/12/1215-String_Cutting/1215.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include // for memset 4 | #include 5 | using namespace std; 6 | 7 | // Note: cost of a cut is relative to the (sub)string that is being cut. 8 | main() 9 | { 10 | int alphabet[26]; 11 | int ds; // datasets 12 | cin >> ds; 13 | for (int i = 0; i < ds; ++i) 14 | { 15 | int numcuts; // 1 <= # cuts <= 1000 16 | cin >> numcuts; 17 | int cutpos[numcuts]; 18 | for (int j = 0; j < numcuts; ++j) 19 | { 20 | cin >> cutpos[j]; 21 | } 22 | string s; 23 | cin >> s; 24 | vector v1, v2; 25 | v1.push_back(s); 26 | int cost = 0; 27 | for (int j = 0; j < numcuts; ++j) // perform k cuts 28 | { 29 | memset(alphabet, 0, sizeof alphabet); 30 | int prev_size = 0, size = 0; 31 | bool cut = false; 32 | for (int k = 0; k < v1.size(); ++k) // find substring to cut 33 | { 34 | //TODO: if WA, ignore duplicate cut positions by storing cutpos in a set. 35 | prev_size = size; 36 | size += v1[k].size(); 37 | if (cutpos[j] < size && !cut) // cut this substring 38 | { 39 | int cutindx = cutpos[j] - prev_size; // cut index relative to substring 40 | string substr1 = v1[k].substr(0, cutindx); // left side of cut 41 | string substr2 = v1[k].substr(cutindx); // right side of cut 42 | v2.push_back(substr1); 43 | v2.push_back(substr2); 44 | cut = true; 45 | 46 | // Calculate cost of the cut 47 | for (int l = 0; l < substr1.size(); ++l) // find unique chars in substr1 48 | { 49 | int idx = substr1[l] - 'a'; 50 | if (!alphabet[idx]) // if first encounter of character 51 | { 52 | alphabet[idx] = 1; 53 | if (substr2.find(substr1[l]) == string::npos) cost++; 54 | } 55 | } 56 | for (int l = 0; l < substr2.size(); ++l) // find unique chars in substr2 57 | { 58 | int idx = substr2[l] - 'a'; 59 | if (!alphabet[idx]) 60 | { 61 | alphabet[idx] = 1; 62 | if (substr1.find(substr2[l]) == string::npos) cost++; 63 | } 64 | } 65 | } 66 | else // also push back any uncut substrings 67 | { 68 | v2.push_back(v1[k]); 69 | } 70 | } 71 | 72 | v1 = v2; // v1 drops its current elements and copies the contents of v2 73 | v2.clear(); // or `v2 = vector();` 74 | 75 | //for (int t = 0; t < v1.size(); ++t) 76 | // cout << v1.at(t) << " "; 77 | //cout << endl; 78 | //cout << "total cost = " << cost << endl; 79 | } 80 | cout << cost << endl; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_06_bellman_ford.java: -------------------------------------------------------------------------------- 1 | import java.util.Collections; 2 | import java.util.Iterator; 3 | import java.util.Scanner; 4 | import java.util.Vector; 5 | 6 | public class ch4_06_bellman_ford { 7 | public static final int INF = 2000000000; 8 | private static Vector< Vector< IntegerPair > > AdjList = 9 | new Vector< Vector< IntegerPair > >(); 10 | 11 | public static void main(String[] args) { 12 | int V, E, a, b, weight; 13 | 14 | /* 15 | // Graph in Figure 4.17, no negative cycle 16 | 5 5 17 | 0 1 1 18 | 0 2 10 19 | 1 3 2 20 | 2 3 -10 21 | 3 4 3 22 | 23 | // Graph in Figure 4.18, negative cycle exists 24 | 3 3 25 | 0 1 1000 26 | 1 2 15 27 | 2 1 -42 28 | */ 29 | 30 | Scanner sc = new Scanner(System.in); 31 | V = sc.nextInt(); 32 | E = sc.nextInt(); 33 | 34 | AdjList.clear(); 35 | for (int i = 0; i < V; i++) { 36 | Vector< IntegerPair > Neighbor = 37 | new Vector < IntegerPair >(); 38 | AdjList.add(Neighbor); // add neighbor list to Adjacency List 39 | } 40 | 41 | for (int i = 0; i < E; i++) { 42 | a = sc.nextInt(); 43 | b = sc.nextInt(); 44 | weight = sc.nextInt(); 45 | AdjList.get(a).add(new IntegerPair(b, weight)); // first time using weight 46 | } 47 | 48 | // as an example, we start from this source (see Figure 1.15) 49 | int s = 0; 50 | Vector< Integer > dist = new Vector< Integer >(); 51 | dist.addAll(Collections.nCopies(V, INF)); 52 | dist.set(s, 0); 53 | 54 | // Bellman Ford routine 55 | for (int i = 0; i < V - 1; i++) // relax all E edges V-1 times, O(V) 56 | for (int u = 0; u < V; u++) { // these two loops = O(E) 57 | Iterator it = AdjList.get(u).iterator(); 58 | while (it.hasNext()) { // relax these edges 59 | IntegerPair v = (IntegerPair)it.next(); 60 | dist.set(v.first(), 61 | Math.min(dist.get(v.first()), dist.get(u) + v.second())); 62 | } 63 | } 64 | 65 | boolean negative_cycle_exist = false; 66 | for (int u = 0; u < V; u++) { // one more pass to check 67 | Iterator it = AdjList.get(u).iterator(); 68 | while (it.hasNext()) { // relax these edges 69 | IntegerPair v = (IntegerPair)it.next(); 70 | if (dist.get(v.first()) > dist.get(u) + v.second()) // should be false, but if possible 71 | negative_cycle_exist = true; // then negative cycle exists! 72 | } 73 | } 74 | 75 | System.out.printf("Negative Cycle Exist? %s\n", negative_cycle_exist ? "Yes" : "No"); 76 | 77 | if (!negative_cycle_exist) 78 | for (int i = 0; i < V; i++) 79 | System.out.printf("SSSP(%d, %d) = %d\n", s, i, dist.get(i)); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/B/B.java: -------------------------------------------------------------------------------- 1 | // Solution to Flip It 2 | 3 | import java.util.*; 4 | 5 | public class Flip { 6 | public static int n,m; 7 | public static Stack grid[][]; 8 | public static Scanner in; 9 | public static int caseNum; 10 | 11 | public static void main(String[] args) { 12 | in = new Scanner(System.in); 13 | caseNum = 0; 14 | while(true) { 15 | n = in.nextInt(); 16 | m = in.nextInt(); 17 | if (m == 0 && n == 0) break; 18 | caseNum++; 19 | grid = new Stack[n][m]; 20 | int top = 0, bottom = n-1, left = 0, right = m-1; 21 | for (int i = 0; i < n; i++) 22 | for (int j = 0; j < m; j++) 23 | grid[i][j] = new Stack(); 24 | for (int i = 0; i < n; i++) 25 | for (int j = 0; j < m; j++) 26 | grid[i][j].push(in.nextInt()); 27 | if (m>1 || n > 1) { 28 | String dir = in.next(); 29 | for (int j = 0; j < dir.length(); j++) { 30 | char c = dir.charAt(j); 31 | switch(c) { 32 | case 'T': for (int i = left; i <= right; i++) { 33 | while(!grid[top][i].empty()) { 34 | int temp = (Integer)(grid[top][i].pop()); 35 | grid[top+1][i].push(-temp); 36 | } 37 | } 38 | top++; 39 | break; 40 | case 'B': for (int i = left; i <= right; i++) { 41 | while(!grid[bottom][i].empty()) { 42 | int temp = (Integer)(grid[bottom][i].pop()); 43 | grid[bottom-1][i].push(-temp); 44 | } 45 | } 46 | bottom--; 47 | break; case 'L': for (int i = top; i <= bottom; i++) { 48 | while(!grid[i][left].empty()) { 49 | int temp = (Integer)(grid[i][left].pop()); 50 | grid[i][left+1].push(-temp); 51 | } 52 | } 53 | left++; 54 | break; 55 | case 'R': for (int i = top; i <= bottom; i++) { 56 | while(!grid[i][right].empty()) { 57 | int temp = (Integer)(grid[i][right].pop()); 58 | grid[i][right-1].push(-temp); 59 | } 60 | } 61 | right--; 62 | break; 63 | } 64 | } 65 | } 66 | System.out.print("Case " + caseNum + ":"); 67 | print(grid[top][left]); 68 | System.out.println(); 69 | } 70 | } 71 | 72 | public static void print(Stack s) { 73 | if (s.empty()) return; 74 | int i = s.pop(); 75 | print(s); 76 | if (i > 0) 77 | System.out.print(" "+i); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_07_UVa10229.java: -------------------------------------------------------------------------------- 1 | /* Modular Fibonacci */ 2 | 3 | import java.util.*; 4 | 5 | class Main { 6 | static int i, n, m, MAX_N = 2; 7 | static long MOD; 8 | 9 | static long[][] matMul(long[][] a, long[][] b) { // O(n^3 ~> 1) as n=2 10 | long[][] ans = new long[2][2]; int i, j, k; 11 | for (i = 0; i < MAX_N; i++) 12 | for (j = 0; j < MAX_N; j++) 13 | for (ans[i][j] = k = 0; k < MAX_N; k++) { 14 | ans[i][j] += (a[i][k] % MOD) * (b[k][j] % MOD); 15 | ans[i][j] %= MOD; // modulo arithmetic is used here 16 | } 17 | return ans; 18 | } 19 | 20 | static long[][] matPow(long[][] base, int p) { // O(n^3 log p ~> log p) 21 | long[][] ans = new long[MAX_N][MAX_N]; int i, j; 22 | for (i = 0; i < MAX_N; i++) 23 | for (j = 0; j < MAX_N; j++) 24 | ans[i][j] = (i == j ? 1 : 0); // prepare identity matrix 25 | while (p > 0) { // iterative version of Divide & Conquer exponentiation 26 | if ((p & 1) == 1) // check if p is odd (the last bit is on) 27 | ans = matMul(ans, base); // update ans 28 | base = matMul(base, base); // square the base 29 | p >>= 1; // divide p by 2 30 | } 31 | return ans; 32 | } 33 | 34 | static int normalExp(int base, int p) { // we just use int data type 35 | int ans = 1; 36 | for (int i = 0; i < p; i++) ans *= base; // O(p) 37 | return ans; } 38 | 39 | static int fastExp(int base, int p) { // O(log p) 40 | if (p == 0) return 1; 41 | else if (p == 1) return base; 42 | else { int res = fastExp(base, p / 2); res *= res; 43 | if (p % 2 == 1) res *= base; 44 | return res; } } 45 | 46 | public static void main(String[] args) { 47 | // just for illustration (not part of UVa 10229 solution), uncomment to compare 48 | // System.out.printf("%d vs %d\n", normalExp(2, 4), fastExp(2, 4)); 49 | // System.out.printf("%d vs %d\n", normalExp(2, 9), fastExp(2, 9)); 50 | // System.out.printf("%d vs %d\n", normalExp(2, 22), fastExp(2, 22)); 51 | 52 | Scanner sc = new Scanner(System.in); 53 | while (sc.hasNext()) { 54 | n = sc.nextInt(); m = sc.nextInt(); 55 | 56 | for (MOD = 1, i = 0; i < m; i++) // set MOD = 2^m 57 | MOD *= 2; 58 | 59 | long[][] ans = new long[MAX_N][MAX_N]; // special Fibonaccci matrix 60 | ans[0][0] = 1; ans[0][1] = 1; 61 | ans[1][0] = 1; ans[1][1] = 0; 62 | 63 | ans = matPow(ans, n); // O(log n) 64 | System.out.println(ans[0][1]); // this if fib(n) 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch5-Mathematics/ch5_07_UVa10229.cpp: -------------------------------------------------------------------------------- 1 | /* Modular Fibonacci */ 2 | 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | typedef long long ll; 9 | ll MOD; 10 | 11 | #define MAX_N 2 // increase this if needed 12 | struct Matrix { ll mat[MAX_N][MAX_N]; }; // to let us return a 2D array 13 | 14 | Matrix matMul(Matrix a, Matrix b) { // O(n^3), but O(1) as n=2 15 | Matrix ans; int i, j, k; 16 | for (i = 0; i < MAX_N; i++) 17 | for (j = 0; j < MAX_N; j++) 18 | for (ans.mat[i][j] = k = 0; k < MAX_N; k++) { 19 | ans.mat[i][j] += (a.mat[i][k] % MOD) * (b.mat[k][j] % MOD); 20 | ans.mat[i][j] %= MOD; // modulo arithmetic is used here 21 | } 22 | return ans; 23 | } 24 | 25 | Matrix matPow(Matrix base, int p) { // O(n^3 log p), but O(log p) as n=2 26 | Matrix ans; int i, j; 27 | for (i = 0; i < MAX_N; i++) 28 | for (j = 0; j < MAX_N; j++) 29 | ans.mat[i][j] = (i == j); // prepare identity matrix 30 | while (p) { // iterative version of Divide & Conquer exponentiation 31 | if (p & 1) // check if p is odd (the last bit is on) 32 | ans = matMul(ans, base); // update ans 33 | base = matMul(base, base); // square the base 34 | p >>= 1; // divide p by 2 35 | } 36 | return ans; 37 | } 38 | 39 | int normalExp(int base, int p) { // for simplicity, we use int data type 40 | int ans = 1; 41 | for (int i = 0; i < p; i++) ans *= base; // O(p) 42 | return ans; } 43 | 44 | int fastExp(int base, int p) { // O(log p) 45 | if (p == 0) return 1; 46 | else if (p == 1) return base; 47 | else { int res = fastExp(base, p / 2); res *= res; 48 | if (p % 2 == 1) res *= base; 49 | return res; } } 50 | 51 | int main() { 52 | // just for illustration (not part of UVa 10229 solution), uncomment to compare 53 | // printf("%d vs %d\n", normalExp(2, 4), fastExp(2, 4)); 54 | // printf("%d vs %d\n", normalExp(2, 9), fastExp(2, 9)); 55 | // printf("%d vs %d\n", normalExp(2, 22), fastExp(2, 22)); 56 | 57 | int i, n, m; 58 | 59 | while (scanf("%d %d", &n, &m) == 2) { 60 | Matrix ans; // special Fibonaccci matrix 61 | ans.mat[0][0] = 1; ans.mat[0][1] = 1; 62 | ans.mat[1][0] = 1; ans.mat[1][1] = 0; 63 | for (MOD = 1, i = 0; i < m; i++) // set MOD = 2^m 64 | MOD *= 2; 65 | ans = matPow(ans, n); // O(log n) 66 | printf("%lld\n", ans.mat[0][1]); // this if fib(n) 67 | } 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch4-Graph/ch4_03_kruskal_prim.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.PriorityQueue; 3 | import java.util.Scanner; 4 | import java.util.Vector; 5 | 6 | public class ch4_03_kruskal_prim { 7 | // Union-Find Disjoint Sets data structure from chapter 2. 8 | private static Vector pset; 9 | private static void initSet(int _size) { pset = new Vector(_size); for (int i = 0; i < _size; i++) pset.add(i); } 10 | private static int findSet(int i) { return (pset.get(i) == i) ? i : (pset.set(i, findSet(pset.get(i)))); } 11 | private static void unionSet(int i, int j) { pset.set(findSet(i), findSet(j)); } 12 | private static boolean isSameSet(int i, int j) { 13 | int a = findSet(i); 14 | int b = findSet(j); 15 | a = findSet(i); // to avoid bug in Java version, we have to call findSet twice 16 | b = findSet(j); 17 | return a == b; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int V, E, a, b, weight; 22 | 23 | /* 24 | // Graph in Figure 4.9 left/4.10, format: list of weighted edges 25 | // This example shows another form of reading graph input 26 | 5 7 27 | 1 2 5 28 | 1 3 5 29 | 1 4 5 30 | 1 5 5 31 | 2 3 2 32 | 3 4 8 33 | 4 5 8 34 | */ 35 | 36 | Scanner sc = new Scanner(System.in); 37 | V = sc.nextInt(); 38 | E = sc.nextInt(); 39 | 40 | // another graph data structure: EdgeList 41 | PriorityQueue < pair < Integer, IntegerPair > > EdgeList = new 42 | PriorityQueue < pair < Integer, IntegerPair > >(1, 43 | new Comparator< pair < Integer, IntegerPair > >() { // overriding the compare method 44 | public int compare(pair < Integer, IntegerPair > i, pair < Integer, IntegerPair > j) { 45 | return j.first() - i.first(); 46 | } 47 | } 48 | ); 49 | 50 | // sort by edge weight O(E log E) 51 | // PQ default: sort descending. Trick: use <(negative) weight(i, j), > 52 | for (int i = 0; i < E; i++) { 53 | a = sc.nextInt(); 54 | b = sc.nextInt(); 55 | weight = sc.nextInt(); 56 | IntegerPair edge = new IntegerPair (--a, --b); 57 | EdgeList.offer(new pair < Integer, IntegerPair > (-weight, edge)); 58 | } 59 | 60 | int mst_cost = 0; initSet(V); // all V are disjoint sets at the beginning 61 | while (!EdgeList.isEmpty()) { // while there exist more edges, O(E) 62 | pair < Integer, IntegerPair > front = EdgeList.poll(); 63 | a = front.second().first(); 64 | b = front.second().second(); 65 | if (!isSameSet(a, b)) { // if no cycle 66 | mst_cost += (-front.first()); // add (negated) -weight of e to MST 67 | unionSet(a, b); // link these two vertices 68 | } 69 | } 70 | System.out.printf("MST cost %d\n", mst_cost); 71 | 72 | 73 | 74 | // Prim's algorithm is not yet implemented... 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /resources/c++_and_stl/competition.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | typedef long long ll; 15 | typedef long double ld; 16 | typedef vector vi; 17 | typedef vector vvi; 18 | typedef pair pii; 19 | typedef vector vii; // vector of integer pairs 20 | typedef set si; 21 | typedef map msi; 22 | 23 | #define VAR(a,b) __typeof(b) a=(b) 24 | #define REP(i,n) for(int i=0;i<(n);++i) // 0 to n 25 | #define FOR(i,a,b) for(VAR(i,a);i<=(b);++i) // a to b, a < b 26 | #define FORD(i,a,b) for(VAR(i,a);i>=(b);--i) // a to b, a > b 27 | #define FORE(a,b) for(VAR(a,(b).begin());a!=(b).end();++a) // for each, e.g. FORE(iter, vect) cout << *iter << endl; 28 | #define SIZE(a) ((int)((a).size())) // e.g. for (int i = 0; i < SIZE(vect); ++i) 29 | #define ALL(v) (v).begin(),(v).end() // e.g. sort(ALL(vect)) 30 | #define FILL(x,a) memset(x,a,sizeof(x)) 31 | #define CLR(x) memset(x,0,sizeof(x)) 32 | #define VE vector 33 | #define SZ size() 34 | #define SZ(v) ((int)(v).size()) 35 | #define PB push_back 36 | #define MP make_pair 37 | #define FI first 38 | #define SE second 39 | #define TRsi(c,it) for(si::iterator it=(c).begin();it!=(c).end();it++) // cout << " " << *it; 40 | #define TRvii(c,it) for(vii::iterator it=(c).begin();it!=(c).end();it++) // cout << " " << *it; 41 | #define TRmsi(c,it) for(msi::iterator it=(c).begin();it!=(c).end();it++) 42 | #define INF 2000000000 // 2 billion 43 | #define SQ(x) ((x)*(x)) 44 | #define getLastDigit(i) i%10 45 | #define remLastDigit(i) i/10 46 | #define char2int(c) c-0 47 | #define char2idx(c) c-'a' 48 | 49 | const double PI=acos(-1.0); //NOTES: PI 50 | const double EPS=1e-11; //NOTES: EPS 51 | 52 | // Translator 53 | bool isUpper(char c){return c>='A' && c<='Z';} //NOTES: isUpper( 54 | bool isLower(char c){return c>='a' && c<='z';} //NOTES: isLower( 55 | bool isLetter(char c){return c>='A' && c<='Z' || c>='a' && c<='z';} //NOTES: isLetter( 56 | bool isDigit(char c){return c>='0' && c<='9';} //NOTES: isDigit( 57 | char toLower(char c){return (isUpper(c))?(c+32):c;} //NOTES: toLower( 58 | char toUpper(char c){return (isLower(c))?(c-32):c;} //NOTES: toUpper( 59 | int str2int(string s){int r=0;istringstream sin(s);sin>>r;return r;} //NOTES: str2int( 60 | int char2int(char c){return (int)c;} //NOTES: char2int( 61 | 62 | // Numeric functions 63 | bool isPowOf2(int i){return (i & i-1) == 0;} //NOTES: isPowOf2 64 | 65 | // TODO: add more (see ACRush's template + Competitive Programming book) 66 | -------------------------------------------------------------------------------- /practice-problems/ECNA-2010/B/outB.dat: -------------------------------------------------------------------------------- 1 | Case 1: 10 13 1 2 2 | Case 2: 3 | Case 3: 22 4 | Case 4: 2 3 5 | Case 5: 950 598 135 423 20 734 862 259 383 31 953 930 727 198 91 303 6 | Case 6: 4 1 7 | Case 7: 2 3 8 | Case 8: 1 4 9 | Case 9: 3 2 10 | Case 10: 6 8 10 4 2 11 | Case 11: 6 8 10 4 2 12 | Case 12: 8 1 3 5 13 | Case 13: 3 1 8 5 14 | Case 14: 3 1 5 8 15 | Case 15: 2 1 6 9 7 4 5 16 | Case 16: 3 8 17 | Case 17: 8 3 18 | Case 18: 25 15 5 23 13 3 21 11 1 17 7 19 9 19 | Case 19: 14 24 20 10 4 12 22 2 6 16 8 18 20 | Case 20: 13 18 3 9 15 25 19 11 21 1 7 17 12 21 | Case 21: 8 18 23 13 1 11 12 22 2 7 14 15 10 4 22 | Case 22: 950 447 487 200 215 798 61 539 650 952 428 970 252 615 940 545 559 872 923 72 441 655 136 720 52 112 174 772 759 528 338 398 301 455 45 874 586 283 340 754 830 470 556 340 246 64 698 800 201 878 843 123 566 800 479 876 73 903 372 507 731 293 880 709 82 423 37 882 109 91 245 481 410 187 9 380 597 907 589 417 381 534 245 441 579 506 993 129 917 284 599 565 45 789 18 239 52 116 583 658 650 172 56 2 574 316 380 743 562 645 937 630 741 738 464 519 961 112 772 825 654 291 526 703 682 960 439 161 486 78 68 315 793 206 345 572 491 260 602 900 215 18 851 969 409 807 806 704 19 693 190 71 610 378 106 908 410 422 917 737 861 260 54 660 282 523 451 621 420 189 807 550 255 317 964 708 406 91 917 698 51 946 420 60 729 948 875 917 581 172 943 21 595 918 280 691 781 816 368 134 509 4 154 897 48 847 622 758 13 23 | Case 23: 781 847 943 48 21 154 897 595 918 4 509 134 280 368 691 60 729 948 875 917 581 172 622 655 441 428 13 950 952 816 758 970 650 338 447 72 136 720 487 615 200 215 798 61 940 545 559 872 923 52 112 174 772 759 252 539 528 398 301 455 45 874 586 283 340 754 830 470 556 340 246 64 698 800 201 878 843 123 566 800 479 876 73 903 372 507 731 293 880 709 82 423 37 882 109 91 245 602 900 215 18 597 161 486 78 68 526 703 682 960 439 825 654 291 45 519 961 112 772 239 630 741 738 464 658 937 56 645 743 562 316 380 574 2 650 172 52 116 583 789 18 284 599 565 245 441 579 506 993 129 917 907 589 417 381 534 315 793 206 345 572 491 260 481 410 187 9 380 851 969 409 807 806 704 19 693 190 71 610 378 106 908 410 422 917 737 861 260 54 660 282 523 451 621 420 189 807 550 255 317 964 708 406 91 917 698 51 946 420 24 | Case 24: 432 17 718 643 351 95 895 624 985 698 14 69 745 366 515 539 668 382 497 743 211 789 32 308 703 707 742 243 570 197 174 238 828 145 821 496 632 208 25 | Case 25: 854 954 663 237 852 95 822 702 286 443 136 812 734 105 845 385 808 630 515 111 855 95 869 604 450 862 68 729 271 659 244 146 563 61 164 794 101 520 858 727 952 18 911 811 103 309 553 68 210 61 313 484 560 459 101 664 26 | Case 26: 205 471 791 672 771 974 97 85 820 998 986 223 251 861 77 400 161 461 195 832 82 897 958 166 850 430 19 891 565 267 27 | Case 27: 223 380 704 366 624 182 41 806 758 319 533 425 780 314 227 766 859 848 924 28 | Case 28: 198 223 82 885 530 991 902 132 931 418 883 841 754 357 781 610 976 510 766 760 992 482 53 920 138 122 451 502 575 331 224 470 864 943 792 341 380 957 362 121 913 29 | -------------------------------------------------------------------------------- /resources/c++_and_stl/ch2-Data_Structures/ch2_07_graph_ds.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | typedef pair ii; 8 | typedef vector vii; 9 | 10 | int main() { 11 | int V, E, total_neighbors, id, weight, a, b; 12 | int AdjMat[100][100]; 13 | vector AdjList; 14 | priority_queue< pair > EdgeList; // one way to store Edge List 15 | 16 | // Try this input for Adjacency Matrix/List/EdgeList 17 | // Adj Matrix 18 | // for each line: |V| entries, 0 or the weight 19 | // Adj List 20 | // for each line: num neighbors, list of neighbors + weight pairs 21 | // Edge List 22 | // for each line: a-b of edge(a,b) and weight 23 | /* 24 | 6 25 | 0 10 0 0 100 0 26 | 10 0 7 0 8 0 27 | 0 7 0 9 0 0 28 | 0 0 9 0 20 5 29 | 100 8 0 20 0 0 30 | 0 0 0 5 0 0 31 | 6 32 | 2 2 10 5 100 33 | 3 1 10 3 7 5 8 34 | 2 2 7 4 9 35 | 3 3 9 5 20 6 5 36 | 3 1 100 2 8 4 20 37 | 1 4 5 38 | 7 39 | 1 2 10 40 | 1 5 100 41 | 2 3 7 42 | 2 5 8 43 | 3 4 9 44 | 4 5 20 45 | 4 6 5 46 | */ 47 | scanf("%d", &V); // we must know this size first! 48 | // remember that if V is > 100, try NOT to use AdjMat! 49 | for (int i = 0; i < V; i++) 50 | for (int j = 0; j < V; j++) 51 | scanf("%d", &AdjMat[i][j]); 52 | 53 | printf("Neighbors of vertex 0:\n"); 54 | for (int j = 0; j < V; j++) // O(|V|) 55 | if (AdjMat[0][j]) 56 | printf("Edge 0-%d (weight = %d)\n", j, AdjMat[0][j]); 57 | 58 | scanf("%d", &V); 59 | AdjList.assign(V, vii()); // quick way to initialize AdjList with V entries of vii 60 | for (int i = 0; i < V; i++) { 61 | scanf("%d", &total_neighbors); 62 | for (int j = 0; j < total_neighbors; j++) { 63 | scanf("%d %d", &id, &weight); 64 | AdjList[i].push_back(ii(id - 1, weight)); // some index adjustment 65 | } 66 | } 67 | 68 | printf("Neighbors of vertex 0:\n"); 69 | for (vii::iterator j = AdjList[0].begin(); j != AdjList[0].end(); j++) 70 | // AdjList[0] contains the required information 71 | // O(k), where k is the number of neighbors 72 | printf("Edge 0-%d (weight = %d)\n", j->first, j->second); 73 | 74 | scanf("%d", &E); 75 | for (int i = 0; i < E; i++) { 76 | scanf("%d %d %d", &a, &b, &weight); 77 | EdgeList.push(make_pair(-weight, ii(a, b))); // trick to reverse sort order 78 | } 79 | 80 | // edges sorted by weight (smallest->largest) 81 | for (int i = 0; i < E; i++) { 82 | pair edge = EdgeList.top(); EdgeList.pop(); 83 | // negate the weight again 84 | printf("weight: %d (%d-%d)\n", -edge.first, edge.second.first, edge.second.second); 85 | } 86 | 87 | return 0; 88 | } 89 | --------------------------------------------------------------------------------