├── 3sum.py ├── README.md ├── article ├── SICILY部分题目的大致分类.txt ├── segment_tree.pdf ├── 动态规划求解“键盘上字母分配”问题.doc ├── 福大第二届程序设计大赛.doc └── 线段树.ppt ├── bk-tree-for-spell-checking ├── .gitignore ├── BKtree.cpp ├── BKtree.h ├── Makefile ├── deserialize.cpp ├── dict.txt ├── levenshtein_distance.cpp ├── levenshtein_distance.h ├── test-BKtree.cpp ├── test-dist.cpp └── unordered_map_serialization.h ├── btree ├── btree.cpp └── btree.h ├── careercup ├── 13.9-smart-ptr.cpp ├── 18.10-transform-words.cpp ├── 18.2-random-shuffle.cpp ├── 18.5-synchronization.cpp ├── 4.4-level-traversal.cpp ├── 4.6-binary-tree-in-order-successor.cpp ├── 4.7-common-anncestor-no-extra-mem.cpp ├── 4.8-all-path-sum.cpp ├── 5.1-set-bits.cpp ├── 5.2-to-binary-string.cpp ├── 5.5-nbits-required-to-convert.cpp ├── 5.7-find-missing-integer.cpp └── website │ └── sort_word.cpp ├── clrs └── min_dist_points │ ├── gen │ ├── gen.cpp │ └── min_dist_points.cpp ├── collinear.py ├── compgeo ├── basic.h ├── graham.h ├── jarvis.h ├── main.cpp ├── point.h ├── segment.h ├── sweep_hull.h └── vector.h ├── concurrency ├── exercise │ ├── deadlock.cpp │ ├── hardware_concurrency.cpp │ ├── hello.cpp │ ├── monte-carlo-pi-all-cores.cpp │ ├── monte-carlo-pi.cpp │ ├── multithread-sum.cpp │ ├── readme.txt │ ├── ref_wrap.cpp │ ├── thread-arguments-problems-fixed.cc │ └── thread-arguments-problems2-fixed.cc ├── producer-consumer-atomic.cpp ├── producer-consumer.cpp ├── race-condition.cpp ├── reporter-assigner.cpp └── thread.cpp ├── counterfeit_coin.py ├── counting.py ├── curve_fitting.py ├── data_structure ├── queue-constant-min.cpp └── stack-constant-min.cpp ├── dp ├── longest_common_subsequence-ii.cpp ├── longest_common_subsequence.cpp ├── longest_common_substring-ii.cpp ├── longest_common_substring.cpp ├── non_decr_seq │ └── non_decr_seq.c ├── schedule │ ├── data.in │ └── schedule.c ├── sum │ ├── data.in │ └── sum.c ├── test-longest_common_subsequence.txt └── test-longest_common_substring.txt ├── external_merge_sort.cpp ├── hashmap.cpp ├── heap └── running-median.cpp ├── interview ├── dropbox │ ├── code-challenge │ │ ├── run.sh │ │ ├── test_cases_word-pattern │ │ │ ├── input000.txt │ │ │ ├── input001.txt │ │ │ ├── input002.txt │ │ │ ├── input003.txt │ │ │ ├── input004.txt │ │ │ ├── input005.txt │ │ │ ├── input006.txt │ │ │ ├── input007.txt │ │ │ ├── input008.txt │ │ │ ├── output000.txt │ │ │ ├── output001.txt │ │ │ ├── output002.txt │ │ │ ├── output003.txt │ │ │ ├── output004.txt │ │ │ ├── output005.txt │ │ │ ├── output006.txt │ │ │ ├── output007.txt │ │ │ └── output008.txt │ │ └── word-pattern.cpp │ ├── phone-interview.txt │ └── practice │ │ ├── eval-boolean-expression.cpp │ │ ├── oral-presentation-of-number.cpp │ │ ├── subsequence-sum-zero.cpp │ │ └── text-form-of-numbers.cpp ├── facebook │ ├── bst-in-order-successor.cpp │ └── largest-in-window.cpp ├── google │ ├── fulltime │ │ └── phone.txt │ └── url_shorten │ │ ├── .gitignore │ │ ├── Makefile │ │ └── shorten.cpp ├── indeed │ ├── coding │ │ ├── bracket.cpp │ │ ├── convict-transfer.cpp │ │ ├── test_cases_bracket │ │ │ ├── input000.txt │ │ │ ├── input001.txt │ │ │ ├── output000.txt │ │ │ └── output001.txt │ │ └── test_cases_convict_transfer │ │ │ ├── input000.txt │ │ │ ├── input001.txt │ │ │ ├── output000.txt │ │ │ └── output001.txt │ └── onsite │ │ ├── coding_challenge.txt │ │ ├── k-closest-point.cpp │ │ ├── lca-dag.cpp │ │ └── reorder-list.txt ├── linkedin │ └── repeated-dna-string.cpp ├── palantir │ ├── .gitignore │ ├── 1st_phone │ │ └── k-largest.cpp │ └── online_test │ │ ├── input000.txt │ │ ├── input001.txt │ │ ├── input002.txt │ │ ├── input003.txt │ │ ├── input004.txt │ │ ├── input005.txt │ │ ├── output000.txt │ │ ├── output001.txt │ │ ├── output002.txt │ │ ├── output003-my.txt │ │ ├── output003.txt │ │ ├── output004-my.txt │ │ ├── output004.txt │ │ ├── output005-my.txt │ │ ├── output005.txt │ │ └── palantir.cpp └── twitter │ ├── findkth.cpp │ ├── median.txt │ ├── plane-region.cpp │ ├── rational.cpp │ ├── test_cases-plane-region │ ├── input000.txt │ ├── input001.txt │ ├── output000.txt │ └── output001.txt │ └── test_cases-rational │ ├── input000.txt │ └── output000.txt ├── kmeans.cpp ├── largest_block └── largest.c ├── leetcode ├── .gitignore ├── 3sum-closest.cpp ├── 3sum.cpp ├── 4sum.cpp ├── add-binary.cpp ├── add-two-numbers.cpp ├── anagrams.cpp ├── atoi.cpp ├── balanced-binary-tree.cpp ├── best-time-to-buy-and-sell-stock-ii.cpp ├── best-time-to-buy-and-sell-stock-iii.cpp ├── best-time-to-buy-and-sell-stock.cpp ├── binary-tree-inorder-traversal.cpp ├── binary-tree-level-order-traversal-ii.cpp ├── binary-tree-level-order-traversal.cpp ├── binary-tree-postorder-traversal.cpp ├── binary-tree-preorder-traversal.cpp ├── binary-tree-zigzag-level-order-traversal.cpp ├── candy.cpp ├── climbing-stairs.cpp ├── clone-graph.cpp ├── combination-sum-ii.cpp ├── combination-sum.cpp ├── combinations.cpp ├── construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── container-with-most-water.cpp ├── convert-sorted-array-to-binary-search-tree.cpp ├── convert-sorted-list-to-binary-search-tree.cpp ├── copy-list-with-random-pointer.cpp ├── count-and-say.cpp ├── decode-ways.cpp ├── distance-maximization.cpp ├── distinct-subsequences.cpp ├── divide-two-integers.cpp ├── edit-distance.cpp ├── evaluate-reverse-polish-notation.cpp ├── first-missing-positive.cpp ├── flatten-binary-tree-to-linked-list.cpp ├── gas-station.cpp ├── generate-parentheses.cpp ├── gray-code.cpp ├── implement-strstr.cpp ├── insert-interval.cpp ├── insertion-sort-list.cpp ├── integer-to-roman.cpp ├── interleaving-string.cpp ├── jump-game-ii.cpp ├── jump-game.cpp ├── kmp.cpp ├── kth-largest-quickselect.cpp ├── largest-rectangle-in-histogram.cpp ├── lca-bst.cpp ├── lca-parent-pointer.cpp ├── lca.cpp ├── leetcode.h ├── length-of-last-word.cpp ├── letter-combinations-of-a-phone-number.cpp ├── level_order_with_sentinel.cpp ├── linked-list-cycle-ii.cpp ├── linked-list-cycle.cpp ├── longest-common-prefix.cpp ├── longest-consecutive-sequence.cpp ├── longest-palindromic-substring.cpp ├── longest-substring-without-repeating-characters.cpp ├── longest-valid-parenthesis.cpp ├── lru-cache-linked-list.cpp ├── lru-cache.cpp ├── max-points-on-a-line.cpp ├── max_depth_of_tree.cpp ├── maximal-rectangle.cpp ├── maximum-path-sum.cpp ├── maximum-product-subarray.cpp ├── maximum-subarray.cpp ├── median-of-two-sorted-arrays.cpp ├── merge-intervals.cpp ├── merge-k-sorted-lists.cpp ├── merge-sorted-array.cpp ├── merge-two-sorted-lists.cpp ├── mergesort.cpp ├── minimum-depth-of-binary-tree.cpp ├── minimum-path-sum.cpp ├── minimum-window-substring.cpp ├── multiply-strings.cpp ├── n-queens-ii.cpp ├── n-queens.cpp ├── next-permutation.cpp ├── palindrome-number.cpp ├── palindrome-partitioning-ii.cpp ├── palindrome-partitioning.cpp ├── palindrome_partitioning.cpp ├── partition-list.cpp ├── pascals-triangle-ii.cpp ├── pascals-triangle.cpp ├── path-sum-ii.cpp ├── path-sum.cpp ├── permutation-sequence.cpp ├── permutations-ii.cpp ├── permutations.cpp ├── plus-one.cpp ├── populating-next-right-pointers-in-each-node-ii.cpp ├── populating-next-right-pointers-in-each-node.cpp ├── powx-n.cpp ├── qsort.cpp ├── recover-binary-search-tree.cpp ├── regular-expression-matching.cpp ├── regular_expression_matching.cpp ├── remove-duplicates-from-sorted-array-ii.cpp ├── remove-duplicates-from-sorted-array.cpp ├── remove-duplicates-from-sorted-list-ii.cpp ├── remove-duplicates-from-sorted-list.cpp ├── remove-element.cpp ├── remove-nth-node-from-end-of-list.cpp ├── reorder-list.cpp ├── restore-ip-address.py ├── reverse-linked-list-ii.cpp ├── reverse-nodes-in-k-group.cpp ├── reverse-words-in-a-string.cpp ├── reverse_integer.cpp ├── reverse_linked_list_recursive.cpp ├── romain-to-integer.cpp ├── roman-to-integer.cpp ├── rotate-image.cpp ├── rotate-list.cpp ├── same_tree.cpp ├── search-a-2d-matrix.cpp ├── search-for-a-range.cpp ├── search-in-rotated-sorted-array-ii.cpp ├── search-in-rotated-sorted-array.cpp ├── search-insert-position.cpp ├── serialize_binary_tree.cpp ├── set-matrix-zeroes.cpp ├── simplify-path.cpp ├── single-number-ii.cpp ├── single_number.cpp ├── sort-colors.cpp ├── sort-list.cpp ├── spiral-matrix-ii.cpp ├── spiral-matrix.cpp ├── sqrtx.cpp ├── subsets-ii.cpp ├── subsets.cpp ├── substring-with-concatenation-of-all-words.cpp ├── sudoku-solver.cpp ├── sum-root-to-leaf-numbers.cpp ├── surrounded-regions.cpp ├── swap-nodes-in-pairs.cpp ├── symmetric-tree.cpp ├── text-justification.cpp ├── thread.cpp ├── trapping-rain-water.cpp ├── tree_graphviz.cpp ├── triangle.cpp ├── two-sum.cpp ├── unique-binary-search-trees-ii.cpp ├── unique-paths-ii.cpp ├── unique-paths.cpp ├── unique_bst.cpp ├── valid-number.cpp ├── valid-palindrome.cpp ├── valid-parentheses.cpp ├── valid-sudoku.cpp ├── validate-binary-search-tree.cpp ├── wildcard-matching.cpp ├── word-break-ii.cpp ├── word-break.cpp ├── word-ladder-ii.cpp ├── word-ladder.cpp ├── word-search.cpp ├── zigzag-conversion.cpp └── zip.cpp ├── quadtree ├── Makefile ├── main.cpp ├── quadtree.cpp └── quadtree.h ├── rmbin.sh ├── sample_proc ├── 01bag │ ├── 01bag.cpp │ └── data.in ├── Makefile ├── dis_sum.c ├── func_ptr.cpp ├── kmp.cpp ├── knapsack.c ├── kth_big.cpp ├── matrix_mul_DP │ ├── data │ ├── matrix_mul_DP.cpp │ ├── matrix_mul_Recursive.cpp │ ├── output │ └── problem ├── max_asent_sequence.cpp ├── max_common_sbusequence │ ├── data.in │ └── max_common_sbusequence.cpp ├── mod_exp.cpp ├── number_theory │ ├── euclid.c │ └── mod_linear_equation.cpp ├── qsort.cpp ├── shortest_path │ ├── shortest_path.cpp │ └── testcase.in ├── sieve.c ├── test.cpp ├── two_egg.c ├── union_find_set.cpp └── xor │ └── xor.cpp ├── shortest-path ├── bellman-ford.h ├── dijkstra.h ├── graph.hpp └── test-shortest-path.cpp ├── sparse_matrix ├── COOMatrix.cpp ├── COOMatrix.h ├── CSCMatrix.cpp ├── CSCMatrix.h ├── CSRMatrix.cpp ├── CSRMatrix.h ├── Makefile ├── sparse_matrix.cpp ├── sparse_matrix.h └── test_matrix.cpp ├── suffix-tree ├── stree2006.cpp └── streed2006.cpp ├── system_design └── search_engine │ ├── .gitignore │ ├── build-index.py │ ├── search.py │ └── stoplist.txt ├── topcoder ├── TCCC03Round4 │ ├── .ChessMetric.cpp.swp │ └── ChessMetric.cpp ├── TCCC03semifinal_round3 │ ├── .ZigZag.cpp.swp │ ├── ZigZag.cpp │ └── data.in ├── TCCC04online_round4 │ ├── BadNeighbors.cpp │ └── data.in ├── TCO03Semifinals4 │ ├── .AvoidRoads.cpp.swp │ ├── AvoidRoads.cpp │ ├── AvoidRoads.c~ │ └── a.out ├── TallPeople.class ├── TallPeople.java ├── WordFind.java ├── getPeople.cpp ├── srm363div1 │ └── HandsShaking.cpp ├── srm397 │ └── SumOfPowers.cpp └── srm412div1 │ └── ForbiddenStrings.cpp ├── trie └── word_locations.cpp ├── uniform_point.py ├── usaco ├── barn1 │ ├── barn1.cpp │ └── milk1.in ├── beads │ ├── beads.cpp │ └── beads.in ├── castle │ ├── castle.c │ ├── castle.in │ └── castle.out ├── checker │ ├── checker.c │ ├── checker.in │ └── checker.out ├── clocks │ ├── clocks.cpp │ └── clocks.in ├── frac1 │ ├── frac1.c │ ├── frac1.in │ └── frac1.out ├── hamming │ ├── hamming.c │ └── hamming.in ├── holstein │ ├── holstein.c │ └── holstein.in ├── lamps │ ├── a.out │ ├── lamps.c │ ├── lamps.c.bak │ ├── lamps.in │ └── lamps.out ├── milk2 │ ├── milk.in │ ├── milk2.cpp │ └── milk2.in ├── milk3 │ ├── milk3.cpp │ └── milk3.in ├── pprime │ ├── pprime.c │ ├── pprime.in │ └── pprime.out ├── preface │ ├── preface.c │ └── preface.in ├── prefix │ ├── prefix │ ├── prefix.c │ ├── prefix.in │ ├── prefix.in2 │ ├── prefix.in3 │ └── prefix.out ├── runround │ ├── a.out │ ├── runround.c │ └── runround.in ├── sample_src.zip ├── sort3 │ ├── sort3.c │ ├── sort3.c.bak │ └── sort3.in ├── sprime │ ├── sprime.c │ ├── sprime.in │ └── sprime.out ├── subset │ ├── a.out │ ├── subset.c │ └── subset.in ├── templcate.c ├── transform │ ├── transform.cpp │ └── transform.in └── zerosum │ ├── zerosum.c │ └── zerosum.in ├── zju ├── 1003 │ └── 1003.cpp ├── 1045 │ └── 1045.cpp ├── 1048 │ └── 1048.cpp ├── 1049 │ └── 1049.cpp └── factorial.c └── zsu ├── 1029 └── rabbit.cpp ├── 1033 ├── cityroad.cpp ├── data └── tags ├── 1035 ├── data ├── dna.cpp └── result ├── 1193 ├── 1193.cpp ├── d ├── data.in └── in ├── 1415 ├── data └── honeycomb.cpp ├── 1426 └── main.cpp ├── 1438 └── 1438.cpp ├── 1443 └── main.cpp ├── 1490 ├── main.cpp └── output.txt ├── 07-08WeeklyContest7 ├── 1000.cpp ├── 1000.in └── 1001.cpp ├── 2008 Weekly Contest 2 ├── 1000 │ └── main.cpp ├── 1001 │ └── main.cpp ├── 1007 │ ├── 1007.cpp │ └── 107.cpp └── 1008 │ ├── main.cpp │ └── test.txt ├── c95 ├── 1000 │ ├── .DIR │ ├── zero.in │ └── zero.std ├── 1001 │ ├── .DIR │ ├── order.in │ ├── order.std │ └── src │ │ ├── gene.cpp │ │ ├── order.in │ │ └── order.std ├── 1002 │ ├── .DIR │ ├── 042080.cpp │ ├── 042112.cpp │ ├── t1 │ ├── t2 │ ├── travel.in │ └── travel.std ├── 1003 │ ├── .DIR │ ├── abbreviation.in │ └── abbreviation.std ├── 1004 │ ├── .DIR │ └── go.in ├── 1005 │ ├── .DIR │ ├── string.in │ └── string.std ├── 1006 │ ├── .DIR │ ├── dna.in │ └── dna.std ├── 1007 │ ├── .DIR │ ├── xiaoshi.in │ └── xiaoshi.std └── show_problem.php.htm └── test └── test.cpp /3sum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Implements the quadratic time algorithm 3 | """ 4 | import random 5 | 6 | def ThreeSum(S): 7 | S.sort() 8 | n = len(S) 9 | for i in range(0, n - 2): 10 | a = S[i] 11 | j = i + 1 12 | k = n - 1 13 | while (j < k): 14 | b, c = S[j],S[k] 15 | sum = a + b + c 16 | if (sum == 0): 17 | return (a, b, c) 18 | elif (sum > 0): 19 | k = k - 1 20 | else: 21 | j = j + 1 22 | return False 23 | 24 | if __name__ == "__main__": 25 | n = 20 26 | S = random.sample(xrange(-200, 200), n) 27 | print S 28 | tuple = ThreeSum(S) 29 | print tuple 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | algorithm 2 | ========= 3 | 4 | My algorithm repository. Contains various snippets for coding questions. 5 | -------------------------------------------------------------------------------- /article/SICILY部分题目的大致分类.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/article/SICILY部分题目的大致分类.txt -------------------------------------------------------------------------------- /article/segment_tree.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/article/segment_tree.pdf -------------------------------------------------------------------------------- /article/动态规划求解“键盘上字母分配”问题.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/article/动态规划求解“键盘上字母分配”问题.doc -------------------------------------------------------------------------------- /article/福大第二届程序设计大赛.doc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/article/福大第二届程序设计大赛.doc -------------------------------------------------------------------------------- /article/线段树.ppt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/article/线段树.ppt -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/.gitignore: -------------------------------------------------------------------------------- 1 | big.txt 2 | serialized.dict 3 | -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/Makefile: -------------------------------------------------------------------------------- 1 | 2 | BKTREE_CPP=test-BKtree.cpp BKtree.cpp levenshtein_distance.cpp 3 | DESERIALIZE_CPP=deserialize.cpp BKtree.cpp levenshtein_distance.cpp 4 | DIST_CPP=test-dist.cpp levenshtein_distance.cpp 5 | bin=bktree test-dist deserialize 6 | 7 | all: $(bin) 8 | 9 | deserialize: $(DESERIALIZE_CPP) 10 | clang++ -std=c++11 -o $@ $(BKTREE_CPP) -lboost_serialization 11 | 12 | bktree: $(BKTREE_CPP) 13 | clang++ -std=c++11 -o $@ $(BKTREE_CPP) -lboost_serialization 14 | 15 | test-dist: $(DIST_CPP) 16 | clang++ -std=c++11 -o $@ $(DIST_CPP) 17 | 18 | clean: 19 | rm -rf *.o $(bin) -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/deserialize.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #include 6 | 7 | #include "BKtree.h" 8 | #include "levenshtein_distance.h" 9 | 10 | int main(int argc, char const *argv[]) 11 | { 12 | if (argc <= 1) { 13 | cerr << "Usage: " << argv[0] << " \n"; 14 | return 1; 15 | } 16 | ifstream ifs(argv[1]); 17 | if (!ifs) { 18 | cerr << "File '" << argv[1] << "' not exist!\n"; 19 | return 2; 20 | } 21 | 22 | BKTree tree; 23 | { 24 | // create and open an archive for input 25 | boost::archive::text_iarchive ia(ifs); 26 | // read class state from archive 27 | ia >> tree; 28 | // archive and stream closed when destructors are called 29 | } 30 | 31 | auto result = tree.search(argv[2], atoi(argv[3])); 32 | copy(result.begin(), result.end(), 33 | ostream_iterator(cout, " ")); 34 | cout << "\n"; 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/dict.txt: -------------------------------------------------------------------------------- 1 | book 2 | books 3 | cake 4 | boo 5 | cape 6 | cart 7 | boon 8 | cook -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/levenshtein_distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using std::vector; 3 | 4 | #include "levenshtein_distance.h" 5 | 6 | size_t levenshtein_distance(const string &a, const string &b) { 7 | int na = a.size(); 8 | int nb = b.size(); 9 | vector > D(na + 1, vector(nb + 1, 0)); 10 | 11 | for (int j = 0; j <= nb; ++j) {D[0][j] = j; } 12 | for (int i = 0; i <= na; ++i) {D[i][0] = i; } 13 | for (int i = 1; i <= na; ++i) { 14 | for (int j = 1; j <= nb; ++j) { 15 | if (a[i-1] != b[j-1]) { 16 | D[i][j] = std::min({D[i-1][j], D[i][j-1], D[i-1][j-1]}); 17 | } else { 18 | D[i][j] = D[i-1][j-1]; 19 | } 20 | } 21 | } 22 | return D[na][nb]; 23 | } 24 | -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/levenshtein_distance.h: -------------------------------------------------------------------------------- 1 | #ifndef _LEVENSHTEIN_DISTANCE_H_ 2 | #define _LEVENSHTEIN_DISTANCE_H_ 3 | 4 | #include 5 | using std::string; 6 | 7 | size_t levenshtein_distance(const string &a, const string &b); 8 | 9 | #endif -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/test-BKtree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | #include 6 | 7 | #include "BKtree.h" 8 | #include "levenshtein_distance.h" 9 | 10 | int main(int argc, char const *argv[]) 11 | { 12 | if (argc <= 1) { 13 | cerr << "Usage: " << argv[0] << " [serialize]\n"; 14 | return 1; 15 | } 16 | ifstream ifs(argv[1]); 17 | if (!ifs) { 18 | cerr << "File '" << argv[1] << "' not exist!\n"; 19 | return 2; 20 | } 21 | 22 | BKTree tree(ifs); 23 | 24 | auto result = tree.search(argv[2], atoi(argv[3])); 25 | copy(result.begin(), result.end(), 26 | ostream_iterator(cout, " ")); 27 | cout << "\n"; 28 | 29 | // serialize the tree 30 | if (argc >= 5) { 31 | std::ofstream ofs(argv[4]); 32 | boost::archive::text_oarchive oa(ofs); 33 | // write class instance to archive 34 | oa << tree; 35 | // archive and stream closed when destructors are called 36 | cout << "Dict serialized to '" << argv[4] << "'\n"; 37 | } 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /bk-tree-for-spell-checking/test-dist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #include "levenshtein_distance.h" 5 | 6 | int main(int argc, char const *argv[]) 7 | { 8 | cout << levenshtein_distance("wat", "cook") << endl; 9 | cout << levenshtein_distance("wat", "book") << endl; 10 | cout << levenshtein_distance("wat", "books") << endl; 11 | cout << levenshtein_distance("wat", "what") << endl; 12 | cout << levenshtein_distance("wat", "water") << endl; 13 | cout << levenshtein_distance("cook", "book") << endl; 14 | cout << levenshtein_distance("cook", "books") << endl; 15 | cout << levenshtein_distance("what", "water") << endl; 16 | return 0; 17 | } -------------------------------------------------------------------------------- /btree/btree.h: -------------------------------------------------------------------------------- 1 | #ifndef _BTREE_H_ 2 | #define _BTREE_H_ 3 | 4 | #include 5 | using std::vector; 6 | 7 | // using knuth's definition: ORDER = # number of children 8 | // then the tree is containing maximum (ORDER-1) keys, 9 | // and minimum (ORDER-1)/2 keys 10 | const int ORDER = 4; 11 | 12 | class Btree{ 13 | public: 14 | Btree(): parent(NULL) { 15 | // data.resize(ORDER-1); 16 | children.resize(ORDER); 17 | } 18 | 19 | void insert(int value); 20 | Btree* find(int value); 21 | 22 | static void insert_node(Btree *node); 23 | 24 | bool full() const {return data.size() == ORDER - 1;} 25 | //void remove(int value); 26 | 27 | vector data; 28 | Btree *parent; 29 | vector children; 30 | }; 31 | 32 | void dump_graphviz(Btree* root); 33 | 34 | #endif /* end of include guard: _BTREE_H_ */ 35 | -------------------------------------------------------------------------------- /careercup/18.5-synchronization.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | class Foo 10 | { 11 | vector pool; 12 | mutex ma; 13 | mutex mb; 14 | mutex mc; 15 | public: 16 | Foo() { 17 | ma.lock(); 18 | mb.lock(); 19 | } 20 | 21 | void A() { 22 | pool.push_back( 23 | thread([=]{ 24 | mc.lock(); 25 | func("A"); 26 | mc.unlock(); 27 | ma.unlock(); 28 | })); 29 | } 30 | void B() { 31 | pool.push_back( 32 | thread([=]{ 33 | ma.lock(); 34 | func("B"); 35 | ma.unlock(); 36 | mb.unlock(); 37 | })); 38 | } 39 | void C() { 40 | pool.push_back( 41 | thread([=]{ 42 | mb.lock(); 43 | mc.lock(); 44 | func("C"); 45 | mc.unlock(); 46 | mb.unlock(); 47 | })); 48 | } 49 | 50 | void func(const string &str) { 51 | cout << "Inside " << str << endl; 52 | } 53 | 54 | ~Foo() { 55 | for (auto &th : pool) { 56 | th.join(); 57 | } 58 | } 59 | }; 60 | 61 | int main(int argc, char const *argv[]) 62 | { 63 | Foo f; 64 | f.A(); 65 | f.B(); 66 | f.C(); 67 | 68 | return 0; 69 | } -------------------------------------------------------------------------------- /careercup/4.4-level-traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../leetcode/leetcode.h" 3 | 4 | list > level_traversal(TreeNode *root) { 5 | list > result; 6 | if (root == NULL) return result; 7 | result.push_back({root}); 8 | while (true) { 9 | auto &prev_list = result.back(); 10 | list mylist; 11 | for (TreeNode *node : prev_list) { 12 | if (node->left != NULL) 13 | mylist.push_back(node->left); 14 | if (node->right != NULL) 15 | mylist.push_back(node->right); 16 | } 17 | if (!mylist.empty()) 18 | result.push_back(mylist); 19 | else 20 | break; 21 | } 22 | return result; 23 | } 24 | 25 | 26 | int main(int argc, char const *argv[]) { 27 | string tree = "50 30 20 10 # # # 40 # # 90 70 60 # # 80 # # 100 # #"; 28 | TreeNode *root = deserialize_tree(tree); 29 | 30 | auto result = level_traversal(root); 31 | for (auto level : result) { 32 | for (auto node : level) { 33 | cout << node->val << ' '; 34 | } 35 | cout << '\n'; 36 | } 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /careercup/4.8-all-path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "../leetcode/leetcode.h" 2 | 3 | class Solution { 4 | vector > result; 5 | public: 6 | vector > all_path_sum(TreeNode *root, int sum) { 7 | vector path; 8 | all_path_sum(root, path, sum); 9 | return result; 10 | } 11 | 12 | void all_path_sum(TreeNode *root, 13 | vector &path, int sum) { 14 | if (root == NULL) return; 15 | 16 | path.push_back(root->val); 17 | int tmp = sum; 18 | for (int i = path.size() - 1; i >= 0; --i) { 19 | tmp -= path[i]; 20 | if (tmp == 0) { 21 | result.push_back(vector(path.begin()+i, path.end())); 22 | } 23 | } 24 | vector c1(path), c2(path); 25 | all_path_sum(root->left, c1, sum); 26 | all_path_sum(root->right, c2, sum); 27 | } 28 | }; 29 | 30 | 31 | int main(int argc, char const *argv[]) { 32 | string tree = "2 3 6 -3 # # -1 # # -4 2 # # 3 1 -5 # # 2 # # 4 # # 4 -3 7 -3 # # -2 # # 2 # # 2 5 # # 1 # #"; 33 | TreeNode *root = deserialize_tree(tree); 34 | 35 | Solution sol; 36 | auto result = sol.all_path_sum(root, 5); 37 | for (auto v : result) { 38 | copy(v.begin(), v.end(), 39 | ostream_iterator(cout, " ")); 40 | cout << '\n'; 41 | } 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /careercup/5.1-set-bits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | const int width = 32; 6 | 7 | // assume i j is valid 8 | void set_bits(int &N, int M, int i, int j){ 9 | int low = (1 << (i+1)) - 1; 10 | int high = ~((1 << (j+1)) - 1); 11 | int mask = low | high; 12 | N = (N & mask) | (M << i); 13 | } 14 | 15 | int main(int argc, char const *argv[]) { 16 | int N = 0b10000000000; 17 | int M = 0b10101; 18 | int i = 7, j = 11; 19 | cout << bitset (N) << endl; 20 | cout << bitset (M) << endl; 21 | set_bits(N, M, i, j); 22 | cout << bitset (N) << endl; 23 | return 0; 24 | } -------------------------------------------------------------------------------- /careercup/5.2-to-binary-string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | string to_binary_string(string &num) { 8 | string binary; 9 | int decimal = num.find("."); 10 | int integral = atoi(num.substr(0, decimal).c_str()); 11 | double fraction = atof(num.substr(decimal, num.size() - decimal).c_str()); 12 | 13 | // integral portion 14 | int p = 1; 15 | while ((p << 1) <= integral) { 16 | p <<= 1; 17 | } 18 | while (p > 0) { 19 | if (integral - p >= 0) { 20 | binary.push_back('1'); 21 | integral -= p; 22 | } else { 23 | binary.push_back('0'); 24 | } 25 | p >>= 1; 26 | } 27 | 28 | binary.push_back('.'); 29 | 30 | // fraction portion 31 | int i = 0; 32 | while (1) { 33 | if (i++ > 32) 34 | return string("ERROR"); 35 | 36 | fraction *= 2; 37 | if ( abs(fraction - 1.0) <= 1e-6 ) { 38 | binary.push_back('1'); 39 | break; 40 | } 41 | else if (fraction > 1) { 42 | binary.push_back('1'); 43 | fraction -= 1; 44 | } else { 45 | binary.push_back('0'); 46 | } 47 | } 48 | 49 | return binary; 50 | } 51 | 52 | int main(int argc, char const *argv[]) 53 | { 54 | string num = "1023.875"; 55 | string binary = to_binary_string(num); 56 | cout << binary << endl; 57 | return 0; 58 | } -------------------------------------------------------------------------------- /careercup/5.5-nbits-required-to-convert.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int nbits(int A, int B) { 6 | int bits = A^B; 7 | bitset<32> b(bits); 8 | return b.count(); 9 | } 10 | 11 | int main(int argc, char const *argv[]) 12 | { 13 | cout << nbits(31, 1<<2) << '\n'; 14 | return 0; 15 | } -------------------------------------------------------------------------------- /careercup/5.7-find-missing-integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int find_missing(vector &A) { 6 | int n = A.size(); 7 | int nbits = sizeof(int) * 8; 8 | int sum = n * (n + 1) / 2; 9 | for (int i = 0; i < n; ++i) { 10 | int x = A[i]; 11 | for (int j = 0; j < nbits; ++j) { 12 | int b = (x>>j) & 1; 13 | sum -= b * (1< A(n); 22 | for (int i = 0; i < n; ++i) { 23 | A[i] = i; 24 | } 25 | A.erase(A.begin()+29); 26 | copy(A.begin(), A.end(), 27 | ostream_iterator(cout, " ")); 28 | cout << '\n'; 29 | 30 | int miss = find_missing(A); 31 | cout << miss << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /careercup/website/sort_word.cpp: -------------------------------------------------------------------------------- 1 | // http://www.careercup.com/question?id=22524667 2 | // http://www.careercup.com/question?id=15555705 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // sort the words according to a dictionary 9 | // assume all char in word appears in dict 10 | string sort_word(string &word, string &dict) { 11 | unordered_map map; 12 | int count = 0; 13 | for (auto c : dict) { 14 | map[c] = count++; 15 | } 16 | 17 | string sorted(word); 18 | sort(sorted.begin(), sorted.end(), [& map](char a, char b) { 19 | return map[a] < map[b]; 20 | }); 21 | 22 | return sorted; 23 | } 24 | 25 | int main(int argc, char const *argv[]) 26 | { 27 | string word = "SHEEP"; 28 | string dict = "PHES"; 29 | string sorted = sort_word(word, dict); 30 | cout << sorted << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /clrs/min_dist_points/gen: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/clrs/min_dist_points/gen -------------------------------------------------------------------------------- /clrs/min_dist_points/gen.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #define MAXVAL 500 6 | using namespace std; 7 | 8 | class pt{ 9 | public: 10 | int x,y; 11 | }; 12 | 13 | struct ltpt{ 14 | bool operator()(const pt & s1, const pt & s2) const { 15 | int a=s1.x*s1.x+s1.y*s1.y; 16 | int b=s2.x*s2.x+s2.y*s2.y; 17 | return (a-b)<0; 18 | } 19 | }; 20 | 21 | 22 | 23 | int main(int argc,char * argv[]){ 24 | if(argc<2) return 1; 25 | int i,n=atoi(argv[1]); 26 | printf("%d\n",n); 27 | map m; 28 | srand(time(NULL)); 29 | for(i=0;i 2 | #include 3 | 4 | double min(double a,double b){ 5 | return (a 6 | using std::sort; 7 | #include "point.h" 8 | #include "segment.h" 9 | #include "vector.h" 10 | 11 | namespace compgeom { 12 | 13 | inline bool is_counter_clockwise(Point p, Point q, Point r) { 14 | Vector pq(p, q), pr(p, r); 15 | int prod = cross_product(pq, pr); 16 | return prod > 0; 17 | } 18 | 19 | static Point _ccw_l; 20 | bool ccw_wrt_l(const Point &p, const Point &q) { 21 | if (_ccw_l == p) return true; 22 | else if (_ccw_l == q) return false; 23 | 24 | return is_counter_clockwise(_ccw_l, p, q); 25 | } 26 | 27 | inline void make_counter_clockwise(Point *pts, int n) { 28 | // find the left most point 29 | int l = 0; 30 | for (int i = 1; i < n; i++) { 31 | if (pts[i].x < pts[l].x) { 32 | l = i; 33 | } 34 | } 35 | 36 | // sort the array according to l 37 | _ccw_l = pts[l]; 38 | sort(pts, pts + n, ccw_wrt_l); 39 | } 40 | 41 | } 42 | 43 | #endif /* end of include guard: _BASIC_H_ */ 44 | -------------------------------------------------------------------------------- /compgeo/graham.h: -------------------------------------------------------------------------------- 1 | #ifndef _GRAHAM_H_ 2 | 3 | #define _GRAHAM_H_ 4 | 5 | #include "point.h" 6 | 7 | namespace compgeom { 8 | 9 | int graham(Point *pts, Point *output, int n) { 10 | // trivial cases: 0, 1, 2 11 | int i; 12 | if (n <= 2) { 13 | for (i = 0; i < n; i++) { 14 | output[i] = pts[i]; 15 | } 16 | return n; 17 | } 18 | // now guarantee to have at least 3 points 19 | 20 | // sort the array as counter-clockwise 21 | make_counter_clockwise(pts, n); 22 | 23 | // now pts[0] is left-most point 24 | int l = 0; 25 | int p = l, q = l + 1, r = l + 2; 26 | output[0] = pts[p]; 27 | output[1] = pts[q]; 28 | int count = 2; 29 | 30 | do { 31 | if (is_counter_clockwise(pts[p], pts[q], pts[r])) { 32 | output[count++] = pts[r]; 33 | p = q; 34 | q = r; 35 | r = (r + 1) % n; 36 | } 37 | else { 38 | // remove q (previously r) 39 | --count; 40 | q = p; 41 | p = (p - 1) < 0? n - 1: p - 1; 42 | } 43 | } while (r != l); 44 | 45 | return count; 46 | } 47 | 48 | } 49 | 50 | #endif /* end of include guard: _GRAHAM_H_ */ 51 | -------------------------------------------------------------------------------- /compgeo/jarvis.h: -------------------------------------------------------------------------------- 1 | #ifndef _JARVIS_H_ 2 | #define _JARVIS_H_ 3 | 4 | #include "point.h" 5 | 6 | namespace compgeom { 7 | 8 | int jarvis(Point *pts, Point *output, int n) { 9 | // trivial cases: 0, 1, 2 10 | int i; 11 | if (n <= 2) { 12 | for (i = 0; i < n; i++) { 13 | output[i] = pts[i]; 14 | } 15 | return n; 16 | } 17 | 18 | // find the left most point 19 | int l = 0; 20 | for (i = 1; i < n; i++) { 21 | if (pts[i].x < pts[l].x) { 22 | l = i; 23 | } 24 | } 25 | 26 | int count = 0; 27 | int p = l, q; 28 | do { 29 | q = (p + 1) % n; 30 | 31 | // find the next point 32 | for (i = 1; i < n; i++) { 33 | if (is_counter_clockwise(pts[p], pts[i], pts[q])) { 34 | q = i; 35 | } 36 | } 37 | 38 | output[count++] = pts[q]; 39 | p = q; 40 | } while (p != l); 41 | 42 | return count; 43 | } 44 | 45 | } 46 | 47 | #endif /* end of include guard: _JARVIS_H_ */ 48 | -------------------------------------------------------------------------------- /compgeo/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "basic.h" 3 | #include "jarvis.h" 4 | #include "graham.h" 5 | #include "sweep_hull.h" 6 | using namespace std; 7 | using namespace compgeom; 8 | 9 | int main(int argc, const char *argv[]) 10 | { 11 | Point pts[] = { 12 | Point(3, 6), 13 | Point(4, 0), 14 | Point(5, 4), 15 | Point(6, 5), 16 | Point(4, 7), 17 | Point(1, 5), 18 | }; 19 | int n = sizeof(pts) / sizeof(Point); 20 | Point *output = new Point[n]; 21 | int count = jarvis(pts, output, n); 22 | for (int i = 0; i < count; i++) { 23 | cout << " " << output[i]; 24 | } 25 | cout << endl; 26 | 27 | count = graham(pts, output, n); 28 | for (int i = 0; i < count; i++) { 29 | cout << " " << output[i]; 30 | } 31 | cout << endl; 32 | 33 | int *next = new int[n]; 34 | int *prev = new int[n]; 35 | count = sweep_hull(pts, n, next, prev); 36 | for (int i = 0, j = 0; i < count; i++, j = next[j]) { 37 | cout << " " << pts[j]; 38 | } 39 | cout << endl; 40 | 41 | delete []output; 42 | delete []prev; 43 | delete []next; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /compgeo/point.h: -------------------------------------------------------------------------------- 1 | #ifndef _POINT_H_ 2 | 3 | #define _POINT_H_ 4 | 5 | #include 6 | using std::ostream; 7 | 8 | namespace compgeom { 9 | 10 | struct Point { 11 | Point(int xx = 0, int yy = 0): x(xx), y(yy) {} 12 | int x, y; 13 | bool operator == (const Point &rhs) { return x == rhs.x && y == rhs.y; } 14 | friend ostream & operator << (ostream &os, const Point &p); 15 | }; 16 | 17 | bool compare_x(const Point &p, const Point &q) { 18 | return p.x < q.x; 19 | } 20 | 21 | inline ostream & operator << (ostream &os, const Point &p) { 22 | os << "(" << p.x << ", " << p.y << ")"; 23 | return os; 24 | } 25 | 26 | } 27 | 28 | #endif /* end of include guard: _POINT_H_ */ 29 | -------------------------------------------------------------------------------- /compgeo/segment.h: -------------------------------------------------------------------------------- 1 | #ifndef _SEGMENT_H_ 2 | 3 | #define _SEGMENT_H_ 4 | 5 | #include "point.h" 6 | 7 | namespace compgeom { 8 | 9 | struct Segment { 10 | Segment(Point ss, Point tt): s(ss), t(tt){} 11 | Point s, t; 12 | }; 13 | 14 | } 15 | 16 | #endif /* end of include guard: _SEGMENT_H_ */ 17 | -------------------------------------------------------------------------------- /compgeo/sweep_hull.h: -------------------------------------------------------------------------------- 1 | #ifndef _SWEEP_HULL_H_ 2 | #define _SWEEP_HULL_H_ 3 | 4 | #include 5 | using std::sort; 6 | 7 | namespace compgeom { 8 | 9 | int sweep_hull(Point *pts, int n, int *next, int *prev) { 10 | // sort according to x-coordinate 11 | sort(pts, pts + n, compare_x); 12 | next[0] = 1; prev[1] = 0; 13 | next[1] = 0; prev[0] = 1; 14 | int count = 2; 15 | 16 | for (int i = 2; i < n; i++) { 17 | if (pts[i].y > pts[i - 1].y) { 18 | prev[i] = i - 1; 19 | next[i] = next[i - 1]; 20 | } 21 | else{ 22 | next[i] = i - 1; 23 | prev[i] = prev[i - 1]; 24 | } 25 | 26 | next[prev[i]] = i; 27 | prev[next[i]] = i; 28 | 29 | count++; 30 | 31 | // remove concave points 32 | while (is_counter_clockwise(pts[i], pts[prev[i]], pts[prev[prev[i]]])) { 33 | next[prev[prev[i]]] = i; 34 | prev[i] = prev[prev[i]]; 35 | count--; 36 | } 37 | 38 | while (is_counter_clockwise(pts[i], pts[next[next[i]]], pts[next[i]])) { 39 | prev[next[next[i]]] = i; 40 | next[i] = next[next[i]]; 41 | count--; 42 | } 43 | } // end of for 44 | return count; 45 | } 46 | 47 | } /* compgeom */ 48 | 49 | #endif /* end of include guard: _SWEEP_HULL_H_ */ 50 | -------------------------------------------------------------------------------- /compgeo/vector.h: -------------------------------------------------------------------------------- 1 | #ifndef _VECTOR_H__ 2 | #define _VECTOR_H__ 3 | 4 | namespace compgeom { 5 | 6 | struct Vector { 7 | Vector(Point s, Point t) { 8 | x = t.x - s.x; 9 | y = t.y - s.y; 10 | } 11 | int x, y; 12 | 13 | }; 14 | 15 | inline int cross_product(Vector &v1, Vector &v2) { 16 | return v1.x * v2.y - v1.y * v2.x; 17 | } 18 | 19 | 20 | } 21 | 22 | #endif /* end of include guard: _VECTOR_H__ */ 23 | -------------------------------------------------------------------------------- /concurrency/exercise/hardware_concurrency.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char const *argv[]) 7 | { 8 | cout << std::thread::hardware_concurrency() << endl; 9 | return 0; 10 | } -------------------------------------------------------------------------------- /concurrency/exercise/hello.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | mutex m; 8 | 9 | // need to apply mutex, otherwise the output is interleaved. 10 | // or use a lock_guard 11 | void say_hello() { 12 | lock_guard my_lock(m); 13 | // m.lock(); 14 | cout << "Hello from " << this_thread::get_id() << endl; 15 | // m.unlock(); 16 | } 17 | 18 | int main(int argc, char const *argv[]) { 19 | const int num_threads = 10; 20 | std::vector threads; 21 | 22 | for (int i = 0; i < num_threads; ++i) { 23 | threads.push_back(thread(&say_hello)); 24 | } 25 | 26 | for (auto &thread : threads) { 27 | thread.join(); 28 | } 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /concurrency/exercise/monte-carlo-pi-all-cores.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int monte_carlo(size_t times) { 7 | default_random_engine generator; 8 | uniform_real_distribution distribution(0,1.0); 9 | size_t count = 0; 10 | for (size_t i = 0; i < times; ++i) 11 | { 12 | double x = distribution(generator); 13 | double y = distribution(generator); 14 | if (x*x + y*y <= 1.0) { 15 | ++count; 16 | } 17 | } 18 | return count; 19 | } 20 | 21 | int main(int argc, char const *argv[]) 22 | { 23 | size_t num_threads = std::thread::hardware_concurrency(); 24 | cout << "# cores: " << num_threads << endl; 25 | 26 | size_t times = 100000000; 27 | vector > results; 28 | for (int i = 0; i < num_threads; ++i) { 29 | results.push_back(async(monte_carlo, times)); 30 | } 31 | 32 | size_t count = 0; 33 | for (auto &res : results) { 34 | count += res.get(); 35 | } 36 | 37 | cout << "Count = " << count; 38 | cout << " Times = " << num_threads * times << endl; 39 | cout << "Pi = " << 4.0 * count / (num_threads * times) << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /concurrency/exercise/monte-carlo-pi.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | double monte_carlo(int times) { 7 | default_random_engine generator; 8 | uniform_real_distribution distribution(0,1.0); 9 | size_t count = 0; 10 | for (int i = 0; i < times; ++i) 11 | { 12 | double x = distribution(generator); 13 | double y = distribution(generator); 14 | if (x*x + y*y <= 1.0) { 15 | ++count; 16 | } 17 | } 18 | cout << "Finish computation\n"; 19 | return 4.0 * count / times; 20 | } 21 | 22 | int main(int argc, char const *argv[]) 23 | { 24 | int times = 100000000; 25 | 26 | cout << "Creating async\n"; 27 | auto res = async(std::launch::async, monte_carlo, times); 28 | 29 | // never execute if deferred 30 | // auto res = async(std::launch::deferred, monte_carlo, times); 31 | cout << "After creating\n"; 32 | 33 | cout << "Result is " << res.get() << endl; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /concurrency/exercise/readme.txt: -------------------------------------------------------------------------------- 1 | Based on: 2 | 3 | https://github.com/graeme-a-stewart/cpp-concurrency 4 | 5 | -------------------------------------------------------------------------------- /concurrency/exercise/ref_wrap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char const *argv[]) { 8 | vector v; 9 | int a = 1, b = 2; 10 | v.push_back(std::ref(a)); 11 | v.push_back(b); 12 | ++v[0]; 13 | 14 | cout << a << " : " << b << endl; 15 | return 0; 16 | } -------------------------------------------------------------------------------- /concurrency/exercise/thread-arguments-problems-fixed.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using std::cout; 7 | using std::endl; 8 | 9 | class Tea { 10 | private: 11 | std::string m_tea; 12 | 13 | public: 14 | const char* tea() { 15 | return m_tea.c_str(); 16 | } 17 | 18 | void set_tea(const char new_tea[]) { 19 | m_tea = new_tea; 20 | } 21 | 22 | Tea(): 23 | m_tea{""} {} 24 | 25 | Tea(const char first_cup[]): 26 | m_tea{first_cup} {} 27 | 28 | Tea(const Tea& other): 29 | m_tea{other.m_tea} {} 30 | 31 | }; 32 | 33 | void tea_selector(Tea& tea, const char new_tea[]) { 34 | tea.set_tea(new_tea); 35 | } 36 | 37 | int main() { 38 | Tea my_cuppa("mint"); 39 | 40 | std::cout << "Tea type: " << my_cuppa.tea() << std::endl; 41 | 42 | // need to use std::ref to create a reference because 43 | // std::thread will copy its argument 44 | // 45 | // auto threaded_tea = std::thread(std::bind(tea_selector, my_cuppa, "black")); 46 | auto threaded_tea = std::thread(std::bind(tea_selector, std::ref(my_cuppa), "black")); 47 | threaded_tea.join(); 48 | 49 | std::cout << "Updated tea type: " << my_cuppa.tea() << std::endl; 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /concurrency/exercise/thread-arguments-problems2-fixed.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define SIZE 10000 8 | 9 | void work_hard(std::vector& d) { 10 | // Sleep here to artificially ensure that thread_spawn() has exited 11 | std::this_thread::sleep_for(std::chrono::milliseconds(100)); 12 | 13 | double sum=0.0; 14 | for (auto& el: d) { 15 | sum += sin(cos(log(abs(el)+1.0))); 16 | } 17 | std::cout << "Hard work is done: " << sum << std::endl; 18 | } 19 | 20 | int thread_spawn() { 21 | std::vector d; 22 | 23 | for (size_t i=0; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | using namespace std; 9 | 10 | int main() { 11 | atomic_int c(0); 12 | bool done = false; 13 | queue goods; 14 | 15 | thread producer([&]() { 16 | for (int i = 0; i < 500; ++i) { 17 | goods.push(i); 18 | c++; 19 | } 20 | 21 | done = true; 22 | }); 23 | 24 | thread consumer([&]() { 25 | while (!done) { 26 | while (!goods.empty()) { 27 | goods.pop(); 28 | c--; 29 | } 30 | } 31 | }); 32 | 33 | producer.join(); 34 | consumer.join(); 35 | cout << "Net: " << c << endl; 36 | cout << "Goods: " << goods.size() << endl; 37 | return 0; 38 | } -------------------------------------------------------------------------------- /concurrency/producer-consumer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | std::mutex m; 10 | 11 | int main() { 12 | int c = 0; 13 | bool done = false; 14 | queue goods; 15 | 16 | thread producer([&]() { 17 | for (int i = 0; i < 500; ++i) { 18 | goods.push(i); 19 | m.lock(); 20 | c++; 21 | m.unlock(); 22 | } 23 | 24 | done = true; 25 | }); 26 | 27 | thread consumer([&]() { 28 | while (!done) { 29 | while (!goods.empty()) { 30 | goods.pop(); 31 | m.lock(); 32 | c--; 33 | m.unlock(); 34 | } 35 | } 36 | }); 37 | 38 | producer.join(); 39 | consumer.join(); 40 | cout << "Net: " << c << endl; 41 | cout << "Goods: " << goods.size() << endl; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /concurrency/race-condition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int sum = 0; 8 | 9 | // race condition: different thread may assign value to sum and overwrite 10 | void square(int x) { 11 | int sq = x * x; 12 | sum = sum + sq; 13 | } 14 | 15 | int main(int argc, char const *argv[]) { 16 | vector pool; 17 | for (int i = 1; i <= 30; ++i) { 18 | pool.push_back(thread(&square, i)); 19 | } 20 | for (auto &th : pool) { 21 | th.join(); 22 | } 23 | cout << sum << endl; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /concurrency/reporter-assigner.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | condition_variable cond_var; 10 | mutex m; 11 | 12 | int main() { 13 | int value = 100; 14 | bool notified = false; 15 | thread reporter([&]() { 16 | unique_lock lock(m); 17 | while (!notified) { 18 | cond_var.wait(lock); 19 | } 20 | cout << "The value is " << value << endl; 21 | }); 22 | 23 | thread assigner([&]() { 24 | value = 20; 25 | notified = true; 26 | cond_var.notify_one(); 27 | }); 28 | 29 | reporter.join(); 30 | assigner.join(); 31 | return 0; 32 | } -------------------------------------------------------------------------------- /concurrency/thread.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using std::cout; 9 | using std::endl; 10 | using std::string; 11 | using std::vector; 12 | 13 | void func(string identifier) { 14 | cout << "Inside func\n"; 15 | for (int i = 0; i < std::numeric_limits::max(); ++i) { 16 | if (i % 100000000 == 0) { 17 | cout << identifier << ": i = " << i << "\n"; 18 | } 19 | } 20 | cout << "End of func\n"; 21 | } 22 | 23 | int main(int argc, char const *argv[]) 24 | { 25 | cout << "About to create thread object\n"; 26 | vector threads; 27 | for (int i = 0; i < 4; ++i) { 28 | threads.push_back(std::thread(&func, std::to_string(i))); 29 | } 30 | cout << "After creating thread object\n"; 31 | for (auto &th : threads) { 32 | th.join(); 33 | } 34 | return 0; 35 | } -------------------------------------------------------------------------------- /counterfeit_coin.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | n=10 4 | 5 | def f(n): 6 | if n==1: 7 | return 0 8 | mini=1000000 9 | #ret = -1 10 | for x in xrange(1,n/2+1): 11 | current=max(x,n-2*x) 12 | if current 4 | #include 5 | using namespace std; 6 | 7 | int longest_common_subsequence(const string &a, const string &b) { 8 | if (a.empty() || b.empty()) return 0; 9 | 10 | int m = a.size(); 11 | int n = b.size(); 12 | vector> D(m+1,vector(n+1, 0)); 13 | for (int i = 1; i <= m; ++i) { 14 | for (int j = 1; j <= n; ++j) { 15 | char ca = a[i-1]; 16 | char cb = b[j-1]; 17 | D[i][j] = max(D[i-1][j], D[i][j-1]); 18 | if (ca != cb) { 19 | D[i][j] = max(D[i][j], D[i-1][j-1]); 20 | } else { 21 | D[i][j] = max(D[i][j], D[i-1][j-1] + 1); 22 | } 23 | } 24 | } 25 | return D[m][n]; 26 | } 27 | 28 | int main(int argc, char const *argv[]) 29 | { 30 | string a, b; 31 | while (cin >> a >> b) { 32 | cout << longest_common_subsequence(a, b) << "\n"; 33 | } 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /dp/longest_common_subsequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(int argc, char *argv[]) 8 | { 9 | string A, B; 10 | while (cin >> A >> B) { 11 | const int MAX_BUFFER = 100; 12 | int D[MAX_BUFFER][MAX_BUFFER] = {0}; 13 | int N = A.size(), M = B.size(); 14 | 15 | for (int i = 1; i <= N; ++i) { 16 | for (int j = 1;j <= M; ++j) { 17 | 18 | D[i][j] = max(D[i-1][j], D[i][j-1]); 19 | if (A[i-1] == B[j-1]) 20 | D[i][j] = max(D[i][j], D[i-1][j-1] + 1); 21 | } 22 | } 23 | 24 | cout << D[N][M] << endl; 25 | } 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /dp/longest_common_substring-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | pair longest_common_substring(const string &a, const string &b) { 8 | int m = a.size(), n = b.size(); 9 | int mlen = 0, endi = -1; 10 | vector> D(m+1, vector(n+1,0)); 11 | for (int i = 1; i <= m; ++i) { 12 | for (int j = 1; j <= n; ++j) { 13 | D[i][j] = 0; 14 | if (a[i-1] == b[j-1]) { 15 | D[i][j] = D[i-1][j-1] + 1; 16 | } 17 | if (D[i][j] > mlen) { 18 | mlen = D[i][j]; 19 | endi = i; 20 | } 21 | } 22 | } 23 | return make_pair(endi-mlen, mlen); 24 | } 25 | 26 | int main(int argc, char const *argv[]) 27 | { 28 | string a, b; 29 | while(cin>>a>>b) { 30 | int len, i; 31 | tie(i, len) = longest_common_substring(a, b); 32 | cout << len << "\n"; 33 | if (len) { 34 | cout << a.substr(i, len) << "\n"; 35 | } 36 | } 37 | return 0; 38 | } -------------------------------------------------------------------------------- /dp/longest_common_substring.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int main(int argc, char *argv[]) 6 | { 7 | const int MAX_BUFFER = 100; 8 | int L[MAX_BUFFER][MAX_BUFFER] = {0}; 9 | 10 | string A="ABDABC"; 11 | string B="ABEABC"; 12 | cout << "Enter A: " << endl; 13 | cin >> A; 14 | cout << "Enter B: " << endl; 15 | cin >> B; 16 | int N = A.size(); 17 | int M = B.size(); 18 | int max_len = 0; 19 | for (int i = 1; i <= N; ++i) { 20 | for (int j = 0;j <= M; ++j) { 21 | if (A[i-1] == B[j-1]) { 22 | L[i][j] = L[i-1][j-1] + 1; 23 | } else 24 | L[i][j] = 0; 25 | if (L[i][j] > max_len) 26 | max_len = L[i][j]; 27 | } 28 | } 29 | cout << max_len << endl; 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /dp/non_decr_seq/non_decr_seq.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX 100 4 | int d[MAX]; /* d[i]: seq[i] ends longest non-deq sequence*/ 5 | int idx[MAX]; 6 | 7 | int main() 8 | { 9 | int seq[]={0,5, 3, 4, 8, 6, 7,1,2,3,4,5}; 10 | int n=sizeof(seq)/4-1; 11 | 12 | d[0]=0;idx[0]=-1; 13 | d[1]=1;idx[1]=1; 14 | 15 | int i,j; 16 | for(i=2;i<=n;i++){ 17 | int max=1; 18 | for(j=1;j= seq[j] ) temp=d[j]+1; 21 | if( temp > max ) max=temp; 22 | } 23 | d[i]=max; 24 | } 25 | printf("%d\n",d[n]); 26 | for(i=1;i<=n;i++) 27 | printf("%d ",d[i]); 28 | printf("\n"); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /dp/schedule/data.in: -------------------------------------------------------------------------------- 1 | 2 4 2 | 3 2 3 | 6 4 | 7 9 3 4 8 4 5 | 8 5 6 4 5 7 6 | 2 3 1 3 4 7 | 2 1 2 2 1 8 | -------------------------------------------------------------------------------- /dp/sum/data.in: -------------------------------------------------------------------------------- 1 | 3 11 2 | 1 3 5 3 | 4 | -------------------------------------------------------------------------------- /dp/sum/sum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX 100 4 | #define M 1000 5 | #define INF 1000000 6 | 7 | int v[MAX]; 8 | int D[M]; 9 | int s,n; 10 | 11 | int main() 12 | { 13 | freopen("data.in","r",stdin); 14 | scanf("%d %d",&n,&s); 15 | int i,j; 16 | for(i=0;i<=s;i++) D[i]=INF; 17 | for(i=0;i 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | pair subsequence_sum_zero(vector &arr) { 9 | unordered_map m; 10 | int sum = 0; 11 | for (int i = 0; i < arr.size(); ++i) { 12 | if (arr[i] == 0) { 13 | return make_pair(i, i); 14 | } 15 | sum += arr[i]; 16 | if (m.find(sum) != m.end()) { 17 | return make_pair(m[sum] + 1, i); 18 | } 19 | m[sum] = i; 20 | } 21 | return make_pair(-1, -1); 22 | } 23 | 24 | int main(int argc, char const *argv[]) { 25 | // vector arr {1, 2, 1, -3, 4}; 26 | vector arr {1, 2, 1, -3, 4}; 27 | auto p = subsequence_sum_zero(arr); 28 | cout << p.first << ", " << p.second << "\n"; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /interview/facebook/bst-in-order-successor.cpp: -------------------------------------------------------------------------------- 1 | #include "../../leetcode/leetcode.h" 2 | 3 | 4 | class Solution { 5 | TreeNode *pred; 6 | TreeNode *succ; 7 | public: 8 | TreeNode *in_order_successor(TreeNode *root, int val) { 9 | pred = succ = NULL; 10 | in_order_traverse(root, val); 11 | return succ; 12 | } 13 | 14 | void in_order_traverse(TreeNode *root, int val) { 15 | if (root == NULL || succ != NULL) return; 16 | 17 | in_order_traverse(root->left, val); 18 | if (pred != NULL && pred->val == val) { 19 | succ = root; 20 | } 21 | 22 | pred = root; 23 | in_order_traverse(root->right, val); 24 | } 25 | }; 26 | 27 | 28 | int main(int argc, char const *argv[]) { 29 | string tree = "50 30 20 10 # # # 40 # # 90 70 60 # # 80 # # 100 # #"; 30 | stringstream sstream(tree); 31 | TreeNode *root = deserialize_tree(tree); 32 | inorder_cout(root); 33 | Solution sol; 34 | string token; 35 | while (sstream >> token) { 36 | if (token == "#") continue; 37 | int val = atoi(token.c_str()); 38 | TreeNode *succ = sol.in_order_successor(root, val); 39 | if (succ != NULL) 40 | cout << "Next of " << val << " : " << succ->val << endl; 41 | } 42 | return 0; 43 | } -------------------------------------------------------------------------------- /interview/google/fulltime/phone.txt: -------------------------------------------------------------------------------- 1 | 1. find median of two sorted arrays 2 | 2. find lines that go through most points. 3 | -------------------------------------------------------------------------------- /interview/google/url_shorten/.gitignore: -------------------------------------------------------------------------------- 1 | shorten 2 | *.db* -------------------------------------------------------------------------------- /interview/google/url_shorten/Makefile: -------------------------------------------------------------------------------- 1 | CC=clang++ 2 | all: 3 | $(CC) -std=c++11 -lsqlite3 -o shorten shorten.cpp -------------------------------------------------------------------------------- /interview/indeed/coding/bracket.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | /* 8 | * Complete the function below. 9 | */ 10 | string validateString(string value) { 11 | stack st; 12 | for (auto c : value) { 13 | if (c == '(' || 14 | c == '[' || 15 | c == '{') { 16 | st.push(c); 17 | } else { 18 | if (st.empty()) { 19 | return "NO"; 20 | } 21 | char t = st.top(); 22 | st.pop(); 23 | if ((c == ')' && t != '(') || 24 | (c == ']' && t != '[') || 25 | (c == '}' && t != '{')) { 26 | return "NO"; 27 | } 28 | } 29 | } 30 | 31 | return st.empty()? "YES" : "NO"; 32 | } 33 | 34 | int main() { 35 | vector values{ 36 | // "", 37 | // "{", 38 | // "}", 39 | // "{(})", 40 | // "[[[((()))]]]{}", 41 | "()", 42 | "()[]{}", 43 | "(]", 44 | "([)]", 45 | "", 46 | "(", 47 | "]", 48 | "{}{}{{{{[[[((()))]]]}}}}", 49 | "{}{}{{{{[[[(((])))]]]}}}}", 50 | }; 51 | for (auto &s : values) { 52 | cout << validateString(s) << endl; 53 | } 54 | return 0; 55 | } 56 | 57 | -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_bracket/input000.txt: -------------------------------------------------------------------------------- 1 | ([]{}) -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_bracket/input001.txt: -------------------------------------------------------------------------------- 1 | {[}] -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_bracket/output000.txt: -------------------------------------------------------------------------------- 1 | YES -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_bracket/output001.txt: -------------------------------------------------------------------------------- 1 | NO -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_convict_transfer/input000.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 2 3 | 1 2 4 | 1 4 -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_convict_transfer/input001.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 3 3 | 1 2 4 | 3 4 5 | 2 3 -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_convict_transfer/output000.txt: -------------------------------------------------------------------------------- 1 | 3 -------------------------------------------------------------------------------- /interview/indeed/coding/test_cases_convict_transfer/output001.txt: -------------------------------------------------------------------------------- 1 | 2 -------------------------------------------------------------------------------- /interview/indeed/onsite/coding_challenge.txt: -------------------------------------------------------------------------------- 1 | Given a log file, which contains some url strings for site visits: 2 | 3 | ...&ctk=abcdefg&ts=123456778&type=search&... 4 | 5 | Basically, it has three components: 6 | 7 | 1. ctk: a key to identify the cookie 8 | 2. ts: timestamp 9 | 3. type: search of click 10 | 11 | The problem asks to write a program to process a log file that contains multiple queries and output session info. A session is defined as: 12 | 13 | A series of events (click or search) that has the same ctk with no time gaps > 15 mins. 14 | 15 | The log file is ordered by timestamp. 16 | 17 | Solution: 18 | 19 | Maintain a hashmap to keep track of the session data and last timestamp of the session, 20 | whenever a new event has time gap > 15mins of this session, we output the session and reset it. 21 | 22 | The problem is that they limit the memory so the above solution will run out of memory. 23 | I changed to map and passed the largest test, however the map has log(n) runtime. 24 | 25 | The optimal solution should be flush out the content of the hashmap periodically, since some session 26 | might have already expired (> 15mins) but the above procedure requires a new event with the same ctk 27 | to kick it out of hashmap. -------------------------------------------------------------------------------- /interview/indeed/onsite/lca-dag.cpp: -------------------------------------------------------------------------------- 1 | // Given a DAG similar to a git history, return a list of commits that 2 | // are ordered by the distance to a given commit. 3 | // 4 | // e.g., 5 | // 0 -- 1 -- 2 -- 3 -- 4 -- 5 6 | // \___6 __ 7 __ / 7 | // \__8 8 | // 9 | // from 5, will be: 5, 4, 3, 7, 2, 6, 1 10 | // Essentially just a BFS 11 | // 12 | // Then a harder problem: find the closest common ancestor commit of two nodes, 13 | // e.g., given 5 and 8, 7 should be returned (1 is further away). -------------------------------------------------------------------------------- /interview/indeed/onsite/reorder-list.txt: -------------------------------------------------------------------------------- 1 | Same as 2 | 3 | https://oj.leetcode.com/problems/reorder-list/ 4 | 5 | I managed to code a find middle, reverse and merge version. 6 | Later I came up the stack solution, but no time to rewrite it. -------------------------------------------------------------------------------- /interview/palantir/.gitignore: -------------------------------------------------------------------------------- 1 | palantir 2 | test* -------------------------------------------------------------------------------- /interview/palantir/online_test/input000.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 0 -------------------------------------------------------------------------------- /interview/palantir/online_test/input001.txt: -------------------------------------------------------------------------------- 1 | 10 2 | 24 27 33 61 30 68 12 64 91 22 3 | 87 5 63 67 41 35 31 93 0 47 4 | 98 29 90 66 42 26 44 73 37 65 5 | 45 25 86 85 18 23 79 2 8 80 6 | 51 28 77 62 59 58 11 75 40 21 7 | 39 76 43 4 13 54 38 83 95 82 8 | 48 19 70 9 15 3 20 36 96 97 9 | 50 60 94 84 49 72 74 52 53 57 10 | 99 46 88 32 34 55 92 1 16 17 11 | 71 7 69 6 14 89 10 81 78 56 -------------------------------------------------------------------------------- /interview/palantir/online_test/output000.txt: -------------------------------------------------------------------------------- 1 | 1 -------------------------------------------------------------------------------- /interview/palantir/online_test/output001.txt: -------------------------------------------------------------------------------- 1 | 15 14 10 9 9 9 6 6 6 5 4 4 3 -------------------------------------------------------------------------------- /interview/palantir/online_test/output002.txt: -------------------------------------------------------------------------------- 1 | 19 19 17 16 15 15 14 14 14 14 13 13 13 13 13 12 12 11 11 11 10 10 10 9 9 9 9 9 9 9 9 9 9 9 8 8 8 8 8 8 7 7 7 7 7 7 6 6 6 6 6 5 5 5 5 5 4 4 4 4 4 4 4 4 4 3 3 3 3 3 3 2 2 2 2 2 2 2 1 1 1 1 -------------------------------------------------------------------------------- /interview/palantir/online_test/output004-my.txt: -------------------------------------------------------------------------------- 1 | 250000 -------------------------------------------------------------------------------- /interview/palantir/online_test/output004.txt: -------------------------------------------------------------------------------- 1 | 250000 -------------------------------------------------------------------------------- /interview/twitter/median.txt: -------------------------------------------------------------------------------- 1 | 250 million users in twitter, each user has a certain followers. 2 | Find the median number. 3 | 4 | I think he's expecting sth. like this: 5 | 6 | http://www.quora.com/Whats-an-algorithm-for-finding-the-median-element-in-an-unsorted-array-in-linear-time-constant-space -------------------------------------------------------------------------------- /interview/twitter/plane-region.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // #include 3 | using namespace std; 4 | 5 | int main() { 6 | int T; 7 | long long N; 8 | cin >> T; 9 | for (int i = 0; i < T; ++i) 10 | { 11 | cin >> N; 12 | long long result; 13 | if (N % 2 == 0) 14 | result = (N+1)*(N/2) + 1; 15 | else 16 | result = (N+1)/2 * N + 1; 17 | cout << result % 1000000000 << endl; 18 | } 19 | return 0; 20 | } -------------------------------------------------------------------------------- /interview/twitter/rational.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int gcd(int a, int b) { 5 | int c; 6 | while (a != 0) { 7 | c = a; 8 | a = b % a; 9 | b = c; 10 | } 11 | return b; 12 | } 13 | 14 | int lcm(int m, int n) 15 | { 16 | return m / gcd(m, n) * n; 17 | } 18 | 19 | int main() { 20 | int N; 21 | cin >> N; 22 | int num = 0, dem = 0; 23 | cin >> num >> dem; 24 | for (int i = 1; i < N; ++i) 25 | { 26 | int ai, bi; 27 | cin >> ai >> bi; 28 | int l = lcm(dem, bi); 29 | num *= (l / dem); 30 | dem = l; 31 | ai *= (l / bi); 32 | num += ai; 33 | } 34 | int g = gcd(num, dem); 35 | // cout << num << " " << dem << "\n"; 36 | // cout << g << "\n"; 37 | num /= g; 38 | dem /= g; 39 | cout << num << " " << dem; 40 | return 0; 41 | } -------------------------------------------------------------------------------- /interview/twitter/test_cases-plane-region/input000.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 3 3 | 2 4 | 4 -------------------------------------------------------------------------------- /interview/twitter/test_cases-plane-region/input001.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 3 3 | 2 4 | 4 -------------------------------------------------------------------------------- /interview/twitter/test_cases-plane-region/output000.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 4 3 | 11 -------------------------------------------------------------------------------- /interview/twitter/test_cases-plane-region/output001.txt: -------------------------------------------------------------------------------- 1 | 7 2 | 4 3 | 11 -------------------------------------------------------------------------------- /interview/twitter/test_cases-rational/input000.txt: -------------------------------------------------------------------------------- 1 | 4 2 | 4 2 3 | 2 4 4 | 2 4 5 | 2 3 -------------------------------------------------------------------------------- /interview/twitter/test_cases-rational/output000.txt: -------------------------------------------------------------------------------- 1 | 11 3 -------------------------------------------------------------------------------- /leetcode/.gitignore: -------------------------------------------------------------------------------- 1 | * 2 | !*.cpp 3 | -------------------------------------------------------------------------------- /leetcode/add-binary.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string addBinary(string a, string b) { 6 | int carry = 0; 7 | // always assume a is longer 8 | if (a.size() < b. size()) 9 | swap(a, b); 10 | 11 | string result; 12 | int p = a.size() - 1, q = b.size() - 1; 13 | for (; q >= 0; p--, q--) { 14 | int ap = a[p] - '0'; 15 | int bq = b[q] - '0'; 16 | int sum = ap ^ bq ^ carry; 17 | result.push_back(sum + '0'); 18 | carry = (ap & bq) | (carry & (ap ^ bq)); 19 | } 20 | 21 | while (p >= 0) { 22 | int ap = a[p] - '0'; 23 | int sum = ap ^ carry; 24 | result.push_back(sum + '0'); 25 | carry = ap & carry; 26 | --p; 27 | } 28 | 29 | if (carry) 30 | result.push_back('1'); 31 | 32 | std::reverse(result.begin(), result.end()); 33 | return result; 34 | } 35 | }; 36 | 37 | int main() { 38 | Solution sol; 39 | vector a = { 40 | "111111", 41 | "0", 42 | "1", 43 | "1", 44 | "101", 45 | }; 46 | vector b = { 47 | "11", 48 | "0", 49 | "0", 50 | "1", 51 | "1" 52 | }; 53 | 54 | for (int i = 0; i < a.size(); ++i) { 55 | cout << sol.addBinary(a[i], b[i]) << '\n'; 56 | } 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /leetcode/balanced-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | bool isBalanced(TreeNode *root) { 6 | int height; 7 | return isBalanced(root, height); 8 | } 9 | bool isBalanced(TreeNode *root, int &height) { 10 | if (root == NULL) { 11 | height = 0; 12 | return true; 13 | } 14 | 15 | int lh = 0, rh = 0; 16 | bool l_bal = isBalanced(root->left, lh); 17 | bool r_bal = isBalanced(root->right, rh); 18 | height = max(lh, rh) + 1; 19 | return (l_bal && r_bal && abs(lh - rh) <= 1); 20 | } 21 | }; 22 | 23 | int main(int argc, char const *argv[]) 24 | { 25 | TreeNode nodes[] = { 26 | TreeNode(1), // 0 27 | TreeNode(2), TreeNode(2), // 1, 2 28 | TreeNode(3), TreeNode(3), // 3, 4 29 | TreeNode(4), TreeNode(4), // 5, 6 30 | }; 31 | nodes[0].left = &nodes[1]; 32 | nodes[0].right = &nodes[2]; 33 | nodes[1].left = &nodes[3]; 34 | nodes[1].right = &nodes[5]; 35 | nodes[2].left = &nodes[6]; 36 | nodes[2].right = &nodes[4]; 37 | 38 | TreeNode *root = &nodes[0]; 39 | Solution sol; 40 | cout << sol.isBalanced(root) << endl; 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /leetcode/best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // the idea is to maintain a lowest point and compute the profit we can earn 7 | // at price[i], where i is greater than the current low point. Update the max accrodingly 8 | class Solution { 9 | public: 10 | int maxProfit(vector &prices) { 11 | if (prices.empty()) return 0; 12 | int profit = 0; 13 | int low = prices[0]; 14 | for (int i = 1; i < prices.size(); ++i) { 15 | low = min(prices[i], low); 16 | profit = max(profit, prices[i] - low); 17 | } 18 | return profit; 19 | } 20 | }; 21 | 22 | int main(int argc, char const *argv[]) 23 | { 24 | // int A[] = {3, 4, 1, 2, 6, 7, 0, 2, 3}; 25 | // int A[] = {3, 0}; 26 | int A[] = {}; 27 | int n = sizeof(A) / sizeof(int); 28 | vector prices(A, A+n); 29 | Solution sol; 30 | int profit = sol.maxProfit(prices); 31 | cout << profit << endl; 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /leetcode/climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int climbStairs(int n) { 7 | int *table = new int[n+1]; 8 | table[0] = 0; 9 | table[1] = 1; 10 | table[2] = 2; 11 | for (int i = 3; i <= n; ++i) { 12 | table[i] = table[i-1] + table[i-2]; 13 | } 14 | return table[n]; 15 | } 16 | }; 17 | 18 | int main(int argc, char const *argv[]) 19 | { 20 | Solution sol; 21 | int n = 5; 22 | int nsol = sol.climbStairs(n); 23 | cout << nsol << endl; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /leetcode/combination-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | #include "array2D.hpp" 3 | 4 | class Solution { 5 | vector > result; 6 | public: 7 | vector > combinationSum(vector &candidates, int target) { 8 | sort(candidates.begin(), candidates.end()); 9 | vector prefix; 10 | combinationSum(candidates, 0, target, prefix); 11 | return result; 12 | } 13 | 14 | void combinationSum(const vector &candidates, 15 | int begin, int target, vector& prefix) { 16 | for (int i = begin; i < candidates.size(); ++i) { 17 | int v = candidates[i]; 18 | if (v == target) { 19 | result.push_back(prefix); 20 | result.back().push_back(v); 21 | } else if (v < target) { 22 | prefix.push_back(v); 23 | combinationSum(candidates, i, target - v, prefix); 24 | prefix.pop_back(); 25 | } else { 26 | break; 27 | } 28 | } 29 | } 30 | }; 31 | 32 | int main() { 33 | Solution sol; 34 | int target = 7; 35 | // vector candidates = {2,3,6,7}; 36 | vector candidates = {1, 2, 3, 4, 5, 6, 7}; 37 | auto result = sol.combinationSum(candidates, target); 38 | print_2D(result); 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /leetcode/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | // interesting idea 2 | #include "leetcode.h" 3 | 4 | // Key observation: the shorter boundary decides the area. 5 | // The only way that we can increase the area is to make the shorter boundary taller 6 | // If we fix right boundary and change left, those with a smaller value must be useless 7 | // that gives us two directions: 8 | // - move left bound to left: we need to consider all as the width is increasing 9 | // - move left bound to right: we only need to consider the taller boundary as the width is decreasing, so this is a better choice 10 | // 11 | // A good visualization: https://oj.leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm 12 | 13 | class Solution { 14 | public: 15 | int maxArea(vector &height) { 16 | int i = 0, j = height.size() - 1; 17 | int max_area = 0; 18 | while (i < j) { 19 | max_area = std::max(max_area, min(height[i], height[j]) * (j-i)); 20 | if ( height[i] < height[j] ) { 21 | i++; 22 | } else { 23 | j--; 24 | } 25 | } 26 | 27 | return max_area; 28 | } 29 | }; 30 | 31 | int main() { 32 | // vector height = {2, 1, 3, 5, 1, 4, 2, 6}; 33 | vector height = {}; 34 | Solution sol; 35 | cout << sol.maxArea(height) << '\n'; 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /leetcode/convert-sorted-list-to-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | // good question, didn't come out the solution at the first hand 2 | // need to practice again 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | TreeNode *sortedListToBST(ListNode *head) { 8 | if (head == NULL) return NULL; 9 | 10 | ListNode *p = head; 11 | int n = 0; 12 | while (p != NULL) { 13 | ++n; 14 | p = p->next; 15 | } 16 | 17 | p = head; 18 | return sortedListToBST(p, 0, n-1); 19 | } 20 | 21 | TreeNode *sortedListToBST(ListNode *&head, int b, int e) { 22 | if (b > e) return NULL; 23 | 24 | int mid = (b+e)/2; 25 | TreeNode *left = sortedListToBST(head, b, mid-1); 26 | TreeNode *node = new TreeNode(head->val); 27 | node->left = left; 28 | head = head->next; 29 | TreeNode *right = sortedListToBST(head, mid+1, e); 30 | node->right = right; 31 | 32 | return node; 33 | } 34 | }; 35 | 36 | int main() { 37 | const int n=10; 38 | ListNode a[n]; 39 | for (int i = 0; i < n; ++i) { 40 | a[i].val = i; 41 | if (i < n-1) 42 | a[i].next = &a[i+1]; 43 | } 44 | 45 | Solution sol; 46 | TreeNode *root = sol.sortedListToBST(&a[0]); 47 | level_order_cout(root); 48 | 49 | return 0; 50 | } -------------------------------------------------------------------------------- /leetcode/copy-list-with-random-pointer.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | struct RandomListNode { 4 | int label; 5 | RandomListNode *next, *random; 6 | RandomListNode(int x) : label(x), next(NULL), random(NULL) {} 7 | }; 8 | 9 | class Solution { 10 | typedef unordered_map Map; 11 | Map map; 12 | 13 | RandomListNode *getOrCreateNode(RandomListNode *p) { 14 | if (p == NULL) return NULL; 15 | RandomListNode *node = map[p]; 16 | if (!node) { 17 | // not exist, create a corresponding node 18 | node = new RandomListNode(p->label); 19 | map[p] = node; 20 | } 21 | return node; 22 | } 23 | 24 | public: 25 | 26 | RandomListNode *copyRandomList(RandomListNode *head) { 27 | RandomListNode *dup = NULL, *tail = NULL; 28 | RandomListNode *p = head; 29 | while (p != NULL) { 30 | RandomListNode *node = getOrCreateNode(p); 31 | RandomListNode *random = getOrCreateNode(p->random); 32 | node->random = random; 33 | 34 | if (dup == NULL) { 35 | dup = tail = node; 36 | } else { 37 | tail->next = node; 38 | tail = tail->next; 39 | } 40 | p = p->next; 41 | } 42 | 43 | return dup; 44 | } 45 | }; 46 | 47 | int main() { 48 | Solution sol; 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /leetcode/count-and-say.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string countAndSay(int n) { 6 | if (n==1) return "1"; 7 | string s("11"); 8 | for (int i = 3; i <= n; ++i) { 9 | string old = s; 10 | s.clear(); 11 | char c = old[0]; 12 | int count = 1; 13 | int j = 1; 14 | while (1) { 15 | if (j >= old.size() || old[j] != c) { 16 | s += to_string(count) + c; 17 | 18 | if (j >= old.size()) 19 | break; 20 | 21 | c = old[j]; 22 | count = 1; 23 | } else { 24 | ++count; 25 | } 26 | ++j; 27 | } // while 28 | } 29 | return s; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution sol; 35 | int n = 10; 36 | for (int i = 1; i <= n; i++) { 37 | cout << sol.countAndSay(i) << endl; 38 | } 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /leetcode/decode-ways.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int numDecodings(string s) { 6 | int n = s.size(); 7 | if (n == 0) return 0; 8 | 9 | vector D(n+1, 0); 10 | if (s[0] < '1' || s[0] > '9') { 11 | return 0; 12 | } 13 | D[0] = D[1] = 1; 14 | for (int i = 1; i < n; ++i) { 15 | int j = i + 1; 16 | int num = (s[i-1] - '0') * 10 + (s[i] - '0'); 17 | 18 | if (num == 0) { 19 | // 00 20 | return 0; 21 | } else if (num >= 1 && num <= 26) { 22 | if (s[i] == '0') { // 10, 20 23 | D[j] = D[j-2]; 24 | } 25 | else if (s[i-1] == '0') { // 01..09 26 | D[j] = D[j-1]; 27 | } else { // 11-19, 21-26 28 | D[j] = D[j-1] + D[j-2]; 29 | } 30 | } else { 31 | if (s[i] == '0') { // 30, 40, ... 32 | return 0; 33 | } else { 34 | // >= 27 35 | D[j] = D[j-1]; 36 | } 37 | } 38 | } // for 39 | 40 | return D[n]; 41 | } 42 | }; 43 | 44 | int main() { 45 | vector ss = { 46 | "1221", 47 | "12", 48 | "0", 49 | "", 50 | "0123", 51 | "1201", 52 | "1200", 53 | "230", 54 | }; 55 | Solution sol; 56 | for (auto &s : ss) { 57 | cout << sol.numDecodings(s) << endl; 58 | } 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /leetcode/distinct-subsequences.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int numDistinct(string S, string T) { 6 | int n = S.size(); 7 | int m = T.size(); 8 | if (n == 0 || m == 0 || m > n) return 0; 9 | 10 | vector pre(n+1, 1), cur(n+1, 1); 11 | 12 | // copy(pre.begin(), pre.end(), ostream_iterator(cout, " ")); 13 | // cout << '\n'; 14 | for (int i = 1; i <= m; ++i) { 15 | for (int j = i; j <= n; ++j) { 16 | if (j > i) 17 | cur[j] = cur[j-1]; 18 | else 19 | cur[j] = 0; 20 | if (S[j-1] == T[i-1]) { 21 | cur[j] += pre[j-1]; 22 | } 23 | } // for j 24 | pre = cur; 25 | // copy(pre.begin(), pre.end(), ostream_iterator(cout, " ")); 26 | // cout << '\n'; 27 | } // for i 28 | 29 | return cur[n]; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution sol; 35 | vector S { 36 | "rabbbit", 37 | "ABCABC", 38 | "A", 39 | "", 40 | "A", 41 | "A", 42 | "fff", 43 | "fffd", 44 | }; 45 | vector T { 46 | "rabbit", 47 | "ABC", 48 | "A", 49 | "A", 50 | "", 51 | "B", 52 | "ffff", 53 | "ffff", 54 | }; 55 | 56 | for (int i = 0; i < S.size(); ++i) { 57 | printf("%d\n", sol.numDistinct(S[i], T[i])); 58 | } 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /leetcode/divide-two-integers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using std::cout; 5 | using std::endl; 6 | 7 | class Solution { 8 | public: 9 | int divide(int dividend, int divisor) { 10 | bool positive = ((dividend >= 0 && divisor >= 0) || (dividend < 0 && divisor < 0)); 11 | 12 | // overflow 13 | unsigned int residue = dividend; 14 | if (dividend < 0) residue = -residue; 15 | 16 | unsigned int div = divisor; 17 | if (divisor < 0) div = -div; 18 | 19 | int q = 0; 20 | 21 | while (residue >= div) { 22 | long int part = div; 23 | long int counter = 1; 24 | while ( (part<<1) > 0 && (part<<1) < residue) { 25 | part <<= 1; 26 | counter <<= 1; 27 | } 28 | q += counter; 29 | residue -= part; 30 | } 31 | return positive? q : -q; 32 | } 33 | }; 34 | 35 | int main() { 36 | // int dividend = std::numeric_limits::max(); 37 | // int divisor = 2; 38 | // int dividend = -1010369383; 39 | // int dividend = -2147483648; 40 | // int divisor = -2147483648; 41 | int dividend = 1; 42 | int divisor = -1; 43 | Solution sol; 44 | cout << dividend / divisor << endl; 45 | cout << sol.divide(dividend, divisor) << endl; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/edit-distance.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int minDistance(string word1, string word2) { 6 | int n = word1.size(), m = word2.size(); 7 | vector pre(m+1), cur(m+1); 8 | // initialize (empty string to word 2) 9 | for (int j = 0; j <= m; ++j) { 10 | pre[j] = j; 11 | cur[j] = j; 12 | } 13 | 14 | for (int i = 1; i <= n; ++i) { 15 | // initialize (word 1 to empty string) 16 | cur[0] = i; 17 | for (int j = 1; j <= m; ++j) { 18 | if (word1[i-1] == word2[j-1]) { 19 | cur[j] = pre[j-1]; 20 | } else { 21 | cur[j] = 1 + std::min({pre[j-1], pre[j], cur[j-1]}); 22 | } 23 | } 24 | pre = cur; 25 | } // for i 26 | 27 | return cur[m]; 28 | } 29 | }; 30 | 31 | int main() { 32 | Solution sol; 33 | vector word1 { 34 | "lime", 35 | "ABCDEF", 36 | "LEET", 37 | "", 38 | "abbb", 39 | "", 40 | }; 41 | vector word2 { 42 | "plie", 43 | "ACE", 44 | "CODER", 45 | "a", 46 | "", 47 | "", 48 | }; 49 | for (int i = 0; i < word1.size(); ++i) { 50 | printf("%s -> %s : %d\n", word1[i].c_str(), word2[i].c_str(), 51 | sol.minDistance(word1[i], word2[i])); 52 | } 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /leetcode/first-missing-positive.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int firstMissingPositive(int A[], int n) { 6 | // recursively swap all the elements in range 1-n 7 | for (int i = 0; i < n; ++i) { 8 | // move to right place 9 | int pos = A[i]; 10 | while ( pos > 0 && pos <= n && A[pos-1] != pos ) { 11 | int tmp = A[pos-1]; 12 | A[pos-1] = pos; 13 | pos = tmp; 14 | } 15 | 16 | // knock out some out of range element 17 | if ( pos <= 0 || pos > n ) { 18 | A[i] = pos; 19 | } 20 | } // for 21 | 22 | // scan for the missing positive 23 | for (int i = 0; i < n; ++i) { 24 | if (A[i] != i+1) return i+1; 25 | } 26 | 27 | // no such element exist 28 | return n+1; 29 | } 30 | }; 31 | 32 | int main() { 33 | Solution sol; 34 | 35 | vector > As { 36 | {1, 2, 0}, 37 | {3, 4, -1, 1}, 38 | {4, 3, 2, 0, 6, 5}, 39 | {4, 3, 2, 1, 6, 5}, 40 | {4, 3, 1, 0, 6, 5}, 41 | {}, 42 | {1}, 43 | }; 44 | 45 | for (auto &A : As) { 46 | int missing = sol.firstMissingPositive(A.data(), A.size()); 47 | printf("%d\n", missing); 48 | } 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /leetcode/flatten-binary-tree-to-linked-list.cpp: -------------------------------------------------------------------------------- 1 | // there is a very elegant code, but I do not understand 2 | // http://oj.leetcode.com/discuss/637/can-you-improve-upon-my-recursive-approach 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | void flatten(TreeNode *root) { 8 | dfs(root); 9 | } 10 | 11 | TreeNode *dfs(TreeNode *root) { 12 | if (root == NULL) return NULL; 13 | 14 | if (root->left == NULL && root->right == NULL) 15 | return root; 16 | 17 | TreeNode *ll = dfs(root->left); 18 | TreeNode *lr = dfs(root->right); 19 | 20 | if (root->left != NULL) { 21 | ll->right = root->right; 22 | root->right = root->left; 23 | root->left = NULL; 24 | } 25 | 26 | if (lr != NULL) 27 | return lr; 28 | else 29 | return ll; 30 | } 31 | }; 32 | 33 | void print_right_child(TreeNode *root) { 34 | while (root != NULL) { 35 | printf("%d ", root->val); 36 | root = root->right; 37 | } 38 | printf("\n"); 39 | } 40 | 41 | int main() { 42 | string tree = "1 2 3 # # 4 # # 5 # 6 # #"; 43 | TreeNode *root = deserialize_tree(tree); 44 | Solution sol; 45 | preorder_cout(root); 46 | sol.flatten(root); 47 | preorder_cout(root); 48 | print_right_child(root); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /leetcode/generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | // interesting problem, practice again 2 | #include 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | vector generateParenthesis(int n) { 8 | vector result; 9 | string prefix(""); 10 | gen(result, prefix, 0, n); 11 | return result; 12 | } 13 | 14 | void gen(vector &result, string prefix, int l, int k) { 15 | if (l == 0 && k == 0) { 16 | result.push_back(prefix); 17 | return; 18 | } 19 | 20 | // insert one left parenthesis 21 | if (k > 0) { 22 | gen(result, prefix + "(", l+1, k-1); 23 | } 24 | 25 | // close one left parenthesis 26 | if (l > 0) { 27 | gen(result, prefix + ")", l-1, k); 28 | } 29 | } 30 | }; 31 | 32 | int main(int argc, char const *argv[]) 33 | { 34 | Solution sol; 35 | auto result = sol.generateParenthesis(4); 36 | for (auto str : result) { 37 | cout << str << '\n'; 38 | } 39 | return 0; 40 | } -------------------------------------------------------------------------------- /leetcode/gray-code.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector grayCode(int n) { 6 | vector result; 7 | result.push_back(0); 8 | if (n == 0) return result; 9 | 10 | result.push_back(1); 11 | 12 | for (int i = 1; i < n; ++i) { 13 | vector tmp(result); 14 | // copy result in reverse order 15 | copy(tmp.rbegin(), tmp.rend(), back_inserter(result)); 16 | // first half remain the same 17 | // set bit 2^i to 1 in the later half 18 | int size = result.size(); 19 | for (int j = size/2; j < size; j++) { 20 | result[j] |= 1 << i; 21 | } 22 | } 23 | return result; 24 | } 25 | }; 26 | 27 | int main(int argc, char const *argv[]) 28 | { 29 | Solution sol; 30 | auto result = sol.grayCode(2); 31 | copy(result.begin(), result.end(), ostream_iterator(cout, " ")); 32 | cout << '\n'; 33 | return 0; 34 | } -------------------------------------------------------------------------------- /leetcode/insertion-sort-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *insertionSortList(ListNode *head) { 6 | if (head == NULL) return NULL; 7 | 8 | ListNode *p = NULL, *q = NULL, *cur = head->next; 9 | head->next = NULL; 10 | while (cur != NULL) { 11 | // search for insert location 12 | p = head; q = NULL; 13 | while (p != NULL && cur->val > p->val) { 14 | q = p; 15 | p = p->next; 16 | } 17 | 18 | ListNode *r = cur; 19 | cur = cur->next; 20 | 21 | if (q == NULL) { 22 | head = r; 23 | } else { 24 | q->next = r; 25 | } 26 | r->next = p; 27 | } 28 | 29 | return head; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution sol; 35 | // vector l = {10, 10, 10, 9, 8, 7}; 36 | // vector l = {10}; 37 | vector l = {3, 9, 2, 1, 0, 10, 7}; 38 | ListNode *head = list_from_array(l); 39 | print_list(head); 40 | ListNode *newhead = sol.insertionSortList(head); 41 | print_list(newhead); 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /leetcode/integer-to-roman.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string intToRoman(int num) { 6 | string tens[] = {"I", "X", "C", "M"}; 7 | string fives[] = {"V", "L", "D"}; 8 | int i = 0; 9 | string val; 10 | while (num != 0) { 11 | int d = num % 10; 12 | num /= 10; 13 | 14 | if (d == 9) { 15 | val = tens[i] + tens[i+1] + val; 16 | } else if ( 5 <= d && d <= 8 ) { 17 | string ii; 18 | for (int j = 1; j <= d - 5; ++j) { 19 | ii += tens[i]; 20 | } 21 | val = fives[i] + ii + val; 22 | } else if ( d == 4 ) { 23 | val = tens[i] + fives[i] + val; 24 | } else if ( 1 <= d && d <= 3 ) { 25 | string ii; 26 | for (int j = 1; j <= d ; ++j) { 27 | ii += tens[i]; 28 | } 29 | val = ii + val; 30 | } else { 31 | // 0 : do nothing 32 | } 33 | ++i; 34 | } 35 | return val; 36 | } 37 | }; 38 | 39 | int main(int argc, char const *argv[]) 40 | { 41 | Solution sol; 42 | cout << sol.intToRoman(3999) << endl; 43 | cout << sol.intToRoman(1234) << endl; 44 | cout << sol.intToRoman(4) << endl; 45 | cout << sol.intToRoman(3987) << endl; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/jump-game-ii.cpp: -------------------------------------------------------------------------------- 1 | // still confusing 2 | // http://oj.leetcode.com/discuss/422/is-there-better-solution-for-jump-game-ii 3 | #include 4 | #include 5 | #include "leetcode.h" 6 | 7 | class Solution { 8 | public: 9 | int jump(int A[], int n) { 10 | if (n <= 1) return 0; 11 | 12 | int last = 0; 13 | int curr = 0; 14 | int step = 0; 15 | for (int i = 0; i < n; ++i) { 16 | if (i > last) { 17 | if (curr == last && last < ) 18 | } 19 | } 20 | return M[n-1]; 21 | } 22 | }; 23 | 24 | int main() { 25 | Solution sol; 26 | vector > A { 27 | {2,3,1,1,4}, 28 | {5, 1, 1, 1, 3, 1, 1, 1,}, 29 | }; 30 | 31 | for (auto v : A) { 32 | printf("%d\n", sol.jump(v.data(), v.size())); 33 | } 34 | 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /leetcode/lca.cpp: -------------------------------------------------------------------------------- 1 | // http://leetcode.com/2011/07/lowest-common-ancestor-of-a-binary-tree-part-i.html 2 | #include "leetcode.h" 3 | 4 | // cases to consider: 5 | // 1. p or q == root: LCA is root 6 | // 2. p and q in different sides of root: LCA is root 7 | 8 | class Solution { 9 | public: 10 | int count = 0; 11 | TreeNode *LCA(TreeNode *root, TreeNode *p, TreeNode *q) { 12 | ++count; 13 | if (root == nullptr) return nullptr; 14 | if (root == p || root == q) return root; // root is in the path 15 | TreeNode *L = LCA(root->left, p, q); 16 | TreeNode *R = LCA(root->right, p, q); 17 | if (L && R) return root; // p, q at both sides 18 | return L? L : R; // p, q at either side, or not found 19 | } 20 | }; 21 | 22 | int main() { 23 | Solution sol; 24 | TreeNode *root = deserialize_tree(string("1 2 4 # # 5 # # 3 # #")); 25 | TreeNode *p = root->left->left; 26 | // TreeNode *q = root->right; 27 | // TreeNode *q = root->left->right; 28 | TreeNode *q = root->left; 29 | TreeNode *lca = sol.LCA(root, p, q); 30 | cout << lca->val << " count: " << sol.count << "\n"; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /leetcode/length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int lengthOfLastWord(const char *s) { 6 | int prev = 0, len = 0; 7 | int i = 0; 8 | char c; 9 | while ( (c = s[i]) != 0) { 10 | if ( c == ' ' ) { 11 | if (len > 0) 12 | prev = len; 13 | len = 0; 14 | } 15 | else 16 | ++len; 17 | 18 | ++i; 19 | } 20 | 21 | if (s[i-1] == ' ') 22 | return prev; 23 | 24 | return len; 25 | } 26 | }; 27 | 28 | int main(int argc, char const *argv[]) 29 | { 30 | const char *str[] = { 31 | "Hello world", 32 | " hello", 33 | "hello ", 34 | "", 35 | " ", 36 | " A", 37 | "A ", 38 | " A ", 39 | "ABC A ", 40 | "A ABC ", 41 | }; 42 | Solution sol; 43 | for (auto s : str) { 44 | cout << sol.lengthOfLastWord(s) << " : '" << s << "'" << endl; 45 | } 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/level_order_with_sentinel.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | void level_order_with_sentinel (TreeNode *root) { 5 | if(root == NULL) return; 6 | queue myqueue; 7 | myqueue.push(root); 8 | myqueue.push(NULL); 9 | while(!myqueue.empty()) { 10 | TreeNode *node = myqueue.front(); 11 | myqueue.pop(); 12 | if (node == NULL) { 13 | cout << '\n'; 14 | if(!myqueue.empty()) 15 | myqueue.push(NULL); 16 | continue; 17 | } 18 | if(node->left) 19 | myqueue.push(node->left); 20 | if(node->right) 21 | myqueue.push(node->right); 22 | cout << node->val << ' '; 23 | } 24 | } 25 | 26 | int main() { 27 | string tree = "3 9 # # 20 15 # # 7 # #"; 28 | TreeNode *root = deserialize_tree(tree); 29 | cout << root << endl; 30 | level_order_cout(root); 31 | level_order_with_sentinel(root); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /leetcode/linked-list-cycle-ii.cpp: -------------------------------------------------------------------------------- 1 | // classical problem. Think & practice again!! 2 | 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | ListNode *detectCycle(ListNode *head) { 8 | if ( head == NULL ) return NULL; 9 | 10 | ListNode *p, *q; 11 | p = q = head; 12 | 13 | do { 14 | p = p->next; 15 | q = q->next; 16 | if (q != NULL) 17 | q = q->next; 18 | 19 | if ( p == q ) 20 | break; 21 | } 22 | while (p != NULL && q != NULL); 23 | 24 | // no cycle 25 | if (p == NULL || q == NULL) 26 | return NULL; 27 | 28 | q = head; // reset 29 | while (p != q) { 30 | q = q->next; 31 | p = p->next; 32 | } 33 | 34 | return p; 35 | } 36 | }; 37 | 38 | int main(int argc, char const *argv[]) 39 | { 40 | const int N = 10; 41 | ListNode nodes[N]; 42 | for (int i = 0; i < N - 1; ++i) { 43 | nodes[i].val = i; 44 | nodes[i].next = &nodes[i+1]; 45 | } 46 | 47 | // make a cycle 48 | nodes[9].val = 9; 49 | nodes[9].next = &nodes[9]; 50 | 51 | Solution sol; 52 | ListNode *head = &nodes[0]; 53 | ListNode *node = sol.detectCycle(head); 54 | if (node!=NULL) 55 | cout << node->val << endl; 56 | return 0; 57 | } -------------------------------------------------------------------------------- /leetcode/longest-common-prefix.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string longestCommonPrefix(vector &strs) { 6 | int n = strs.size(); 7 | if (n == 0) return ""; 8 | if (n == 1) return strs[0]; 9 | 10 | int i; 11 | string prefix; 12 | int l = 0; 13 | while (1) { 14 | if (l >= strs[0].size()) return prefix; 15 | char c = strs[0][l]; 16 | for (int i = 1; i < n; ++i) { 17 | if (l >= strs[i].size()) return prefix; 18 | 19 | if (c != strs[i][l]) return prefix; 20 | } 21 | prefix.push_back(c); 22 | ++l; 23 | } 24 | } 25 | }; 26 | 27 | int main() { 28 | vector strs = { 29 | "abcbbb", 30 | "abc", 31 | "abcdef", 32 | "abccf", 33 | "abc" 34 | }; 35 | Solution sol; 36 | cout << sol.longestCommonPrefix(strs) << endl; 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /leetcode/longest-substring-without-repeating-characters.cpp: -------------------------------------------------------------------------------- 1 | // http://leetcode.com/2011/05/longest-substring-without-repeating-characters.html 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | int lengthOfLongestSubstring(string s) { 7 | int n = s.size(); 8 | if (n <= 1) return n; 9 | 10 | unordered_map map; 11 | map[s[0]] = 0; 12 | int max = 1; 13 | int len = 1; 14 | vector start(n); // records starting point of max substring ended at i 15 | start[0] = 0; 16 | for (int i = 1; i < n; ++i) { 17 | char c = s[i]; 18 | 19 | if (map.find(c) != map.end()) { 20 | // found repeating char 21 | int cid = map[c]; 22 | start[i] = cid + 1; 23 | for(int j = start[i-1]; j < cid; ++j) { 24 | map.erase(s[j]); 25 | len--; 26 | } 27 | map[c] = i; 28 | } else { 29 | start[i] = start[i-1]; 30 | map[c] = i; 31 | ++len; 32 | max = std::max(max, i - start[i] + 1); 33 | } 34 | } // for 35 | 36 | return max; 37 | } 38 | }; 39 | 40 | int main() { 41 | vector str { 42 | "abcabcbb", 43 | "bbbb", 44 | "abcabdeaghi" 45 | }; 46 | Solution sol; 47 | for (auto &s : str) { 48 | printf("%d\n", sol.lengthOfLongestSubstring(s)); 49 | } 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /leetcode/max_depth_of_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /** 5 | * Definition for binary tree 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 11 | * }; 12 | */ 13 | 14 | 15 | struct TreeNode { 16 | int val; 17 | TreeNode *left; 18 | TreeNode *right; 19 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 20 | }; 21 | 22 | 23 | class Solution { 24 | public: 25 | int maxDepth(TreeNode *root) { 26 | if (root == NULL) return 0; 27 | int left_height = maxDepth(root->left); 28 | int right_height = maxDepth(root->right); 29 | int depth = (left_height > right_height) ? left_height : right_height; 30 | return depth + 1; 31 | } 32 | }; 33 | 34 | int main() { 35 | TreeNode* root = new TreeNode(1); 36 | TreeNode* a = new TreeNode(2); 37 | TreeNode* b = new TreeNode(3); 38 | root->left = a; root->right = b; 39 | 40 | TreeNode* c = new TreeNode(4); 41 | TreeNode* d = new TreeNode(5); 42 | TreeNode* e = new TreeNode(6); 43 | 44 | a->left = c; 45 | c->right = d; 46 | b->right = e; 47 | 48 | Solution sol; 49 | cout << sol.maxDepth(root) << endl; 50 | cout << sol.maxDepth(a) << endl; 51 | cout << sol.maxDepth(b) << endl; 52 | cout << sol.maxDepth(e) << endl; 53 | return 0; 54 | } -------------------------------------------------------------------------------- /leetcode/maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | int maxSum_; 5 | public: 6 | int maxPathSumFromRoot(TreeNode *root) { 7 | if (root == NULL) { 8 | return 0; 9 | } 10 | 11 | int leftSum = maxPathSumFromRoot(root->left); 12 | int rightSum = maxPathSumFromRoot(root->right); 13 | 14 | // using root 15 | int sumFromRoot = max({ 16 | root->val, 17 | root->val + leftSum, 18 | root->val + rightSum}); 19 | 20 | // use or not use root 21 | maxSum_ = max({ 22 | maxSum_, 23 | sumFromRoot, 24 | root->val + leftSum + rightSum}); 25 | return sumFromRoot; 26 | } 27 | 28 | int maxPathSum(TreeNode *root) { 29 | if (root == NULL) { 30 | return 0; 31 | } 32 | 33 | maxSum_ = root->val; 34 | maxPathSumFromRoot(root); 35 | return maxSum_; 36 | } 37 | }; 38 | 39 | int main() { 40 | // TreeNode *root = deserialize_tree(string("-2 2 1 # # 3 # # -3 # #")); 41 | // TreeNode *root = deserialize_tree(string("1 2 # # 3 # #")); 42 | TreeNode *root = deserialize_tree(string("-3 # #")); 43 | Solution sol; 44 | cout << sol.maxPathSum(root) << endl; 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /leetcode/maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int maxSubArray(int A[], int n) { 7 | int sum = A[0], mm = A[0]; 8 | for (int i = 1; i < n; ++i) { 9 | if (sum < 0 && A[i] >= 0) { 10 | sum = A[i]; 11 | } 12 | else if (sum + A[i] > 0) { 13 | sum += A[i]; 14 | } 15 | else { 16 | sum = A[i]; 17 | } 18 | if (sum > mm) mm = sum; 19 | } 20 | return mm; 21 | } 22 | }; 23 | 24 | int main(int argc, char const *argv[]) 25 | { 26 | // int A[] = {-2,1,-3,4,-1,2,1,-5,4}; 27 | int A[] = {-2,-3,-1,-5}; 28 | int n = sizeof(A) / sizeof(int); 29 | Solution sol; 30 | int sum = sol.maxSubArray(A, n); 31 | cout << sum << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /leetcode/minimum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int minDepth(TreeNode *root) { 6 | if (root == NULL) return 0; 7 | 8 | int ldepth = minDepth(root->left); 9 | int rdepth = minDepth(root->right); 10 | 11 | if (root->left == NULL) { 12 | return 1 + rdepth; 13 | } 14 | 15 | if (root->right == NULL) { 16 | return 1 + ldepth; 17 | } 18 | 19 | return 1 + min(ldepth, rdepth); 20 | } 21 | 22 | }; 23 | 24 | int main(int argc, char const *argv[]) 25 | { 26 | string serialized_tree("3 9 # # 20 15 # 8 4 # # # 7 # #"); 27 | TreeNode *root = deserialize_tree(serialized_tree); 28 | Solution sol; 29 | cout << sol.minDepth(root) << endl; 30 | cout << sol.minDepth(NULL) << endl; 31 | cout << sol.minDepth(root->left) << endl; 32 | cout << sol.minDepth(root->right) << endl; 33 | cout << sol.minDepth(root->right->left) << endl; 34 | 35 | return 0; 36 | } -------------------------------------------------------------------------------- /leetcode/palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | 6 | // overflow version 7 | bool isPalindrome(int x) { 8 | int orig = x; 9 | x = abs(x); 10 | long long y = 0; 11 | while (x != 0) { 12 | int d = x % 10; 13 | x /= 10; 14 | y = 10 * y + d; 15 | } 16 | return orig == y; 17 | } 18 | }; 19 | 20 | int main(int argc, char const *argv[]) 21 | { 22 | int x = 123454321; 23 | Solution sol; 24 | cout << sol.isPalindrome(x) << endl; 25 | 26 | int neg = -x; 27 | cout << sol.isPalindrome(x) << endl; 28 | 29 | int big = 0x7fffffff; 30 | cout << big << endl; 31 | cout << sol.isPalindrome(big) << endl; 32 | return 0; 33 | } -------------------------------------------------------------------------------- /leetcode/palindrome-partitioning.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | #include "array2D.hpp" 3 | 4 | class Solution { 5 | public: 6 | bool isPalindrome(string &s) { 7 | int i = 0, j = s.size() - 1; 8 | while (i <= j) { 9 | if (s[i] != s[j]) 10 | return false; 11 | ++i; 12 | --j; 13 | } 14 | return true; 15 | } 16 | 17 | vector > partition(string s) { 18 | vector > result; 19 | int n = s.size(); 20 | for (int i = 1; i <= n; ++i) { 21 | string sub = s.substr(n-i, i); 22 | if ( isPalindrome(sub) ) { 23 | string remain = s.substr(0, n-i); 24 | vector > tmp = partition(remain); 25 | if (tmp.empty()) 26 | result.push_back(vector(1, sub)); 27 | for (auto vec: tmp) { 28 | result.push_back(vec); 29 | result.back().push_back(sub); 30 | } 31 | } 32 | } // for 33 | 34 | return result; 35 | } 36 | }; 37 | 38 | int main() { 39 | Solution sol; 40 | vector strs = { 41 | "ab", 42 | "aab", 43 | "abba", 44 | "abcba", 45 | "a", 46 | "", 47 | }; 48 | for (auto s : strs) { 49 | cout << s << ": [\n"; 50 | auto result = sol.partition(s); 51 | print_2D(result); 52 | cout << "]\n"; 53 | } 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /leetcode/pascals-triangle-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector getRow(int rowIndex) { 6 | vector pre, cur; 7 | vector *p = &cur, *q = ⪯ 8 | pre.push_back(1); 9 | 10 | for (int i = 1; i <= rowIndex; ++i) { 11 | p->resize(i+1); 12 | (*p)[0] = (*p)[i] = 1; 13 | for (int j = 1; j < i ; ++j) { 14 | (*p)[j] = (*q)[j-1] + (*q)[j]; 15 | } 16 | swap(p, q); 17 | } 18 | return *q; 19 | } 20 | }; 21 | 22 | int main(int argc, char const *argv[]) 23 | { 24 | Solution sol; 25 | int rowId = 10; 26 | auto result = sol.getRow(rowId); 27 | copy(result.begin(), result.end(), 28 | ostream_iterator(cout, " ")); 29 | cout << '\n'; 30 | return 0; 31 | } -------------------------------------------------------------------------------- /leetcode/pascals-triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void output(vector > &result) { 6 | for (auto row : result) { 7 | for (auto i : row) { 8 | cout << i << " "; 9 | } 10 | cout << endl; 11 | } 12 | } 13 | 14 | class Solution { 15 | public: 16 | vector > generate(int numRows) { 17 | vector > result(numRows); 18 | if (numRows == 0) return result; 19 | result[0].push_back(1); 20 | for (int r = 1; r < numRows; r++) { 21 | int n = r + 1; 22 | result[r].resize(n); 23 | for (int i = 0; i < n; i++) { 24 | int ll = ((i - 1) >= 0) ? (result[r-1][i-1]) : 0; 25 | int rr = (i < r) ? (result[r-1][i]) : 0; 26 | result[r][i] = ll + rr; 27 | } 28 | } 29 | return result; 30 | } 31 | }; 32 | 33 | 34 | int main(int argc, char const *argv[]) 35 | { 36 | int numRows = 10; 37 | Solution sol; 38 | auto result = sol.generate(numRows); 39 | output(result); 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /leetcode/path-sum.cpp: -------------------------------------------------------------------------------- 1 | // this one is tricky, should practice again 2 | 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | bool hasPathSum(TreeNode *root, int sum) { 8 | if (root == NULL) return false; 9 | 10 | return hasPathSum_recursive(root, sum); 11 | } 12 | 13 | bool hasPathSum_recursive(TreeNode *root, int sum) { 14 | // if (root == NULL) { 15 | // return sum == 0; 16 | // } 17 | 18 | if (root->left == NULL && root->right == NULL) { 19 | // it's a leaf node 20 | return sum == root->val; 21 | } 22 | 23 | bool result = false; 24 | if (root->left != NULL) { 25 | result = hasPathSum_recursive(root->left, sum - root->val); 26 | if (result) return true; 27 | } 28 | 29 | if (root->right != NULL) { 30 | result = hasPathSum_recursive(root->right, sum - root->val); 31 | } 32 | 33 | return result; 34 | } 35 | }; 36 | 37 | int main(int argc, char const *argv[]) 38 | { 39 | string tree("5 4 11 7 # # 2 # # # 8 13 # # 4 # 1 # #"); 40 | TreeNode* root = deserialize_tree(tree); 41 | preorder_cout(root); 42 | 43 | Solution sol; 44 | cout << sol.hasPathSum(NULL, 0) << endl; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /leetcode/permutation-sequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "leetcode.h" 4 | 5 | // idea: each time determine the number at ith position 6 | // by counting how many permutaitons left 7 | class Solution { 8 | public: 9 | string getPermutation(int n, int k) { 10 | string result; 11 | vector l(n, '1'); 12 | int fac = 1; 13 | for (int i = 0; i < n; ++i) { 14 | fac *= (i+1); 15 | l[i] += i; 16 | } 17 | 18 | k -= 1; 19 | k %= fac; 20 | for (int i = 0; i < n; ++i) { 21 | fac /= (n-i); 22 | int idx = k / fac; 23 | k %= fac; 24 | result.push_back(l[idx]); 25 | l.erase(l.begin() + idx); 26 | } 27 | 28 | return result; 29 | } 30 | }; 31 | 32 | int main() { 33 | Solution sol; 34 | 35 | for (int i = 1; i <= 25; ++i) { 36 | cout << sol.getPermutation(4, i) << endl; 37 | } 38 | 39 | cout << sol.getPermutation(8, 30654) << endl; 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /leetcode/permutations-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | #include "array2D.hpp" 3 | 4 | class Solution { 5 | vector > result; 6 | vector visited; 7 | public: 8 | vector > permuteUnique(vector &num) { 9 | vector prefix; 10 | sort(num.begin(), num.end()); 11 | visited.assign(num.size(), 0); 12 | permuteUnique(prefix, num, 0); 13 | return result; 14 | } 15 | 16 | void permuteUnique(vector prefix, vector &num, int depth) { 17 | int n = num.size(); 18 | if (depth == n) { 19 | result.push_back(prefix); 20 | return; 21 | } 22 | 23 | bool has_prev = false; 24 | int prev = -1; 25 | for (int i = 0; i < n; ++i) { 26 | if (visited[i] || (has_prev && num[i] == prev)) 27 | continue; 28 | 29 | has_prev = true; 30 | prev = num[i]; 31 | visited[i] = true; 32 | prefix.push_back(num[i]); 33 | permuteUnique(prefix, num, depth+1); 34 | prefix.pop_back(); 35 | visited[i] = false; 36 | } 37 | } 38 | }; 39 | 40 | int main() { 41 | Solution sol; 42 | vector num {1, 1, 2, 2}; 43 | auto result = sol.permuteUnique(num); 44 | print_2D(result); 45 | 46 | return 0; 47 | } -------------------------------------------------------------------------------- /leetcode/permutations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | vector > permute(vector &num) { 7 | vector > result; 8 | if (num.size() == 1) { 9 | result.push_back(num); 10 | return result; 11 | } 12 | 13 | for (size_t i = 0; i < num.size(); ++i ) { 14 | vector rest; 15 | for(size_t j = 0; j < num.size(); ++j) { 16 | if (j != i) rest.push_back(num[j]); 17 | } 18 | 19 | auto partial = permute(rest); 20 | for(auto it = partial.begin(); it != partial.end(); it++) { 21 | // note: inserting to front of vector is inefficient 22 | // only for the sake of matching the OJ's answer order 23 | it->insert(it->begin(), num[i]); 24 | result.push_back(*it); 25 | } 26 | } 27 | return result; 28 | } 29 | }; 30 | 31 | int main(int argc, char const *argv[]) 32 | { 33 | Solution sol; 34 | int A[] = {1, 2, 3}; 35 | int n = sizeof(A) / sizeof(int); 36 | vector num(A, A + n); 37 | auto result = sol.permute(num); 38 | for (auto row : result) { 39 | copy(row.begin(), row.end(), ostream_iterator(cout, " ")); 40 | cout << '\n'; 41 | } 42 | return 0; 43 | } -------------------------------------------------------------------------------- /leetcode/plus-one.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector plusOne(vector &digits) { 6 | vector result(digits); 7 | int n = digits.size(); 8 | bool carry = true; 9 | for (int i = n - 1; i >= 0; i--) { 10 | if (carry) { 11 | result[i] += 1; 12 | if (result[i] >= 10) { 13 | result[i] = 0; 14 | carry = true; 15 | if (i == 0) 16 | result.insert(result.begin(), 1); 17 | } else { 18 | break; 19 | } 20 | } 21 | } 22 | return result; 23 | } 24 | }; 25 | 26 | int main(int argc, char const *argv[]) 27 | { 28 | Solution sol; 29 | // int A[] = {9, 9, 1, 1, 9, 9}; 30 | int A[] = {9, 9, 9, 9, 9, 9}; 31 | // int A[] = {9}; 32 | // int A[] = {8}; 33 | int n = sizeof(A) / sizeof(n); 34 | vector digits(A, A+n); 35 | 36 | copy(digits.begin(), digits.end(), ostream_iterator(cout, "")); 37 | cout << '\n'; 38 | auto result = sol.plusOne(digits); 39 | copy(result.begin(), result.end(), ostream_iterator(cout, "")); 40 | cout << '\n'; 41 | return 0; 42 | } -------------------------------------------------------------------------------- /leetcode/powx-n.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | double pow(double x, int n) { 6 | if (n == 0) return 1; 7 | if (n == 1) return x; 8 | 9 | bool inv = false; 10 | if (n < 0) { 11 | inv = true; 12 | n = -n; 13 | } 14 | 15 | if (n % 2 == 0) { 16 | double half = pow(x, n/2); 17 | double hh = half * half; 18 | return inv ? 1.0 / hh : hh; 19 | } { 20 | double half = pow(x, (n-1)/2); 21 | double hh = half * half * x; 22 | return inv ? 1.0 / hh : hh; 23 | } 24 | } 25 | }; 26 | 27 | int main() { 28 | Solution sol; 29 | for (int i = -32; i <= 32; ++i) { 30 | printf("%.10e\n", sol.pow(34.00515, i)); 31 | // cout << sol.pow(2, i) << '\n'; 32 | } 33 | 34 | return 0; 35 | } -------------------------------------------------------------------------------- /leetcode/remove-duplicates-from-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int removeDuplicates(int A[], int n) { 6 | if (n <= 2) return n; 7 | 8 | int nn = 0; 9 | int count = 1; 10 | for (int i = 1; i < n; i++) { 11 | if (A[i] == A[nn]) { 12 | if (count < 2) { 13 | A[++nn] = A[i]; 14 | count++; 15 | } 16 | } else { 17 | A[++nn] = A[i]; 18 | count = 1; 19 | } 20 | } // for 21 | 22 | return nn + 1; 23 | } 24 | }; 25 | 26 | int main(int argc, char const *argv[]) 27 | { 28 | // int A[] = {1, 1, 1, 2, 2, 3}; 29 | // int A[] = {1, 2}; 30 | // int A[] = {2}; 31 | // int A[] = {}; 32 | int A[] = {1, 1, 1, 1, 1, 2, 3, 3, 3, 3,}; 33 | int n = sizeof(A) / sizeof(int); 34 | Solution sol; 35 | int nn = sol.removeDuplicates(A, n); 36 | 37 | for (int i = 0; i < nn; ++i) 38 | { 39 | cout << A[i] << " "; 40 | } 41 | cout << '\n'; 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /leetcode/remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int removeDuplicates(int A[], int n) { 7 | if (n <= 1) return n; 8 | int p = 1; 9 | int cur = A[0]; 10 | for (int i = 1; i < n; i++) { 11 | if (A[i] == cur) 12 | continue; 13 | cur = A[i]; 14 | A[p++] = cur; 15 | } 16 | return p; 17 | } 18 | }; 19 | 20 | int main(int argc, char const *argv[]) 21 | { 22 | Solution sol; 23 | // int A[] = {1,1,2,2,2,3,3,4,4,4,4,5,6,7,7,7}; 24 | // int A[] = {3}; 25 | int A[] = {3,3,3,3}; 26 | int n = sizeof(A) / sizeof(int); 27 | int nn = sol.removeDuplicates(A, n); 28 | cout << "New length = " << nn << endl; 29 | for (int i = 0; i < nn; ++i) 30 | { 31 | cout << A[i] << " "; 32 | } 33 | cout << endl; 34 | return 0; 35 | } -------------------------------------------------------------------------------- /leetcode/remove-element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int removeElement(int A[], int n, int elem) { 7 | int q = -1; 8 | int i=0; 9 | for (i = 0; i < n; ++i) { 10 | if (A[i] == elem) { 11 | // search for the next non-elem 12 | if ( q == -1 ) q = i + 1; 13 | while (q < n && A[q] == elem) 14 | ++q; 15 | 16 | // cannot find one 17 | if (q == n) break; 18 | 19 | // swap them 20 | A[i] = A[q]; 21 | A[q] = elem; 22 | } 23 | } 24 | return i; 25 | } 26 | }; 27 | 28 | int main(int argc, char const *argv[]) 29 | { 30 | Solution sol; 31 | int A[] = {1, 2, 3, 3, 5, 3, 7, 8}; 32 | // int A[] = {0}; 33 | int elem = 3; 34 | int n = sizeof(A) / sizeof(int); 35 | int nn = sol.removeElement(A, n, elem); 36 | cout << nn << endl; 37 | for (int i : A) 38 | cout << i << " "; 39 | cout << endl; 40 | return 0; 41 | } -------------------------------------------------------------------------------- /leetcode/remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | // brain-teaser, interesting question. Practice (think) again! 2 | 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | ListNode *removeNthFromEnd(ListNode *head, int n) { 8 | if (head == NULL) return NULL; 9 | 10 | // assume n is valid 11 | ListNode *p, *q, *r; 12 | p = q = head; 13 | r = NULL; 14 | 15 | for (int i = 0; i < n - 1; ++i) { 16 | p = p->next; 17 | } 18 | 19 | while (p->next != NULL) { 20 | p = p->next; 21 | r = q; 22 | q = q->next; 23 | } 24 | 25 | if ( r == NULL ) { 26 | head = q->next; 27 | } else { 28 | r->next = q->next; 29 | } 30 | return head; 31 | } 32 | }; 33 | 34 | int main(int argc, char const *argv[]) 35 | { 36 | Solution sol; 37 | int a[] = {1,2,3,4,5}; 38 | int n = sizeof(a) / sizeof(int); 39 | for (int i = 1; i <= n; ++i) { 40 | ListNode *head = list_from_array(a, n); 41 | head = sol.removeNthFromEnd(head, i); 42 | print_list(head); 43 | } 44 | return 0; 45 | } -------------------------------------------------------------------------------- /leetcode/reorder-list.cpp: -------------------------------------------------------------------------------- 1 | // Another solution is: 2 | // 1. find the middle point of the list (two pointers, one go 2x, one go 1x) 3 | // 2. reverse the last half of the list 4 | // 3. merge two list 5 | // Time complexity will still be O(n), two passes, code is more complicated though. 6 | 7 | #include 8 | #include "leetcode.h" 9 | 10 | class Solution { 11 | public: 12 | void reorderList(ListNode *head) { 13 | if (head == NULL) return; 14 | 15 | stack st; 16 | ListNode *p = head; 17 | while (p != NULL) { 18 | st.push(p); 19 | p = p->next; 20 | } 21 | 22 | int n = st.size(); 23 | p = head; 24 | for (int i = 0; i < n/2; ++i) { 25 | ListNode *q = st.top(); 26 | st.pop(); 27 | q->next = p->next; 28 | p->next = q; 29 | p = q->next; 30 | } 31 | 32 | // fix the loop 33 | p->next = NULL; 34 | } 35 | }; 36 | 37 | int main() { 38 | vector > arr{ 39 | {1, 2, 3, 4, 5,}, 40 | {1, 2, 3, 4, 5, 6}, 41 | {1}, 42 | {1, 2}, 43 | {} 44 | }; 45 | Solution sol; 46 | for (auto v : arr) { 47 | ListNode *head = list_from_array(v.data(), v.size()); 48 | print_list(head); 49 | sol.reorderList(head); 50 | print_list(head); 51 | } 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /leetcode/restore-ip-address.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param s, a string 3 | # @return a list of strings 4 | def restoreIpAddresses(self, s): 5 | self.solution = [] 6 | self.prefix = [] 7 | self.getIPAddress(s, 4) 8 | return self.solution 9 | 10 | def valid(self, s): 11 | if not s: 12 | return False 13 | if len(s) > 1 and s[0] == '0': 14 | return False 15 | num = int(s) 16 | return True if num >= 0 and num <= 255 else False 17 | 18 | def getIPAddress(self, s, depth): 19 | # depth: 20 | # 4 3 2 1 21 | # 255.255.255.0 22 | if depth == 1 and self.valid(s): 23 | self.solution.append('.'.join(self.prefix + [s])) 24 | # print 'found %s' % self.solution[-1] 25 | return 26 | elif depth > 1: 27 | length = 1 28 | while length <= len(s) and self.valid(s[0:length]): 29 | self.prefix.append(s[0:length]) 30 | # wait = raw_input() 31 | # print 'adding %s, depth = %d' % (s[0:length], depth) 32 | # print self.prefix 33 | self.getIPAddress(s[length:], depth-1) 34 | self.prefix.pop() 35 | length += 1 36 | 37 | sol = Solution() 38 | l = sol.restoreIpAddresses('010010') 39 | print l -------------------------------------------------------------------------------- /leetcode/reverse-linked-list-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *reverseBetween(ListNode *head, int m, int n) { 6 | if (head == NULL) return NULL; 7 | 8 | ListNode *old_tail = NULL, *rhead = head; 9 | 10 | // search for reverse start point 11 | int i = 1; 12 | while (i < m) { 13 | ++i; 14 | old_tail = rhead; 15 | rhead = rhead->next; 16 | } 17 | 18 | // start to reverse 19 | ListNode *q = NULL, *p = rhead, *r = NULL; 20 | while (i <= n) { 21 | ++i; 22 | r = q; 23 | q = p; 24 | p = p->next; 25 | q->next = r; 26 | } 27 | 28 | // q points to the tail of reverse list 29 | if (old_tail != NULL) { 30 | old_tail->next = q; 31 | } else { 32 | // m = 1 33 | head = q; 34 | } 35 | 36 | rhead->next = p; 37 | 38 | return head; 39 | } 40 | 41 | }; 42 | 43 | int main() { 44 | ListNode nodes[5]; 45 | int i; 46 | for (i = 0; i < 4; ++i) 47 | { 48 | nodes[i].val = i+1; 49 | nodes[i].next = &nodes[i+1]; 50 | } 51 | nodes[i].val = i+1; 52 | Solution sol; 53 | ListNode *head = &nodes[0]; 54 | int m = 4, n = 5; 55 | print_list(head); 56 | head = sol.reverseBetween(head, m, n); 57 | print_list(head); 58 | 59 | return 0; 60 | } -------------------------------------------------------------------------------- /leetcode/reverse-words-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | void reverseWords(string &s) { 7 | stringstream ss(s); 8 | string word; 9 | stack st; 10 | while (ss >> word) { 11 | st.push(word); 12 | } 13 | 14 | s.clear(); 15 | while (!st.empty()) { 16 | s += st.top() + " "; 17 | st.pop(); 18 | } 19 | int n = s.size(); 20 | if (n > 0) 21 | s.resize(n-1); 22 | } 23 | 24 | }; 25 | 26 | int main() { 27 | vector ss { 28 | "the sky is blue", 29 | " the sky is blue ", 30 | }; 31 | 32 | Solution sol; 33 | for (auto s : ss) { 34 | sol.reverseWords(s); 35 | cout << s << endl; 36 | } 37 | 38 | return 0; 39 | } -------------------------------------------------------------------------------- /leetcode/reverse_integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int reverse(int x) { 7 | int negative = x < 0 ? (-1) : 1; 8 | if (negative == -1) 9 | x = -x; 10 | int c = 0; 11 | while ( x > 0 ) { 12 | int r = x % 10; 13 | c = c * 10 + r; 14 | x = x / 10; 15 | } 16 | return negative * c; 17 | } 18 | }; 19 | 20 | int main(int argc, char const *argv[]) 21 | { 22 | Solution sol; 23 | cout << sol.reverse(123) << endl; 24 | cout << sol.reverse(-123) << endl; 25 | cout << sol.reverse(0) << endl; 26 | cout << sol.reverse(-0) << endl; 27 | return 0; 28 | } -------------------------------------------------------------------------------- /leetcode/reverse_linked_list_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | void reverse_print_list(ListNode *head) { 4 | if (head == NULL) return; 5 | 6 | reverse_print_list(head->next); 7 | cout << head->val << ' '; 8 | } 9 | 10 | int main() { 11 | ListNode nodes[5]; 12 | int i; 13 | for (i = 0; i < 4; ++i) 14 | { 15 | nodes[i].val = i+1; 16 | nodes[i].next = &nodes[i+1]; 17 | } 18 | nodes[i].val = i+1; 19 | ListNode *head = &nodes[0]; 20 | print_list(head); 21 | reverse_print_list(head); 22 | cout << '\n'; 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /leetcode/romain-to-integer.cpp: -------------------------------------------------------------------------------- 1 | // rule can be found here 2 | // http://www.onlineconversion.com/roman_numerals_advanced.htm 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | int getnum(char C) { 7 | int d = 0; 8 | char c = toupper(C); 9 | switch (c) { 10 | case 'I': 11 | d = 1; 12 | break; 13 | case 'V': 14 | d = 5; 15 | break; 16 | case 'X': 17 | d = 10; 18 | break; 19 | case 'L': 20 | d = 50; 21 | break; 22 | case 'C': 23 | d = 100; 24 | break; 25 | case 'D': 26 | d = 500; 27 | break; 28 | case 'M': 29 | d = 1000; 30 | break; 31 | default: 32 | break; 33 | } 34 | return d; 35 | } 36 | public: 37 | int romanToInt(string s) { 38 | int v = 0; 39 | int p = 0, q = -1; 40 | for (char c : s) { 41 | p = getnum(c); 42 | if (q != -1 && p > q) { 43 | v -= q; 44 | v += p - q; 45 | q = -1; 46 | } else { 47 | v += p; 48 | q = p; 49 | } 50 | } 51 | return v; 52 | } 53 | }; 54 | 55 | int main(int argc, char const *argv[]) 56 | { 57 | Solution sol; 58 | string s("IC"); 59 | cout << sol.romanToInt(s) << endl; 60 | return 0; 61 | } -------------------------------------------------------------------------------- /leetcode/roman-to-integer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int romanToInt(string s) { 9 | 10 | } 11 | }; 12 | 13 | int main(int argc, char const *argv[]) 14 | { 15 | string s = "xxxi"; 16 | cout << romanToInt(s) << endl; 17 | return 0; 18 | } -------------------------------------------------------------------------------- /leetcode/rotate-image.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | #include "array2D.hpp" 3 | 4 | class Solution { 5 | public: 6 | void rotate(vector > &matrix) { 7 | int n = matrix.size(); 8 | for (int i = 0; i < (n)/2; ++i) { 9 | int m = n - 1 - i; 10 | for (int j = i; j < m; ++j) { 11 | int &a = matrix[i][j]; 12 | int &b = matrix[j][m]; 13 | int &c = matrix[m][m-j+i]; 14 | int &d = matrix[m-j+i][i]; 15 | int tmp = d; 16 | d = c; 17 | c = b; 18 | b = a; 19 | a = tmp; 20 | } 21 | } 22 | } 23 | }; 24 | 25 | int main() { 26 | const int n = 5; 27 | int A[][n] = { 28 | {1, 2, 3, 4, 5}, 29 | {6, 7, 8, 9, 10}, 30 | {11, 12, 13, 14, 15}, 31 | {16, 17, 18, 19, 20}, 32 | }; 33 | 34 | int m = sizeof(A) / sizeof(int [n]); 35 | auto matrix = fromCArray ((int*)A, m, n); 36 | print_2D(matrix); 37 | cout << '\n'; 38 | 39 | Solution sol; 40 | sol.rotate(matrix); 41 | print_2D(matrix); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /leetcode/rotate-list.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | ListNode *rotateRight(ListNode *head, int k) { 6 | 7 | // get the length of list 8 | int len = 0; 9 | ListNode *p = head, *tail = NULL; 10 | while (p != NULL) { 11 | ++len; 12 | tail = p; 13 | p = p->next; 14 | } 15 | 16 | // handle trivial cases 17 | if (len <= 1 || k % len == 0) return head; 18 | 19 | int idx = len - (k % len); 20 | ListNode *newhead = head, *newtail = NULL; 21 | while (idx > 0) { 22 | newtail = newhead; 23 | newhead = newhead->next; 24 | --idx; 25 | } 26 | 27 | tail->next = head; 28 | newtail->next = NULL; 29 | return newhead; 30 | } 31 | }; 32 | 33 | int main() { 34 | Solution sol; 35 | vector nodes { 36 | 1, 2, 3, 4, 5, 37 | }; 38 | 39 | int n = 10; 40 | for (int i = 0; i < n; ++i) { 41 | vector cp(nodes); 42 | for (int j = 0; j < cp.size() - 1; ++j) { 43 | cp[j].next = &cp[j+1]; 44 | } 45 | printf("k=%d\n", i); 46 | ListNode *head = &cp[0]; 47 | print_list(head); 48 | head = sol.rotateRight(head, i); 49 | print_list(head); 50 | } 51 | 52 | return 0; 53 | } -------------------------------------------------------------------------------- /leetcode/same_tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct TreeNode { 5 | int val; 6 | TreeNode *left; 7 | TreeNode *right; 8 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | bool isSameTree(TreeNode *p, TreeNode *q) { 14 | if (p == NULL && q == NULL) 15 | return true; 16 | else if (p == NULL || q == NULL) 17 | return false; 18 | 19 | return p->val == q->val && 20 | isSameTree(p->left, q->left) && 21 | isSameTree(p->right, q->right); 22 | } 23 | }; 24 | 25 | int main() { 26 | TreeNode* root = new TreeNode(1); 27 | TreeNode* a = new TreeNode(1); 28 | TreeNode* b = new TreeNode(1); 29 | root->left = a; root->right = b; 30 | 31 | TreeNode* c = new TreeNode(1); 32 | TreeNode* d = new TreeNode(1); 33 | TreeNode* e = new TreeNode(1); 34 | 35 | a->left = c; 36 | c->right = d; 37 | b->right = e; 38 | 39 | Solution sol; 40 | cout << sol.isSameTree(root, root) << endl; 41 | cout << sol.isSameTree(NULL, root) << endl; 42 | cout << sol.isSameTree(a, b) << endl; 43 | cout << sol.isSameTree(c, b) << endl; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /leetcode/search-for-a-range.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector searchRange(int A[], int n, int target) { 6 | int l = bsearch(A, 0, n-1, target); 7 | if ( l >= n || A[l] != target ) { 8 | return vector{-1, -1}; 9 | } 10 | 11 | int r = bsearch(A, 0, n-1, target+1); 12 | return vector{l, r-1}; 13 | } 14 | 15 | // return index of the leftmost target, or the insert position 16 | int bsearch(int A[], int b, int e, int target) { 17 | if (b > e) return e+1; 18 | 19 | int m = (b+e) / 2; 20 | if (A[m] == target) { 21 | int l = bsearch(A, b, m-1, target); 22 | if (l != -1) 23 | return l; 24 | else 25 | return m; 26 | } else if (A[m] < target) { 27 | return bsearch(A, m+1, e, target); 28 | } else { 29 | return bsearch(A, b, m-1, target); 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | Solution sol; 36 | int A[] = {5, 7, 8, 8, 8, 8, 9, 10}; 37 | int target = 8; 38 | int n = sizeof(A) / sizeof(int); 39 | auto result = sol.searchRange(A, n, target); 40 | printf("%d, %d\n", result[0], result[1]); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /leetcode/search-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | // good question! think and practice again 2 | // it's like a generalization of b-search 3 | #include "leetcode.h" 4 | 5 | class Solution { 6 | public: 7 | int search(int A[], int n, int target) { 8 | int b = 0, e = n-1; 9 | while (b <= e) { 10 | int m = (b+e) / 2; 11 | if (A[m] == target) { 12 | return m; 13 | } 14 | 15 | if (A[b] <= A[m]) { 16 | if ( A[b] <= target && target <= A[m] ) { 17 | e = m-1; 18 | } else { 19 | b = m+1; 20 | } 21 | } else { // A[b] > A[m] 22 | if (A[m] <= target && target <= A[e]) { 23 | b = m+1; 24 | } else { 25 | e = m-1; 26 | } 27 | } 28 | } // while 29 | return -1; 30 | } 31 | }; 32 | 33 | int main(int argc, char const *argv[]) 34 | { 35 | int A[] = {4, 5, 6, 7, 0, 1, 2, 3}; 36 | // int A[] = {0, 1, 2, 3, 4, 5, 6, 7, }; 37 | // int A[] = {0}; 38 | // int A[] = {}; 39 | int n = sizeof(A) / sizeof(int); 40 | Solution sol; 41 | for (int i = -3; i < n + 3; ++i) { 42 | cout << sol.search(A, n, i) << endl; 43 | } 44 | 45 | return 0; 46 | } -------------------------------------------------------------------------------- /leetcode/search-insert-position.cpp: -------------------------------------------------------------------------------- 1 | // http://oj.leetcode.com/problems/search-insert-position/ 2 | 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int searchInsert(int A[], int n, int target) { 9 | if (n <= 0) return 0; 10 | int b = 0, e = n - 1; 11 | while (b < e) { 12 | int mid = (b+e)/2; 13 | if (A[mid] == target) 14 | return mid; 15 | else if (A[mid] < target) { 16 | b = mid + 1; 17 | } else { 18 | e = mid - 1; 19 | } 20 | } 21 | 22 | // b == e 23 | int ret; 24 | if (A[b] == target) 25 | ret = b; 26 | else if (A[b] < target) 27 | ret = b + 1; 28 | else 29 | ret = b; 30 | 31 | return ret; 32 | } 33 | }; 34 | 35 | int main(int argc, char const *argv[]) 36 | { 37 | Solution sol; 38 | int A[] = {1,3,5,6}; 39 | cout << sol.searchInsert(A, 4, 5) << endl; 40 | cout << sol.searchInsert(A, 4, 2) << endl; 41 | cout << sol.searchInsert(A, 4, 7) << endl; 42 | cout << sol.searchInsert(A, 4, 0) << endl; 43 | cout << sol.searchInsert(A, 4, 1) << endl; 44 | 45 | int B[] = {1, 3}; 46 | cout << sol.searchInsert(B, 2, 2) << endl; 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/serialize_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | int main(int argc, char const *argv[]) 4 | { 5 | 6 | TreeNode nodes[] = { 7 | TreeNode(1), // 0 8 | TreeNode(2), TreeNode(2), // 1, 2 9 | TreeNode(3), TreeNode(3), // 3, 4 10 | TreeNode(4), TreeNode(4), // 5, 6 11 | }; 12 | nodes[0].left = &nodes[1]; 13 | nodes[0].right = &nodes[2]; 14 | nodes[1].left = &nodes[3]; 15 | nodes[1].right = &nodes[5]; 16 | nodes[2].left = &nodes[6]; 17 | nodes[2].right = &nodes[4]; 18 | 19 | TreeNode *root = &nodes[0]; 20 | preorder_cout(root); 21 | 22 | serialize_tree("tmp.txt", root); 23 | TreeNode *read = deserialize_tree("tmp.txt"); 24 | preorder_cout(read); 25 | 26 | read = deserialize_tree(string("1 2 # # 3 4 # 5 # #")); 27 | preorder_cout(read); 28 | inorder_cout(read); 29 | return 0; 30 | } -------------------------------------------------------------------------------- /leetcode/single-number-ii.cpp: -------------------------------------------------------------------------------- 1 | // http://oj.leetcode.com/discuss/857/constant-space-solution 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public:; 7 | int singleNumber(int A[], int n) { 8 | // ones: appeared exactly once 9 | // twos: appeared exactly twice 10 | // threes: appeared exactly three times 11 | int ones = 0, twos = 0, threes = 0; 12 | for (int i = 0; i < n; ++i) { 13 | int tmp = twos; 14 | threes = twos & A[i]; 15 | twos |= ones & A[i]; // ones & A[i]: increment to two 16 | twos &= ~threes; // remove threes 17 | ones = (ones ^ A[i]) & ~tmp; 18 | } 19 | return ones; 20 | } 21 | }; 22 | 23 | int main(int argc, char const *argv[]) 24 | { 25 | // int A[] = {1, 2, 3, 1, 4, 2, 3, 1, 2, 3}; 26 | // int A[] = {4}; 27 | // int A[] = {4, 1, 1, 1}; 28 | int n = sizeof(A) / sizeof(n); 29 | Solution sol; 30 | cout << sol.singleNumber(A, n) << endl; 31 | return 0; 32 | } -------------------------------------------------------------------------------- /leetcode/single_number.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | int singleNumber(int A[], int n) { 7 | int a = A[0]; 8 | for (int i = 1; i < n; ++i) 9 | { 10 | a ^= A[i]; 11 | } 12 | return a; 13 | } 14 | }; 15 | 16 | int main() { 17 | Solution sol; 18 | int A[] = {1, 2, 3, 4, 5, 4, 3, 2, 1}; 19 | cout << sol.singleNumber(A, 10) << endl; 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /leetcode/sqrtx.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class SolutionV2 { 5 | public: 6 | int sqrt(int x) { 7 | if (x <= 0) return 0; 8 | 9 | int b = 1, e = x, ans = 0; 10 | while (b <= e) { 11 | int m = b + (e - b) / 2; // prevent overflow 12 | if (m <= x / m) { 13 | ans = m; 14 | b = m + 1; 15 | } else 16 | e = m - 1; 17 | } 18 | 19 | return ans; 20 | } 21 | }; 22 | 23 | class Solution { 24 | public: 25 | int sqrt(int x) { 26 | if (x < 0) return 0; 27 | if (x <= 1) return x; 28 | 29 | int l = 1, r = (1<<16)-1; 30 | do { 31 | unsigned int mid = l + (r - l) / 2; 32 | unsigned int sq = mid * mid; 33 | // printf("%d %d\n", mid, sq); 34 | if (sq == x) 35 | return mid; 36 | else if (sq > x) { 37 | r = mid; 38 | } else { 39 | l = mid; 40 | } 41 | } while (l < r - 1); 42 | return l; 43 | } 44 | }; 45 | 46 | int main() { 47 | Solution sol; 48 | 49 | int n = 100; 50 | for (int i = 0; i <= n; ++i) { 51 | int xx = sol.sqrt(i); 52 | printf("%d^2 <= %d\n", xx, i); 53 | } 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /leetcode/subsets-ii.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | #include "array2D.hpp" 4 | 5 | class Solution { 6 | set > result; 7 | public: 8 | vector > subsetsWithDup(vector &S) { 9 | vector prefix; 10 | sort(S.begin(), S.end()); 11 | 12 | subsets(S, prefix, -1); 13 | vector > ret(result.begin(), result.end()); 14 | return ret; 15 | } 16 | 17 | void subsets(vector &S, vector &prefix, int depth) { 18 | if (depth == S.size()) return; 19 | 20 | if (depth != -1) { 21 | prefix.push_back(S[depth]); 22 | } 23 | result.insert(prefix); 24 | 25 | for (int i = depth+1; i < S.size(); ++i) { 26 | subsets(S, prefix, i); 27 | } 28 | 29 | if (!prefix.empty()) 30 | prefix.pop_back(); 31 | } 32 | }; 33 | 34 | int main() { 35 | Solution sol; 36 | // int A[] = {}; 37 | int A[] = {1, 2, 2}; 38 | int n = sizeof(A) / sizeof(int); 39 | vector S(A, A+n); 40 | auto result = sol.subsetsWithDup(S); 41 | cout << "Total = " << result.size() << endl; 42 | print_2D(result); 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /leetcode/subsets.cpp: -------------------------------------------------------------------------------- 1 | // this can be done iteratively, like DP 2 | // think and practice again 3 | // http://oj.leetcode.com/discuss/15/how-to-adapt-subsets-i-solution-to-subsets-ii-problem 4 | 5 | #include "leetcode.h" 6 | #include "array2D.hpp" 7 | 8 | class Solution { 9 | vector > result; 10 | public: 11 | vector > subsets(vector &S) { 12 | vector prefix; 13 | sort(S.begin(), S.end()); 14 | // result.push_back(prefix); 15 | 16 | subsets(S, prefix, -1); 17 | return result; 18 | } 19 | 20 | void subsets(vector &S, vector &prefix, int depth) { 21 | if (depth == S.size()) return; 22 | 23 | if (depth != -1) { 24 | prefix.push_back(S[depth]); 25 | } 26 | result.push_back(prefix); 27 | 28 | for (int i = depth+1; i < S.size(); ++i) { 29 | subsets(S, prefix, i); 30 | } 31 | 32 | if (!prefix.empty()) 33 | prefix.pop_back(); 34 | } 35 | }; 36 | 37 | int main() { 38 | Solution sol; 39 | // int A[] = {}; 40 | int A[] = {1, 2, 2}; 41 | int n = sizeof(A) / sizeof(int); 42 | vector S(A, A+n); 43 | auto result = sol.subsets(S); 44 | cout << "Total = " << result.size() << endl; 45 | print_2D(result); 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/thread.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | const int nthread = 10; 13 | mutex mtx; // for synchronzied IO 14 | atomic counter (0); 15 | vector call_count(nthread); 16 | 17 | void increment_count(int thread_id) { 18 | // auto id = this_thread::get_id(); 19 | while (counter < 100) { 20 | this_thread::sleep_for(chrono::seconds(rand() % 5)); 21 | mtx.lock(); 22 | cout << "Thread " << thread_id << " incrementing counter to " << ++counter << endl; 23 | ++call_count[thread_id]; 24 | mtx.unlock(); 25 | } 26 | } 27 | 28 | int main(int argc, char const *argv[]) 29 | { 30 | vector pool; 31 | for (int i = 0; i < nthread; ++i) { 32 | pool.push_back(thread(increment_count, i)); 33 | } 34 | 35 | for (int i = 0; i < nthread; ++i) { 36 | pool[i].join(); 37 | } 38 | 39 | cout << "Call count for threads:\n"; 40 | copy(call_count.begin(), call_count.end(), 41 | ostream_iterator(cout, " ")); 42 | cout << '\n'; 43 | return 0; 44 | } -------------------------------------------------------------------------------- /leetcode/tree_graphviz.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | int main() { 4 | string str; 5 | getline(cin, str); 6 | TreeNode *root = deserialize_tree_level(str); 7 | dump_tree_graphviz("tree", root); 8 | 9 | return 0; 10 | } -------------------------------------------------------------------------------- /leetcode/triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | #include "array2D.hpp" 3 | 4 | class Solution { 5 | public: 6 | int minimumTotal(vector > &triangle) { 7 | int n = triangle.size(); 8 | if (n == 0) return 0; 9 | if (n == 1) return triangle[0][0]; 10 | 11 | vector p(n), q(n); 12 | q[0] = triangle[0][0]; 13 | int min = 9999; 14 | for (int i = 1; i < n; ++i) { 15 | int m = triangle[i].size(); 16 | p[0] = q[0] + triangle[i][0]; 17 | p[m-1] = q[m-2] + triangle[i][m-1]; 18 | min = std::min(p[0], p[m-1]); 19 | for (int j = 1; j < m-1; ++j) { 20 | p[j] = std::min(q[j-1], q[j]) + triangle[i][j]; 21 | if (p[j] < min) 22 | min = p[j]; 23 | } 24 | q = p; 25 | } // for 26 | 27 | return min; 28 | } 29 | }; 30 | 31 | int main() { 32 | // Array2D::type triangle = { 33 | // {2}, 34 | // {3,4}, 35 | // {6,5,7}, 36 | // {4,1,8,3} 37 | // }; 38 | Array2D::type triangle = { 39 | {3}, 40 | {3,3}, 41 | {3,3,3}, 42 | {1,3,3,2} 43 | }; 44 | Solution sol; 45 | int result = sol.minimumTotal(triangle); 46 | cout << result << endl; 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /leetcode/two-sum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | vector twoSum(vector &numbers, int target) { 7 | unordered_map idx; 8 | for (int i = 0; i < numbers.size(); ++i) { 9 | idx[numbers[i]] = i; 10 | } 11 | 12 | for (int i = 0; i < numbers.size(); ++i) 13 | { 14 | int r = target - numbers[i]; 15 | int j; 16 | if (idx.find(r) != idx.end() && (j = idx[r]) != i) { 17 | int j = idx[r]; 18 | if (i > j) 19 | swap(i, j); 20 | return vector {i+1, j+1}; 21 | } 22 | } 23 | return vector{0, 0}; 24 | } 25 | }; 26 | 27 | int main() { 28 | Solution sol; 29 | // vector numbers{2, 7, 11, 15}; 30 | // vector numbers{7, 2, 11, 15}; 31 | vector numbers{3,2,4}; 32 | int target = 6; 33 | auto result = sol.twoSum(numbers, target); 34 | printf("%d %d\n", result[0], result[1]); 35 | return 0; 36 | } -------------------------------------------------------------------------------- /leetcode/unique-binary-search-trees-ii.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | vector generateTrees(int n) { 6 | return generateTrees(1, n); 7 | } 8 | 9 | vector generateTrees(int b, int e) { 10 | vector result; 11 | if (b>e) result.push_back(NULL); 12 | 13 | for (int i = b; i <= e; ++i) { 14 | auto left = generateTrees(b, i-1); 15 | auto right = generateTrees(i+1, e); 16 | for (auto l : left) { 17 | for (auto r : right) { 18 | TreeNode *root = new TreeNode(i); 19 | root->left = l; 20 | root->right = r; 21 | result.push_back(root); 22 | } 23 | } 24 | } 25 | 26 | return result; 27 | } 28 | }; 29 | 30 | int main() { 31 | Solution sol; 32 | auto result = sol.generateTrees(0); 33 | for (auto root : result) { 34 | preorder_cout(root); 35 | } 36 | 37 | return 0; 38 | } -------------------------------------------------------------------------------- /leetcode/unique-paths.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | int uniquePaths(int m, int n) { 6 | if (m <= 0 || n <= 0) return 0; 7 | vector> D(m+1, vector(n+1, 0)); 8 | for (int i = 1; i <= m; ++i) { 9 | for (int j = 1; j <= n; ++j) { 10 | if (i == 1 && j == 1) { 11 | D[i][j] = 1; 12 | continue; 13 | } 14 | D[i][j] = D[i-1][j] + D[i][j-1]; 15 | } 16 | } 17 | return D[m][n]; 18 | } 19 | }; 20 | 21 | class Solution { 22 | int array[105][105]; 23 | public: 24 | int uniquePaths(int m, int n) { 25 | array[0][0] = 1; 26 | for (int i = 0; i < m; ++i) 27 | { 28 | for (int j = 0; j < n; ++j) { 29 | if (i - 1 >= 0) 30 | array[i][j] += array[i-1][j]; 31 | if (j - 1 >= 0) 32 | array[i][j] += array[i][j-1]; 33 | } 34 | } // for 35 | 36 | return array[m-1][n-1]; 37 | } 38 | }; 39 | 40 | int main(int argc, char const *argv[]) 41 | { 42 | Solution sol; 43 | int m = 3, n = 3; 44 | cout << sol.uniquePaths(m, n) << '\n'; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /leetcode/unique_bst.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | public: 6 | const static int MAX = 10000; 7 | int numTrees(int n) { 8 | int a[MAX]; 9 | a[0] = 1; 10 | a[1] = 1; 11 | a[2] = 2; 12 | 13 | for (int j = 3; j <= n; ++j) { 14 | int sum = 0; 15 | for (int i = 0; i <= (j-2) / 2; ++i) 16 | { 17 | sum += a[i] * a[j-1-i]; 18 | } 19 | a[j] = 2 * sum; 20 | if (j % 2 != 0) { 21 | int t = a[(j-1)/2]; 22 | a[j] += t * t; 23 | } 24 | } 25 | 26 | return a[n]; 27 | } 28 | }; 29 | 30 | int main(int argc, char const *argv[]) 31 | { 32 | Solution sol; 33 | cout << sol.numTrees(3) << endl; 34 | cout << sol.numTrees(4) << endl; 35 | cout << sol.numTrees(5) << endl; 36 | return 0; 37 | } -------------------------------------------------------------------------------- /leetcode/valid-palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | bool isPalindrome(string s) { 7 | if (s.empty()) return true; 8 | 9 | int n = s.size(); 10 | int i = 0, j = n - 1; 11 | while (i <= j) { 12 | if (!isalnum(s[i])) { 13 | ++i; 14 | continue; 15 | } 16 | if (!isalnum(s[j])) { 17 | --j; 18 | continue; 19 | } 20 | if (tolower(s[i]) != tolower(s[j])) 21 | return false; 22 | 23 | ++i; 24 | --j; 25 | } 26 | 27 | return true; 28 | } 29 | }; 30 | 31 | int main() { 32 | Solution sol; 33 | vector str { 34 | "A man, a plan, a canal: Panama", 35 | "", 36 | "a", 37 | ".", 38 | ".a", 39 | "a.a", 40 | "race a car" 41 | }; 42 | 43 | for (auto &s : str) { 44 | cout << sol.isPalindrome(s) << '\n'; 45 | } 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | bool isValid(string s) { 7 | stack st; 8 | for (char c : s) { 9 | if (c == '(' || c == '[' || c == '{') 10 | st.push(c); 11 | else { 12 | if (st.empty()) 13 | return false; 14 | char l = st.top(); 15 | if ((l == '(' && c == ')') || 16 | (l == '[' && c == ']') || 17 | (l == '{' && c == '}')) 18 | st.pop(); 19 | else 20 | return false; 21 | } 22 | } // for 23 | if (!st.empty()) 24 | return false; 25 | 26 | return true; 27 | } 28 | }; 29 | 30 | int main(int argc, char const *argv[]) 31 | { 32 | string s[] = { 33 | "()", 34 | "()[]{}", 35 | "(]", 36 | "([)]", 37 | "", 38 | "(", 39 | "]", 40 | "{}{}{{{{[[[((()))]]]}}}}", 41 | "{}{}{{{{[[[(((])))]]]}}}}", 42 | }; 43 | Solution sol; 44 | for (string str : s) { 45 | cout << str << ": " << sol.isValid(str) << endl; 46 | } 47 | return 0; 48 | } -------------------------------------------------------------------------------- /leetcode/validate-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "leetcode.h" 3 | 4 | class Solution { 5 | public: 6 | bool isValidBST(TreeNode *root) { 7 | int low = numeric_limits::min(); 8 | int high = numeric_limits::max(); 9 | return isValidBST(root, low, high); 10 | } 11 | 12 | bool isValidBST(TreeNode *root, int low, int high) { 13 | if (root == NULL) return true; 14 | 15 | if (root->val <= low || root->val >= high) 16 | return false; 17 | 18 | return isValidBST(root->left, low, root->val) && 19 | isValidBST(root->right, root->val, high); 20 | } 21 | }; 22 | 23 | int main() { 24 | vector trees = { 25 | "9 5 3 # # 7 6 # # 8 # # #", 26 | "9 5 3 # # 7 6 # # 8 # # 12 10 # 11 # # 13 # #", 27 | "1 2 3 # # # #", 28 | "3 2 1 # # # #", 29 | "#", 30 | "1 # #", 31 | "3 1 # # 2 # #", 32 | "2 1 # # 3 # #", 33 | }; 34 | Solution sol; 35 | 36 | for (auto tree : trees) { 37 | TreeNode *root = deserialize_tree(tree); 38 | cout << sol.isValidBST(root) << '\n'; 39 | } 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /leetcode/zigzag-conversion.cpp: -------------------------------------------------------------------------------- 1 | #include "leetcode.h" 2 | 3 | class Solution { 4 | public: 5 | string convert(string s, int nRows) { 6 | if (s == "" || nRows == 1) return s; 7 | 8 | vector rows(nRows); 9 | 10 | int r = 0; 11 | int dir = 1; 12 | for (int i = 0; i < s.size(); ++i) { 13 | rows[r].push_back(s[i]); 14 | r += dir; 15 | if (r == nRows-1 || r == 0) 16 | dir *= -1; 17 | } 18 | 19 | string result; 20 | for (auto &s : rows) { 21 | result += s; 22 | } 23 | 24 | return result; 25 | } 26 | }; 27 | 28 | int main() { 29 | Solution sol; 30 | vector str { 31 | "PAYPALISHIRING", 32 | "P", 33 | "", 34 | }; 35 | 36 | for (auto s : str) { 37 | for (int i = 1; i <= s.size()+5; ++i) { 38 | printf("%d : %s\n", i, sol.convert(s, i).c_str()); 39 | } 40 | } 41 | 42 | 43 | return 0; 44 | } -------------------------------------------------------------------------------- /leetcode/zip.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | template 9 | auto zip(const T&... containers) -> boost::iterator_range> 10 | { 11 | auto zip_begin = boost::make_zip_iterator(boost::make_tuple(std::begin(containers)...)); 12 | auto zip_end = boost::make_zip_iterator(boost::make_tuple(std::end(containers)...)); 13 | return boost::make_iterator_range(zip_begin, zip_end); 14 | } 15 | 16 | int main(int argc, char const *argv[]) 17 | { 18 | std::vector a {4, 5, 6}; 19 | double b[] = {7, 8, 9}; 20 | std::list c {"a", "b", "c"}; 21 | for (auto tup : zip(a, b, c, a)) 22 | { 23 | int x, w; 24 | double y; 25 | std::string z; 26 | boost::tie(x, y, z, w) = tup; 27 | printf("%d %g %s %d\n", x, y, z.c_str(), w); 28 | } 29 | return 0; 30 | } -------------------------------------------------------------------------------- /quadtree/Makefile: -------------------------------------------------------------------------------- 1 | main: 2 | g++ -o quadtree_demo main.cpp quadtree.cpp 3 | -------------------------------------------------------------------------------- /quadtree/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #include "quadtree.h" 5 | 6 | int main(int argc, const char *argv[]) 7 | { 8 | Point zero(0,0); 9 | Box box(zero, 50, 50); 10 | Point pts[] = {Point(10, 10), 11 | Point(20, 20), 12 | Point(-10, -40), 13 | Point(-10, 35), 14 | Point(15, -20), 15 | Point(-5, 25), 16 | Point(30, -40) 17 | }; 18 | 19 | QuadTree* tree = new QuadTree(box); 20 | 21 | int numPoints = sizeof(pts) / sizeof(Point); 22 | for (int i = 0; i < numPoints; ++i) 23 | tree->insertPoint(pts[i]); 24 | 25 | cout << "Insert center x, y, half width, half height: " ; 26 | double x, y, hw, hh; 27 | cin >> x >> y >> hw >> hh; 28 | vector ret = tree->queryRange(Box(Point(x, y), hw, hh)); 29 | 30 | for (int i = 0; i < ret.size(); i++) { 31 | cout << " (" << ret[i].x_ << ", " << ret[i].y_ << ")"; 32 | } 33 | cout << endl; 34 | 35 | delete tree; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /quadtree/quadtree.h: -------------------------------------------------------------------------------- 1 | #ifndef QUADTREE_X5BFPQGD 2 | 3 | #define QUADTREE_X5BFPQGD 4 | 5 | #include 6 | using namespace std; 7 | 8 | class Point { 9 | public: 10 | Point(double x, double y): x_(x), y_(y) {} 11 | double x_, y_; 12 | }; 13 | 14 | class Box { 15 | public: 16 | Box(Point center, double half_width, double half_height): 17 | center_(center), half_width_(half_width), half_height_(half_height) {} 18 | Point center_; 19 | double half_width_, half_height_; 20 | 21 | bool containsPoint(const Point &pt) const{ 22 | return (pt.x_ >= center_.x_ - half_width_) && 23 | (pt.x_ <= center_.x_ + half_width_) && 24 | (pt.y_ >= center_.y_ - half_height_) && 25 | (pt.y_ <= center_.y_ + half_height_); 26 | } 27 | }; 28 | 29 | const int MAX_POINTS = 4; 30 | class QuadTree { 31 | public: 32 | QuadTree(const Box &box) : box_(box){} 33 | ~QuadTree() {deleteSelf();} 34 | 35 | bool insertPoint(const Point &pt); 36 | vector queryRange(const Box &range); 37 | 38 | vector plist_; 39 | Box box_; 40 | 41 | QuadTree* NW_; 42 | QuadTree* NE_; 43 | QuadTree* SW_; 44 | QuadTree* SE_; 45 | 46 | private: 47 | void deleteSelf(); 48 | void splitSelf(); 49 | }; 50 | 51 | #endif /* end of include guard: QUADTREE_X5BFPQGD */ 52 | -------------------------------------------------------------------------------- /rmbin.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | find . -name "*.out" -exec rm {} \; 4 | -------------------------------------------------------------------------------- /sample_proc/01bag/01bag.cpp: -------------------------------------------------------------------------------- 1 | // 0-1背包问题 2 | #include 3 | #include 4 | 5 | const int MAXM = 100; 6 | const int MAXN = 100; 7 | int m; // the capibility of the bag 8 | int n; // number of the items 9 | int w[MAXN+1]; // weight 10 | int p[MAXN+1]; // price 11 | int dp[MAXM+1][MAXN+1]; 12 | int select[MAXN+1]; 13 | 14 | int main() 15 | { 16 | FILE * f = freopen("data.in","r",stdin); 17 | fscanf(f,"%d %d",&m,&n); 18 | int i,j; 19 | for(i=1;i<=n;i++) fscanf(f,"%d",&w[i]); 20 | for(i=1;i<=n;i++) fscanf(f,"%d",&p[i]); 21 | // init 22 | for(i=0;i<=m;i++) dp[i][0] = 0; 23 | for(j=0;j<=n;j++) dp[0][j] = 0; 24 | 25 | for(i=1;i<=m;i++) 26 | { 27 | for(j=1;j<=n;j++) 28 | { 29 | if( i dp[i][j-1] ) dp[i][j] = temp; 35 | else dp[i][j] = dp[i][j-1]; 36 | } 37 | } 38 | } 39 | 40 | i=m;j=n; 41 | memset(select,0,sizeof(select)); 42 | while(i>0 && j>0) 43 | { 44 | if( dp[i][j] > dp[i][j-1] ) 45 | { 46 | select[j] = 1; 47 | i-=w[j]; 48 | } 49 | j--; 50 | } 51 | // back track to see which item has been chosed 52 | printf("%d\n",dp[m][n]); 53 | for(i=1;i<=n;i++) printf("%d ",select[i]); 54 | printf("\n"); 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /sample_proc/01bag/data.in: -------------------------------------------------------------------------------- 1 | 15 6 2 | 5 3 7 2 3 4 3 | 3 6 5 4 3 4 4 | 22 5 5 | 3 5 7 8 9 6 | 4 6 7 9 10 7 | 10 5 8 | 2 2 6 5 4 9 | 6 3 5 4 6 10 | -------------------------------------------------------------------------------- /sample_proc/Makefile: -------------------------------------------------------------------------------- 1 | CC=/usr/bin/gcc 2 | out := ${FILE:.cpp,.c=} 3 | 4 | default: 5 | echo $(out) 6 | .phony clean: 7 | rm -rf *.out 8 | -------------------------------------------------------------------------------- /sample_proc/dis_sum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int N=100; 4 | 5 | int max(int a,int b){return a>b? a:b;} 6 | 7 | int main(){ 8 | int a[N]; 9 | int i,n; 10 | scanf("%d",&n); 11 | for(i=0;i=q ) { 17 | if( a[i]+q>=p ){ //max is a[i]+q 18 | pi=1; 19 | t=a[i]+q; 20 | } 21 | else{ // max is p 22 | pi=0; 23 | t=p; 24 | } 25 | } 26 | else{ 27 | if( q>=p ){// max is q 28 | pi=0; 29 | t=q; 30 | } 31 | else{// max is p 32 | pi=0; 33 | t=p; 34 | } 35 | } 36 | } 37 | else{// compare p is enough 38 | if( p>=a[i]+p){ 39 | t = p; 40 | pi= 0; 41 | } 42 | else{ 43 | t = a[i]+p; 44 | pi=1; 45 | } 46 | } 47 | q=p;p=t; 48 | } 49 | 50 | printf("%d\n",p); 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /sample_proc/func_ptr.cpp: -------------------------------------------------------------------------------- 1 | // 函数指针示例 2 | #include 3 | 4 | class C { 5 | public: 6 | int foo(int a){printf("foo\n");} 7 | int bar(int a){printf("bar\n");} 8 | void test() { 9 | int (C::*p)(int); 10 | p = &C::foo; 11 | p = &C::bar; 12 | (this->*p)(1); 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | C c; 19 | c.test(); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /sample_proc/knapsack.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | 5 | return 0; 6 | } 7 | -------------------------------------------------------------------------------- /sample_proc/matrix_mul_DP/data: -------------------------------------------------------------------------------- 1 | 3 2 | 3 | 10 100 5 50 4 | 5 | 4 6 | 7 | 50 10 40 30 5 8 | -------------------------------------------------------------------------------- /sample_proc/matrix_mul_DP/output: -------------------------------------------------------------------------------- 1 | Case 1 2 | 3 | 7500 (A1A2)A3 4 | 5 | Case 2 6 | 7 | 10500 A1(A2(A3A4)) 8 | -------------------------------------------------------------------------------- /sample_proc/matrix_mul_DP/problem: -------------------------------------------------------------------------------- 1 | 矩阵连乘问题 2 | 3 | 问题描述 4 | 5 | 给定n个矩阵A1,A2,…,An,其中,Ai与Aj+1是可乘的,i=1,2,…,n-1。 6 | 7 | 你的任务是要确定矩阵连乘的运算次序,使计算这n个矩阵的连乘积A1A2…An时总的元素乘法次数达到最少。 8 | 9 | 例如:3个矩阵A1,A2,A3,阶分别为10×100、100×5、5×50,计算连乘积A1A2A3时按(A1A2)A3所需的元素乘法次数达到最少,为7500次。 10 | 11 | 输入 12 | 13 | 测试数据有若干组,每组测试数据有2行。 14 | 15 | 每组测试数据的第1行是一个整数n,(0 4 | #include 5 | #include 6 | #include 7 | 8 | void print(int a[],int size) 9 | { 10 | for(int i=0;imax ) 32 | max = d[j]; 33 | } 34 | d[i]=max+1; 35 | } 36 | int max=0; 37 | for(int i=1;imax) max = d[i]; 39 | delete [] d; 40 | return max; 41 | } 42 | 43 | int main() 44 | { 45 | const int N = 15; 46 | int seq[N]={0,1,0,3,0,5,0,7,0,9,0,11,15,0}; 47 | //genRndSeq(seq,N); 48 | print(seq,N); 49 | 50 | int max=maxSubSeq(seq,N); 51 | printf("%d\n",max); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /sample_proc/max_common_sbusequence/data.in: -------------------------------------------------------------------------------- 1 | xyxzyxyzzy 2 | xzyzxyzxyzxy 3 | -------------------------------------------------------------------------------- /sample_proc/mod_exp.cpp: -------------------------------------------------------------------------------- 1 | // compute modular exponentiation: a^b mod n 2 | #include 3 | using namespace std; 4 | 5 | // input: a>=0 b>=0 n>0 6 | // output: remainder of a^b mod n 7 | unsigned int mod_exp(unsigned int a,unsigned int b,unsigned int n){ 8 | unsigned int d=1; 9 | unsigned int c=0x80000000;// 31b set to 1, others 0 10 | // search for the first non-zero bit of b 11 | while( (c&b) == 0 ) c>>=1; 12 | // traverse all the bit of b 13 | while(c>0){ 14 | d = (d*d)%n; 15 | if( (c&b) > 0){// current bit is 1 16 | d = (d*a)%n; 17 | } 18 | c>>=1; 19 | } 20 | return d; 21 | } 22 | 23 | int main(){ 24 | unsigned int a,b,n; 25 | while(cin>>a>>b>>n){ 26 | cout< 2 | #include 3 | #include 4 | #include 5 | 6 | const int MAXNUM=1000000; 7 | BYTE num[MAXNUM]; 8 | typedef char BYTE; 9 | 10 | int main(int argc,char * argv[]){ 11 | if(argc<2) { 12 | printf("Usage: sieve [n]\n"); 13 | return 1; 14 | } 15 | int n=atoi(argv[1]); 16 | if(n>MAXNUM){ 17 | printf("n < %d\n",MAXNUM); 18 | return 2; 19 | } 20 | memset(num,0,sizeof(num)); 21 | int i,j; 22 | int sqrn = sqrt(n); 23 | for(i=2;i<=sqrn;i++){ 24 | if( num[i] == 0 ){// it's a prime 25 | j=2; 26 | int mul; 27 | do{ 28 | mul=i*j; 29 | num[mul] = 1; 30 | j++; 31 | }while(mul <= n); 32 | } 33 | } 34 | for(i=2;i<=n;i++) 35 | if( num[i] == 0) 36 | printf("%d\n",i); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /sample_proc/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Member 3 | { 4 | public: 5 | virtual void answer(){printf("member\n");} 6 | }; 7 | 8 | class Teacher:public Member 9 | { 10 | public: 11 | void answer(){printf("Teacher\n");} 12 | }; 13 | 14 | class Student:public Member 15 | { 16 | public: 17 | void answer(){printf("Student\n");} 18 | }; 19 | 20 | int main() 21 | { 22 | Member m; 23 | Teacher t; 24 | Student s; 25 | Member * p = &m; 26 | p->answer(); 27 | p=&t; 28 | p->answer(); 29 | p=&s; 30 | p->answer(); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /sample_proc/two_egg.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define INF 2<<15 5 | 6 | int main(){ 7 | int d[3][105]; 8 | memset(d,0,sizeof(d)); 9 | int i,j,k; 10 | for(i=0;i<=100;i++){ 11 | d[1][i]=i; 12 | } 13 | d[2][1]=1;d[2][0]=d[1][0]=0; 14 | int min=INF,max; 15 | for(i=2;i<=2;i++) 16 | for(j=2;j<=100;j++){ 17 | min=INF; 18 | for(k=1;k<=j;k++){ 19 | int a=d[i-1][k-1]; 20 | int b=d[i][j-k]; 21 | max=(a>b?a:b); 22 | if(min>max)min=max; 23 | } 24 | d[i][j]=min+1; 25 | } 26 | for(j=1;j<=100;j++){ 27 | printf("%d %d\n",d[1][j],d[2][j]); 28 | } 29 | printf("%d\n",d[2][100]); 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /sample_proc/xor/xor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | //random-number generation functor 9 | class ExampleRnd 10 | { 11 | public: 12 | size_t operator( )(size_t n) const 13 | { return(rand( )%n ); } 14 | }; 15 | 16 | 17 | int main(int argc,char * argv[]){ 18 | srand(time(NULL)); 19 | int n=argv[1][0]-'0'; 20 | int num=atoi(argv[2]); 21 | vector v(2*n+1); 22 | int i; 23 | for(i=0;i::iterator iter = v.begin(); 31 | int temp=0; 32 | while(iter!=v.end()){ 33 | temp ^= *iter; 34 | cout<< *iter << " "; 35 | iter++; 36 | } 37 | cout< 5 | #include 6 | using std::vector; 7 | using std::numeric_limits; 8 | 9 | #include "graph.hpp" 10 | 11 | 12 | bool bellman_ford( 13 | const Graph &G, 14 | vector &dist, 15 | vector &pred) { 16 | 17 | int N = num_vertices(G); 18 | dist.assign(N, numeric_limits::max()); 19 | dist[0] = 0; 20 | pred.assign(N, -1); 21 | 22 | IndexMap index = get(vertex_index, G); 23 | auto weight = get(edge_weight, G); 24 | graph_traits::edge_iterator ei, ei_end; 25 | for (int i = 0; i < N - 1; ++i) { 26 | for (boost::tie(ei, ei_end) = edges(G); ei != ei_end; ++ei) { 27 | int u = index[source(*ei, G)]; 28 | int v = index[target(*ei, G)]; 29 | if (dist[u] != numeric_limits::max() && 30 | get(weight, *ei) + dist[u] < dist[v]) { 31 | dist[v] = get(weight, *ei) + dist[u]; 32 | pred[v] = u; 33 | } 34 | } 35 | } 36 | 37 | for (boost::tie(ei, ei_end) = edges(G); ei != ei_end; ++ei) { 38 | int u = index[source(*ei, G)]; 39 | int v = index[target(*ei, G)]; 40 | if (get(weight, *ei) + dist[u] < dist[v]) { 41 | return false; 42 | } 43 | } 44 | 45 | return true; 46 | } 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /shortest-path/dijkstra.h: -------------------------------------------------------------------------------- 1 | #ifndef __DIJKSTRA_H__ 2 | #define __DIJKSTRA_H__ 3 | 4 | #include 5 | using namespace std; 6 | 7 | void dijkstra( 8 | const vector > &graph, 9 | vector &dist, 10 | vector &path) { 11 | // assume 0 = s, n-1 = t 12 | int n = graph.size(); 13 | dist.assign(n, numeric_limits::max()); 14 | path.assign(n, -1); 15 | vector visited(n, false); 16 | dist[0] = 0; 17 | 18 | // execute n times (visit n vertices) 19 | for (int i = 0; i < n; ++i) { 20 | // find the vertices that is closest to visited set 21 | // this can be implemented using priority queue 22 | int minj = -1; 23 | int mind = numeric_limits::max(); 24 | for (int j = 0; j < n; ++j) { 25 | if (visited[j]) continue; 26 | if (dist[j] < mind) { 27 | mind = dist[j]; 28 | minj = j; 29 | } 30 | } 31 | 32 | visited[minj] = true; 33 | // update the distance from minj to its adj neighbors 34 | for (int j = 0; j < n; ++j) { 35 | if (!visited[j] && 36 | graph[minj][j] != -1 && 37 | dist[j] > dist[minj] + graph[minj][j]) { 38 | // update path to i as s->minj->j 39 | dist[j] = dist[minj] + graph[minj][j]; 40 | path[j] = minj; 41 | } 42 | } 43 | } 44 | } 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /shortest-path/graph.hpp: -------------------------------------------------------------------------------- 1 | #ifndef _GRAPH_H_ 2 | #define _GRAPH_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | using namespace boost; 8 | 9 | typedef adjacency_list > Graph; 11 | typedef std::pair Edge; 12 | typedef property_map::type IndexMap; 13 | typedef property_map::type EdgeWeightMap; 14 | 15 | #endif 16 | -------------------------------------------------------------------------------- /sparse_matrix/COOMatrix.h: -------------------------------------------------------------------------------- 1 | #ifndef _COOMATRIX_H_ 2 | #define _COOMATRIX_H_ 3 | 4 | #include 5 | #include "sparse_matrix.h" 6 | 7 | typedef std::tuple Triplet; 8 | 9 | class COOMatrix { 10 | public: 11 | COOMatrix() : row_(0), col_(0){}; 12 | COOMatrix(const Matrix &mat); 13 | int row() {return row_;} 14 | int col() {return col_;} 15 | 16 | Matrix dense() const; 17 | COOMatrix transpose() const; 18 | 19 | vector ijv; 20 | friend COOMatrix operator * (COOMatrix &A, COOMatrix &B); 21 | private: 22 | int row_; 23 | int col_; 24 | }; 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /sparse_matrix/CSCMatrix.h: -------------------------------------------------------------------------------- 1 | #ifndef _CSCMATRIX_H_ 2 | #define _CSCMATRIX_H_ 3 | #include 4 | using std::ostream; 5 | #include "sparse_matrix.h" 6 | 7 | class CSRMatrix; 8 | class CSCMatrix { 9 | public: 10 | CSCMatrix() : rowsize(0) {} 11 | CSCMatrix(const vector> &mat) { 12 | dense2csc(mat, val, row_ind, col_ptr); 13 | if (!mat.empty()) 14 | rowsize = mat[0].size(); 15 | } 16 | 17 | CSRMatrix transpose(); 18 | vector> dense() const; 19 | 20 | int nnz() const {return val.size();} 21 | int row() const {return rowsize;} 22 | int col() const {return col_ptr.size() - 1;} 23 | 24 | vector val; 25 | vector row_ind; 26 | vector col_ptr; 27 | 28 | friend class CSRMatrix; 29 | friend CSRMatrix operator * (const CSRMatrix &A, const CSCMatrix &B); 30 | friend ostream &operator << (ostream &os, const CSCMatrix &m); 31 | 32 | private: 33 | int rowsize; 34 | }; 35 | #endif -------------------------------------------------------------------------------- /sparse_matrix/CSRMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include "CSRMatrix.h" 2 | #include "CSCMatrix.h" 3 | using std::ostream_iterator; 4 | 5 | CSCMatrix CSRMatrix::transpose() { 6 | CSCMatrix s; 7 | s.val = val; 8 | s.row_ind = col_ind; 9 | s.col_ptr = row_ptr; 10 | s.rowsize = colsize; 11 | return s; 12 | } 13 | 14 | ostream & operator << (ostream &os, const CSRMatrix &s) { 15 | os << s.row() << " x " << s.col(); 16 | os << "\nval: "; 17 | copy(s.val.begin(), s.val.end(), 18 | ostream_iterator(os, " ")); 19 | os << "\ncol_ind: "; 20 | copy(s.col_ind.begin(), s.col_ind.end(), 21 | ostream_iterator(os, " ")); 22 | os << "\nrow_ptr: "; 23 | copy(s.row_ptr.begin(), s.row_ptr.end(), 24 | ostream_iterator(os, " ")); 25 | return os; 26 | } 27 | 28 | vector> CSRMatrix::dense() const { 29 | vector> d(row(), vector(col())); 30 | 31 | for (int i = 0; i < row_ptr.size() - 1; ++i) { 32 | for (int k = row_ptr[i]; k < row_ptr[i+1]; ++k) { 33 | d[i][col_ind[k]] = val[k]; 34 | } 35 | } 36 | return d; 37 | } 38 | -------------------------------------------------------------------------------- /sparse_matrix/CSRMatrix.h: -------------------------------------------------------------------------------- 1 | #ifndef _CSRMATRIX_H_ 2 | #define _CSRMATRIX_H_ 3 | #include "sparse_matrix.h" 4 | #include 5 | using std::ostream; 6 | 7 | class CSCMatrix; 8 | class CSRMatrix { 9 | public: 10 | CSRMatrix() : colsize(0) {} 11 | CSRMatrix(const vector> &mat) { 12 | dense2csr(mat, val, col_ind, row_ptr); 13 | if (!mat.empty()) 14 | colsize = mat[0].size(); 15 | } 16 | 17 | CSCMatrix transpose(); 18 | vector> dense() const; 19 | 20 | int nnz() const {return val.size();} 21 | int row() const {return row_ptr.size() - 1;} 22 | int col() const {return colsize;} 23 | 24 | vector val; 25 | vector col_ind; 26 | vector row_ptr; 27 | 28 | friend class CSCMatrix; 29 | friend ostream & operator << (ostream &os, const CSRMatrix &s); 30 | friend CSRMatrix operator * (const CSRMatrix &A, const CSCMatrix &B); 31 | 32 | private: 33 | int colsize; 34 | }; 35 | 36 | #endif -------------------------------------------------------------------------------- /sparse_matrix/Makefile: -------------------------------------------------------------------------------- 1 | CC=clang++ 2 | CPP=CSCMatrix.cpp CSRMatrix.cpp test_matrix.cpp sparse_matrix.cpp COOMatrix.cpp 3 | OBJ=$(CPP:.cpp=.o) 4 | CXXFLAGS=-std=c++11 5 | 6 | test-matrix: $(OBJ) 7 | clang++ -o $@ $(OBJ) 8 | 9 | %.o: %.cpp 10 | $(CC) $(CXXFLAGS) -c $< -o $@ 11 | 12 | clean: 13 | rm -rf *.o test-matrix -------------------------------------------------------------------------------- /sparse_matrix/sparse_matrix.h: -------------------------------------------------------------------------------- 1 | #ifndef _SPARSE_MATRIX_H_ 2 | #define _SPARSE_MATRIX_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | using std::vector; 8 | using std::abs; 9 | using std::ostream; 10 | 11 | #define FPRECISION 1e-6 12 | #define FZERO(x) (abs(x) < FPRECISION) 13 | 14 | typedef vector> Matrix; 15 | 16 | // dense matrix to csr 17 | void dense2csr(const Matrix &mat, 18 | vector &val, vector &col_ind, vector &row_ptr); 19 | 20 | // dense matrix to csc 21 | void dense2csc(const Matrix &mat, 22 | vector &val, vector &row_ind, vector &col_ptr); 23 | 24 | ostream &operator << (ostream &os, const Matrix &mat); 25 | 26 | #endif -------------------------------------------------------------------------------- /sparse_matrix/test_matrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #include "sparse_matrix.h" 5 | #include "CSCMatrix.h" 6 | #include "CSRMatrix.h" 7 | #include "COOMatrix.h" 8 | 9 | void test_dense2csr(const vector> &mat) { 10 | CSRMatrix s(mat); 11 | cout << s << "\n"; 12 | cout << "Dense :\n"; 13 | cout << s.dense() << "\n"; 14 | CSCMatrix t = s.transpose(); 15 | cout << t << "\n"; 16 | cout << "Dense :\n"; 17 | cout << t.dense() << "\n"; 18 | 19 | auto r = s * t; 20 | cout << "s * t:\n"; 21 | cout << r << "\n"; 22 | cout << "Dense :\n"; 23 | cout << r.dense() << "\n"; 24 | } 25 | 26 | void test_dense2csc(const vector> &mat) { 27 | CSCMatrix s(mat); 28 | 29 | cout << s.dense() << "\n"; 30 | } 31 | 32 | void test_coo(const vector> &mat) { 33 | COOMatrix s(mat); 34 | COOMatrix t = s.transpose(); 35 | cout << s.dense() << "\n"; 36 | cout << t.dense() << "\n"; 37 | cout << (s * t).dense() << "\n"; 38 | } 39 | 40 | int main(int argc, char const *argv[]) 41 | { 42 | vector> mat { 43 | {10, 0, 0, 0, -2, 0}, 44 | {3, 9, 0, 0, 0, 3}, 45 | {0, 7, 8, 7, 0, 0}, 46 | {3, 0, 8, 7, 5, 0}, 47 | {0, 8, 0, 9, 9, 13}, 48 | {0, 4, 0, 0, 2, -1}, 49 | }; 50 | 51 | test_dense2csr(mat); 52 | // test_dense2csc(mat); 53 | test_coo(mat); 54 | return 0; 55 | } -------------------------------------------------------------------------------- /system_design/search_engine/.gitignore: -------------------------------------------------------------------------------- 1 | tfidf 2 | corpus 3 | -------------------------------------------------------------------------------- /system_design/search_engine/build-index.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from os import listdir 3 | from os.path import isfile, join 4 | from collections import defaultdict 5 | import sys 6 | import pickle 7 | import math 8 | import re 9 | 10 | # build inverted index given a corpus directory 11 | 12 | # tf: reverse index and term frequency, e.g., 13 | # cat: {1.txt: 0.2, 2.txt: 0.5} 14 | 15 | # idf: inverse document frequency 16 | # idf(x) = log (Ndocs / Ndoc has x ) 17 | # e.g., 18 | # {cat: 0.5, dog: 0.2} 19 | 20 | # this is for serialization 21 | def defaultfloat(): 22 | return defaultdict(float) 23 | 24 | def build(path, output): 25 | files = [ f for f in listdir(path) if isfile(join(path,f)) ] 26 | tf = defaultdict(defaultfloat) 27 | idf = defaultdict(float) 28 | for fname in files: 29 | fullname = path + "/" + fname 30 | with open(fullname) as f: 31 | nwords = 0 32 | for line in f: 33 | for word in line.replace(',', '').split(): 34 | nwords += 1 35 | # update reverse index 36 | tf[word][fullname] = (tf[word][fullname] + 1) / nwords 37 | idf[word] = math.log(1.0 * len(files) / len(tf[word])) 38 | 39 | with open(output, 'wb') as f: 40 | pickle.dump(tf, f) 41 | pickle.dump(idf, f) 42 | 43 | 44 | if __name__ == "__main__": 45 | build(sys.argv[1], sys.argv[2]) 46 | -------------------------------------------------------------------------------- /system_design/search_engine/search.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # main features 4 | # 5 | # build-index.py build the inverted index with tf-idf, and serialize them into data 6 | # search.py computes the TF-IDF, returns the ranked documents and the score 7 | # 8 | # TODO: consider stoplist 9 | 10 | import sys 11 | import pickle 12 | from collections import defaultdict 13 | import operator 14 | 15 | 16 | # this is for serialization 17 | def defaultfloat(): 18 | return defaultdict(float) 19 | 20 | def search(indexpath, query): 21 | with open(indexpath, 'rb') as f: 22 | tf = pickle.load(f) 23 | idf = pickle.load(f) 24 | 25 | # generate candidate file list 26 | scores = defaultdict(float) 27 | for word in set(query.split()): 28 | for fname, tfword in tf[word].iteritems(): 29 | scores[fname] += tfword * idf[word] 30 | # candidates |= set(tf[word].keys()) 31 | 32 | sorted_scores = sorted(scores.items(), key=operator.itemgetter(1), reverse=True) 33 | print sorted_scores 34 | 35 | 36 | if __name__ == "__main__": 37 | search(sys.argv[1], sys.argv[2]) -------------------------------------------------------------------------------- /system_design/search_engine/stoplist.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/system_design/search_engine/stoplist.txt -------------------------------------------------------------------------------- /topcoder/TCCC03Round4/.ChessMetric.cpp.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/topcoder/TCCC03Round4/.ChessMetric.cpp.swp -------------------------------------------------------------------------------- /topcoder/TCCC03semifinal_round3/.ZigZag.cpp.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/topcoder/TCCC03semifinal_round3/.ZigZag.cpp.swp -------------------------------------------------------------------------------- /topcoder/TCCC03semifinal_round3/data.in: -------------------------------------------------------------------------------- 1 | 61 82 126 97 167 186 119 154 155 142 153 181 172 192 223 272 273 260 280 330 329 350 273 324 349 306 385 375 420 416 435 457 373 477 395 487 500 439 493 537 518 549 542 500 524 541 512 589 549 543 2 | -------------------------------------------------------------------------------- /topcoder/TCCC04online_round4/BadNeighbors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * http://www.topcoder.com/stat?c=problem_statement&pm=2402&rd=5009 3 | * Dynamic Programming 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | const int MAX=60; 10 | int n; /* [2..40] */ 11 | int d[MAX]; 12 | int m1[MAX]; /* [1..n-1] */ 13 | int m2[MAX]; /* [2..n] */ 14 | 15 | class BadNeighbors{ 16 | public: 17 | int maxDonations(vector donations){ 18 | m1[0]=0;m1[1]=d[1]; 19 | int i,j; 20 | for(i=2;i<=n-1;i++){ 21 | int x=m1[i-1]; 22 | int y=m1[i-2]+d[i]; 23 | if( x>y ) m1[i] = x; 24 | else m1[i]=y; 25 | } 26 | 27 | m2[0]=0;m2[1]=0;m2[2]=d[2]; 28 | for(i=3;i<=n;i++){ 29 | int x=m2[i-1]; 30 | int y=m2[i-2]+d[i]; 31 | if( x>y ) m2[i] = x; 32 | else m2[i] = y; 33 | } 34 | int out=0; 35 | if( m1[n-1] > m2[n] ) out=m1[n-1]; 36 | else out=m2[n]; 37 | return out; 38 | } 39 | }; 40 | 41 | int main() 42 | { 43 | freopen("data.in","r",stdin); 44 | n=0; 45 | int temp; 46 | while(scanf("%d",&temp) != EOF){ 47 | n++; 48 | d[n]=temp; 49 | m1[n]=m2[n]=temp; 50 | } 51 | 52 | /* 53 | for(i=0;i<=n;i++) 54 | printf("%d\t%d\n",m1[i],m2[i]); 55 | printf("%d\n",n); 56 | */ 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /topcoder/TCCC04online_round4/data.in: -------------------------------------------------------------------------------- 1 | 445 298 806 321 703 71 514 289 881 992 675 644 470 469 430 353 461 907 392 394 244 544 185 350 958 192 930 453 726 844 819 197 797 323 889 835 142 650 538 87 2 | -------------------------------------------------------------------------------- /topcoder/TCO03Semifinals4/.AvoidRoads.cpp.swp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/topcoder/TCO03Semifinals4/.AvoidRoads.cpp.swp -------------------------------------------------------------------------------- /topcoder/TCO03Semifinals4/AvoidRoads.c~: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX 102 4 | 5 | struct path{ 6 | int a,b,c,d; 7 | }; 8 | 9 | long long d[MAX][MAX]; 10 | int width=6; 11 | int height=6 ; 12 | char * bad[]={"0 0 0 1","6 6 5 6"}; 13 | 14 | int main() 15 | { 16 | int n=sizeof(bad)/4; // elements count in bad 17 | int i,j; 18 | for(i=0;i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class TallPeople{ 8 | public: 9 | vector< vector > ppl; 10 | vector getPeople(vector people){ 11 | int i; 12 | for(i=0;i v; 16 | return v; 17 | } 18 | 19 | }; 20 | 21 | int main(){ 22 | TallPeople p; 23 | string s[]={"9 2 3", "4 8 7"}; 24 | vector ppl(s,s+2); 25 | vector v=p.getPeople(ppl); 26 | vector::iterator i=v.begin(); 27 | while(i!=v.end()){ 28 | cout<<*i< 2 | 3 | class HandsShaking{ 4 | public: 5 | long long countPerfect(int n){ 6 | long long d[60]; 7 | d[2]=1; 8 | int i; 9 | for(i=4;i<=n;i+=2){ 10 | d[i]=3*d[i-2]-1; 11 | } 12 | return d[n]; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /topcoder/srm397/SumOfPowers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class SumOfPowers{ 5 | public: 6 | unsigned int mod_exp(unsigned int a,unsigned int b,unsigned int n){ 7 | unsigned int d=1; 8 | unsigned int c=0x80000000;// 31b set to 1, others 0 9 | // search for the first non-zero bit of b 10 | while( (c&b) == 0 ) c>>=1; 11 | // traverse all the bit of b 12 | while(c>0){ 13 | d = (d*d)%n; 14 | if( (c&b) > 0){// current bit is 1 15 | d = (d*a)%n; 16 | } 17 | c>>=1; 18 | } 19 | return d; 20 | } 21 | 22 | int value(int n,int k){ 23 | int mod = 1000000007; 24 | int sum=0; 25 | for(int i=1;i<=n;i++){ 26 | sum = (sum + mod_exp(i,k,mod)) % mod; 27 | } 28 | return sum; 29 | } 30 | }; 31 | 32 | int main(){ 33 | SumOfPowers s; 34 | int n,k; 35 | while(cin>>n>>k){ 36 | cout< 7 | 8 | int M,S,C; 9 | char stall[210]; 10 | 11 | int main() 12 | { 13 | freopen("milk1.in","r",stdin); 14 | //freopen("milk1.out","w",stdout); 15 | scanf("%d%d%d",&M,&S,&C); 16 | int i; 17 | for(i=0;i 7 | 8 | char * num_str[]={"","I","V","X","L","C","D","M"}; 9 | enum NUM{DUMMY,I,V,X,L,C,D,M}; 10 | int N; 11 | int c[8]; 12 | /* 13 | int n[9][4][8]={ 14 | }; 15 | */ 16 | 17 | int inc(int x){ 18 | int base=0; 19 | while(x > 0){ 20 | int d = x%10; 21 | //printf("d=%d\n",d); 22 | x=x/10; 23 | switch(d){ 24 | case 0:break; 25 | case 3: c[base+I]++; 26 | case 2: c[base+I]++; 27 | case 1: c[base+I]++; 28 | break; 29 | case 9: c[base+X]++; 30 | c[base+I]++; 31 | break; 32 | c[base+V]++; 33 | case 8: c[base+I]++; 34 | case 7: c[base+I]++; 35 | case 4: 36 | case 6: c[base+I]++; 37 | default:c[base+V]++; 38 | break; 39 | } 40 | base += 2; 41 | } 42 | return 0; 43 | } 44 | 45 | void output(){ 46 | int i; 47 | for(i=1;i<8;i++) 48 | if(c[i]>0) 49 | printf("%s %d\n",num_str[i],c[i]); 50 | } 51 | 52 | int main(){ 53 | freopen("preface.in","r",stdin); 54 | #ifndef LOCAL 55 | freopen("preface.out","w",stdout); 56 | #endif 57 | scanf("%d",&N); 58 | int i; 59 | for(i=1;i<=N;i++) 60 | inc(i); 61 | output(); 62 | 63 | #ifdef LOCAL 64 | // output sth. here 65 | #endif 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /usaco/preface/preface.in: -------------------------------------------------------------------------------- 1 | 3499 2 | -------------------------------------------------------------------------------- /usaco/prefix/prefix: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/usaco/prefix/prefix -------------------------------------------------------------------------------- /usaco/prefix/prefix.in: -------------------------------------------------------------------------------- 1 | A AB BA CA BBC 2 | . 3 | ABABACABAABC 4 | -------------------------------------------------------------------------------- /usaco/prefix/prefix.in2: -------------------------------------------------------------------------------- 1 | A B C 2 | . 3 | DABCDHETHBNAGRKGJTHNUE 4 | -------------------------------------------------------------------------------- /usaco/prefix/prefix.out: -------------------------------------------------------------------------------- 1 | 11 2 | -------------------------------------------------------------------------------- /usaco/runround/a.out: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/usaco/runround/a.out -------------------------------------------------------------------------------- /usaco/runround/runround.c: -------------------------------------------------------------------------------- 1 | /* 2 | ID: iveney1 3 | LANG: C 4 | TASK: runround 5 | */ 6 | #include 7 | #include 8 | 9 | int isR(int M){ 10 | int digits[10]; 11 | int used[10]; // 1-9 12 | memset(used,0,sizeof(used)); 13 | int tmp=M,n=0,p; 14 | while(tmp!=0){ 15 | p=tmp%10; 16 | if( p == 0 || used[p] ) return 0; 17 | used[p]=1; 18 | digits[n++]=p; 19 | tmp/=10; 20 | } 21 | int i; 22 | memset(used,0,sizeof(used)); 23 | for(i=0;i 7 | #define MAXSIZE 1005 8 | 9 | int arr[MAXSIZE]; 10 | int c[4]; 11 | #define ABS(a) ((a)<0?(-(a)):(a)) 12 | #define MIN(a,b) ((a)<(b)?(a):(b)) 13 | #define MAX(a,b) ((a)<(b)?(b):(a)) 14 | 15 | int main(){ 16 | freopen("sort3.in","r",stdin); 17 | #ifndef LOCAL 18 | freopen("sort3.out","w",stdout); 19 | #endif 20 | 21 | int N; 22 | int i; 23 | scanf("%d\n",&N); 24 | for(i=0;i 7 | #define MAX 1005 8 | 9 | int arr[MAX]; 10 | 11 | int main(){ 12 | freopen("sort3.in","r",stdin); 13 | #ifndef LOCAL 14 | freopen("sort3.out","w",stdout); 15 | #endif 16 | 17 | int N; 18 | int i; 19 | scanf("%d\n",&N); 20 | for(i=0;i 7 | #include 8 | 9 | const int plist[]={1,2,3,5,7,9}; 10 | int psize=6; 11 | 12 | int isprime(int n) { 13 | if(n<=1) return 0; 14 | int i; 15 | int root = (int) sqrt(n); 16 | for(i=2;i<=root;i++) 17 | if( n % i == 0 ) 18 | return 0; 19 | return 1; 20 | } 21 | 22 | int dfs(int num,int depth){ 23 | if( !isprime(num) ) return -1; 24 | else if(depth <= 0) { 25 | printf("%d\n",num); 26 | return num; 27 | } 28 | int i,temp; 29 | for(i=0;i 7 | 8 | int main(){ 9 | freopen("PROB.in","r",stdin); 10 | #ifndef LOCAL 11 | freopen("PROB.out","w",stdout); 12 | #endif 13 | 14 | #ifdef LOCAL 15 | // output sth. here 16 | #endif 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /usaco/transform/transform.in: -------------------------------------------------------------------------------- 1 | 3 2 | @-@ 3 | --- 4 | @@- 5 | @-@ 6 | @-- 7 | --@ -------------------------------------------------------------------------------- /usaco/zerosum/zerosum.c: -------------------------------------------------------------------------------- 1 | /* 2 | ID: iveney1 3 | LANG: C 4 | TASK: zerosum 5 | */ 6 | #include 7 | 8 | int N; 9 | 10 | void input(){ 11 | scanf("%d\n",N); 12 | } 13 | 14 | int main(){ 15 | freopen("zerosum.in","r",stdin); 16 | #ifndef LOCAL 17 | freopen("zerosum.out","w",stdout); 18 | #endif 19 | input(); 20 | 21 | #ifdef LOCAL 22 | // output sth. here 23 | #endif 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /usaco/zerosum/zerosum.in: -------------------------------------------------------------------------------- 1 | 7 2 | -------------------------------------------------------------------------------- /zju/1003/1003.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iveney/algorithm/183361df858caf51e3b080ef97aa105ecba68d25/zju/1003/1003.cpp -------------------------------------------------------------------------------- /zju/1045/1045.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | double len; 7 | double ep=0.001; 8 | do 9 | { 10 | scanf("%lf",&len); 11 | if( len < ep ) 12 | break; 13 | int i=0; 14 | double sum=0; 15 | while(sum < len) 16 | { 17 | i++; 18 | sum+=1.0/(1.0+i); 19 | } 20 | printf("%d card(s)\n",i); 21 | }while(1); 22 | } -------------------------------------------------------------------------------- /zju/1048/1048.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | double sum=0.0; 7 | for(int i=0;i<12;i++) 8 | { 9 | double balance; 10 | scanf("%lf",&balance); 11 | sum+=balance; 12 | } 13 | printf("$%.2lf\n",sum/12.0); 14 | } -------------------------------------------------------------------------------- /zju/1049/1049.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | const double PI = 3.1415926; 5 | int main() 6 | { 7 | int N; 8 | scanf("%d",&N); 9 | double Rs[1001]; 10 | int set=0; 11 | for(int i=1;i<=N;i++) 12 | { 13 | double x,y; 14 | scanf("%lf %lf",&x,&y); 15 | double len = sqrt(x*x+y*y); 16 | double R; 17 | int j; 18 | for(j=1;j<=1000;j++) 19 | { 20 | if( j < set ) 21 | { 22 | R = Rs[j]; 23 | } 24 | else 25 | { 26 | double area = 50.0*j; 27 | R = Rs[j] = sqrt(2 * area / PI); 28 | set = j; 29 | } 30 | if( R-len > 0.0 ) 31 | break; 32 | } 33 | printf("Property %d: This property will begin eroding in year %d.\n",i,j); 34 | } 35 | printf("END OF OUTPUT.\n"); 36 | } 37 | -------------------------------------------------------------------------------- /zju/factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int last = 1; 5 | int mul = 1; 6 | 7 | int main() 8 | { 9 | int T; 10 | scanf("%d",&T); 11 | for(int t=0;t 2 | 3 | int main() 4 | { 5 | int t; 6 | int n; 7 | scanf("%d",&t); 8 | for(int s=0;stemp ) min = temp; 17 | if( max 2 | #include 3 | 4 | const int N=40; 5 | int m,d; 6 | int num[N][N]; // high precision 7 | 8 | void add(int c[],int a[],int b[]) 9 | { 10 | memset(c,0,sizeof(num[0])); 11 | for(int i=0;i=0;high--) 22 | printf("%d",a[high]); 23 | printf("\n"); 24 | } 25 | 26 | int main() 27 | { 28 | while(1) 29 | { 30 | scanf("%d %d",&m,&d); 31 | if(m==0 || d==0) break; 32 | memset(num,0,sizeof(num)); 33 | num[0][0]=1; 34 | // before mth month,the rabbits are sequentially increased 35 | for(int i=1;i=0;j--) 42 | { 43 | if( num[d][j] > 0 ) 44 | { 45 | high=j;break; 46 | } 47 | } 48 | output(high,num[d]); 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /zsu/1033/data: -------------------------------------------------------------------------------- 1 | 5 6 2 | 1 3 | 1 1 5 6 4 | 7 6 5 | 2 6 | 1 1 7 2 7 | 2 2 3 5 8 | 7 6 9 | 2 10 | 1 1 7 2 11 | 2 3 3 4 12 | 7 6 13 | 2 14 | 1 5 7 2 15 | 2 1 3 5 16 | 0 0 17 | -------------------------------------------------------------------------------- /zsu/1033/tags: -------------------------------------------------------------------------------- 1 | !_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ 2 | !_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ 3 | !_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ 4 | !_TAG_PROGRAM_NAME Exuberant Ctags // 5 | !_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ 6 | !_TAG_PROGRAM_VERSION 5.6 // 7 | main cityroad.cpp /^int main()$/;" f 8 | -------------------------------------------------------------------------------- /zsu/1035/dna.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | const int N=105; 4 | char dna[N][N]; 5 | 6 | bool cmp(char a[],char b[]) 7 | { 8 | int i=0; 9 | while(a[i]!='\0' && b[i]!='\0') 10 | { 11 | switch(a[i]) 12 | { 13 | case 'A':if(b[i]!='T')return false; 14 | break; 15 | case 'T':if(b[i]!='A')return false; 16 | break; 17 | case 'C':if(b[i]!='G')return false; 18 | break; 19 | case 'G':if(b[i]!='C')return false; 20 | break; 21 | } 22 | i++; 23 | } 24 | if(a[i] == '\0' && b[i] == '\0') 25 | {// they matched 26 | // printf("%s\n%s\n",a,b); 27 | a[0]=b[0]='\0'; // set as used 28 | return true; 29 | } 30 | return false; 31 | } 32 | 33 | int main() 34 | { 35 | int i,j; 36 | int n,T; 37 | unsigned int match=0; 38 | FILE * f = stdin;// freopen("data","r",stdin); 39 | fscanf(f,"%d",&T); 40 | for(int count=0;count 2 | #include 3 | 4 | const int N = 20; 5 | int a[N][N][15]; 6 | 7 | void init(int origin) 8 | { 9 | memset(a,0,sizeof(a)); 10 | a[origin][origin][0]=1; 11 | } 12 | 13 | int main() 14 | { 15 | //FILE * f=freopen("data","r",stdin); 16 | FILE *f = stdin; 17 | int count,numCase; 18 | fscanf(f,"%d",&numCase); 19 | for(count=0;count 2 | #include 3 | //#include 4 | 5 | int prices[20010]; 6 | 7 | int cmp(const void * l,const void * r) 8 | { 9 | return (*(int*)r) - (*(int*)l); 10 | } 11 | 12 | int main() 13 | { 14 | int t,n; 15 | //FILE * f=freopen("shopaholic.in","r",stdin); 16 | FILE * f = stdin; 17 | fscanf(f,"%d",&t); 18 | for(int i=0;i 2 | 3 | int q[100]; 4 | 5 | int main() 6 | { 7 | int t,n,m; 8 | scanf("%d",&t); 9 | for(int i=0;i 2 | 3 | struct Node 4 | { 5 | int pre; 6 | int num; 7 | }; 8 | 9 | int main() 10 | { 11 | 12 | return 0; 13 | } -------------------------------------------------------------------------------- /zsu/2008 Weekly Contest 2/1001/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int n; 7 | scanf("%d",&n); 8 | 9 | 10 | for(int i=0;i 2 | 3 | const int G_row = 10; 4 | const int G_column = 20; 5 | 6 | int main() 7 | { 8 | int **GG; 9 | GG = new int*[G_row]; 10 | int i; 11 | for(i = 0; i < (G_row); i++) 12 | GG[i] = new int[G_column]; 13 | 14 | for (i = 0; i < (G_row); i++) 15 | { 16 | delete [] GG[i]; 17 | } 18 | delete [] GG; 19 | GG = NULL; 20 | return 0; 21 | } 22 | --------------------------------------------------------------------------------