├── .gitignore ├── PAT ├── PAT_A │ ├── c++ │ │ ├── .gitignore │ │ ├── pat1001.cpp │ │ ├── pat1002.cpp │ │ ├── pat1003.cpp │ │ ├── pat1004.cpp │ │ ├── pat1005.cpp │ │ ├── pat1006.cpp │ │ ├── pat1007.cpp │ │ ├── pat1008.cpp │ │ ├── pat1009.cpp │ │ ├── pat1010.cpp │ │ ├── pat1011.cpp │ │ ├── pat1012.cpp │ │ ├── pat1013.cpp │ │ ├── pat1015.cpp │ │ ├── pat1016.cpp │ │ ├── pat1017.cpp │ │ ├── pat1018.cpp │ │ ├── pat1019.cpp │ │ ├── pat1020.cpp │ │ ├── pat1021.cpp │ │ ├── pat1022.cpp │ │ ├── pat1023.cpp │ │ ├── pat1024.cpp │ │ ├── pat1025.cpp │ │ ├── pat1026.cpp │ │ ├── pat1027.cpp │ │ ├── pat1028.cpp │ │ ├── pat1029.cpp │ │ ├── pat1030.cpp │ │ ├── pat1031.cpp │ │ ├── pat1032.cpp │ │ ├── pat1033.cpp │ │ ├── pat1034.cpp │ │ ├── pat1035.cpp │ │ ├── pat1036.cpp │ │ ├── pat1037.cpp │ │ ├── pat1038.cpp │ │ ├── pat1039.cpp │ │ ├── pat1040.cpp │ │ ├── pat1041.cpp │ │ ├── pat1042.cpp │ │ ├── pat1043.cpp │ │ ├── pat1044.cpp │ │ ├── pat1045.cpp │ │ ├── pat1046.cpp │ │ ├── pat1047.cpp │ │ ├── pat1048.cpp │ │ ├── pat1049.cpp │ │ ├── pat1050.cpp │ │ ├── pat1051.cpp │ │ ├── pat1052.cpp │ │ ├── pat1053.cpp │ │ ├── pat1054.cpp │ │ ├── pat1055.cpp │ │ ├── pat1056.cpp │ │ ├── pat1057.cpp │ │ ├── pat1058.cpp │ │ ├── pat1059.cpp │ │ ├── pat1060.cpp │ │ ├── pat1061.cpp │ │ ├── pat1062.cpp │ │ ├── pat1063.cpp │ │ ├── pat1064.cpp │ │ ├── pat1065.cpp │ │ ├── pat1066.cpp │ │ ├── pat1067.cpp │ │ ├── pat1068.cpp │ │ ├── pat1069.cpp │ │ ├── pat1070.cpp │ │ ├── pat1071.cpp │ │ ├── pat1072.cpp │ │ ├── pat1073.cpp │ │ ├── pat1074.cpp │ │ ├── pat1075.cpp │ │ ├── pat1076.cpp │ │ ├── pat1077.cpp │ │ ├── pat1078.cpp │ │ ├── pat1079.cpp │ │ ├── pat1080.cpp │ │ ├── pat1081.cpp │ │ ├── pat1082.cpp │ │ ├── pat1083.cpp │ │ ├── pat1084.cpp │ │ ├── pat1085.cpp │ │ ├── pat1086.cpp │ │ ├── pat1087.cpp │ │ ├── pat1088.cpp │ │ ├── pat1089.cpp │ │ ├── pat1090.cpp │ │ ├── pat1091.cpp │ │ ├── pat1097.cpp │ │ ├── pat1098.cpp │ │ ├── pat1099.cpp │ │ ├── pat1100.cpp │ │ ├── pat1101.cpp │ │ ├── pat1102.cpp │ │ ├── pat1103.cpp │ │ ├── pat1104.cpp │ │ ├── pat1105.cpp │ │ ├── pat1106.cpp │ │ ├── pat1107.cpp │ │ ├── pat1108.cpp │ │ ├── pat1109.cpp │ │ ├── pat1110.cpp │ │ ├── pat1111.cpp │ │ ├── pat1112.cpp │ │ ├── pat1113.cpp │ │ ├── pat1114.cpp │ │ └── pat1115.cpp │ └── python │ │ ├── README.md │ │ ├── pat1004.py │ │ ├── pat1005.py │ │ ├── pat1006.py │ │ ├── pat1008.py │ │ ├── pat1013.py │ │ ├── pat1023.py │ │ └── pat1024.py ├── PAT_B │ ├── pat1001.py │ ├── pat1002.py │ ├── pat1003.py │ ├── pat1004.py │ └── pat1030.py ├── PAT_T │ ├── pat1001.cpp │ ├── pat1002.cpp │ ├── pat1003.cpp │ ├── pat1008.cpp │ ├── pat1009.cpp │ └── pat1010.cpp └── README.md ├── POJ ├── README ├── poj1050.cpp ├── poj1080.cpp ├── poj1088.cpp ├── poj1141.cpp ├── poj1159.cpp ├── poj1163.cpp ├── poj1185.cpp ├── poj1195.cpp ├── poj1260.cpp ├── poj1276.cpp ├── poj1463.cpp ├── poj1692.cpp ├── poj1836.cpp ├── poj1837.cpp ├── poj1984.cpp ├── poj1986.cpp ├── poj2104.cpp ├── poj2135.cpp ├── poj2155.cpp ├── poj2175.cpp ├── poj2182.cpp ├── poj2186.cpp ├── poj2187.cpp ├── poj2299.cpp ├── poj2342.cpp ├── poj2352.cpp ├── poj2375.cpp ├── poj2406.cpp ├── poj2479.cpp ├── poj2516.cpp ├── poj2528.cpp ├── poj2533.cpp ├── poj2553.cpp ├── poj2762.cpp ├── poj2823.cpp ├── poj3061.cpp ├── poj3067.cpp ├── poj3069.cpp ├── poj3167.cpp ├── poj3176.cpp ├── poj3253.cpp ├── poj3254.cpp ├── poj3261.cpp ├── poj3267.cpp ├── poj3276.cpp ├── poj3281.cpp ├── poj3311.cpp ├── poj3320.cpp ├── poj3342.cpp ├── poj3468.cpp ├── poj3469.cpp ├── poj3686.cpp ├── poj3693.cpp └── poj4045.cpp ├── README.md ├── codeforces ├── 627A.cpp ├── 638B.cpp ├── 650A.cpp └── README ├── codejam ├── 2013 │ ├── R1A │ │ ├── A.py │ │ ├── B.py │ │ └── C-small.py │ └── R1B │ │ ├── A.py │ │ ├── C.py │ │ └── garbled_email_dictionary.txt ├── 2014 │ ├── Qualification │ │ ├── A.cpp │ │ ├── B.cpp │ │ ├── C.cpp │ │ └── D.cpp │ ├── Round1A │ │ ├── A.cpp │ │ └── B.cpp │ └── Round1C │ │ └── A.cpp ├── 2016 │ └── Qualification │ │ ├── A.py │ │ ├── B.py │ │ ├── C.py │ │ └── D-small.py └── README ├── hiho ├── hiho1014.cpp ├── hiho1015.cpp ├── hiho1040.cpp ├── hiho1050.cpp ├── hiho1052.cpp ├── hiho1066.cpp ├── hiho1091.cpp ├── hiho1097.cpp ├── hiho1098.cpp ├── hiho1105.cpp └── hiho1175.cpp └── leetcode ├── 3sum-closest.cpp ├── 3sum.cpp ├── 4sum.cpp ├── README.md ├── add-two-numbers.cpp ├── balanced-binary-tree.cpp ├── basic-calculator-ii.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-iv.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-maximum-path-sum.cpp ├── binary-tree-postorder-traversal.cpp ├── binary-tree-preorder-traversal.cpp ├── binary-tree-zigzag-level-order-traversal.cpp ├── bitwise-and-of-numbers-range.cpp ├── candy.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 ├── contains-duplicate-iii.cpp ├── count-primes.cpp ├── course-schedule-ii.cpp ├── course-schedule.cpp ├── decode-ways.cpp ├── divide-two-integers.cpp ├── dungeon-game.cpp ├── expression-add-operators.cpp ├── find-median-from-data-stream.cpp ├── find-minimum-in-rotated-sorted-array.cpp ├── find-the-duplicate-number.cpp ├── first-missing-positive.cpp ├── flatten-binary-tree-to-linked-list.cpp ├── fraction-to-recurring-decimal.cpp ├── game-of-life.cpp ├── gas-station.cpp ├── generate-parentheses.cpp ├── gray-code.cpp ├── h-index-ii.cpp ├── h-index.cpp ├── insert-interval.cpp ├── integer-to-english-words.cpp ├── interleaving-string.cpp ├── kth-largest-element-in-an-array.cpp ├── letter-combinations-of-a-phone-number.cpp ├── linked-list-cycle-ii.cpp ├── linked-list-cycle.cpp ├── longest-palindromic-substring.cpp ├── longest-substring-without repeating characters.cpp ├── longest-valid-parentheses.cpp ├── max-points-on-a-line.cpp ├── maximum-depth-of-binary tree.cpp ├── median-of-two-sorted-arrays.cpp ├── merge-intervals.cpp ├── merge-k-sorted-lists .cpp ├── merge-two-sorted-lists .cpp ├── minimum-depth-of-binary-tree.cpp ├── minimum-size-subarray-sum.cpp ├── missing-number.cpp ├── multiply-strings.cpp ├── n-queens.cpp ├── next-permutation.cpp ├── nim-game.cpp ├── number-of-1-bits.cpp ├── palindrome-number.cpp ├── perfect-squares.cpp ├── permutation-sequence.cpp ├── permutations-ii.cpp ├── permutations.cpp ├── populating-next-right-pointers-in-each-node.cpp ├── powx-n.cpp ├── rectangle-area.cpp ├── remove-duplicates-from-sorted-array-ii.cpp ├── remove-duplicates-from-sorted-array.cpp ├── remove-duplicates-from-sorted-list .cpp ├── remove-duplicates-from-sorted-list-ii.cpp ├── remove-nth-node-from-end-of-list.cpp ├── repeated-dna-sequences.cpp ├── restore-ip-addresses.cpp ├── reverse-integer.cpp ├── reverse-linked-list-ii.cpp ├── reverse-nodes-in-k-group.cpp ├── reverse-words-in-a-string.cpp ├── rotate-array.cpp ├── rotate-image.cpp ├── same-tree.cpp ├── search-for-a-range.cpp ├── set-matrix-zeroes.cpp ├── shortest-palindrome.cpp ├── simplify-path.cpp ├── single-number.cpp ├── sliding-window-maximum.cpp ├── sort-colors.cpp ├── sqrtx.cpp ├── subsets.cpp ├── substring-with-concatenation-of-all-words.cpp ├── sudoku-solver.cpp ├── swap-nodes-in-pairs.cpp ├── symmetric-tree.cpp ├── text-justification.cpp ├── two-sum.cpp ├── unique-binary-search-trees-ii.cpp ├── unique-binary-search-trees.cpp ├── valid-parentheses.cpp ├── validate-binary-search-tree.cpp ├── word-break-ii.cpp ├── word-break.cpp └── word-ladder-ii.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1001.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits). 3 | 4 | Input 5 | 6 | Each input file contains one test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space. 7 | 8 | Output 9 | 10 | For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format. 11 | 12 | Sample Input 13 | -1000000 9 14 | Sample Output 15 | -999,991 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | using namespace std; 23 | 24 | int main() 25 | { 26 | int a, b; 27 | cin >> a >> b; 28 | a += b; 29 | if(a < 0) { 30 | cout << '-'; 31 | a = -a; 32 | } 33 | string digits = to_string(a); 34 | for(int i=0, size=digits.size(); i 20 | #include 21 | 22 | using namespace std; 23 | 24 | const int max_n = 1001; 25 | float a[max_n], b[max_n], c[max_n]; 26 | 27 | void read_poly(float a[]) { 28 | int k; 29 | scanf("%d", &k); 30 | for (int i=0; i > res; 43 | for (int i=0; i=0; --i) { 51 | printf("%d %.1f%c", res[i].first, res[i].second, i==0?'\n':' '); 52 | } 53 | } 54 | return 0; 55 | 56 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1004.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child. 3 | Input 4 | Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format: 5 | ID K ID[1] ID[2] ... ID[K] 6 | 7 | where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 01. 8 | Output 9 | For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line. 10 | The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output "0 1" in a line. 11 | Sample Input 12 | 2 1 13 | 01 1 02 14 | 15 | Sample Output 16 | 0 1 17 | */ 18 | #include 19 | #include 20 | #include 21 | 22 | using namespace std; 23 | 24 | int main() 25 | { 26 | int n, m; 27 | cin >> n >> m; 28 | vector> G(n+1); 29 | for (int i=0; i> f >> k; 32 | G[f].resize(k); 33 | for (int j=0; j> G[f][j]; 35 | } 36 | vector res; 37 | vector level = {1}; 38 | while (level.size()!=0) { 39 | vector next; 40 | int cnt = 0; 41 | for (auto &x : level) 42 | if (G[x].size()) 43 | for (auto &y : G[x]) next.push_back(y); 44 | else ++cnt; 45 | res.push_back(cnt); 46 | level = next; 47 | } 48 | for (int i=0; i 14 | #include 15 | 16 | using namespace std; 17 | 18 | char tab[][10]={"zero", "one", "two", "three", "four", "five", 19 | "six", "seven", "eight", "nine"}; 20 | 21 | int main() 22 | { 23 | string str; 24 | cin >> str; 25 | int sum = 0; 26 | for (auto &ch:str) 27 | sum += ch-'0'; 28 | string res = to_string(sum); 29 | for (int i=0; i 21 | #include 22 | 23 | using namespace std; 24 | 25 | int main() 26 | { 27 | int n; 28 | cin >> n; 29 | pair si, so; 30 | si = make_pair("", "23:59:59"); 31 | so = make_pair("", "00:00:00"); 32 | while (n--) { 33 | string a, b, c; 34 | cin >> a >> b >> c; 35 | if (b < si.second) si = make_pair(a, b); 36 | if (c > so.second) so = make_pair(a, c); 37 | } 38 | cout << si.first << " " << so.first << endl; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1008.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The highest building in our city has only one elevator. A request list is made up with N positive numbers. The numbers denote at which floors the elevator will stop, in specified order. It costs 6 seconds to move the elevator up one floor, and 4 seconds to move down one floor. The elevator will stay for 5 seconds at each stop. 3 | 4 | For a given request list, you are to compute the total time spent to fulfill the requests on the list. The elevator is on the 0th floor at the beginning and does not have to return to the ground floor when the requests are fulfilled. 5 | 6 | Input Specification: 7 | 8 | Each input file contains one test case. Each case contains a positive integer N, followed by N positive numbers. All the numbers in the input are less than 100. 9 | 10 | Output Specification: 11 | 12 | For each test case, print the total time on a single line. 13 | 14 | Sample Input: 15 | 3 2 3 1 16 | Sample Output: 17 | 41 18 | */ 19 | #include 20 | 21 | int main() 22 | { 23 | int n; 24 | scanf("%d", &n); 25 | int curfloor = 0; 26 | int ntime = 0; 27 | for(int i=0; i 0) 32 | ntime += nfloor*6; 33 | else if( nfloor < 0) 34 | ntime += (-nfloor)*4; 35 | ntime += 5; 36 | curfloor = floor; 37 | } 38 | printf("%d", ntime); 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1009.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This time, you are supposed to find A*B where A and B are two polynomials. 3 | Input Specification: 4 | Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10, 0 <= NK < ... < N2 < N1 <=1000. 5 | Output Specification: 6 | For each test case you should output the product of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate up to 1 decimal place. 7 | Sample Input 8 | 2 1 2.4 0 3.2 9 | 2 2 1.5 1 0.5 10 | 11 | Sample Output 12 | 3 3 3.6 2 6.0 1 1.6 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | using namespace std; 22 | 23 | void read_poly(unordered_map &um) { 24 | int k; 25 | cin >> k; 26 | while (k--) { 27 | int a; 28 | float b; 29 | cin >> a >> b; 30 | um[a] += b; 31 | } 32 | } 33 | 34 | 35 | int main() 36 | { 37 | unordered_map ua, ub; 38 | map uc; 39 | read_poly(ua); 40 | read_poly(ub); 41 | for (auto &x : ua) 42 | for (auto &y : ub) 43 | uc[x.first+y.first] += x.second*y.second; 44 | vector> res; 45 | for (auto &x : uc) 46 | if (x.second != 0.f) 47 | res.push_back(x); 48 | if (res.size() == 0) printf("0"); 49 | else { 50 | printf("%d ", res.size()); 51 | for (int i=res.size()-1; i>=0; --i) 52 | printf("%d %.1f%c", res[i].first, res[i].second, i?' ':'\n'); 53 | } 54 | return 0; 55 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1013.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly. 3 | For example, if we have 3 cities and 2 highways connecting city1-city2 and city1-city3. Then if city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3. 4 | Input 5 | Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern. 6 | Output 7 | For each of the K cities, output in a line the number of highways need to be repaired if that city is lost. 8 | Sample Input 9 | 3 2 3 10 | 1 2 11 | 1 3 12 | 1 2 3 13 | 14 | Sample Output 15 | 1 16 | 0 17 | 0 18 | */ 19 | #include 20 | #include 21 | 22 | using namespace std; 23 | 24 | void dfs(int v, vector& used, vector>&g) 25 | { 26 | used[v] = true; 27 | for (auto t : g[v]) 28 | if (!used[t]) dfs(t, used, g); 29 | } 30 | 31 | int main() 32 | { 33 | int n, m, k; 34 | cin >> n >> m >> k; 35 | vector> g(n); 36 | for (int i=0; i> a >> b; 39 | g[a-1].push_back(b-1); 40 | g[b-1].push_back(a-1); 41 | } 42 | for (int i=0; i> t; 45 | vector used(n); 46 | used[t-1] = true; 47 | int cnt = 0; 48 | for (int j=0; j 26 | #include 27 | #include 28 | 29 | using namespace std; 30 | 31 | int to_int(const string &str, int d) { 32 | int res = 0; 33 | for (auto ch : str) 34 | res = res*d + ch-'0'; 35 | return res; 36 | } 37 | 38 | string to_reversed_string(int n, int d) { 39 | string res; 40 | do { 41 | res += '0'+n%d; 42 | n /= d; 43 | }while(n); 44 | return res; 45 | } 46 | 47 | bool is_prime(int n) { 48 | if (n == 1) return false; 49 | for (int i=2; i*i<=n; ++i) 50 | if (n%i == 0) return false; 51 | return true; 52 | } 53 | 54 | int main() 55 | { 56 | int n, d; 57 | while (cin >> n >> d) { 58 | string str = to_reversed_string(n, d); 59 | int a = to_int(str, d); 60 | if (is_prime(a) && is_prime(n)) 61 | cout << "Yes" << endl; 62 | else 63 | cout << "No" << endl; 64 | } 65 | return 0; 66 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1023.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again! 3 | Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number. 4 | Input Specification: 5 | Each input file contains one test case. Each case contains one positive integer with no more than 20 digits. 6 | Output Specification: 7 | For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number. 8 | Sample Input: 9 | 1234567899 10 | 11 | Sample Output: 12 | Yes 13 | 2469135798 14 | 15 | */ 16 | #include 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | 22 | string mul(const string& str, int n) 23 | { 24 | string res; 25 | int c = 0; 26 | for (int i=str.length()-1; i>=0; --i) { 27 | int v = c+(str[i]-'0')*n; 28 | res += '0'+v%10; 29 | c = v/10; 30 | } 31 | if (c) res.push_back(c+'0'); 32 | reverse(res.begin(), res.end()); 33 | return res; 34 | } 35 | 36 | int main() 37 | { 38 | string a; 39 | cin >> a; 40 | string b = mul(a, 2), c = b; 41 | sort(a.begin(), a.end()); 42 | sort(b.begin(), b.end()); 43 | cout << (a==b?"Yes":"No") << endl; 44 | cout << c << endl; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1027.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values. 3 | Input 4 | Each input file contains one test case which occupies a line containing the three decimal color values. 5 | Output 6 | For each test case you should output the Mars RGB value in the following format: first output "#", then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a "0" to the left. 7 | Sample Input 8 | 15 43 71 9 | 10 | Sample Output 11 | #123456 12 | */ 13 | 14 | #include 15 | 16 | int main() { 17 | char radix[] = "0123456789ABC"; 18 | int a[3]; 19 | for (int i = 0; i < 3; i++) 20 | scanf("%d", &a[i]); 21 | printf("#"); 22 | for (int i = 0; i < 3; i++) 23 | printf("%c%c", radix[a[i]/13], radix[a[i]%13]); 24 | return 0; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1031.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given any string of N (>=5) characters, you are asked to form the characters into the shape of U. For example, "helloworld" can be printed as: 3 | h d 4 | e l 5 | l r 6 | lowo 7 | 8 | That is, the characters must be printed in the original order, starting top-down from the left vertical line with n1characters, then left to right along the bottom line with n2 characters, and finally bottom-up along the vertical line with n3 characters. And more, we would like U to be as squared as possible -- that is, it must be satisfied that n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = N. 9 | Input Specification: 10 | Each input file contains one test case. Each case contains one string with no less than 5 and no more than 80 characters in a line. The string contains no white space. 11 | Output Specification: 12 | For each test case, print the input string in the shape of U as specified in the description. 13 | Sample Input: 14 | helloworld! 15 | 16 | Sample Output: 17 | h ! 18 | e d 19 | l l 20 | lowor 21 | */ 22 | 23 | #include 24 | #include 25 | #include 26 | 27 | int main() { 28 | char str[82]; 29 | 30 | scanf("%s", str); 31 | 32 | int N = strlen(str); 33 | 34 | int n2, n, N2; 35 | 36 | n = -1; 37 | for (n2 = 3; n2 <= N; n2++) { 38 | if ((N + 2 - n2) % 2) { 39 | continue; 40 | } 41 | 42 | if ((N + 2 - n2) / 2 <= n2) { 43 | if ((N + 2 - n2) / 2 > n) { 44 | n = (N + 2 - n2) / 2; 45 | N2 = n2; 46 | } 47 | } 48 | } 49 | 50 | for (int i = 0; i < n - 1; i++) { 51 | printf("%c", str[i]); 52 | for (int j = 0; j < N2 - 2; j++) { 53 | printf(" "); 54 | } 55 | printf("%c\n", str[N - 1 - i]); 56 | } 57 | 58 | for (int i = (n - 1); i < (n - 1 + N2); i++) { 59 | printf("%c", str[i]); 60 | } 61 | 62 | 63 | return 0; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1040.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given "Is PAT&TAP symmetric?", the longest symmetric sub-string is "s PAT&TAP s", hence you must output 11. 3 | Input Specification: 4 | Each input file contains one test case which gives a non-empty string of length no more than 1000. 5 | Output Specification: 6 | For each test case, simply print the maximum length in a line. 7 | Sample Input: 8 | Is PAT&TAP symmetric? 9 | 10 | Sample Output: 11 | 11 12 | */ 13 | #include 14 | #include 15 | #include 16 | 17 | using std::max; 18 | 19 | const int max_n = 1001; 20 | char s[max_n]; 21 | 22 | int main() 23 | { 24 | gets(s); 25 | int len = strlen(s); 26 | int res = 0; 27 | for (int i=0; i=0 && i+j=0 && i+j+1 21 | #include 22 | 23 | using namespace std; 24 | const int max_n = 100001; 25 | pair tab[max_n]; 26 | 27 | int main() 28 | { 29 | int n; 30 | cin >> n; 31 | for (int i=0; i> x; 34 | tab[x].first++; 35 | tab[x].second = i; 36 | } 37 | int res = -1, id = max_n; 38 | for (int i=1; i 20 | #include 21 | #include 22 | 23 | using namespace std; 24 | 25 | int main() 26 | { 27 | int n; 28 | cin >> n; 29 | vector v(n); 30 | int sum = 0; 31 | for (int i=0; i> x; 34 | v[i] = sum; 35 | sum += x; 36 | } 37 | int k; 38 | cin >> k; 39 | while (k--) { 40 | int a, b; 41 | cin >> a >> b; 42 | if (--a > --b) swap(a, b); 43 | cout << min(v[b]-v[a], sum-v[b]+v[a]) << endl; 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1049.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | The task is simple: given any positive integer N, you are supposed to count the total number of 1's in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1's in 1, 10, 11, and 12. 3 | 4 | Input Specification: 5 | 6 | Each input file contains one test case which gives the positive N (<=230). 7 | 8 | Output Specification: 9 | 10 | For each test case, print the number of 1's in one line. 11 | 12 | Sample Input: 13 | 12 14 | Sample Output: 15 | 5 16 | */ 17 | #include 18 | 19 | int f(int n) 20 | { 21 | if (n < 10) return n?1:0; 22 | int p = 1; 23 | while (n/p >= 10) 24 | p *= 10; 25 | int d = n / p; 26 | int a = d*f(p-1); 27 | int b = d==1?(n%p+1):p; 28 | int c = n%p; 29 | return a + b + f(c); 30 | } 31 | 32 | int main() 33 | { 34 | int n; 35 | scanf("%d", &n); 36 | printf("%d\n", f(n)); 37 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1050.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1. Your task is simply to calculate S1 - S2 for any given strings. However, it might not be that simple to do it fast. 3 | Input Specification: 4 | Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively. The string lengths of both strings are no more than 10^4. It is guaranteed that all the characters are visible ASCII codes and white space, and a new line character signals the end of a string. 5 | Output Specification: 6 | For each test case, print S1 - S2 in one line. 7 | Sample Input: 8 | They are students. 9 | aeiou 10 | 11 | Sample Output: 12 | Thy r stdnts. 13 | 14 | */ 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | 22 | int ctoi(char c) { 23 | if (c == ' ') { 24 | return 0; 25 | } 26 | if (c <= 'Z' && c >= 'A') { 27 | return 1 + c - 'A'; 28 | } 29 | if (c <= 'z' && c >= 'a') { 30 | return 50 + c - 'a'; 31 | } 32 | } 33 | 34 | int main() { 35 | bool bucket[256]; 36 | 37 | for (int i = 0; i < 256; i++) { 38 | bucket[i] = true; 39 | } 40 | 41 | char s1[10002], s2[100002]; 42 | 43 | int ndelete = 0; 44 | char ch; 45 | int len = 0; 46 | 47 | while ((s1[len++] = getchar()) != '\n') 48 | ; 49 | 50 | while ((ch = getchar()) != '\n') { 51 | if (bucket[ch]) { 52 | ndelete++; 53 | bucket[ch] = false; 54 | 55 | if (ndelete > 256) { 56 | break; 57 | } 58 | } 59 | 60 | } 61 | 62 | for (int i = 0; i < len; i++) { 63 | if (bucket[s1[i]]) { 64 | printf("%c", s1[i]); 65 | } 66 | } 67 | 68 | return 0; 69 | } 70 | 71 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1051.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4. 3 | Input Specification: 4 | Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space. 5 | Output Specification: 6 | For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not. 7 | Sample Input: 8 | 5 7 5 9 | 1 2 3 4 5 6 7 10 | 3 2 1 7 5 6 4 11 | 7 6 5 4 3 2 1 12 | 5 6 4 3 7 2 1 13 | 1 7 6 5 4 3 2 14 | 15 | Sample Output: 16 | YES 17 | NO 18 | NO 19 | YES 20 | NO 21 | */ 22 | #include 23 | #include 24 | 25 | int main() { 26 | int size, n, nquery; 27 | 28 | char input[2000]; 29 | 30 | scanf("%d %d %d", &size, &n, &nquery); 31 | 32 | bool *stack = new bool[n + 1]; 33 | 34 | for (int i = 0; i < nquery; i++) { 35 | int lastv = -1; 36 | 37 | bool dobreak = false; 38 | for (int j = 0; j <= n; j++) { 39 | stack[j] = true; 40 | } 41 | for (int j = 0; j < n; j++) { 42 | int v; 43 | 44 | scanf("%d", &v); 45 | 46 | if (dobreak) { 47 | continue; 48 | } 49 | 50 | if ((v - j) > size) { 51 | printf("NO\n"); 52 | dobreak = true; 53 | continue; 54 | } 55 | 56 | stack[v] = false; 57 | 58 | for (int k = lastv - 1; k > v; k--) { 59 | if (stack[k]) { 60 | dobreak = true; 61 | printf("NO\n"); 62 | break; 63 | } 64 | 65 | } 66 | lastv = v; 67 | } 68 | if (!dobreak) { 69 | printf("YES\n"); 70 | } 71 | 72 | } 73 | 74 | return 0; 75 | } 76 | 77 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1054.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Behind the scenes in the computer's memory, color is always talked about as a series of 24 bits of information for each pixel. In an image, the color with the largest proportional area is called the dominant color. A strictly dominant color takes more than half of the total area. Now given an image of resolution M by N (for example, 800x600), you are supposed to point out the strictly dominant color. 3 | Input Specification: 4 | Each input file contains one test case. For each case, the first line contains 2 positive numbers: M (<=800) and N (<=600) which are the resolutions of the image. Then N lines follow, each contains M digital colors in the range [0, 224). It is guaranteed that the strictly dominant color exists for each input image. All the numbers in a line are separated by a space. 5 | Output Specification: 6 | For each test case, simply print the dominant color in a line. 7 | Sample Input: 8 | 5 3 9 | 0 0 255 16777215 24 10 | 24 24 0 0 24 11 | 24 0 24 24 24 12 | 13 | Sample Output: 14 | 24 15 | 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | using namespace std; 23 | 24 | int main() { 25 | int m, n; 26 | 27 | cin >> m >> n; 28 | 29 | int a = -1; 30 | int time = 0; 31 | int discard = 0; 32 | 33 | for (int i = 0; i < m * n; i++) { 34 | int x; 35 | 36 | scanf("%d", &x); 37 | 38 | if (a < 0) { 39 | a = x; 40 | time = 1; 41 | } else { 42 | if (a != x) { 43 | time--; 44 | discard += 2; 45 | if (time <= 0) { 46 | a = -1; 47 | } 48 | } else { 49 | time++; 50 | if (time > (m * n - discard) / 2) { 51 | break; 52 | } 53 | } 54 | } 55 | } 56 | 57 | cout << a; 58 | return 0; 59 | } 60 | 61 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1058.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | If you are a fan of Harry Potter, you would know the world of magic has its own currency system -- as Hagrid explained it to Harry, "Seventeen silver Sickles to a Galleon and twenty-nine Knuts to a Sickle, it's easy enough." Your job is to write a program to compute A+B where A and B are given in the standard form of "Galleon.Sickle.Knut" (Galleon is an integer in [0, 10^7], Sickle is an integer in [0, 17), and Knut is an integer in [0, 29)). 3 | 4 | Input Specification: 5 | 6 | Each input file contains one test case which occupies a line with A and B in the standard form, separated by one space. 7 | 8 | Output Specification: 9 | 10 | For each test case you should output the sum of A and B in one line, with the same format as the input. 11 | 12 | Sample Input: 13 | 3.2.1 10.16.27 14 | Sample Output: 15 | 14.1.28 16 | */ 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | int main() 23 | { 24 | char s1[30], s2[30]; 25 | 26 | scanf("%s %s", s1, s2); 27 | 28 | int index1[3], index2[3]; 29 | 30 | int i=0; 31 | 32 | index1[0] = 0; 33 | int index = 1; 34 | while(true) 35 | { 36 | char ch = s1[i]; 37 | 38 | if( ch == '.' ) 39 | { 40 | s1[i] = '\0'; 41 | index1[index++] = i+1; 42 | } 43 | else if( ch == '\0' ) 44 | { 45 | break; 46 | } 47 | i++; 48 | } 49 | 50 | index2[0] = 0; 51 | index = 1; 52 | i = 0; 53 | while(true) 54 | { 55 | char ch = s2[i]; 56 | 57 | if( ch == '.' ) 58 | { 59 | s2[i] = '\0'; 60 | index2[index++] = i+1; 61 | } 62 | else if( ch == '\0' ) 63 | { 64 | break; 65 | } 66 | i++; 67 | } 68 | 69 | int a[3] = {0,0,0}; 70 | 71 | for(int i=0; i<3; i++) 72 | { 73 | a[i] = atoi(s1+index1[i]) + atoi(s2+index2[i]); 74 | } 75 | 76 | a[1] += a[2]/29; 77 | 78 | a[2] %= 29; 79 | 80 | a[0] += a[1]/17; 81 | 82 | a[1] %= 17; 83 | 84 | printf("%d.%d.%d", a[0], a[1], a[2]); 85 | 86 | return 0; 87 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1059.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1 * p2^k2 *…*pm^km. 3 | 4 | Input Specification: 5 | 6 | Each input file contains one test case which gives a positive integer N in the range of long int. 7 | 8 | Output Specification: 9 | 10 | Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi's are prime factors of N in increasing order, and the exponent ki is the number of pi -- hence when there is only one pi, ki is 1 and must NOT be printed out. 11 | 12 | Sample Input: 13 | 97532468 14 | Sample Output: 15 | 97532468=2^2*11*17*101*1291 16 | */ 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | 22 | struct node 23 | { 24 | int key; 25 | int time; 26 | 27 | node(){} 28 | node(int k):key(k), time(1){} 29 | }; 30 | 31 | vector primes; 32 | bool isprime(int p); 33 | 34 | int main() 35 | { 36 | int m; 37 | 38 | scanf("%d", &m); 39 | 40 | printf("%d=", m); 41 | 42 | if (m == 1) { 43 | printf("1"); 44 | return 0; 45 | } 46 | vector factors; 47 | int p = 2; 48 | while (m > 1) 49 | { 50 | while (m%p == 0) { 51 | if (factors.size()) 52 | { 53 | if (factors.back().key == p) { 54 | factors.back().time ++; 55 | } 56 | else { 57 | factors.push_back(node(p)); 58 | } 59 | } 60 | else 61 | { 62 | factors.push_back(node(p)); 63 | } 64 | 65 | m /= p; 66 | } 67 | 68 | while (!isprime(++p)) 69 | ; 70 | } 71 | 72 | for (int i=0; i 1) { 79 | printf("^%d", factors[i].time); 80 | } 81 | } 82 | return 0; 83 | } 84 | 85 | bool isprime(int p) 86 | { 87 | for (int i=0; i C. 3 | 4 | Input Specification: 5 | 6 | The first line of the input gives the positive number of test cases, T (<=10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces. 7 | 8 | Output Specification: 9 | 10 | For each test case, output in one line "Case #X: true" if A+B>C, or "Case #X: false" otherwise, where X is the case number (starting from 1). 11 | 12 | Sample Input: 13 | 3 14 | 1 2 3 15 | 2 3 4 16 | 9223372036854775807 -9223372036854775808 0 17 | Sample Output: 18 | Case #1: false 19 | Case #2: true 20 | Case #3: false 21 | */ 22 | #include 23 | #include 24 | 25 | using namespace std; 26 | 27 | typedef long long ll; 28 | 29 | bool solve(ll a, ll b, ll c) 30 | { 31 | ll sum = a+b; 32 | if (a > 0 && b > 0 && sum <= 0) return true; 33 | if (a < 0 && b < 0 && sum >= 0) return false; 34 | return sum > c; 35 | } 36 | 37 | int main() 38 | { 39 | int n; 40 | scanf("%d", &n); 41 | for (int i=0; i 34 | #include 35 | #include 36 | 37 | using namespace std; 38 | 39 | int foo(int v) { 40 | string s = to_string(v); 41 | s.resize(4, '0'); 42 | sort(s.begin(), s.end()); 43 | string t = s; 44 | reverse(t.begin(), t.end()); 45 | int a = stoi(s), b = stoi(t); 46 | printf("%04d - %04d = %04d\n", b, a, b - a); 47 | return b - a; 48 | } 49 | 50 | int main() { 51 | int n; 52 | scanf("%d", &n); 53 | while ((n = foo(n)) && n != 6174); 54 | return 0; 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1079.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flexwang-zz/CodeTest/db4c4a4f5cf5c3bf94b5fcc91183571ec4c6a666/PAT/PAT_A/c++/pat1079.cpp -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1084.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | On a broken keyboard, some of the keys are worn out. So when you type some sentences, the characters corresponding to those keys will not appear on screen. 3 | 4 | Now given a string that you are supposed to type, and the string that you actually type out, please list those keys which are for sure worn out. 5 | 6 | Input Specification: 7 | 8 | Each input file contains one test case. For each case, the 1st line contains the original string, and the 2nd line contains the typed-out string. Each string contains no more than 80 characters which are either English letters [A-Z] (case insensitive), digital numbers [0-9], or "_" (representing the space). It is guaranteed that both strings are non-empty. 9 | 10 | Output Specification: 11 | 12 | For each test case, print in one line the keys that are worn out, in the order of being detected. The English letters must be capitalized. Each worn out key must be printed once only. It is guaranteed that there is at least one worn out key. 13 | 14 | Sample Input: 15 | 7_This_is_a_test 16 | _hs_s_a_es 17 | Sample Output: 18 | 7TI 19 | */ 20 | 21 | #include 22 | #include 23 | 24 | #define size 100 25 | 26 | char cap(char ch) { 27 | if (ch <= 'z' && ch >= 'a') { 28 | return ch - 32; 29 | } 30 | 31 | return ch; 32 | } 33 | 34 | bool contains(char *str, int len, char ch) { 35 | for (int i = 0; i < len; i++) { 36 | if (str[i] == ch) 37 | return true; 38 | } 39 | 40 | return false; 41 | } 42 | 43 | int main() 44 | { 45 | char str1[size], str2[size]; 46 | char result[size]; 47 | 48 | int len1, len2, len3; 49 | 50 | scanf("%s %s", str1, str2); 51 | 52 | len1 = strlen(str1); 53 | len2 = strlen(str2); 54 | 55 | len3 = 0; 56 | 57 | memset(result, '\0', size); 58 | 59 | int i2 = 0; 60 | for (int i1 = 0, i2=0; i1 < len1; i1++, i2++) { 61 | while (str1[i1] && str1[i1] != str2[i2]) { 62 | if (!contains(result, len3, cap(str1[i1]))) { 63 | result[len3++] = cap(str1[i1]); 64 | } 65 | i1++; 66 | } 67 | } 68 | 69 | printf("%s\n", result); 70 | 71 | return 0; 72 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1085.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sequence of positive integers and another positive integer p. The sequence is said to be a "perfect sequence" if M <= m * p where M and m are the maximum and minimum numbers in the sequence, respectively. 3 | 4 | Now given a sequence and a parameter p, you are supposed to find from the sequence as many numbers as possible to form a perfect subsequence. 5 | 6 | Input Specification: 7 | 8 | Each input file contains one test case. For each case, the first line contains two positive integers N and p, where N (<= 10^5) is the number of integers in the sequence, and p (<= 1^09) is the parameter. In the second line there are N positive integers, each is no greater than ^109. 9 | 10 | Output Specification: 11 | 12 | For each test case, print in one line the maximum number of integers that can be chosen to form a perfect subsequence. 13 | 14 | Sample Input: 15 | 10 8 16 | 2 3 20 4 5 1 6 7 8 9 17 | Sample Output: 18 | 8 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | using namespace std; 26 | 27 | typedef long long LL; 28 | 29 | int main() 30 | { 31 | LL n, p; 32 | 33 | cin >> n >> p; 34 | 35 | vector v(n); 36 | 37 | for (LL i = 0LL; i < n; i++) { 38 | cin >> v[i]; 39 | } 40 | 41 | sort(v.begin(), v.end()); 42 | LL result = 0; 43 | LL end = 0; 44 | for (LL begin = 0; begin < n; begin++) { 45 | LL target = v[begin]; 46 | LL e; 47 | for (e = end; e < n; e++) { 48 | if (v[e] > target*p) 49 | break; 50 | } 51 | 52 | end = e; 53 | 54 | if (e - begin > result) 55 | result = e - begin; 56 | } 57 | 58 | cout << result << endl; 59 | 60 | return 0; 61 | 62 | } -------------------------------------------------------------------------------- /PAT/PAT_A/c++/pat1104.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a sequence of positive numbers, a segment is defined to be a consecutive subsequence. For example, given the sequence {0.1, 0.2, 0.3, 0.4}, we have 10 segments: (0.1) (0.1, 0.2) (0.1, 0.2, 0.3) (0.1, 0.2, 0.3, 0.4) (0.2) (0.2, 0.3) (0.2, 0.3, 0.4) (0.3) (0.3, 0.4) (0.4). 3 | 4 | Now given a sequence, you are supposed to find the sum of all the numbers in all the segments. For the previous example, the sum of all the 10 segments is 0.1 + 0.3 + 0.6 + 1.0 + 0.2 + 0.5 + 0.9 + 0.3 + 0.7 + 0.4 = 5.0. 5 | 6 | Input Specification: 7 | 8 | Each input file contains one test case. For each case, the first line gives a positive integer N, the size of the sequence which is no more than 10^5. The next line contains N positive numbers in the sequence, each no more than 1.0, separated by a space. 9 | 10 | Output Specification: 11 | 12 | For each test case, print in one line the sum of all the numbers in all the segments, accurate up to 2 decimal places. 13 | 14 | Sample Input: 15 | 4 16 | 0.1 0.2 0.3 0.4 17 | Sample Output: 18 | 5.00 19 | 20 | */ 21 | 22 | #include 23 | 24 | int main() 25 | { 26 | int n; 27 | double sum = 0.0; 28 | scanf("%d", &n); 29 | for (int i=0; i=n; and m-n is the minimum of all the possible values. 3 | 4 | Input Specification: 5 | 6 | Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 10^4. The numbers in a line are separated by spaces. 7 | 8 | Output Specification: 9 | 10 | For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line. 11 | 12 | Sample Input: 13 | 12 14 | 37 76 20 98 76 42 53 95 60 81 58 93 15 | Sample Output: 16 | 98 95 93 17 | 42 37 81 18 | 53 20 76 19 | 58 60 76 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | using namespace std; 27 | int b[9999][100]; 28 | void print(int *a, int m, int n) 29 | { 30 | int dj[] = {0, 1, 0, -1}; 31 | int dk[] = {1, 0, -1, 0}; 32 | for (int i=m*n-1,j=0,k=0,dir=0; i>=0; --i) { 33 | b[j][k] = a[i]; 34 | int j0 = dj[dir] + j; 35 | int k0 = dk[dir] + k; 36 | if (j0 < 0 || j0 >= m || k0 < 0 || k0 >= n || b[j0][k0]) 37 | dir = (dir+1)%4; 38 | j += dj[dir]; 39 | k += dk[dir]; 40 | } 41 | for (int i=0; i 1) positive integers, you are supposed to partition them into two disjoint sets A1 and A2 of n1 and n2 numbers, respectively. Let S1 and S2 denote the sums of all the numbers in A1 and A2, respectively. You are supposed to make the partition so that |n1 - n2| is minimized first, and then |S1 - S2| is maximized. 3 | 4 | Input Specification: 5 | 6 | Each input file contains one test case. For each case, the first line gives an integer N (2 <= N <= 10^5), and then N positive integers follow in the next line, separated by spaces. It is guaranteed that all the integers and their sum are less than 231. 7 | 8 | Output Specification: 9 | 10 | For each case, print in a line two numbers: |n1 - n2| and |S1 - S2|, separated by exactly one space. 11 | 12 | Sample Input 1: 13 | 10 14 | 23 8 10 99 46 2333 46 1 666 555 15 | Sample Output 1: 16 | 0 3611 17 | Sample Input 2: 18 | 13 19 | 110 79 218 69 3721 100 29 135 2 6 13 5188 85 20 | Sample Output 2: 21 | 1 9359 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | using namespace std; 30 | 31 | int main() 32 | { 33 | int n; 34 | cin >> n; 35 | vector v(n); 36 | for (auto&x : v) 37 | cin >> x; 38 | sort(v.begin(), v.end()); 39 | int sum = accumulate(v.begin(), v.end(), 0); 40 | int d1 = accumulate(v.begin(), v.begin()+n/2, 0); 41 | int d2 = accumulate(v.begin(), v.begin()+(n+1)/2, 0); 42 | int x = n%2?1:0; 43 | int y = max(sum-d1*2, sum-d2*2); 44 | cout << x << " " << y; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /PAT/PAT_A/python/README.md: -------------------------------------------------------------------------------- 1 | Notification 2 | ========= 3 | Due to the wellknown extra overhead of Python, TLE(Time Limitation exceed) would occur for the following problem. 4 | 5 | - [1013](https://www.patest.cn/contests/pat-a-practise/1013) 6 | 7 | But still, we can see what consice code we can achieve with Python. 8 | 9 | -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1004.py: -------------------------------------------------------------------------------- 1 | n, m = map(int, input().split()) 2 | g = [[] for _ in range(n+1)] 3 | for i in range(m): 4 | lt = list(map(int, input().split())) 5 | g[lt[0]] = lt[2:] 6 | level = [1] 7 | res = [] 8 | while level: 9 | next = [] 10 | cnt = 0 11 | for i in level: 12 | for j in g[i]: 13 | next.append(j) 14 | if not g[i]: 15 | cnt += 1 16 | res.append(str(cnt)) 17 | level = next 18 | print(' '.join(res)) -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1005.py: -------------------------------------------------------------------------------- 1 | word=['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] 2 | sum = sum(map(int, input())) 3 | lt = [word[int(i)] for i in str(sum)] 4 | print(' '.join(lt)) -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1006.py: -------------------------------------------------------------------------------- 1 | lt = [] 2 | for i in range(int(input())): 3 | lt.append(input().split()) 4 | a = min(lt, key=lambda x:x[1])[0] 5 | b = max(lt, key=lambda x:x[2])[0] 6 | print('%s %s'%(a, b)) 7 | 8 | -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1008.py: -------------------------------------------------------------------------------- 1 | lt = list(map(int, input().split()))[1:] 2 | cur = 0 3 | def f(x): 4 | global cur 5 | if x-cur > 0: 6 | res = 5+(x-cur)*6 7 | else: 8 | res = 5+(cur-x)*4 9 | cur = x 10 | return res 11 | res = sum(map(f, lt)) 12 | print(res) -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1013.py: -------------------------------------------------------------------------------- 1 | def find(v, root): 2 | if root[v] != v: 3 | root[v] = find(root[v], root) 4 | return root[v] 5 | def unit(v, t, root): 6 | rv = find(v, root) 7 | rt = find(t, root) 8 | if rv != rt: 9 | root[rv] = rt 10 | n, m, k = map(int, input().split()) 11 | es = [tuple(map(int, input().split())) for _ in range(m)] 12 | for t in map(int, input().split()): 13 | root = list(range(n)) 14 | for e in es: 15 | if e[0] != t and e[1] != t: 16 | unit(e[0]-1, e[1]-1, root) 17 | res = sum(map(lambda x,y:x == y, range(n), root)) 18 | print(res-2) -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1023.py: -------------------------------------------------------------------------------- 1 | a = int(input()) 2 | if sorted(str(a)) == sorted(str(a*2)): 3 | print("Yes") 4 | else: 5 | print("No") 6 | print(a*2) -------------------------------------------------------------------------------- /PAT/PAT_A/python/pat1024.py: -------------------------------------------------------------------------------- 1 | n, k = map(int, input().split()) 2 | is_pal = lambda x: str(x) == str(x)[::-1] 3 | rev = lambda x: int(str(x)[::-1]) 4 | i = 0 5 | while not is_pal(n) and i < k: 6 | n += rev(n) 7 | i += 1 8 | print('%d\n%d'%(n, i)); -------------------------------------------------------------------------------- /PAT/PAT_B/pat1001.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 卡拉兹(Callatz)猜想: 3 | 4 | 对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。这样一直反复砍下去,最后一定在某一步得到n=1。卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展…… 5 | 6 | 我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1? 7 | 8 | 输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。 9 | 10 | 输出格式:输出从n计算到1需要的步数。 11 | 12 | 输入样例: 13 | 3 14 | 输出样例: 15 | 5 16 | ''' 17 | n = int(input()) 18 | t = 0 19 | while n != 1: 20 | n = n/2 if n%2==0 else (3*n+1)/2 21 | t += 1 22 | print(t) -------------------------------------------------------------------------------- /PAT/PAT_B/pat1002.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。 3 | 4 | 输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10100。 5 | 6 | 输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。 7 | 8 | 输入样例: 9 | 1234567890987654321123456789 10 | 输出样例: 11 | yi san wu 12 | ''' 13 | s = input() 14 | total = 0 15 | for c in s: 16 | total += int(c) 17 | d = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4':'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', 18 | '9':'jiu'} 19 | s = str(total) 20 | for i in range(len(s)): 21 | print(d[s[i]], end=' ' if i != len(s)-1 else '\n') -------------------------------------------------------------------------------- /PAT/PAT_B/pat1003.py: -------------------------------------------------------------------------------- 1 | ''' 2 | “答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。 3 | 4 | 得到“答案正确”的条件是: 5 | 6 | 1. 字符串中必须仅有P, A, T这三种字符,不可以包含其它字符; 7 | 2. 任意形如 xPATx 的字符串都可以获得“答案正确”,其中 x 或者是空字符串,或者是仅由字母 A 组成的字符串; 8 | 3. 如果 aPbTc 是正确的,那么 aPbATca 也是正确的,其中 a, b, c 均或者是空字符串,或者是仅由字母 A 组成的字符串。 9 | 10 | 现在就请你为PAT写一个自动裁判程序,判定哪些字符串是可以获得“答案正确”的。 11 | 输入格式: 每个测试输入包含1个测试用例。第1行给出一个自然数n (<10),是需要检测的字符串个数。接下来每个字符串占一行,字符串长度不超过100,且不包含空格。 12 | 13 | 输出格式:每个字符串的检测结果占一行,如果该字符串可以获得“答案正确”,则输出YES,否则输出NO。 14 | 15 | 输入样例: 16 | 8 17 | PAT 18 | PAAT 19 | AAPATAA 20 | AAPAATAAAA 21 | xPATx 22 | PT 23 | Whatever 24 | APAAATAA 25 | 输出样例: 26 | YES 27 | YES 28 | YES 29 | YES 30 | NO 31 | NO 32 | NO 33 | NO 34 | ''' 35 | def accept(s): 36 | ca0 = 0 37 | ca1 = 0 38 | ca2 = 0 39 | cp = 0 40 | ct = 0 41 | for c in s: 42 | if c != 'P' and c != 'A' and c != 'T': 43 | return False 44 | if c == 'P': 45 | if cp > 0 or ct > 0: 46 | return False 47 | else: 48 | cp += 1 49 | if c == 'T': 50 | if cp == 0 or ct > 0: 51 | return False 52 | else: 53 | ct += 1 54 | if c == 'A': 55 | if cp == 0: 56 | ca0 += 1 57 | elif ct == 0: 58 | ca1 += 1 59 | else: 60 | ca2 += 1 61 | if cp > 0 and ct > 0 and ca1 > 0 and (ca2 - ca0) == ca0 * (ca1 - 1): 62 | return True 63 | return False 64 | 65 | 66 | n = int(input()) 67 | for i in range(n): 68 | s = input() 69 | print('YES' if accept(s) else 'NO') -------------------------------------------------------------------------------- /PAT/PAT_B/pat1004.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。 3 | 4 | 输入格式:每个测试输入包含1个测试用例,格式为 5 | 6 | 第1行:正整数n 7 | 第2行:第1个学生的姓名 学号 成绩 8 | 第3行:第2个学生的姓名 学号 成绩 9 | ... ... ... 10 | 第n+1行:第n个学生的姓名 学号 成绩 11 | 其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。 12 | 输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。 13 | 14 | 输入样例: 15 | 3 16 | Joe Math990112 89 17 | Mike CS991301 100 18 | Mary EE990830 95 19 | 输出样例: 20 | Mike CS991301 21 | Joe Math990112 22 | ''' 23 | n = int(input()) 24 | l = [] 25 | for i in range(n): 26 | t = input().split() 27 | l.append((int(t[2]), t[0], t[1])) 28 | def get_key(t): 29 | return t[0] 30 | l.sort(key=get_key) 31 | print('%s %s'%(l[-1][1], l[-1][2])) 32 | print('%s %s'%(l[0][1], l[0][2])) -------------------------------------------------------------------------------- /PAT/PAT_B/pat1030.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 给定一个正整数数列,和正整数p,设这个数列中的最大值是M,最小值是m,如果M <= m * p,则称这个数列是完美数列。 3 | 4 | 现在给定参数p和一些正整数,请你从中选择尽可能多的数构成一个完美数列。 5 | 6 | 输入格式: 7 | 8 | 输入第一行给出两个正整数N和p,其中N(<= 105)是输入的正整数的个数,p(<= 109)是给定的参数。第二行给出N个正整数,每个数不超过109。 9 | 10 | 输出格式: 11 | 12 | 在一行中输出最多可以选择多少个数可以用它们组成一个完美数列。 13 | 14 | 输入样例: 15 | 10 8 16 | 2 3 20 4 5 1 6 7 8 9 17 | 输出样例: 18 | 8 19 | ''' 20 | p = int(input().split()[1]) 21 | arr = [int(s) for s in input().split()] 22 | n = len(arr) 23 | arr.sort() 24 | ans = 0 25 | i = j = 0 26 | while j < n: 27 | if arr[j] <= arr[i] * p: 28 | ans = (j-i+1) if (j-i+1)>ans else ans 29 | j += 1 30 | else: 31 | i += 1 32 | print(ans) 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /PAT/README.md: -------------------------------------------------------------------------------- 1 | learn more about PAT: https://www.patest.cn/ 2 | -------------------------------------------------------------------------------- /POJ/README: -------------------------------------------------------------------------------- 1 | learn more about POJ: http://poj.org 2 | -------------------------------------------------------------------------------- /POJ/poj1088.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flexwang-zz/CodeTest/db4c4a4f5cf5c3bf94b5fcc91183571ec4c6a666/POJ/poj1088.cpp -------------------------------------------------------------------------------- /POJ/poj1159.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Description 3 | 4 | A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. 5 | 6 | As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome. 7 | Input 8 | 9 | Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct. 10 | Output 11 | 12 | Your program is to write to standard output. The first line contains one integer, which is the desired minimal number. 13 | Sample Input 14 | 15 | 5 16 | Ab3bd 17 | Sample Output 18 | 19 | 2 20 | */ 21 | #include 22 | #include 23 | using namespace std; 24 | const int max_n = 5001; 25 | int n; 26 | char a[max_n]; 27 | int dp[2][max_n]; 28 | 29 | int main() 30 | { 31 | scanf("%d%s", &n, a); 32 | 33 | for (int i=1; i<=n; i++) 34 | for (int j=1; j<=n; j++) 35 | if (a[i-1] == a[n-1-(j-1)]) 36 | dp[i&1][j] = dp[(i-1)&1][j-1] + 1; 37 | else 38 | dp[i&1][j] = max(dp[(i-1)&1][j], dp[i&1][j-1]); 39 | printf("%d\n", n-dp[n&1][n]); 40 | return 0; 41 | } -------------------------------------------------------------------------------- /POJ/poj1163.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Description 3 | 4 | 7 5 | 3 8 6 | 8 1 0 7 | 2 7 4 4 8 | 4 5 2 6 5 9 | 10 | (Figure 1) 11 | Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right. 12 | Input 13 | 14 | Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99. 15 | Output 16 | 17 | Your program is to write to standard output. The highest sum is written as an integer. 18 | Sample Input 19 | 20 | 5 21 | 7 22 | 3 8 23 | 8 1 0 24 | 2 7 4 4 25 | 4 5 2 6 5 26 | Sample Output 27 | 28 | 30 29 | */ 30 | #include 31 | #include 32 | using namespace std; 33 | const int max_n = 105; 34 | int a[max_n][max_n]; 35 | int dp[max_n][max_n]; 36 | int n; 37 | 38 | int main() 39 | { 40 | scanf("%d", &n); 41 | for (int i=0; i=0; i--) 47 | for (int j=0; j<=i; j++) 48 | dp[i][j] = max(dp[i+1][j], dp[i+1][j+1])+a[i][j]; 49 | printf("%d\n", dp[0][0]); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /POJ/poj1692.cpp: -------------------------------------------------------------------------------- 1 | //#define POJ_1692 2 | #ifdef POJ_1692 3 | #include 4 | #include 5 | #include 6 | 7 | using std::max; 8 | 9 | const int max_n = 105; 10 | int n1, n2; 11 | int a[max_n], b[max_n]; 12 | int dp[max_n][max_n]; 13 | 14 | int main() 15 | { 16 | int ncase; 17 | scanf("%d", &ncase); 18 | while (ncase--) { 19 | scanf("%d%d", &n1, &n2); 20 | for (int i=0; i=0&&b[k1]!=a[i-1]; k1--); 31 | for (k2=i-2; k2>=0&&a[k2]!=b[j-1]; k2--); 32 | if (k1 >=0 && k2>=0) 33 | dp[i][j] = max(dp[i][j], dp[k2][k1]+2); 34 | } 35 | 36 | } 37 | printf("%d\n", dp[n1][n2]); 38 | } 39 | 40 | return 0; 41 | } 42 | 43 | #endif -------------------------------------------------------------------------------- /POJ/poj1836.cpp: -------------------------------------------------------------------------------- 1 | //#define POJ_1836 2 | #ifdef POJ_1836 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | const int max_n = 1001; 10 | int n; 11 | float h[max_n]; 12 | int dp[max_n]; 13 | 14 | int main() 15 | { 16 | scanf("%d", &n); 17 | for (int i=0; i=0; j--) { 27 | for (int k=j+1; k<=i; k++) 28 | if (h[k] < h[i] || k==i) { 29 | if (h[j] < h[k]) 30 | dp[ 31 | } 32 | 33 | } 34 | ans = min(ans, local_ans); 35 | } 36 | printf("%d\n", ans); 37 | return 0; 38 | } 39 | 40 | #endif -------------------------------------------------------------------------------- /POJ/poj1984.cpp: -------------------------------------------------------------------------------- 1 | //#define POJ_1984 2 | #ifdef POJ_1984 3 | #include 4 | 5 | #endif -------------------------------------------------------------------------------- /POJ/poj2104.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void init_segment(vector > &seg, vector& v, int id, int l, int r) { 8 | if (l+1 == r) { 9 | seg[id].push_back(v[l]); 10 | return; 11 | } 12 | int m = l+(r-l)/2; 13 | init_segment(seg, v, id*2+1, l, m); 14 | init_segment(seg, v, id*2+2, m, r); 15 | seg[id].resize(r-l); 16 | merge(seg[id*2+1].begin(), seg[id*2+1].end(), seg[id*2+2].begin(), seg[id*2+2].end(), seg[id].begin()); 17 | } 18 | 19 | int get_cnt(vector > &data, int id, int l, int r, int a, int b, int x) { 20 | if (b <= l || r <= a) return 0; 21 | if (a <= l && b >= r) return upper_bound(data[id].begin(), data[id].end(), x)-data[id].begin(); 22 | else { 23 | int m = l+(r-l)/2; 24 | return get_cnt(data, id*2+1, l, m, a, b, x) 25 | + get_cnt(data, id*2+2, m, r, a, b, x); 26 | } 27 | } 28 | int main() 29 | { 30 | int n, m; 31 | scanf("%d %d", &n, &m); 32 | vector v(n), sv; 33 | for (int i=0; i > data(size); 39 | init_segment(data, v, 0, 0, n); 40 | for (int i=0; i 2 | #include 3 | #include 4 | const int max_n = 1000001; 5 | char s[max_n]; 6 | int rank[max_n], sa[max_n], lcp[max_n], tmp[max_n], k; 7 | int n; 8 | bool compare(int i, int j) 9 | { 10 | if (rank[i] != rank[j]) return rank[i] < rank[j]; 11 | int ri = (i+k)<=n?rank[i+k]:-1; 12 | int rj = (j+k)<=n?rank[j+k]:-1; 13 | return ri < rj; 14 | } 15 | 16 | void compute_sa() 17 | { 18 | for (int i=0; i<=n; i++) { 19 | sa[i] = i; 20 | rank[i] = i0) h--; 41 | for (;j+h 31 | #include 32 | #include 33 | 34 | using std::max; 35 | 36 | const int max_n = 50005; 37 | int a[max_n], dp[max_n]; 38 | int n; 39 | 40 | int main() 41 | { 42 | int ncase; 43 | scanf("%d", &ncase); 44 | 45 | while (ncase--) { 46 | scanf("%d", &n); 47 | for (int i=0; i=1; i--) { 56 | temp += a[i]; 57 | back = max(back, temp); 58 | ans = max(ans, back + dp[i]); 59 | temp = max(0, temp); 60 | } 61 | printf("%d\n", ans); 62 | } 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /POJ/poj2533.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Description 3 | 4 | A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (a1, a2, ..., aN) be any sequence (ai1, ai2, ..., aiK), where 1 <= i1 < i2 < ... < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8). 5 | 6 | Your program, when given the numeric sequence, must find the length of its longest ordered subsequence. 7 | Input 8 | 9 | The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000 10 | Output 11 | 12 | Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence. 13 | Sample Input 14 | 15 | 7 16 | 1 7 3 5 9 4 8 17 | Sample Output 18 | 19 | 4 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | using namespace std; 27 | 28 | vector v; 29 | vector dp; 30 | int main() 31 | { 32 | int n; 33 | scanf("%d", &n); 34 | v.resize(n); 35 | dp.resize(n+1, INT_MAX); 36 | for (int i=0; i=0; i--) 42 | if (dp[i] != INT_MAX) { 43 | printf("%d\n", i); 44 | return 0; 45 | } 46 | return 0; 47 | } -------------------------------------------------------------------------------- /POJ/poj2553.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flexwang-zz/CodeTest/db4c4a4f5cf5c3bf94b5fcc91183571ec4c6a666/POJ/poj2553.cpp -------------------------------------------------------------------------------- /POJ/poj2823.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define max_n 1000001 5 | int que1[max_n], que2[max_n]; 6 | int a[max_n]; 7 | int ans1[max_n], ans2[max_n]; 8 | int n, k; 9 | int s1, s2, t1, t2; 10 | 11 | int search1(int l, int r, int *que, int ai) 12 | { 13 | while (l+1 < r) { 14 | int m = (l+r)/2; 15 | if (a[que[m]] <= ai) 16 | l = m; 17 | else 18 | r = m; 19 | } 20 | return l; 21 | } 22 | 23 | int search2(int l, int r, int *que, int ai) 24 | { 25 | while (l+1 < r) { 26 | int m = (l+r)/2; 27 | if (a[que[m]] >= ai) 28 | l = m; 29 | else 30 | r = m; 31 | } 32 | return l; 33 | } 34 | 35 | int main() 36 | { 37 | scanf("%d %d", &n, &k); 38 | for (int i=0; i a[i]) 42 | t1--; 43 | while (s2 < t2 && a[que2[t2-1]] < a[i]) 44 | t2 --; 45 | que1[t1++] = i; 46 | que2[t2++] = i; 47 | if (i >= k-1) { 48 | ans1[i-k+1] = a[que1[s1]]; 49 | ans2[i-k+1] = a[que2[s2]]; 50 | if (que1[s1] == i-k+1) s1++; 51 | if (que2[s2] == i-k+1) s2++; 52 | } 53 | } 54 | for (int i=0; i 24 | #include 25 | using namespace std; 26 | 27 | vector ns; 28 | int n, S; 29 | int ncase; 30 | int main() 31 | { 32 | scanf("%d", &ncase); 33 | 34 | for (int ic=0; ic= S && s <= n-1) { 50 | if (ans == 0 || ans > t-s) 51 | ans = t - s; 52 | sum -= ns[s++]; 53 | } 54 | if (t > n-1) 55 | break; 56 | } 57 | 58 | printf("%d\n", ans); 59 | } 60 | return 0; 61 | } -------------------------------------------------------------------------------- /POJ/poj3067.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/flexwang-zz/CodeTest/db4c4a4f5cf5c3bf94b5fcc91183571ec4c6a666/POJ/poj3067.cpp -------------------------------------------------------------------------------- /POJ/poj3167.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Description 3 | 4 | The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this: 5 | 6 | 7 7 | 8 | 9 | 10 | 3 8 11 | 12 | 13 | 14 | 8 1 0 15 | 16 | 17 | 18 | 2 7 4 4 19 | 20 | 21 | 22 | 4 5 2 6 5 23 | Then the other cows traverse the triangle starting from its tip and moving "down" to one of the two diagonally adjacent cows until the "bottom" row is reached. The cow's score is the sum of the numbers of the cows visited along the way. The cow with the highest score wins that frame. 24 | 25 | Given a triangle with N (1 <= N <= 350) rows, determine the highest possible sum achievable. 26 | Input 27 | 28 | Line 1: A single integer, N 29 | 30 | Lines 2..N+1: Line i+1 contains i space-separated integers that represent row i of the triangle. 31 | Output 32 | 33 | Line 1: The largest sum achievable using the traversal rules 34 | Sample Input 35 | 36 | 5 37 | 7 38 | 3 8 39 | 8 1 0 40 | 2 7 4 4 41 | 4 5 2 6 5 42 | Sample Output 43 | 44 | 30 45 | Hint 46 | 47 | Explanation of the sample: 48 | 49 | 7 50 | 51 | * 52 | 53 | 3 8 54 | 55 | * 56 | 57 | 8 1 0 58 | 59 | * 60 | 61 | 2 7 4 4 62 | 63 | * 64 | 65 | 4 5 2 6 5 66 | The highest score is achievable by traversing the cows as shown above. 67 | */ 68 | #include 69 | #include 70 | using namespace std; 71 | const int max_n = 360; 72 | int dp[max_n][max_n]; 73 | int n; 74 | int b[max_n][max_n]; 75 | 76 | int main() 77 | { 78 | scanf("%d", &n); 79 | for (int i=0; i=0; i--) 85 | for (int j=0; j<=i; j++) 86 | dp[i][j] = max(dp[i+1][j], dp[i+1][j+1])+b[i][j]; 87 | printf("%d\n", dp[0][0]); 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /POJ/poj3176.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | const int max_n = 360; 5 | int dp[max_n][max_n]; 6 | int n; 7 | int b[max_n][max_n]; 8 | 9 | int main() 10 | { 11 | scanf("%d", &n); 12 | for (int i=0; i=0; i--) 18 | for (int j=0; j<=i; j++) 19 | dp[i][j] = max(dp[i+1][j], dp[i+1][j+1])+b[i][j]; 20 | printf("%d\n", dp[0][0]); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /POJ/poj3254.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | typedef long long ll; 5 | const int mod = 100000000; 6 | const int max_n = 13; 7 | vector possible; 8 | int no[max_n]; 9 | ll dp[max_n][1< 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int get_turn(vector v, int k) { 8 | int n = v.size(); 9 | vector turned(n, false); 10 | int nturn = 0; 11 | int ans = 0; 12 | for (int i=0; i+k<=n; i++) { 13 | if (i-k>=0 && turned[i-k]) nturn--; 14 | if (nturn%2) v[i] = !v[i]; 15 | if (!v[i]) { 16 | ans ++; 17 | nturn ++; 18 | turned[i] = true; 19 | } 20 | } 21 | for (int i=n-k+1; i=0 && turned[i-k]) nturn--; 23 | if (nturn%2) v[i] = !v[i]; 24 | if (!v[i]) return INT_MAX; 25 | } 26 | return ans; 27 | } 28 | 29 | int main() 30 | { 31 | int n; 32 | cin >> n; 33 | vector v(n); 34 | for (int i=0; i> t; 37 | v[i] = t=="F"?true:false; 38 | } 39 | 40 | int ans = n+1, k; 41 | for (int i=1; i<=n; i++) { 42 | int cur = get_turn(v, i); 43 | if (cur < ans) { 44 | ans = cur; 45 | k = i; 46 | } 47 | } 48 | cout << k << " " << ans< 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | struct edge{ 8 | int to, cap, rev; 9 | edge(int t, int c, int r):to(t), cap(c), rev(r){} 10 | }; 11 | 12 | const int max_n = 20005; 13 | vector G[max_n]; 14 | bool used[max_n]; 15 | int n, m, nv; 16 | 17 | void add_edge(int from, int to, int cap) 18 | { 19 | G[from].push_back(edge(to, cap, G[to].size())); 20 | G[to].push_back(edge(from, 0, G[from].size()-1)); 21 | } 22 | int dfs(int s, int t, int f) 23 | { 24 | used[s] = true; 25 | if (s==t) return f; 26 | for (int i=0; i 0) { 29 | int d = dfs(e.to, t, min(f, e.cap)); 30 | if (d > 0) { 31 | e.cap -= d; 32 | G[e.to][e.rev].cap += d; 33 | return d; 34 | } 35 | } 36 | } 37 | return 0; 38 | } 39 | int main() 40 | { 41 | scanf("%d%d", &n, &m); 42 | int s = n; 43 | int t = s + 1; 44 | nv = t + 1; 45 | for (int i=0; i 2 | #include 3 | #include 4 | using std::sort; 5 | const int max_n = 100001; 6 | char s[max_n]; 7 | int sa[max_n], rank[max_n], tmp[max_n], lcp[max_n], k; 8 | int n; 9 | 10 | bool compair(int i, int j) 11 | { 12 | if (rank[i] != rank[j]) return rank[i] < rank[j]; 13 | int ri = i+k<=n?rank[i+k]:-1; 14 | int rj = j+k<=n?rank[j+k]:-1; 15 | return ri < rj; 16 | } 17 | 18 | void compute_sa() 19 | { 20 | for (int i=0; i<=n; i++) { 21 | sa[i] = i; 22 | rank[i] = i 0) h--; 43 | for (;h+j 4 | 5 | using namespace std; 6 | 7 | typedef long long ll; 8 | 9 | ll get_bit(ll a, ll idx) { 10 | return a & (1ll<> s >> x; 19 | ll a = 1, b = 0; 20 | for (int i=1; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | const int max_n = 'z'+1; 8 | char graph[max_n]; 9 | bool used[max_n]; 10 | int n; 11 | int indegree[max_n]; 12 | 13 | void build_graph(const string &str) { 14 | used[str[0]] = true; 15 | for (int i=0; i+1> n; 26 | while (n--) { 27 | string str; 28 | cin >> str; 29 | build_graph(str); 30 | } 31 | stack st; 32 | for (char i='a'; i<='z'; ++i) 33 | if (!indegree[i] && used[i]) st.push(i); 34 | while (!st.empty()) { 35 | char p = st.top(); 36 | st.pop(); 37 | cout << p; 38 | if (graph[p]) st.push(graph[p]); 39 | } 40 | return 0; 41 | } -------------------------------------------------------------------------------- /codeforces/650A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | typedef long long ll; 5 | 6 | ll c2(ll n) { 7 | return n*(n-1)/2; 8 | } 9 | int main() 10 | { 11 | int n; 12 | unordered_map xm, ym; 13 | map, ll> m; 14 | cin >> n; 15 | for (int i=0; i> x >> y; 18 | xm[x] ++; 19 | ym[y] ++; 20 | m[make_pair(x, y)] ++; 21 | } 22 | ll res = 0; 23 | for (auto x:xm) 24 | res += c2(x.second); 25 | for (auto y:ym) 26 | res += c2(y.second); 27 | for (auto x:m) 28 | res -= c2(x.second); 29 | cout << res << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /codeforces/README: -------------------------------------------------------------------------------- 1 | learn more about CODEFORCES: http://codeforces.com/ 2 | -------------------------------------------------------------------------------- /codejam/2013/R1A/A.py: -------------------------------------------------------------------------------- 1 | def ink(n, r): 2 | return int(2*n*n+(2*r-1)*n) 3 | 4 | def b_search(start, end, r, t): 5 | if (end-start) <= 1: 6 | return start 7 | mid = int((end+start)/2) 8 | result = ink(mid,r) 9 | 10 | if result == t: 11 | return mid 12 | elif result > t: 13 | return b_search(start, mid, r, t) 14 | else: 15 | return b_search(mid, end, r, t) 16 | 17 | T = eval(input()) 18 | 19 | for i in range(1, T+1): 20 | r, t = map(int, input().split()) 21 | n = 1 22 | while ink(n,r) <= t: 23 | n *= 2 24 | print("Case #%d: %d" %(i,b_search(n/2, n, r, t))) 25 | -------------------------------------------------------------------------------- /codejam/2013/R1A/B.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | class Energy: 4 | def __init__(self, size, vi): 5 | self.size = size 6 | self.vi = vi 7 | 8 | t = eval(input()) 9 | 10 | for i in range(1, t+1): 11 | e,r,n = map(int, input().split()) 12 | v = map(int, input().split()) 13 | 14 | energy = [Energy(e,0)] 15 | gain = 0 16 | 17 | for vi in v: 18 | size = 0 19 | for j in range(len(energy)-1, -1, -1): 20 | if energy[j].vi <= vi: 21 | gain -= energy[j].size*energy[j].vi 22 | size += energy[j].size 23 | energy.pop() 24 | else: 25 | break 26 | gain += size*vi 27 | energy.append(Energy(size, vi)) 28 | 29 | R = r 30 | if r > e: 31 | energy = [Energy(e,0)] 32 | else: 33 | for j in range(len(energy)): 34 | if R > energy[j].size: 35 | R -= energy[j].size 36 | elif R == energy[j].size: 37 | j += 1 38 | break 39 | else: 40 | energy[j].size -= R 41 | break 42 | energy = energy[j:] 43 | energy.append(Energy(min(r,e), 0)) 44 | print("Case #%d: %d" %(i, gain)) -------------------------------------------------------------------------------- /codejam/2013/R1A/C-small.py: -------------------------------------------------------------------------------- 1 | def solve1(clue): 2 | dict = {2*5*5:"255", 3*5*5:"355", 4*5*5:"455", 5*5*5:"555", 3 | 2*4*4:"244", 3*4*4:"344", 4*4*4:"444", 5*4*4:"445", 4 | 2*3*3:"233", 3*3*3:"333", 4*3*3:"334", 5*3*3:"335", 5 | 2*3*4:"234", 2*3*5:"235", 3*4*5:"345" 6 | } 7 | if clue in dict: 8 | print(dict[clue]) 9 | return True 10 | return False 11 | 12 | def hasn(a, n): 13 | for x in a: 14 | if x%n == 0: 15 | return True 16 | return False 17 | def hasn2(a, n): 18 | for x in a: 19 | if x==n: 20 | return True 21 | return False 22 | input() 23 | input() 24 | print("Case #1:") 25 | for i in range(1, 101): 26 | a = map(int, input().split()) 27 | 28 | clue1 = max(a) 29 | if not solve1(clue1): 30 | if hasn(a, 25): 31 | solved = False 32 | for x in [4,2,3]: 33 | if hasn(a, x): 34 | solved = True 35 | print("%d55" %x) 36 | break 37 | if not solved: 38 | print("255") 39 | elif hasn(a, 9): 40 | solved = False 41 | for x in [4,2,5]: 42 | if hasn(a, x): 43 | solved = True 44 | print("%d33" %x) 45 | break 46 | if not solved: 47 | print("233") 48 | elif hasn(a, 16): 49 | solved = False 50 | for x in [3,5]: 51 | if hasn(a, x): 52 | solved = True 53 | print("%d44" %x) 54 | break 55 | if not solved: 56 | print("244") 57 | else: 58 | print("234") -------------------------------------------------------------------------------- /codejam/2013/R1B/A.py: -------------------------------------------------------------------------------- 1 | T = eval(input()) 2 | 3 | for i in range(1, T+1): 4 | a,n = map(int, input().split()) 5 | l = [int(x) for x in input().split()] 6 | l.sort() 7 | totalop = 0 8 | minop = n 9 | 10 | if a <= 1: 11 | print("Case #%d: %d" %(i, n)) 12 | else: 13 | for j in range(n): 14 | while a <= l[j]: 15 | a = 2*a - 1 16 | totalop += 1 17 | if totalop + (n-j-1) < minop: 18 | minop = totalop + (n-j-1) 19 | elif totalop >= minop: 20 | break 21 | a += l[j] 22 | print("Case #%d: %d" %(i, minop)) -------------------------------------------------------------------------------- /codejam/2013/R1B/C.py: -------------------------------------------------------------------------------- 1 | filehandle = open("F:\\GitHub\\CodeTest\\codejam\\2013R1B\\garbled_email_dictionary.txt") 2 | 3 | dict = filehandle.readlines() 4 | 5 | maxlen = 0 6 | for x in dict: 7 | if len(x) > maxlen: 8 | maxlen = len(x) 9 | print(maxlen) 10 | 11 | T = eval(input()) 12 | 13 | for i in range(1, T+1): 14 | s = input() -------------------------------------------------------------------------------- /codejam/2014/Qualification/A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int T; 11 | 12 | cin >>T; 13 | 14 | for (int t=1; t<=T; t++) { 15 | int a[4][4]; 16 | int r1, r2; 17 | vector a1(4), a2(4); 18 | cin >> r1; 19 | 20 | for (int i=0; i<16; i++) { 21 | cin >> a[i/4][i%4]; 22 | 23 | if (i/4 == r1-1) { 24 | a1[i%4] = a[i/4][i%4]; 25 | } 26 | } 27 | 28 | cin >> r2; 29 | 30 | for (int i=0; i<16; i++) { 31 | cin >> a[i/4][i%4]; 32 | 33 | if (i/4 == r2-1) { 34 | a2[i%4] = a[i/4][i%4]; 35 | } 36 | } 37 | 38 | int nsame = 0; 39 | int answer = 0; 40 | for (int i=0; i<4; i++) { 41 | vector::iterator iter = find(a2.begin(), a2.end(), a1[i]); 42 | 43 | if (iter != a2.end()) { 44 | answer = a1[i]; 45 | nsame ++; 46 | } 47 | else { 48 | 49 | } 50 | } 51 | cout<<"Case #"< 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define min2(a, b) (a)<(b)?(a):(b) 10 | 11 | int main() 12 | { 13 | int T; 14 | 15 | cin >>T; 16 | 17 | for (int t=1; t<=T; t++) { 18 | cout<<"Case #"<>c>>f>>x; 22 | 23 | double mintime; 24 | 25 | double d0 = f*c-f*x+2*c; 26 | 27 | if (d0 > 0) { 28 | mintime = x/2.f; 29 | } 30 | else { 31 | double n = (f*x-2*c)/(f*c); 32 | 33 | int n1 = (int)n; 34 | int n2 = n1 + 1; 35 | 36 | double time_for_farm = 0.; 37 | 38 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int T; 10 | 11 | cin >>T; 12 | 13 | for (int t=1; t<=T; t++) { 14 | cout<<"Case #"<>n; 19 | 20 | vector a1(n); 21 | vector a2(n); 22 | 23 | for (int i=0; i> a1[i]; 25 | } 26 | 27 | for (int i=0; i> a2[i]; 29 | } 30 | 31 | sort(a1.begin(), a1.end(), greater()); 32 | sort(a2.begin(), a2.end(), greater()); 33 | 34 | 35 | int score = 0; 36 | int i2 = 0; 37 | for (int i=0; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | typedef long long LL; 10 | 11 | #define INF 1e6 12 | 13 | vector f; 14 | int time; 15 | 16 | 17 | inline int bitcount(LL n) { 18 | unsigned int c =0 ; 19 | while (n >0) 20 | { 21 | if((n &1) ==1) 22 | ++c ; 23 | n >>=1 ; 24 | } 25 | return c ; 26 | } 27 | 28 | inline void Permutation(int start, int end, vector list, LL lastr) 29 | { 30 | int i; 31 | if (start >= end) 32 | { 33 | LL result = f[start-1]^list[start-1]; 34 | 35 | if (result == lastr) { 36 | time = min(time, bitcount(result)); 37 | } 38 | 39 | return; 40 | } 41 | 42 | for (i = start; i < end; i++) 43 | { 44 | 45 | LL result = f[start]^list[i]; 46 | if (lastr < 0 || lastr == result) { 47 | swap(list[i], list[start]); 48 | Permutation(start+1, end, list, result); 49 | swap(list[i], list[start]); 50 | } 51 | } 52 | } 53 | int main() 54 | { 55 | int T; 56 | 57 | cin >>T; 58 | 59 | for (int t=1; t<=T; t++) { 60 | cout << "Case #" << t << ": "; 61 | int n, l; 62 | cin >> n >> l; 63 | 64 | vector flow(n), require(n); 65 | 66 | for (int i=0; i> flow[i]; 68 | } 69 | 70 | for (int i=0; i> require[i]; 72 | } 73 | 74 | vector r(n); 75 | f = vector(n); 76 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | 8 | struct Node{ 9 | vector children; 10 | }; 11 | 12 | vector nodes; 13 | vector available; 14 | inline int bfs(int n) { 15 | vector children; 16 | 17 | for (int i=0; i ndelete; 30 | 31 | for (int i=0; i()); 40 | 41 | return ndelete[0]+ndelete[1]+1; 42 | } 43 | 44 | int main() 45 | { 46 | int T; 47 | 48 | cin >> T; 49 | 50 | for (int t=1; t<=T; t++) { 51 | cout << "Case #" << t << ": "; 52 | int nnode; 53 | 54 | cin >> nnode; 55 | 56 | nodes = vector(nnode); 57 | 58 | for (int i=0; i> a >> b; 62 | nodes[a-1].children.push_back(b-1); 63 | nodes[b-1].children.push_back(a-1); 64 | } 65 | 66 | int nreserve = 0; 67 | for (int i=0; i(nnode, true); 69 | available[i] = false; 70 | int x = bfs(i); 71 | if (x > nreserve) { 72 | nreserve = x; 73 | } 74 | 75 | } 76 | 77 | cout << nnode-nreserve << endl; 78 | } 79 | } -------------------------------------------------------------------------------- /codejam/2014/Round1C/A.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | 8 | using namespace std; 9 | 10 | typedef long long LL; 11 | 12 | const LL base = 1LL << 40; 13 | 14 | inline LL gcd(LL a, LL b) { 15 | if (b > a) { 16 | swap(a, b); 17 | } 18 | 19 | while (b) { 20 | LL d = a%b; 21 | a = b; 22 | b = d; 23 | } 24 | 25 | return a; 26 | } 27 | 28 | inline bool isvalid(LL a) { 29 | if ( a > base) return false; 30 | 31 | LL p = 1; 32 | 33 | while (p < a) { 34 | p <<= 1; 35 | } 36 | 37 | return p == a; 38 | } 39 | 40 | int main() 41 | { 42 | int T; 43 | 44 | cin >>T; 45 | 46 | for (int t=1; t<=T; t++) { 47 | cout << "Case #" << t << ": "; 48 | 49 | LL p, q; 50 | 51 | string str; 52 | 53 | cin >> str; 54 | 55 | std::replace(str.begin(), str.end(), '/', ' '); 56 | 57 | istringstream is(str); 58 | 59 | is >>p >> q; 60 | 61 | LL g = gcd(p, q); 62 | 63 | p /= g; 64 | q /= g; 65 | 66 | if (!isvalid(q)) { 67 | cout << "impossible" << endl; 68 | continue; 69 | } 70 | 71 | p *= base/q; 72 | 73 | int result = 0; 74 | int i = 0; 75 | while (p) { 76 | if (p&1LL) { 77 | result = i; 78 | } 79 | 80 | i ++; 81 | p >>= 1; 82 | } 83 | 84 | cout << 40-result << endl; 85 | } 86 | return 0; 87 | } -------------------------------------------------------------------------------- /codejam/2016/Qualification/A.py: -------------------------------------------------------------------------------- 1 | def f(n): 2 | if n == 0: 3 | return 'INSOMNIA' 4 | tab = [False]*10 5 | cnt = 0 6 | sum = 0 7 | while tab != [True]*10: 8 | sum += n 9 | cnt += 1 10 | s = str(sum) 11 | for ch in s: 12 | tab[int(ch)] = True 13 | return str(sum) 14 | 15 | ncase = int(input()) 16 | for ic in range(ncase): 17 | print('Case #%d: %s'%((ic+1), f(int(input())))) 18 | -------------------------------------------------------------------------------- /codejam/2016/Qualification/B.py: -------------------------------------------------------------------------------- 1 | def f(s): 2 | cnt = 0 3 | for c in reversed(s): 4 | if c=='+' and cnt%2!=0 or c=='-' and cnt%2==0: 5 | cnt += 1 6 | return cnt 7 | ncase = int(input()) 8 | for ic in range(ncase): 9 | print('Case #%d: %d'%(ic+1, f(input()))) -------------------------------------------------------------------------------- /codejam/2016/Qualification/C.py: -------------------------------------------------------------------------------- 1 | def gen_primes(n): 2 | lt = [2] 3 | cur = 3 4 | while len(lt) < n: 5 | flag = True 6 | for i in lt: 7 | if cur % i == 0: 8 | flag = False 9 | break 10 | if i*i > cur: 11 | break 12 | if flag: 13 | lt.append(cur) 14 | cur += 1 15 | return lt 16 | def is_prime(n, primes): 17 | for p in primes: 18 | if n%p == 0: 19 | return p 20 | if p*p > n: 21 | return -1 22 | return -1 23 | def to_int(s, b): 24 | res = 0 25 | for c in s: 26 | res = res*b + int(c) 27 | return res 28 | def test(s, primes): 29 | div = [-1]*9 30 | for b in range(2, 11): 31 | n = to_int(s, b) 32 | d = is_prime(n, primes) 33 | if d < 0: 34 | return None 35 | else: 36 | div[b-2] = d 37 | return div 38 | 39 | N, J = map(int, input().split()) 40 | primes = gen_primes(10000) 41 | print('Case #1:') 42 | cnt = 0 43 | for i in range(1<<(N-2)): 44 | form = '{0:0%db}'%(N-2) 45 | s = '1'+form.format(i)+'1' 46 | div = test(s, primes) 47 | if div is not None: 48 | print(s, end='') 49 | for d in div: 50 | print(' %d'%d, end='') 51 | print() 52 | cnt += 1 53 | if cnt == J: 54 | break 55 | 56 | -------------------------------------------------------------------------------- /codejam/2016/Qualification/D-small.py: -------------------------------------------------------------------------------- 1 | ncase = int(input()) 2 | for ic in range(ncase): 3 | k, c, s = map(int, input().split()) 4 | print("Case #%d:"%(ic+1), end='') 5 | for i in range(k): 6 | print(' %d'%(1+i*k**(c-1)), end='') 7 | print() -------------------------------------------------------------------------------- /codejam/README: -------------------------------------------------------------------------------- 1 | This is some source code for google code jam. 2 | Learn more about gcj: https://code.google.com/codejam/ -------------------------------------------------------------------------------- /hiho/hiho1014.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct TrieNode 8 | { 9 | TrieNode():cnt(0){} 10 | unordered_map um; 11 | int cnt; 12 | }; 13 | 14 | class Trie{ 15 | public: 16 | Trie():root(new TrieNode()){} 17 | void insert(const string& str) { 18 | TrieNode *node = root; 19 | for (int i=0; ium.find(str[i]) == node->um.end()) 21 | node->um[str[i]] = new TrieNode(); 22 | node = node->um[str[i]]; 23 | node->cnt++; 24 | } 25 | } 26 | int search(const string& str) { 27 | TrieNode *node = root; 28 | for (int i=0; ium.find(str[i]) == node->um.end()) return 0; 30 | node = node->um[str[i]]; 31 | } 32 | return node->cnt; 33 | } 34 | private: 35 | TrieNode *root; 36 | }; 37 | 38 | int main() 39 | { 40 | Trie trie; 41 | int n, m; 42 | cin >> n; 43 | for (int i=0; i> str; 46 | trie.insert(str); 47 | } 48 | cin >> m; 49 | for (int i=0; i> str; 52 | cout << trie.search(str) << endl; 53 | } 54 | return 0; 55 | } -------------------------------------------------------------------------------- /hiho/hiho1015.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector getNext(string str) { 8 | vector next(str.length()+1); 9 | next[0] = -1; 10 | for (int i=1; i<=str.length(); i++) { 11 | int k = next[i-1]; 12 | while (k>=0 && str[k] != str[i-1]) 13 | k = next[k]; 14 | next[i] = k+1; 15 | } 16 | return next; 17 | } 18 | 19 | int main() 20 | { 21 | int ncase; 22 | cin >> ncase; 23 | while (ncase--) { 24 | string a, b; 25 | cin >> a >> b; 26 | vector next = getNext(a); 27 | int cnt = 0; 28 | for (int i=0,j=0; i=0 && b[i] != a[j]) 30 | j = next[j]; 31 | j++; 32 | if (j == a.length()) { 33 | j = next[j]; 34 | cnt++; 35 | } 36 | } 37 | cout << cnt << endl; 38 | } 39 | return 0; 40 | } -------------------------------------------------------------------------------- /hiho/hiho1040.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct P{ 6 | long long x, y; 7 | P(){} 8 | P(int xx, int yy):x(xx), y(yy){} 9 | bool is_zero() const {return x==0 && y==0;} 10 | }; 11 | 12 | P operator-(const P&p1, const P&p2) { 13 | return P(p1.x-p2.x, p1.y-p2.y); 14 | } 15 | 16 | long long operator*(const P&p1, const P&p2) { 17 | return p1.x*p2.x+p1.y*p2.y; 18 | } 19 | long long operator^(const P&p1, const P&p2) { 20 | return p1.x*p2.y - p1.y*p2.x; 21 | } 22 | 23 | bool parallel(const P&p1, const P&p2) { 24 | return (p1^p2) == 0; 25 | } 26 | int main() 27 | { 28 | int ncase; 29 | cin >> ncase; 30 | while (ncase--) { 31 | P p[4], q[4], d[4]; 32 | bool flag=true; 33 | for (int i=0; i<4; i++) { 34 | cin >> p[i].x >> p[i].y >> q[i].x >> q[i].y; 35 | d[i] = p[i]-q[i]; 36 | if (d[i].is_zero()) flag = false; 37 | } 38 | if (flag) { 39 | int s1[2], s2[2]; 40 | s1[0] = 0; 41 | s1[1] = 1; 42 | for (int i=2; i<4; i++) { 43 | if (parallel(d[0], d[i])) { 44 | s1[1] = i; 45 | break; 46 | } 47 | } 48 | if (s1[1] != 1) { 49 | if (s1[1] = 2) s2 = {1, 3}; 50 | else s2 = {1, 2}; 51 | } 52 | else { 53 | s2[0] = 2; 54 | s2[1] = 3; 55 | } 56 | 57 | if (!parallel(d[s1[0]], d[s1[1]]) 58 | || !parallel(d[s2[0]], d[s2[1]]) 59 | || d[s1[0]]*d[s2[0]]) 60 | flag = false; 61 | if (flag) { 62 | if (parallel(p[s1[0]]-p[s1[1]], d[s1[1]]) 63 | || parallel(p[s2[0]]-p[s2[1]], d[s2[1]])) 64 | flag = false; 65 | } 66 | } 67 | if (flag) cout << "YES"; 68 | else cout << "NO"; 69 | if (ncase) cout << endl; 70 | 71 | } 72 | return 0; 73 | } 74 | 75 | -------------------------------------------------------------------------------- /hiho/hiho1050.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | vector> G; 8 | 9 | void add_edge(int a, int b) { 10 | a--, b--; 11 | G[a].push_back(b); 12 | G[b].push_back(a); 13 | } 14 | 15 | int dfs(int id, int p, int &ans) { 16 | int m1=0, m2=0; 17 | for (int i=0; i= m1) { 22 | m2 = m1; 23 | m1 = d; 24 | } 25 | else if (d > m2) m2 = d; 26 | } 27 | ans = max(ans, m1+m2+1); 28 | return m1+1; 29 | } 30 | 31 | int main() 32 | { 33 | int n; 34 | cin >> n; 35 | G.resize(n); 36 | for (int i=1; i> a >> b; 39 | add_edge(a, b); 40 | } 41 | int root = 0; 42 | int ans = 0; 43 | dfs(root, -1, ans); 44 | cout << --ans << endl; 45 | return 0; 46 | } -------------------------------------------------------------------------------- /hiho/hiho1052.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int ncase; 11 | cin >> ncase; 12 | while (ncase--) { 13 | string str; 14 | int k; 15 | cin >> str >> k; 16 | int cnt = 0, offset = str.length()-k; 17 | for (int i=0; i um; 19 | for (int j=i; j 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int n; 11 | cin >> n; 12 | unordered_map um; 13 | 14 | } -------------------------------------------------------------------------------- /hiho/hiho1091.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | int n, m; 10 | cin >> n >> m; 11 | vector a(n), b(n); 12 | for (int i=0; i> a[i] >> b[i]; 14 | vector> dp(n+1, vector(m+1, 0)); 15 | for (int i=0; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int n; 11 | cin >> n; 12 | vector> G(n, vector(n, 0)); 13 | vector dist(n, INT_MAX); 14 | vector visited(n, false); 15 | priority_queue,vector>, greater>> pq; 16 | for (int i=0; i> G[i][j]; 19 | dist[0] = 0; 20 | pq.push(make_pair(0, 0)); 21 | int ans = 0; 22 | while (!pq.empty()) { 23 | pair p = pq.top(); 24 | pq.pop(); 25 | int id = p.second, d = p.first; 26 | if (visited[id]) continue; 27 | visited[id] = true; 28 | ans += d; 29 | for (int i=0; i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct E{ 8 | int s, t, w; 9 | }; 10 | bool operator<(const E&e1, const E&e2) { 11 | return e1.w&v, int n) { 15 | v.resize(n); 16 | for (int i=0; i& v) { 21 | if (id == v[id]) return id; 22 | return v[id] = find(v[id], v); 23 | } 24 | 25 | int main() 26 | { 27 | int n, m; 28 | cin >> n >> m; 29 | vector es; 30 | for (int i=0; i> a >> b >> w; 33 | es.push_back({a-1, b-1, w}); 34 | } 35 | sort(es.begin(), es.end()); 36 | vector v; 37 | init(v, n); 38 | int ans = 0; 39 | for (int i=0; i 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | const int mod = 142857; 9 | 10 | vector> G; 11 | vector indegree; 12 | vector subsize; 13 | void add_edge(int a, int b){ 14 | a--, b--; 15 | G[a].push_back(b); 16 | indegree[b]++; 17 | } 18 | 19 | int main() 20 | { 21 | int n, m, k; 22 | cin >> n >> m >> k; 23 | subsize.resize(n, 0); 24 | for (int i=0; i> a; 27 | subsize[--a]++; 28 | } 29 | indegree.resize(n); 30 | G.resize(n); 31 | for (int i=0; i> x >> y; 34 | add_edge(x, y); 35 | } 36 | queue q; 37 | for (int i=0; i& nums, int target) { 4 | int ans = 0x5fffffff; 5 | sort(nums.begin(), nums.end()); 6 | 7 | for (int i = 0; i + 2 < nums.size(); i++) { 8 | int p1 = i + 1; 9 | int p2 = nums.size() - 1; 10 | 11 | while (p1 < p2) { 12 | if (abs(nums[i] + nums[p1] + nums[p2] - target) < abs(ans - target)) 13 | ans = nums[i] + nums[p1] + nums[p2]; 14 | if (nums[i] + nums[p1] + nums[p2] < target) 15 | p1++; 16 | else 17 | p2--; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/3sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | vector> ans; 5 | sort(nums.begin(), nums.end()); 6 | 7 | for (int i = 0; i + 2 < nums.size(); i++) { 8 | if (i && nums[i] == nums[i - 1]) continue; 9 | int p1 = i + 1; 10 | int p2 = nums.size() - 1; 11 | 12 | while (p1 < p2) { 13 | if (p1 > i + 1 && nums[p1] == nums[p1 - 1]) { 14 | p1++; 15 | continue; 16 | } 17 | if (p2 < nums.size() - 1 && nums[p2] == nums[p2 + 1]) { 18 | p2--; 19 | continue; 20 | } 21 | if (nums[p1] + nums[p2] < -nums[i]) 22 | p1++; 23 | else if (nums[p1] + nums[p2] > -nums[i]) 24 | p2--; 25 | else { 26 | vector t; 27 | t.push_back(nums[i]); 28 | t.push_back(nums[p1]); 29 | t.push_back(nums[p2]); 30 | ans.push_back(t); 31 | p1++; 32 | } 33 | } 34 | } 35 | 36 | return ans; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/4sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> fourSum(vector& nums, int target) { 4 | vector> ans; 5 | if (nums.size() < 4) return ans; 6 | sort(nums.begin(), nums.end()); 7 | 8 | for (int i=0; i v; 26 | v.push_back(nums[i]); 27 | v.push_back(nums[j]); 28 | v.push_back(nums[p1]); 29 | v.push_back(nums[p2]); 30 | ans.push_back(v); 31 | p1++; 32 | } 33 | else if (nums[p1]+nums[p2]+t < target) 34 | p1++; 35 | else 36 | p2--; 37 | } 38 | } 39 | 40 | } 41 | 42 | return ans; 43 | } 44 | }; -------------------------------------------------------------------------------- /leetcode/README.md: -------------------------------------------------------------------------------- 1 | LeetCode OJ is a platform for preparing technical coding interviews. 2 | Learn more: https://leetcode.com/ 3 | 4 | Below are some of my posts on leetcode discuss. 5 | 6 | - [Gray Code](https://leetcode.com/discuss/55510/4-lines-c-code) 7 | - [Find Peak Element](https://leetcode.com/discuss/43826/my-simple-c-logn-solution) 8 | - [Sliding Window Maximum](https://leetcode.com/discuss/46594/clean-c-o-n-solution-using-a-deque) 9 | -------------------------------------------------------------------------------- /leetcode/add-two-numbers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 | ListNode* head = NULL; 13 | int carry = 0; 14 | ListNode** p = &head; 15 | 16 | while (l1 || l2) { 17 | if (l1 && l2) { 18 | int val = l1->val+l2->val+carry; 19 | *p = new ListNode(val%10); 20 | carry = val/10; 21 | l1 = l1->next; 22 | l2 = l2->next; 23 | } 24 | else if (l1) { 25 | int val = l1->val + carry; 26 | *p = new ListNode(val%10); 27 | carry = val/10; 28 | l1 = l1->next; 29 | } 30 | else { 31 | int val = l2->val + carry; 32 | *p = new ListNode(val%10); 33 | carry = val/10; 34 | l2 = l2->next; 35 | } 36 | p = &(*p)->next; 37 | } 38 | if (carry) *p = new ListNode(carry); 39 | return head; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/balanced-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isBalanced(TreeNode *root) { 13 | return height(root)>=0; 14 | } 15 | 16 | int max( int a, int b) 17 | { 18 | return (a>b)?a:b; 19 | } 20 | 21 | int abs(int a) 22 | { 23 | return a>=0?a:-a; 24 | } 25 | 26 | int height(TreeNode* node) 27 | { 28 | if( node) 29 | { 30 | int left = height(node->left); 31 | int right = height(node->right); 32 | 33 | 34 | if( left < 0 || right < 0) 35 | { 36 | return -1; 37 | } 38 | 39 | if( abs(left-right) >= 2) 40 | { 41 | return -1; 42 | } 43 | 44 | return max(height(node->right), height(node->left)) + 1; 45 | } 46 | else 47 | { 48 | return 0; 49 | } 50 | } 51 | }; -------------------------------------------------------------------------------- /leetcode/basic-calculator-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int nextNum(string &s, int &i) { 4 | int num = 0; 5 | for (;i='0' && s[i] <= '9') 7 | num = num*10 + s[i]-'0'; 8 | else if (s[i] == ' ') continue; 9 | else break; 10 | return num; 11 | } 12 | int calculate(string s) { 13 | int i = 0; 14 | int result = 0; 15 | int cur = nextNum(s, i); 16 | char last_op = ' '; 17 | while (i != s.length()) { 18 | if (s[i] == '*') cur *= nextNum(s, ++i); 19 | else if (s[i] == '/') cur /= nextNum(s, ++i); 20 | else if (last_op == '+') result += cur, last_op=s[i], cur = nextNum(s, ++i); 21 | else if (last_op == '-') result -= cur, last_op=s[i], cur = nextNum(s, ++i); 22 | else result = cur, last_op = s[i], cur = nextNum(s, ++i); 23 | } 24 | if (last_op == ' ') return cur; 25 | else if (last_op == '+') return result+cur; 26 | else return result-cur; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /leetcode/best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector &prices) { 4 | int size = prices.size(); 5 | 6 | if( size <= 0) 7 | { 8 | return 0; 9 | } 10 | 11 | int profit = 0; 12 | int last = prices[0]; 13 | 14 | for( int i=1; i &prices) { 4 | 5 | int size = prices.size(); 6 | 7 | if( size <= 0) 8 | { 9 | return 0; 10 | } 11 | int profit = 0; 12 | 13 | vector p(size, 0); 14 | 15 | int min = prices[0]; 16 | int maxprofit = 0; 17 | for(int i=0; i maxprofit) 20 | { 21 | maxprofit = prices[i] - min; 22 | } 23 | p[i] = maxprofit; 24 | 25 | if( min > prices[i]) 26 | { 27 | min = prices[i]; 28 | } 29 | } 30 | 31 | int max = prices[size-1]; 32 | maxprofit = 0; 33 | for(int i=size-1; i>=0; i--) 34 | { 35 | if( max-prices[i] > maxprofit) 36 | { 37 | maxprofit = max - prices[i]; 38 | } 39 | if( maxprofit+p[i] > profit) 40 | { 41 | profit = maxprofit+p[i]; 42 | } 43 | 44 | if( max < prices[i]) 45 | { 46 | max = prices[i]; 47 | } 48 | } 49 | 50 | return profit; 51 | } 52 | }; -------------------------------------------------------------------------------- /leetcode/best-time-to-buy-and-sell-stock-iv.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(int k, vector& prices) { 4 | if (prices.size() < 2) return 0; 5 | if (k >= prices.size()/2) { 6 | int ans = 0; 7 | for (int i=1; i dp(prices.size()); 12 | for (int i=0; i &prices) { 4 | if( prices.size() <= 0) 5 | { 6 | return 0; 7 | } 8 | 9 | int min = prices[0]; 10 | int maxprofit = 0; 11 | 12 | for( int i=0,size=prices.size(); i maxprofit) 15 | { 16 | maxprofit = prices[i]-min; 17 | } 18 | if( prices[i] < min) 19 | { 20 | min = prices[i]; 21 | } 22 | } 23 | 24 | return maxprofit; 25 | } 26 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector inorderTraversal(TreeNode *root) { 13 | vector result; 14 | 15 | vector stack; 16 | 17 | TreeNode* curnode = root; 18 | 19 | do 20 | { 21 | while(curnode) 22 | { 23 | stack.push_back(curnode); 24 | curnode = curnode->left; 25 | } 26 | 27 | if( stack.size()) 28 | { 29 | curnode = stack.back(); 30 | stack.pop_back(); 31 | 32 | result.push_back(curnode->val); 33 | 34 | curnode = curnode->right; 35 | } 36 | 37 | 38 | }while(stack.size() || curnode); 39 | 40 | return result; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-level-order-traversal-ii.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector > levelOrderBottom(TreeNode *root) { 13 | vector curlayer; 14 | vector> result; 15 | 16 | if( !root) 17 | { 18 | return result; 19 | } 20 | 21 | curlayer.push_back(root); 22 | 23 | while(curlayer.size()) 24 | { 25 | vector nextlayer; 26 | vector r; 27 | for(int i=0,size=curlayer.size(); ival); 31 | 32 | if( curlayer[i]->left) 33 | { 34 | nextlayer.push_back(curlayer[i]->left); 35 | } 36 | 37 | if( curlayer[i]->right) 38 | { 39 | nextlayer.push_back(curlayer[i]->right); 40 | } 41 | } 42 | result.insert(result.begin(), r); 43 | curlayer = nextlayer; 44 | } 45 | 46 | return result; 47 | } 48 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector > levelOrder(TreeNode *root) { 13 | 14 | vector> result; 15 | 16 | vector curlayer; 17 | 18 | if (root) 19 | { 20 | curlayer.push_back(root); 21 | } 22 | 23 | while (curlayer.size()) 24 | { 25 | vector layer; 26 | vector nextlayer; 27 | 28 | for (int i=0, size=curlayer.size(); ival); 31 | 32 | if (curlayer[i]->left) 33 | { 34 | nextlayer.push_back(curlayer[i]->left); 35 | } 36 | 37 | if (curlayer[i]->right) 38 | { 39 | nextlayer.push_back(curlayer[i]->right); 40 | } 41 | } 42 | 43 | if (layer.size()) 44 | { 45 | result.push_back(layer); 46 | } 47 | 48 | curlayer = nextlayer; 49 | } 50 | 51 | return result; 52 | } 53 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-maximum-path-sum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxPathSum(TreeNode* root) { 13 | int ans = INT_MIN; 14 | maxPathSum(root, ans); 15 | return ans; 16 | } 17 | 18 | int maxPathSum(TreeNode* node, int &ans) { 19 | //1 20 | if (!node) 21 | return 0; 22 | 23 | //2 24 | int left_chain = max(0, maxPathSum(node->left, ans)); 25 | int right_chain = max(0, maxPathSum(node->right, ans)); 26 | 27 | ans = max(ans, left_chain + node->val + right_chain); 28 | return max(left_chain+node->val, right_chain+node->val); 29 | } 30 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector postorderTraversal(TreeNode *root) { 13 | vector result; 14 | 15 | vector stack; 16 | 17 | stack.push_back(root); 18 | 19 | while(stack.size()) 20 | { 21 | TreeNode* t = stack.back(); 22 | stack.pop_back(); 23 | 24 | if( t) 25 | { 26 | result.insert(result.begin(), t->val); 27 | 28 | stack.push_back(t->left); 29 | stack.push_back(t->right); 30 | } 31 | } 32 | 33 | return result; 34 | 35 | } 36 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector preorderTraversal(TreeNode *root) { 13 | vector result; 14 | 15 | vector stack; 16 | 17 | stack.push_back(root); 18 | 19 | while(stack.size()) 20 | { 21 | TreeNode* t = stack.back(); 22 | stack.pop_back(); 23 | 24 | if( t) 25 | { 26 | result.push_back(t->val); 27 | 28 | stack.push_back(t->right); 29 | 30 | stack.push_back(t->left); 31 | } 32 | } 33 | return result; 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/binary-tree-zigzag-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | vector> zigzagLevelOrder(TreeNode* root) { 13 | vector > ans; 14 | int level_cnt = 0; 15 | deque q; 16 | 17 | if (root) q.push_back(root); 18 | int pop_cnt = 1, push_cnt = 0; 19 | 20 | vector temp; 21 | while (!q.empty()) { 22 | TreeNode *node; 23 | if (level_cnt%2 == 1) { 24 | node = q.back(); 25 | q.pop_back(); 26 | } 27 | else { 28 | node = q.front(); 29 | q.pop_front(); 30 | } 31 | pop_cnt--; 32 | temp.push_back(node->val); 33 | if (level_cnt%2 == 0) { 34 | if (node->left) { 35 | q.push_back(node->left); 36 | push_cnt++; 37 | } 38 | if (node->right) { 39 | q.push_back(node->right); 40 | push_cnt++; 41 | } 42 | } 43 | else { 44 | if (node->right) { 45 | q.push_front(node->right); 46 | push_cnt++; 47 | } 48 | if (node->left) { 49 | q.push_front(node->left); 50 | push_cnt++; 51 | } 52 | } 53 | 54 | if (pop_cnt == 0) { 55 | pop_cnt = push_cnt; 56 | push_cnt = 0; 57 | level_cnt ++; 58 | ans.push_back(temp); 59 | temp.clear(); 60 | } 61 | } 62 | 63 | return ans; 64 | } 65 | }; -------------------------------------------------------------------------------- /leetcode/bitwise-and-of-numbers-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int rangeBitwiseAnd(int m, int n) { 4 | int ans = 0; 5 | for (int i=31; i>=0; i--) { 6 | int t1 = m&(1< &ratings) { 4 | int len = ratings.size(); 5 | int ans = len; 6 | vector c(len, 0); 7 | vector> ps(len); 8 | for (int i=0; i 0 && r > ratings[pos-1]) 18 | cc = max(cc, c[pos-1]+1); 19 | if (pos < len-1 && r > ratings[pos+1]) 20 | cc = max(cc, c[pos+1]+1); 21 | c[pos] = cc; 22 | ans += cc; 23 | } 24 | return ans; 25 | } 26 | }; -------------------------------------------------------------------------------- /leetcode/combination-sum-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum2(vector& candidates, int target) { 4 | sort(candidates.begin(), candidates.end()); 5 | vector> ans; 6 | vector v; 7 | combinationSum2(ans, candidates, v, target, 0); 8 | 9 | return ans; 10 | } 11 | 12 | void combinationSum2(vector>& ans, vector& candidates, vector& v, int target, int begin) { 13 | if (target == 0) { 14 | ans.push_back(v); 15 | return; 16 | } 17 | 18 | for (int i=begin; i= candidates[i]; i++) { 19 | if (i != begin && candidates[i] == candidates[i-1]) continue; 20 | v.push_back(candidates[i]); 21 | combinationSum2(ans, candidates, v, target-candidates[i], i+1); 22 | v.pop_back(); 23 | } 24 | } 25 | }; -------------------------------------------------------------------------------- /leetcode/combination-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> combinationSum(vector& candidates, int target) { 4 | sort(candidates.begin(), candidates.end()); 5 | vector> ans; 6 | 7 | vector>> v; 8 | v.push_back(make_pair(target, vector())); 9 | 10 | for (int i = 0; i& vp = v.back().second; 17 | vp.resize(vp.size() + k, candidates[i]); 18 | } 19 | } 20 | } 21 | for (int i = 0; i> combine(int n, int k) { 4 | vector> ans; 5 | vector comb; 6 | combine(ans, comb, k, n, 0); 7 | return ans; 8 | } 9 | 10 | void combine(vector> &ans, vector& comb, int k, int n, int begin) 11 | { 12 | if (comb.size() == k) { 13 | ans.push_back(comb); 14 | return; 15 | } 16 | 17 | for (int i=begin+1; i<=n; i++) { 18 | comb.push_back(i); 19 | combine(ans, comb, k, n, i); 20 | comb.pop_back(); 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/construct-binary-tree-from-inorder-and-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* buildTree(vector& inorder, vector& postorder) { 4 | TreeNode* root; 5 | int s = postorder.size()-1; 6 | buildTree(postorder, s, inorder, 0, inorder.size(), root); 7 | return root; 8 | } 9 | 10 | void buildTree(vector& postorder, int& s, vector& inorder, int left, int right, TreeNode* &node) 11 | { 12 | if (left == right) { 13 | node = NULL; 14 | return; 15 | } 16 | 17 | int i; 18 | for (i = left; i < right; i++) { 19 | if (inorder[i] == postorder[s]) 20 | break; 21 | } 22 | node = new TreeNode(postorder[s]); 23 | 24 | if (i != right - 1) 25 | buildTree(postorder, --s, inorder, i + 1, right, node->right); 26 | if (i != left) 27 | buildTree(postorder, --s, inorder, left, i, node->left); 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/construct-binary-tree-from-preorder-and-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | TreeNode* buildTree(vector& preorder, vector& inorder) { 4 | TreeNode* root; 5 | int s = 0; 6 | buildTree(preorder, s, inorder, 0, inorder.size(), root); 7 | return root; 8 | } 9 | 10 | void buildTree(vector& preorder, int& s, vector& inorder, int left, int right, TreeNode* &node) 11 | { 12 | if (left == right) { 13 | node = NULL; 14 | return; 15 | } 16 | int i; 17 | for (i = left; i < right; i++) { 18 | if (inorder[i] == preorder[s]) 19 | break; 20 | } 21 | node = new TreeNode(preorder[s]); 22 | if (i != left) 23 | buildTree(preorder, ++s, inorder, left, i, node->left); 24 | if (i != right - 1) 25 | buildTree(preorder, ++s, inorder, i+1, right, node->right); 26 | } 27 | }; -------------------------------------------------------------------------------- /leetcode/container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxArea(vector& height) { 4 | int ans = 0; 5 | 6 | int s = 0, t = height.size()-1; 7 | 8 | while (s < t) { 9 | ans = max(ans, min(height[s], height[t])*(t-s)); 10 | if (height[s] < height[t]) 11 | s++; 12 | else 13 | t--; 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/contains-duplicate-iii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool containsNearbyAlmostDuplicate(vector& nums, int k, int t) { 4 | multiset windows; 5 | int k2 = 0; 6 | for (int i=0; i::iterator iter = windows.lower_bound(nums[i]-t); 8 | if (iter != windows.end() && *iter-nums[i] <= t) 9 | return true; 10 | windows.insert(nums[i]); 11 | if (k2 == k) 12 | windows.erase(windows.find(nums[i-k])); 13 | else 14 | k2++; 15 | } 16 | return false; 17 | } 18 | 19 | }; -------------------------------------------------------------------------------- /leetcode/count-primes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int countPrimes(int n) { 4 | if (n < 2) return 0; 5 | vector flag(n, true); 6 | int ans = n-2; 7 | for (int i=2; i findOrder(int numCourses, vector>& prerequisites) { 4 | vector> G(numCourses); 5 | vector indegree(numCourses, 0); 6 | 7 | for (int i=0; i q; 15 | for (int i=0; i ans; 19 | while (!q.empty()) { 20 | int v = q.front(); 21 | ans.push_back(v); 22 | q.pop(); 23 | for (int i=0; i(); 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /leetcode/course-schedule.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canFinish(int numCourses, vector>& prerequisites) { 4 | vector > G(numCourses); 5 | for (int i=0; i state(numCourses, 0); 8 | for (int i=0; i > &G, vector &state) { 14 | if (state[v] == 1) 15 | return false; 16 | if (state[v] == 2) 17 | return true; 18 | state[v] = 1; 19 | for (int i=0; i=0 && s[i-2]!='0' && (s[i-2]-'0')*10+s[i-1]-'0' <= 26) 13 | dp[i] += dp[i-2]; 14 | } 15 | return dp[len]; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/divide-two-integers.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int divide(int dividend, int divisor) { 4 | if (divisor == 0) return INT_MAX; 5 | 6 | int sign = 1; 7 | unsigned int udividend, udivisor; 8 | udividend = dividend; 9 | udivisor = divisor; 10 | if (dividend < 0 && divisor< 0) { 11 | udividend = dividend==INT_MIN?(unsigned int)INT_MAX+1:-dividend; 12 | udivisor = divisor==INT_MIN?(unsigned int)INT_MAX+1:-divisor; 13 | } 14 | else if (dividend < 0) { 15 | udividend = dividend==INT_MIN?(unsigned int)INT_MAX+1:-dividend; 16 | sign = -1; 17 | } 18 | else if (divisor < 0) { 19 | udivisor = divisor==INT_MIN?(unsigned int)INT_MAX+1:-divisor; 20 | sign = -1; 21 | } 22 | 23 | unsigned int ans = 0; 24 | unsigned p = 1; 25 | while ((udivisor << 1) <= udividend && (udivisor << 1) > 0) { 26 | udivisor <<= 1; 27 | p <<= 1; 28 | } 29 | 30 | while (p) { 31 | if (udividend >= udivisor) { 32 | ans += p; 33 | udividend -= udivisor; 34 | 35 | } 36 | udivisor >>= 1; 37 | p >>= 1; 38 | } 39 | if ((int)ans < 0 && sign > 0) return INT_MAX; 40 | return sign<0 ? -ans : ans; 41 | } 42 | }; -------------------------------------------------------------------------------- /leetcode/dungeon-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int calculateMinimumHP(vector>& dungeon) { 4 | int m = dungeon.size(); 5 | int n = m==0?0:dungeon[0].size(); 6 | 7 | if (m==0 || n==0) return 0; 8 | 9 | vector> dp(m, vector(n)); 10 | 11 | for (int i=m-1; i>=0; i--) 12 | for (int j=n-1; j>=0; j--) 13 | if (i==m-1 && j==n-1) 14 | dp[i][j] = max(1, 1-dungeon[i][j]); 15 | else if (i==m-1) 16 | dp[i][j] = max(1, dp[i][j+1]-dungeon[i][j]); 17 | else if (j==n-1) 18 | dp[i][j] = max(1, dp[i+1][j]-dungeon[i][j]); 19 | else 20 | dp[i][j] = max(1, min(dp[i][j+1], dp[i+1][j])-dungeon[i][j]); 21 | return dp[0][0]; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/expression-add-operators.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void helper(vector& ans, int s, string ex, string &num, long long cur, long long last, int target) { 4 | if (s == num.length()) { 5 | if (cur == target) 6 | ans.push_back(ex); 7 | return; 8 | } 9 | long long n = 0; 10 | for (int i = s; is) return; 13 | string this_num = num.substr(s, i - s + 1); 14 | if (ex == "") { 15 | helper(ans, i + 1, this_num, num, n, n, target); 16 | } 17 | else { 18 | helper(ans, i + 1, ex + "+" + this_num, num, cur + n, n, target); 19 | helper(ans, i + 1, ex + "-" + this_num, num, cur - n, -n, target); 20 | helper(ans, i + 1, ex + "*" + this_num, num, cur - last + last*n, last*n, target); 21 | } 22 | } 23 | } 24 | vector addOperators(string num, int target) { 25 | vector ans; 26 | helper(ans, 0, "", num, 0, 0, target); 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/find-median-from-data-stream.cpp: -------------------------------------------------------------------------------- 1 | class MedianFinder { 2 | public: 3 | 4 | // Adds a number into the data structure. 5 | void addNum(int num) { 6 | if (pmax.empty() || pmax.top() >= num) { 7 | pmax.push(num); 8 | if (pmin.size()+1 < pmax.size()) 9 | pmin.push(pmax.top()), pmax.pop(); 10 | } 11 | else { 12 | pmin.push(num); 13 | if (pmax.size() < pmin.size()) 14 | pmax.push(pmin.top()), pmin.pop(); 15 | } 16 | } 17 | 18 | // Returns the median of current data stream 19 | double findMedian() { 20 | if (pmax.size() == pmin.size()) return (pmax.top()+pmin.top())/2.0; 21 | else return pmax.top(); 22 | } 23 | private: 24 | priority_queue pmax; 25 | priority_queue, greater> pmin; 26 | }; 27 | 28 | // Your MedianFinder object will be instantiated and called as such: 29 | // MedianFinder mf; 30 | // mf.addNum(1); 31 | // mf.findMedian(); -------------------------------------------------------------------------------- /leetcode/find-minimum-in-rotated-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findMin(vector& nums) { 4 | int l = -1, r = nums.size()-1; 5 | while (l+1 < r) { 6 | int m = (l+r)/2; 7 | if (nums[m] < nums[r]) 8 | r = m; 9 | else 10 | l = m; 11 | } 12 | return nums[r]; 13 | } 14 | }; -------------------------------------------------------------------------------- /leetcode/find-the-duplicate-number.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | int findDuplicate(vector& nums) { 5 | vector v = nums; 6 | for (int i=0; i& nums) { 4 | for (int i=0; i 0 && nums[i] <= nums.size() && nums[i] != i+1 && nums[i] != nums[nums[i]-1]) 6 | swap(nums[i], nums[nums[i]-1]); 7 | } 8 | for (int i=0; iright; 30 | 31 | flatten(root->left, last); //flatten the root->left 32 | 33 | root->right = root->left; //linked the flattened root->left to the root->right 34 | 35 | last->right = right; //linked the origin root->right to the most right of the current root->right 36 | 37 | root->left = NULL; //empty root->left 38 | 39 | flatten(right, last); //flatten the root->right 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/fraction-to-recurring-decimal.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | long long myabs(int n) { 4 | long long ans = n; 5 | return ans>=0?ans:-ans; 6 | } 7 | string fractionToDecimal(int numerator, int denominator) { 8 | int sign = 1; 9 | if (numerator < 0 && denominator > 0 || numerator > 0 && denominator < 0) sign = -1; 10 | long long n = myabs(numerator); 11 | long long d = myabs(denominator); 12 | string ans; 13 | ans += to_string(n/d); 14 | n %= d; 15 | if (n) ans += '.'; 16 | unordered_map tab; 17 | while (n) { 18 | if (tab.find(n) == tab.end()) { 19 | tab[n] = ans.length(); 20 | ans += to_string(n*10/d); 21 | n = n*10%d; 22 | } 23 | else { 24 | int start = tab.find(n)->second; 25 | ans.insert(ans.begin()+start, '('); 26 | ans += ')'; 27 | break; 28 | } 29 | } 30 | if (sign == -1 && ans != "0") ans = "-"+ans; 31 | 32 | return ans; 33 | } 34 | }; -------------------------------------------------------------------------------- /leetcode/game-of-life.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void gameOfLife(vector>& board) { 4 | int m = board.size(); 5 | int n = m==0?0:board[0].size(); 6 | if (n==0) return; 7 | vector> dup = board; 8 | for (int i=0; i=m || y<0 || y>=n) continue; 16 | if (dup[x][y]) nlive++; 17 | } 18 | if (nlive < 2) board[i][j] = 0; 19 | else if (nlive > 3) board[i][j] = 0; 20 | if (nlive == 3) board[i][j] = 1; 21 | } 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/gas-station.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int canCompleteCircuit(vector &gas, vector &cost) { 4 | 5 | int size = gas.size(); 6 | int cur = 0; 7 | int start = 0; 8 | int end = 0; 9 | 10 | do 11 | { 12 | while (cur >= 0) 13 | { 14 | cur += (gas[end]-cost[end]); 15 | 16 | end = (end+1)%size; 17 | if (end == start) 18 | { 19 | break; 20 | } 21 | } 22 | 23 | while (cur < 0) 24 | { 25 | start = (start+size-1)%size; 26 | 27 | cur += gas[start] - cost[start]; 28 | 29 | if (end == start) 30 | { 31 | break; 32 | } 33 | } 34 | }while (start != end); 35 | 36 | if (cur >= 0) 37 | { 38 | return start; 39 | } 40 | 41 | return -1; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/generate-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector generateParenthesis(int n) { 4 | vector strs; 5 | generateParenthesis(strs, string(), n, n); 6 | return strs; 7 | } 8 | 9 | void generateParenthesis(vector& strs,string str, int l, int r) { 10 | if (l==0 && r==0) 11 | strs.push_back(str); 12 | if (l > 0) 13 | generateParenthesis(strs, str+'(', l-1, r); 14 | if (r > l) 15 | generateParenthesis(strs, str+')', l, r-1); 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/gray-code.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector grayCode(int n) { 4 | vector ans(1<>1); 7 | return ans; 8 | } 9 | }; -------------------------------------------------------------------------------- /leetcode/h-index-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | int npaper = citations.size(); 5 | int l = 0, r = npaper+1; 6 | while (l+1 < r) { 7 | int m = (l+r) / 2; 8 | if (citations[npaper-m] >= m) 9 | l = m; 10 | else 11 | r = m; 12 | } 13 | return l; 14 | } 15 | }; -------------------------------------------------------------------------------- /leetcode/h-index.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hIndex(vector& citations) { 4 | int nbucket = citations.size()+1; 5 | vector buckets(nbucket, 0); 6 | for (auto c:citations) { 7 | int idx = c>=nbucket?0:nbucket-1-c; 8 | buckets[idx]++; 9 | } 10 | int h = 0; 11 | for (int i=0; i insert(vector& intervals, Interval newInterval) { 13 | vector result; 14 | int i; 15 | for (i=0; i= 10) 22 | ans += words2[num%100-10]; 23 | else if (num % 100 < 10 && num % 100 > 0) 24 | ans += words1[num%100]; 25 | else if (num % 100 >= 20) { 26 | ans += words3[num%100/10]; 27 | if (num%10 > 0) 28 | ans += words1[num%10]; 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/interleaving-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isInterleave(string s1, string s2, string s3) { 4 | int len1 = s1.length(); 5 | int len2 = s2.length(); 6 | int len3 = s3.length(); 7 | if (len1+len2!=len3) return false; 8 | 9 | vector> dp(len1+1, vector(len2+1, false)); 10 | 11 | dp[0][0] = true; 12 | for (int i=0; i& nums, int k) { 4 | priority_queue, greater> que; 5 | 6 | for (int i=0; i letterCombinations(string digits) { 4 | string key[] = { " ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz", "+", " ", "#" }; 5 | int sum = 1; 6 | vector strs; 7 | if (digits.size() == 0) 8 | return strs; 9 | for (int i = 0; inext; 20 | fast = fast->next; 21 | 22 | if(fast) 23 | { 24 | fast = fast->next; 25 | if( fast == slow) 26 | { 27 | break; 28 | } 29 | } 30 | else 31 | { 32 | break; 33 | } 34 | } 35 | 36 | if( !fast ) 37 | { 38 | return NULL; 39 | } 40 | else 41 | { 42 | slow = head; 43 | 44 | while( slow != fast) 45 | { 46 | slow = slow->next; 47 | fast = fast->next; 48 | } 49 | 50 | return slow; 51 | } 52 | } 53 | }; -------------------------------------------------------------------------------- /leetcode/linked-list-cycle.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | bool hasCycle(ListNode *head) { 12 | if (!head) return false; 13 | 14 | ListNode* p1 = head, *p2 = head; 15 | 16 | while (p2->next && p2->next->next) { 17 | p1 = p1->next; 18 | p2 = p2->next->next; 19 | if (p1 == p2) return true; 20 | } 21 | return false; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/longest-palindromic-substring.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string longestPalindrome(string s) { 4 | const int max_n = 1001; 5 | bool dp[max_n][max_n]; 6 | memset(dp, 0, sizeof(dp)); 7 | 8 | int len = s.length(); 9 | for (int i = 0; i < len; i++) 10 | for (int j = 0; j < 2; j++) { 11 | if (i + j <= len) { 12 | // printf("%d %d\n", i, j); 13 | dp[i][i + j] = true; 14 | } 15 | } 16 | 17 | for (int l = 2; l <= len; l++) 18 | for (int i = 0; i < len; i++) { 19 | if (i + l <= len && dp[i + 1][i + l - 1] && s[i] == s[i + l - 1]) 20 | dp[i][i + l] = true; 21 | } 22 | int max_l = 1; 23 | int max_s = 0; 24 | 25 | for (int i = 0; i < len; i++) 26 | for (int j = 1; j <= len; j++) 27 | if (dp[i][i + j] && j > max_l) { 28 | max_l = j; 29 | max_s = i; 30 | } 31 | 32 | return s.substr(max_s, max_l); 33 | } 34 | }; -------------------------------------------------------------------------------- /leetcode/longest-substring-without repeating characters.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int lengthOfLongestSubstring(string s) { 4 | 5 | int size = s.length(); 6 | map dict; 7 | 8 | int curlen = 0; 9 | int maxlen = 0; 10 | int start = 0; 11 | 12 | for(int i=0; i maxlen) 21 | { 22 | maxlen = curlen; 23 | } 24 | } 25 | else 26 | { 27 | for (start; start < i; start++) 28 | { 29 | if (s[start] == ch) 30 | { 31 | start++; 32 | break; 33 | } 34 | dict[s[start]] = false; 35 | curlen--; 36 | } 37 | } 38 | } 39 | 40 | return maxlen; 41 | 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/longest-valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int longestValidParentheses(string s) { 4 | stack st; 5 | vector len(s.length()+1, 0); 6 | 7 | for (int i=0; i& points) { 13 | int ans = 0; 14 | for (auto p:points) { 15 | int same = 0; 16 | unordered_map um; 17 | for (auto q:points) { 18 | if (p.x == q.x && p.y==q.y) 19 | same ++; 20 | else 21 | um[atan2(q.y-p.y, q.x-p.x)]++; 22 | } 23 | ans = max(ans, same); 24 | for (auto x:um) 25 | ans = max(ans, same+x.second); 26 | } 27 | return ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /leetcode/maximum-depth-of-binary tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int maxDepth(TreeNode *root) { 13 | int depth = 0; 14 | vector curlayer; 15 | 16 | if( root) 17 | { 18 | curlayer.push_back(root); 19 | } 20 | 21 | while( curlayer.size()) 22 | { 23 | depth++; 24 | vector nextlayer; 25 | for( int i=0,size=curlayer.size(); ileft) 28 | { 29 | nextlayer.push_back(curlayer[i]->left); 30 | } 31 | if( curlayer[i]->right) 32 | { 33 | nextlayer.push_back(curlayer[i]->right); 34 | } 35 | } 36 | curlayer = nextlayer; 37 | } 38 | 39 | return depth; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/median-of-two-sorted-arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double findMedianSortedArrays(int A[], int m, int B[], int n) { 4 | 5 | double a = (double)findk( A, 0, m-1, B, 0, n-1, (m+n-1)/2); 6 | double b = (double)findk( A, 0, m-1, B, 0, n-1, (m+n)/2); 7 | 8 | return (a+b)/2.0; 9 | 10 | } 11 | 12 | int findk(int A[], int m1, int m2, int B[], int n1, int n2, int k) 13 | { 14 | if( m2 < m1) 15 | { 16 | return B[n1+k]; 17 | } 18 | 19 | if( n2 < n1) 20 | { 21 | return A[m1+k]; 22 | }; 23 | 24 | int a = (m1+m2+1)/2; 25 | int b = (n1+n2+1)/2; 26 | 27 | int mid = (m2-m1+1)/2 + (n2-n1+1)/2+1; 28 | 29 | if (k >= mid) 30 | { 31 | if (A[a]>B[b]) 32 | { 33 | return findk(A, m1, m2, B, b+1, n2, k-(b-n1)-1); 34 | } 35 | else 36 | { 37 | return findk(A, a+1, m2, B, n1, n2, k-(a-m1)-1); 38 | } 39 | } 40 | else 41 | { 42 | if (A[a]>B[b]) 43 | { 44 | return findk(A, m1, a-1, B, n1, n2, k); 45 | } 46 | else 47 | { 48 | return findk(A, m1, m2, B, n1, b-1, k); 49 | } 50 | } 51 | } 52 | }; -------------------------------------------------------------------------------- /leetcode/merge-intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | static bool comp(const Interval& in1, const Interval& in2) { 4 | if (in1.start == in2.start) 5 | return in1.end < in2.end; 6 | return in1.start < in2.start; 7 | } 8 | vector merge(vector& intervals) { 9 | vector ans; 10 | if (intervals.size() == 0) return ans; 11 | sort(intervals.begin(), intervals.end(), comp); 12 | 13 | for (int i=0; i ans.back().end) 15 | ans.push_back(intervals[i]); 16 | else if (intervals[i].end <= ans.back().end) 17 | continue; 18 | else 19 | ans.back().end = max(ans.back().end, intervals[i].end); 20 | } 21 | return ans; 22 | } 23 | 24 | }; -------------------------------------------------------------------------------- /leetcode/merge-k-sorted-lists .cpp: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Definition for singly-linked list. 4 | * struct ListNode { 5 | * int val; 6 | * ListNode *next; 7 | * ListNode(int x) : val(x), next(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | ListNode* mergeKLists(vector& lists) { 13 | priority_queue, vector >, greater > > que; 14 | 15 | for (int i=0; ival, lists[i])); 18 | 19 | ListNode* head = NULL; 20 | ListNode** pt = &head; 21 | while (!que.empty()) { 22 | pair p = que.top(); 23 | que.pop(); 24 | *pt = new ListNode(p.first); 25 | pt = &(*pt)->next; 26 | if (p.second->next) 27 | que.push(make_pair(p.second->next->val, p.second->next)); 28 | } 29 | 30 | return head; 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/merge-two-sorted-lists .cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 | ListNode* head = NULL; 13 | ListNode *p = &head; 14 | 15 | while (l1 || l2) { 16 | if (l1 && l2) { 17 | if (l1->val > l2->val) { 18 | *p = new ListNode(l2->val); 19 | l2 = l2->next; 20 | } 21 | else { 22 | *p = new ListNode(l1->val); 23 | l1 = l1->next; 24 | } 25 | } 26 | else if (l1) { 27 | *p = new ListNode(l1->val); 28 | l1 = l1->next; 29 | } 30 | else { 31 | *p = new ListNode(l2->val); 32 | l2 = l2->next; 33 | } 34 | p = &(*p)->next; 35 | } 36 | return head; 37 | } 38 | }; -------------------------------------------------------------------------------- /leetcode/minimum-depth-of-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | int minDepth(TreeNode *root) { 13 | int depth = 0; 14 | 15 | if( !root) 16 | { 17 | return depth; 18 | } 19 | 20 | vector curlayer; 21 | curlayer.push_back(root); 22 | while(true) 23 | { 24 | vector nextlayer; 25 | 26 | for( int i=0,size=curlayer.size(); ileft && !curlayer[i]->right) 29 | { 30 | return depth+1; 31 | } 32 | else 33 | { 34 | if( curlayer[i]->left) 35 | { 36 | nextlayer.push_back(curlayer[i]->left); 37 | } 38 | 39 | if( curlayer[i]->right) 40 | { 41 | nextlayer.push_back(curlayer[i]->right); 42 | } 43 | } 44 | } 45 | 46 | curlayer = nextlayer; 47 | 48 | depth ++; 49 | } 50 | } 51 | }; -------------------------------------------------------------------------------- /leetcode/minimum-size-subarray-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int minSubArrayLen(int s, vector& nums) { 4 | int sum = 0; 5 | int a = 0, b = 0; 6 | int ans = INT_MAX; 7 | for (;;) { 8 | if (sum < s) { 9 | if (b >= nums.size()) 10 | break; 11 | sum += nums[b++]; 12 | } 13 | else { 14 | ans = min(ans, b-a); 15 | sum -= nums[a++]; 16 | } 17 | } 18 | if (ans == INT_MAX) 19 | return 0; 20 | } 21 | }; -------------------------------------------------------------------------------- /leetcode/missing-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int missingNumber(vector& nums) { 4 | for (int i=0; i=0; i--) { 19 | int val = (num[i]-'0')*d+c; 20 | ans[i] = val%10 + '0'; 21 | c = val/10; 22 | } 23 | if (c) 24 | ans = (char)(c+'0')+ans; 25 | return ans; 26 | } 27 | 28 | string add(string num1, string num2) { 29 | //if (num1 == "" || num1 == "0") return num2; 30 | int len = max(num1.size(), num2.size()); 31 | string ans(len,'0'); 32 | int p1 = num1.size()-1, p2 = num2.size()-1; 33 | int p3 = ans.size()-1; 34 | int c = 0; 35 | while (p1>=0 || p2>=0) { 36 | if (p1>=0 && p2>=0) { 37 | int val = num1[p1]-'0'+num2[p2]-'0'+c; 38 | ans[p3] = val%10 + '0'; 39 | p1--; p2--; 40 | c = val/10; 41 | } 42 | else if (p1>=0) { 43 | int val = num1[p1]-'0'+c; 44 | ans[p3] = val%10 + '0'; 45 | p1--; 46 | c = val/10; 47 | } 48 | else { 49 | int val = num2[p2]-'0'+c; 50 | ans[p3] = val%10+'0'; 51 | p2--; 52 | c = val/10; 53 | } 54 | p3--; 55 | } 56 | 57 | if (c) 58 | ans = "1" + ans; 59 | return ans; 60 | } 61 | }; -------------------------------------------------------------------------------- /leetcode/n-queens.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector > solveNQueens(int n) { 4 | vector > ans; 5 | vector col(n); 6 | solveNQueens(ans, col, 0, n); 7 | return ans; 8 | } 9 | 10 | void solveNQueens(vector > &ans, vector& col, int i, int n) { 11 | if (i == n) { 12 | print(ans, col); 13 | return; 14 | } 15 | for (int j=0; j& col, int i) { 23 | for (int j=0; j > &ans, const vector& col) { 32 | vector v; 33 | int n = col.size(); 34 | for (int i=0; i& nums) { 4 | if (nums.size() <= 1) return; 5 | int p; 6 | for (p=nums.size()-1; p>0; p--) 7 | if (nums[p] > nums[p-1]) 8 | break; 9 | if (p) { 10 | int p2; 11 | for (p2=nums.size()-1; p2>p; p2--) 12 | if (nums[p2] > nums[p-1]) break; 13 | swap(nums[p2], nums[p-1]); 14 | } 15 | reverse(nums.begin()+p, nums.end()); 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/nim-game.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool canWinNim(int n) { 4 | return n%4; 5 | } 6 | }; -------------------------------------------------------------------------------- /leetcode/number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int hammingWeight(uint32_t n) { 4 | int ans = 0; 5 | while (n) { 6 | ans ++; 7 | n -= n&(-n); 8 | } 9 | return ans; 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isPalindrome(int x) { 4 | if (x < 0) return false; 5 | int p1 = 0, p2 = x; 6 | while (p2 > 0) { 7 | p1 = p1*10 + p2%10; 8 | p2 /= 10; 9 | } 10 | return p1 == x; 11 | } 12 | }; -------------------------------------------------------------------------------- /leetcode/perfect-squares.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numSquares(int n) { 4 | vector dp(n+1); 5 | for (int i=0; i<=n; i++) 6 | dp[i] = i; 7 | for (int i=2; i<=n; i++){ 8 | for (int j=1; j*j<=i; j++) 9 | dp[i] = min(dp[i], dp[i-j*j]+1); 10 | } 11 | return dp[n]; 12 | } 13 | }; -------------------------------------------------------------------------------- /leetcode/permutation-sequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string getPermutation(int n, int k) { 4 | k--; 5 | string ans; 6 | vector tab; 7 | vector used(n, false); 8 | int p = 1; 9 | tab.push_back(1); 10 | for (int i = 2; i <= n; i++) { 11 | p *= i - 1; 12 | tab.push_back(p); 13 | } 14 | 15 | for (int i = 0; i < n; i++) { 16 | int t = k / tab[n - i - 1]; 17 | k %= tab[n - i - 1]; 18 | int t2 = 0; 19 | int j = 0; 20 | for (j = 0; j < n; j++) 21 | if (!used[j] && t2++ == t) 22 | break; 23 | used[j] = true; 24 | ans += '1' + j; 25 | } 26 | return ans; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/permutations-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> permuteUnique(vector& nums) { 4 | vector> ans; 5 | sort(nums.begin(), nums.end()); 6 | permute(ans, nums, 0); 7 | return ans; 8 | } 9 | 10 | void permute(vector>& ans, vector& perm, int begin) 11 | { 12 | if (begin == perm.size()) { 13 | ans.push_back(perm); 14 | return; 15 | } 16 | unordered_set used; 17 | for (int i=begin; i> permute(vector& nums) { 4 | vector> ans; 5 | permute(ans, nums, 0); 6 | return ans; 7 | } 8 | 9 | void permute(vector>& ans, vector& perm, int begin) 10 | { 11 | if (begin == perm.size()) { 12 | ans.push_back(perm); 13 | return; 14 | } 15 | 16 | for (int i=begin; i=0; i--) 17 | if (id & (1<right; 18 | else node = node->left; 19 | return node; 20 | } 21 | 22 | void connect(TreeLinkNode *node, int id, int level, TreeLinkNode *root) { 23 | if (!node) return; 24 | node->next = getNode(root, id+1, level); 25 | connect(node->left, id<<1, level+1, root); 26 | connect(node->right, (id<<1)+1, level+1, root); 27 | } 28 | 29 | void connect(TreeLinkNode *root) { 30 | connect(root, 0, 0, root); 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/powx-n.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | double myPow(double x, int n) { 4 | int e = n<0?-n:n; 5 | double p = n<0?1.0/x:x; 6 | double ans = 1.0; 7 | for (int i=0; i<32; i++) { 8 | if (e&(1<= t2 || s2 >= t1) return 0; 9 | return min(t1, t2) - max(s1, s2); 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/remove-duplicates-from-sorted-array-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int i=0, j=0; 5 | int last=0, time=0; 6 | 7 | while (i < nums.size()) { 8 | if (nums[i] == last) 9 | time++; 10 | else { 11 | time = 1; 12 | last = nums[i]; 13 | } 14 | 15 | if (time <= 2) 16 | nums[j++] = nums[i++]; 17 | else 18 | i++; 19 | } 20 | return j; 21 | } 22 | }; -------------------------------------------------------------------------------- /leetcode/remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int removeDuplicates(vector& nums) { 4 | int nunique = 0; 5 | int pre; 6 | for (int i=0; ival==cur->val) 17 | { 18 | last->next = cur->next; 19 | delete cur; 20 | cur = last->next; 21 | } 22 | else 23 | { 24 | last = cur; 25 | cur = cur->next; 26 | } 27 | 28 | } 29 | 30 | return head; 31 | } 32 | }; -------------------------------------------------------------------------------- /leetcode/remove-duplicates-from-sorted-list-ii.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* deleteDuplicates(ListNode* head) { 12 | ListNode* node = NULL; 13 | ListNode**pt = &node; 14 | 15 | ListNode *pre = NULL; 16 | 17 | while (head) { 18 | if ((!pre || pre->val!= head->val) && (!head->next || head->val!=head->next->val)) { 19 | *pt = new ListNode(head->val); 20 | pt = &(*pt)->next; 21 | } 22 | pre = head; 23 | head = head->next; 24 | } 25 | 26 | return node; 27 | } 28 | }; -------------------------------------------------------------------------------- /leetcode/remove-nth-node-from-end-of-list.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* removeNthFromEnd(ListNode* head, int n) { 12 | ListNode** p1 = &head, *p2 = head; 13 | for (int i=0; inext; 15 | while (p2) { 16 | p1 = &(*p1)->next; 17 | p2 = p2->next; 18 | } 19 | 20 | ListNode* temp = *p1; 21 | *p1 = temp->next; 22 | delete temp; 23 | return head; 24 | } 25 | }; -------------------------------------------------------------------------------- /leetcode/repeated-dna-sequences.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findRepeatedDnaSequences(string s) { 4 | vector ans; 5 | if (s.length() < 0) return ans; 6 | unordered_map tab; 7 | int v = 0, mask=(1<<18)-1; 8 | for (int i=0; i<10; i++) { 9 | v <<= 2; 10 | v += c2int(s[i]); 11 | } 12 | tab[v]++; 13 | for (int i=10; i restoreIpAddresses(string s) { 4 | vector ans; 5 | string t(s.length() + 3,' '); 6 | gao(s, ans, t, 0, 0); 7 | return ans; 8 | } 9 | 10 | void gao(string &s, vector& ans, string& t, int begin, int idx) { 11 | if (begin == s.length() && idx == 4) { 12 | ans.push_back(t); 13 | return; 14 | } 15 | if (idx >= 4 || begin >= s.length()) return; 16 | int ip = 0; 17 | for (int i = 0; i<3 && begin + i 255) break; 21 | t[begin + idx + i] = s[i + begin]; 22 | if (idx < 3) t[begin + idx + i + 1] = '.'; 23 | gao(s, ans, t, begin + i + 1, idx + 1); 24 | } 25 | } 26 | }; -------------------------------------------------------------------------------- /leetcode/reverse-integer.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int reverse(int x) { 4 | int sign = x >= 0 ? 1 : -1; 5 | if (x < 0) x = -x; 6 | 7 | vector digits; 8 | 9 | do{ 10 | digits.push_back(x % 10); 11 | x /= 10; 12 | } while (x>0); 13 | 14 | int ans = 0; 15 | 16 | for (int i = 0; i < digits.size(); i++) { 17 | if (ans != ans*10/10) return 0; 18 | ans = ans * 10 + digits[i]; 19 | if (ans < 0) return 0; 20 | } 21 | 22 | return ans*sign; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /leetcode/reverse-linked-list-ii.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* reverseBetween(ListNode* head, int m, int n) { 12 | //if (!head) return head; 13 | ListNode **p = &head; 14 | for (int i=1; inext; 16 | ListNode *tail = *p; 17 | for (int i=m; inext; 19 | tail->next = tail->next->next; 20 | temp->next = *p; 21 | *p = temp; 22 | } 23 | return head; 24 | } 25 | }; -------------------------------------------------------------------------------- /leetcode/reverse-nodes-in-k-group.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* reverseKGroup(ListNode* head, int k) { 12 | ListNode* node, *pre = NULL; 13 | ListNode* l = NULL, *head2; 14 | ListNode**pt = &l, **tail=NULL; 15 | int i = 0; 16 | while (head) { 17 | 18 | node = new ListNode(head->val); 19 | node->next = pre; 20 | pre = node; 21 | if (i%k == 0) { 22 | tail = &(node->next); 23 | head2 = head; 24 | } 25 | if (++i % k == 0) { 26 | *pt = node; 27 | pt = tail; 28 | pre = NULL; 29 | } 30 | 31 | head = head->next; 32 | } 33 | 34 | if (i%k != 0) 35 | *pt = head2; 36 | 37 | return l; 38 | } 39 | }; -------------------------------------------------------------------------------- /leetcode/reverse-words-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void reverseWords(string &s) { 4 | if (s.length() == 0) return; 5 | reverse(s.begin(), s.end()); 6 | int p1 = 0, p2; 7 | int len = 0; 8 | for (p2=0; p2& nums, int k) { 4 | int len = nums.size(); 5 | k %= len; 6 | reverse(nums, len-k, len-1); 7 | reverse(nums, 0, len-k-1); 8 | reverse(nums, 0, nums.size()-1); 9 | } 10 | 11 | int gcd(int a, int b) { 12 | return b?gcd(b, a%b):a; 13 | } 14 | 15 | void rotate(vector& nums, int k) { 16 | int len = nums.size(); 17 | if (!len) return; 18 | k %= len; 19 | if (!k) return; 20 | int g = gcd(k, len); 21 | for (int i=0; i& nums, int s, int t) { 29 | while (s < t) { 30 | swap(nums[s], nums[t]); 31 | s++; 32 | t--; 33 | } 34 | } 35 | }; -------------------------------------------------------------------------------- /leetcode/rotate-image.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void rotate(vector>& matrix) { 4 | int n = matrix.size(); 5 | for (int i=0; ival == q->val) 16 | { 17 | return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 18 | } 19 | else 20 | { 21 | return false; 22 | } 23 | } 24 | else if( !p && !q) 25 | { 26 | return true; 27 | } 28 | else 29 | { 30 | return false; 31 | } 32 | } 33 | }; -------------------------------------------------------------------------------- /leetcode/search-for-a-range.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector searchRange(vector& nums, int target) { 4 | int l = 0, r = nums.size(); 5 | vector ans(2, -1); 6 | while (l+1 < r) { 7 | int m = (l+r)>>1; 8 | if (nums[m] <= target) 9 | l = m; 10 | else 11 | r = m; 12 | } 13 | if (nums[l] != target) 14 | return ans; 15 | ans[1] = l; 16 | l = -1, r = nums.size()-1; 17 | while (l+1 < r) { 18 | int m = (l+r)>>1; 19 | if (nums[m] < target) 20 | l = m; 21 | else 22 | r = m; 23 | } 24 | ans[0] = r; 25 | return ans; 26 | } 27 | }; -------------------------------------------------------------------------------- /leetcode/set-matrix-zeroes.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void setZeroes(vector>& matrix) { 4 | int m = matrix.size(); 5 | int n = m==0?0:matrix[0].size(); 6 | bool first_r = false, first_c = false; 7 | 8 | for (int i=0; i next; 8 | getNext(str, next); 9 | int sn = s.length(); 10 | return t.substr(0, sn-next.back())+s; 11 | } 12 | 13 | void getNext(string &s, vector &next) { 14 | int len = s.length(); 15 | next.resize(len); 16 | next[0] = -1; 17 | for (int i=1; i= 0 && s[k] != s[i-1]) 20 | k = next[k]; 21 | next[i] = k+1; 22 | } 23 | } 24 | }; -------------------------------------------------------------------------------- /leetcode/simplify-path.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | string simplifyPath(string path) { 4 | string result; 5 | int length = path.length(); 6 | 7 | vector paths; 8 | string onepath; 9 | 10 | bool in = false; 11 | 12 | for (int i=0; i maxSlidingWindow(vector& nums, int k) { 4 | deque dq; 5 | vector ans; 6 | for (int i=0; i=k-1) ans.push_back(nums[dq.front()]); 12 | } 13 | return ans; 14 | } 15 | }; -------------------------------------------------------------------------------- /leetcode/sort-colors.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void sortColors(vector& nums) { 4 | int i=0, j=0, k=nums.size()-1; 5 | while (j<=k) { 6 | if (nums[j]<1) swap(nums[j++], nums[i++]); 7 | else if (nums[j] > 1) swap(nums[j], nums[k--]); 8 | else j++; 9 | } 10 | } 11 | }; -------------------------------------------------------------------------------- /leetcode/sqrtx.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int mySqrt(int x) { 4 | if (x < 2) return x; 5 | int l = 1, r = x; 6 | while (l+1 < r) { 7 | int m = l+(r-l)/2; 8 | if (x/m < m) r = m; 9 | else l = m; 10 | } 11 | return l; 12 | } 13 | }; -------------------------------------------------------------------------------- /leetcode/subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a set of distinct integers, S, return all possible subsets. 3 | 4 | Note: 5 | Elements in a subset must be in non-descending order. 6 | The solution set must not contain duplicate subsets. 7 | For example, 8 | If S = [1,2,3], a solution is: 9 | 10 | [ 11 | [3], 12 | [1], 13 | [2], 14 | [1,2,3], 15 | [1,3], 16 | [2,3], 17 | [1,2], 18 | [] 19 | ] 20 | */ 21 | 22 | class Solution { 23 | public: 24 | vector > subsets(vector &S) { 25 | 26 | int size = 1<> result(size); 31 | 32 | for (int i=0; i>1; 44 | j++; 45 | } 46 | } 47 | 48 | return result; 49 | } 50 | }; -------------------------------------------------------------------------------- /leetcode/substring-with-concatenation-of-all-words.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector findSubstring(string s, vector& words) { 4 | unordered_map dict; 5 | for (string&word:words) 6 | dict[word]++; 7 | int wl = words[0].size(); 8 | vector ans; 9 | for (int i=0; i tdict; 13 | for (int j=i; j+wl<=s.length(); j+=wl) { 14 | string str = s.substr(j, wl); 15 | if (dict.find(str) == dict.end()) { 16 | tdict.clear(); 17 | count = 0; 18 | left = j+wl; 19 | } 20 | else { 21 | tdict[str]++; 22 | if (tdict[str] <= dict[str]) 23 | count ++; 24 | else { 25 | while (tdict[str] > dict[str]) { 26 | string s2 = s.substr(left, wl); 27 | tdict[s2]--; 28 | if (tdict[s2] < dict[str]) count--; 29 | left += wl; 30 | } 31 | } 32 | if (count == words.size()) { 33 | ans.push_back(left); 34 | tdict[s.substr(left, wl)]--; 35 | left += wl; 36 | count--; 37 | } 38 | } 39 | } 40 | } 41 | return ans; 42 | } 43 | }; -------------------------------------------------------------------------------- /leetcode/sudoku-solver.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool row[9][9], col[9][9], sq[9][9]; 4 | void solveSudoku(vector>& board) { 5 | for (int i=0; i<9; i++) 6 | for (int j=0; j<9; j++) 7 | if (board[i][j] != '.') 8 | fill(i, j, board[i][j]-'1'); 9 | go(0, 0, board); 10 | } 11 | 12 | bool go(int i, int j, vector> &board) { 13 | if (i > 8) return true; 14 | if (board[i][j] != '.') { 15 | next(i, j); 16 | return go(i, j, board); 17 | } 18 | int i0 = i, j0 = j; 19 | next(i, j); 20 | for (int k=0; k<9; k++) { 21 | if (check(i0, j0, k)) { 22 | fill(i0, j0, k); 23 | if (go(i, j, board)) { 24 | board[i0][j0] = k+'1'; 25 | return true; 26 | } 27 | unfill(i0, j0, k); 28 | } 29 | } 30 | return false; 31 | } 32 | 33 | void next(int &i, int &j) { 34 | if (j == 8) { 35 | i++; 36 | j = 0; 37 | } 38 | else 39 | j++; 40 | } 41 | 42 | void fill(int i, int j, int n) { 43 | row[i][n] = true; 44 | col[j][n] = true; 45 | sq[i/3*3+j/3][n] = true; 46 | } 47 | 48 | void unfill(int i, int j, int n) { 49 | row[i][n] = false; 50 | col[j][n] = false; 51 | sq[i/3*3+j/3][n] = false; 52 | } 53 | 54 | bool check(int i, int j, int n) { 55 | return !(row[i][n] || col[j][n] || sq[i/3*3+j/3][n]); 56 | } 57 | }; -------------------------------------------------------------------------------- /leetcode/swap-nodes-in-pairs.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode(int x) : val(x), next(NULL) {} 7 | * }; 8 | */ 9 | class Solution { 10 | public: 11 | ListNode* swapPairs(ListNode* head) { 12 | if (!head || !head->next) return head; 13 | ListNode* p1 = head; 14 | ListNode* new_head, **lastp = &new_head; 15 | 16 | while (p1 && p1->next) { 17 | ListNode* temp = p1->next->next; 18 | *lastp = p1->next; 19 | p1->next->next = p1; 20 | p1->next = temp; 21 | lastp = &(p1->next); 22 | p1 = temp; 23 | } 24 | 25 | return new_head; 26 | } 27 | }; -------------------------------------------------------------------------------- /leetcode/symmetric-tree.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for binary tree 3 | * struct TreeNode { 4 | * int val; 5 | * TreeNode *left; 6 | * TreeNode *right; 7 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 | * }; 9 | */ 10 | class Solution { 11 | public: 12 | bool isSymmetric(TreeNode *root) { 13 | if (root) 14 | { 15 | return isSymmetric(root->right, root->left); 16 | } 17 | 18 | return true; 19 | } 20 | 21 | bool isSymmetric(TreeNode *r1, TreeNode *r2) 22 | { 23 | if (!r1 && !r2) 24 | { 25 | return true; 26 | } 27 | else if (r1 && r2) 28 | { 29 | if (r1->val != r2->val) 30 | { 31 | return false; 32 | } 33 | 34 | return isSymmetric(r1->right, r2->left) && isSymmetric(r1->left, r2->right); 35 | } 36 | else 37 | { 38 | return false; 39 | } 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/text-justification.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector fullJustify(vector& words, int maxWidth) { 4 | int i = 0; 5 | vector ans; 6 | while (i < words.size()) { 7 | int j = i + 1; 8 | int len = words[i].length(); 9 | while (j < words.size() && len + words[j].length() + 1 <= maxWidth) 10 | len += words[j++].length() + 1; 11 | bool lastLine = false; 12 | if (j == words.size()) lastLine = true; 13 | int ngap = j - i - 1; 14 | int nspace = maxWidth - len; 15 | int space_per_gap = ngap == 0 ? 0:nspace / ngap; 16 | string line = words[i]; 17 | for (int k = i + 1; k < j; k++) { 18 | if (!lastLine) 19 | for (int l = 0; l<=space_per_gap; l++) 20 | line += " "; 21 | if (k - i - 1 < nspace%ngap || lastLine) 22 | line += " "; 23 | line += words[k]; 24 | } 25 | line.resize(maxWidth, ' '); 26 | i = j; 27 | ans.push_back(line); 28 | } 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /leetcode/two-sum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector twoSum(vector &numbers, int target) { 4 | vector ans(2); 5 | map m; 6 | for (int i=0; i::iterator iter = m.find(target-numbers[i]); 8 | if (iter != m.end()) { 9 | ans[0] = iter->second+1; 10 | ans[1] = i+1; 11 | break; 12 | } 13 | m.insert(make_pair(numbers[i], i)); 14 | } 15 | return ans; 16 | } 17 | }; -------------------------------------------------------------------------------- /leetcode/unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int numTrees(int n) { 4 | return numTrees(0, n-1); 5 | } 6 | 7 | int numTrees(int start, int end) 8 | { 9 | if( end - start <= 0) 10 | { 11 | return 1; 12 | } 13 | 14 | int result = 0; 15 | 16 | for( int i=start; i<=end; i++) 17 | { 18 | result += numTrees(start, i-1)*numTrees(i+1,end); 19 | } 20 | 21 | return result; 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/valid-parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool isValid(string s) { 4 | stack st; 5 | for (int i=0; ival; 19 | if ((low && val <= *low) || (up && val >= *up)) return false; 20 | return isValidBST(root->left, low, &val) 21 | && isValidBST(root->right, &val, up); 22 | } 23 | }; -------------------------------------------------------------------------------- /leetcode/word-break-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector wordBreak(string s, unordered_set& wordDict) { 4 | vector ans; 5 | int min_len = INT_MAX, max_len = INT_MIN; 6 | for (unordered_set::iterator iter=wordDict.begin(); iter != wordDict.end(); iter++) { 7 | min_len = min(min_len, (int)iter->length()); 8 | max_len = max(max_len, (int)iter->length()); 9 | } 10 | if (!canWordBreak(s, wordDict, min_len, max_len)) 11 | return ans; 12 | wordBreak(s, wordDict, string(), ans, min_len, max_len); 13 | return ans; 14 | } 15 | 16 | void wordBreak(string s, unordered_set& wordDict, string v, vector& ans, int min_len, int max_len) { 17 | if (s.length() == 0) { 18 | ans.push_back(v); 19 | return; 20 | } 21 | if (v.length() != 0) v.push_back(' '); 22 | for (int i=min_len; i<=s.length() && i<=max_len; i++) { 23 | string t = s.substr(0, i); 24 | if (wordDict.find(t) != wordDict.end()) 25 | wordBreak(s.substr(i), wordDict, v+t, ans, min_len, max_len); 26 | } 27 | } 28 | 29 | bool canWordBreak(std::string &s, std::unordered_set &wordDict, int min_len, int max_len) { 30 | int len = s.length(); 31 | vector dp(len+1, false); 32 | dp[0] = true; 33 | for (int i=1; i<=len; i++) 34 | for (int l=min_len; l<=max_len && i-l>=0; l++) 35 | if (dp[i-l] && wordDict.count(s.substr(i-l, l))) { 36 | dp[i] = true; 37 | break; 38 | } 39 | return dp[len]; 40 | } 41 | }; -------------------------------------------------------------------------------- /leetcode/word-break.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | bool wordBreak(string s, unordered_set& wordDict) { 4 | int len = s.length(); 5 | int max_len = 0, min_len = len+1; 6 | for (unordered_set::iterator iter=wordDict.begin(); iter!=wordDict.end(); ++iter) { 7 | max_len = max(max_len, (int)iter->length()); 8 | min_len = min(min_len, (int)iter->length()); 9 | } 10 | 11 | vector dp(len+1, false); 12 | dp[len] = true; 13 | for (int i=len-1; i>=0; i--) { 14 | for (int j=min_len; j<=min(max_len, len-i); j++) 15 | if (dp[i+j] && wordDict.find(s.substr(i, j)) != wordDict.end()) { 16 | dp[i] = true; 17 | } 18 | } 19 | 20 | return dp[0]; 21 | } 22 | }; --------------------------------------------------------------------------------