├── Adhoc └── UVa 10954 - Add All.cpp ├── Bruteforce ├── 12325 - Zombies Treasure Chest.cpp └── UVa 725 - Division.cpp ├── CONTRIBUTING.md ├── Data Structure ├── UVa 11988 - Broken Keyboard v2.cpp ├── UVa 11988 - Broken Keyboard.cpp └── UVa 673 Parantheses Balance.cpp ├── Dynamic Programming ├── UVa 1347 - Tour.cpp └── UVa 437 - The Tower of Babylon.cpp ├── Easy Problems ├── Exercises │ ├── Timus 1025 - Democracy in Danger.py │ ├── Timus 1079 - Maximum.cpp │ ├── Timus 1149 - Sinus Dances.cpp │ ├── Timus 1313 - Some Words about Sports.py │ ├── Timus 1319 - Hotel.py │ ├── UVa 10340 - All in All.cpp │ ├── UVa 12412 - A Typical Homework.py │ ├── UVa 1583 - Digit Generator.py │ ├── UVa 1584 - Circular Sequence.cpp │ ├── UVa 1589 - Xiangqi.py │ ├── UVa 1590 - IP Networks.py │ ├── UVa 1591 - Data Mining.py │ ├── UVa 201 - Squares.py │ ├── UVa 213 - Message Decoding.py │ ├── UVa 220 - Othello.cpp │ ├── UVa 232 - Corssword Answers.py │ ├── UVa 272 - TEX Quotes.py │ ├── UVa 340 - Master-Mind Hints.cpp │ ├── UVa 508 - Morese Mismatches.cpp │ ├── UVa 509 - RAID.cpp │ ├── UVa 512 - Spreadsheet Tracking.py │ └── UVa 815 - Flooded.py ├── Timus 1000 - A+B Problem.cpp ├── Timus 1005 - Stone Pile v1.cpp ├── Timus 1005 - Stone Pile v2.cpp ├── Timus 1005 - Stone Pile v3.cpp ├── Timus 1005 - Stone Pile v4.cpp ├── Timus 1014 - Product of Digits.cpp ├── Timus 1020 - Rope.cpp ├── Timus 1044 - Lucky Tickets (Easy).cpp ├── Timus 1197 - Lonesome Knight.cpp ├── UVa 12108 - Extraordinarily Tired Students.cpp ├── UVa 202 - Repeating Decimals.cpp └── UVa 253 - Cube Painting.cpp ├── Geometry └── UVa 10283 - The Kissing Circles.cpp ├── Graph Theory └── UVa 10048 - Audiophobia.cpp ├── Greedy └── CF 26B - Regular Bracket Sequence.cpp ├── Mathematics ├── UVA 12169 - Disgruntled Judge.cpp ├── UVa 10375 - Choose and divide.cpp └── UVa 11582 - Colossal Fibonacci Numbers!.cpp ├── STL ├── Exercises │ ├── UVa 10763 - Foreign Exchange v2.cpp │ ├── UVa 10763 - Foreign Exchange.cpp │ ├── UVa 10935 - Throwing Cards Away I.cpp │ ├── UVa 12333 - Revenge of Fibonacci.cpp │ ├── UVa 12504 - Updating a Dictionary.cpp │ ├── UVa 1593 - Alignment of Code.cpp │ ├── UVa 1594 - Ducci Sequence.cpp │ ├── UVa 1595 - Symmetry.cpp │ ├── UVa 1596 - Bug Hunt.cpp │ ├── UVa 212 - Use of Hospital Facilities.cpp │ ├── UVa 230 - Borrowers.cpp │ ├── UVa 400 - Unix ls.cpp │ ├── UVa 511 - Do You Know the Way to San Jose?.cpp │ └── UVa 822 - Queue and A.cpp ├── Timus 1209 - 1, 10, 100, 1000....py ├── UVA 136 - Ugly Numbers.cpp ├── UVa 101 - The Blocks Problem.cpp ├── UVa 10815 - Andy's First Dictionary.cpp ├── UVa 10815 - Andy's First Dictionary.py ├── UVa 12096 - The SetStack Computer.cpp ├── UVa 12100 - Printer Queue.cpp ├── UVa 156 - Anagrams.cpp ├── UVa 1592 - Database.py └── UVa 540 - Team Queue.cpp ├── UVa 10474 Where is the Marble?.cpp └── readme.md /Adhoc/UVa 10954 - Add All.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | typedef pair ii; 6 | 7 | int main() { 8 | int n; while(scanf("%d", &n) && n) { 9 | ll ans = 0, x, y; 10 | priority_queue, greater > q; 11 | for(int i = 0; i < n; ++i) scanf("%d", &x), q.push(x); 12 | while(q.size() > 1){ 13 | x = q.top(); q.pop(); 14 | y = q.top(); q.pop(); 15 | ans += (x += y); 16 | if(q.empty()) break; 17 | q.push(x); 18 | } 19 | printf("%lld\n", ans); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Bruteforce/12325 - Zombies Treasure Chest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long n, s1, v1, s2, v2; 5 | 6 | int main() 7 | { 8 | int t; 9 | scanf("%d", &t); 10 | 11 | for(int tc = 1; tc <= t; tc++) 12 | { 13 | scanf("%lld %lld %lld %lld %lld", &n, &s1, &v1, &s2, &v2); 14 | 15 | if(s2 > s1){ 16 | swap(s1, s2); 17 | swap(v1, v2); 18 | } 19 | 20 | long long ans = 0; 21 | 22 | if(s1 > sqrt(n)){ 23 | for(int i = 0; i*s1 <= n; i++) 24 | ans = max(ans, (n - s1*i)/s2 * v2 + v1 * i); 25 | } 26 | 27 | else{ 28 | if(v1*s2 < v2*s1) 29 | swap(s1, s2), swap(v1, v2); 30 | 31 | for(int i = 0; i <= s1 && n - s2*i >= 0; i++) 32 | ans = max(ans, (n - i * s2)/s1 * v1 + i * v2); 33 | } 34 | 35 | printf("Case #%d: %lld\n", tc, ans); 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Bruteforce/UVa 725 - Division.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int N; 5 | bool flag = false; 6 | 7 | int main() { 8 | while(cin >> N && N) { 9 | if(flag) puts(""); flag = true; 10 | bool found = false; 11 | for(int fghij = 1234; fghij <= 98765 / N; fghij++) { 12 | int used = (fghij < 10000), tmp; 13 | int abcde = fghij*N; 14 | tmp = abcde; 15 | while(tmp > 0) { 16 | used |= 1 << (tmp % 10); 17 | tmp /= 10; 18 | } 19 | tmp = fghij; 20 | while(tmp > 0) { 21 | used |= 1 << (tmp % 10); 22 | tmp /= 10; 23 | } 24 | if(used == (1 << 10) - 1) { 25 | found = true; 26 | printf("%0.5d / %0.5d = %d\n", abcde, fghij, N); 27 | } 28 | } 29 | if(!found) printf("There are no solutions for %d.\n", N); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guideline 2 | 3 | 1. Use naming format ``` - ```. For example - 4 | 5 | **_UVa 202 - Repeating Decimals v2.cpp_** 6 | 7 | Here include `````` only for >1, i. e. mentioning v1 is not necessary. 8 | 9 | 2. Put code for exercise problems in the ```Exercises``` folder of the chapter. 10 | 11 | 3. For alternate solutions, put the solving technique in a comment at the top of the file. Like this: 12 | ```cpp 13 | /** 14 | * Problem: Timus 1005 - Stone Pile 15 | * Approach: bitmask with memorization 16 | **/ 17 | ``` 18 | In file name, put v1, v2 etc. 19 | 4. See the existing files for more formatting guideline. 20 | -------------------------------------------------------------------------------- /Data Structure/UVa 11988 - Broken Keyboard v2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // We keep a long string 'res', this will store everything inserted to end. 5 | // When we go to beginning, we satar another small string, and grow that untill 6 | // we go to end. Store these pieces of string and at last print them first. Then 7 | // Print the long string. 8 | 9 | int main() { 10 | string str; 11 | while(getline(cin, str)) { 12 | string res = ""; bool go = 0; 13 | string tmp = ""; 14 | vector v; 15 | for(int i = 0; i < str.size(); i++) { 16 | if(str[i] == '[') { 17 | if(go == 1) 18 | v.push_back(tmp), tmp = ""; 19 | go = 1; 20 | continue; 21 | } 22 | if(str[i] == ']') { 23 | v.push_back(tmp); 24 | tmp = ""; go = 0; 25 | continue; 26 | } 27 | if(go) tmp += str[i]; 28 | else res += str[i]; 29 | } v.push_back(tmp); 30 | for(int i = v.size() - 1; i >= 0; i--) 31 | cout << v[i]; 32 | cout << res << endl; 33 | } 34 | } -------------------------------------------------------------------------------- /Data Structure/UVa 11988 - Broken Keyboard.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | char line[100100]; 5 | while(scanf("%s",line) != EOF) { 6 | list l; 7 | list::iterator it = l.begin(); 8 | int len = strlen(line); 9 | for(int i = 0; i < len; i++) { 10 | if(line[i] == '[') it = l.begin(); 11 | else if (line[i] == ']') it = l.end(); 12 | else l.insert(it,line[i]); 13 | } 14 | for(it = l.begin(); it!=l.end(); it++) 15 | printf("%c",*it); 16 | puts(""); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Data Structure/UVa 673 Parantheses Balance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void solve(string ex){ 6 | 7 | /* if(ex.size()%2){ 8 | cout<<"No\n"; 9 | return; 10 | }*/ 11 | 12 | stack s; 13 | for (char c : ex) { 14 | // cout<>tc; 43 | // cin>>s; 44 | getline(cin,s); 45 | while(tc--){ 46 | //cout< 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | typedef pair ii; 6 | 7 | struct point { 8 | double x, y; 9 | double dist(point &p) { 10 | return hypot(x - p.x, y - p.y); 11 | } 12 | } p[1111]; 13 | 14 | double dp[1010][1010]; 15 | bool vis[1010][1010]; 16 | int n; 17 | 18 | double call(int i, int j) { 19 | if(i == n-1 && j == n-1) return 0; 20 | if(j == n - 1) 21 | return call(i + 1, j) + p[i].dist(p[i + 1]); 22 | if(i == n - 1) 23 | return call(i, j + 1) + p[j].dist(p[j + 1]); 24 | if(vis[i][j]) return dp[i][j]; 25 | 26 | int k = max(i, j) + 1; 27 | vis[i][j] = 1; 28 | return dp[i][j] = min(call(k, j) + p[i].dist(p[k]), 29 | call(i, k) + p[j].dist(p[k])); 30 | 31 | } 32 | int main(int argc, char const *argv[]) { 33 | while(scanf("%d", &n) == 1) { 34 | for(int i = 0; i < n; i++){ 35 | scanf("%lf %lf", &p[i].x, &p[i].y); 36 | } 37 | memset(vis, 0, sizeof vis); 38 | printf("%.2f\n", call(0, 0)); 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /Dynamic Programming/UVa 437 - The Tower of Babylon.cpp: -------------------------------------------------------------------------------- 1 | //Bismillahir Rahmanir Rahim 2 | #include 3 | using namespace std; 4 | typedef long long ll; 5 | typedef pair ii; 6 | 7 | struct box { 8 | int x,y,z; 9 | bool operator < ( const box &p) const { 10 | return pair{{x,y},{z}} < pair{{p.x,p.y},p.z}; 11 | } 12 | }; 13 | 14 | ll dp[111111]; 15 | int main(int argc, char const *argv[]) { 16 | int n, co = 0; 17 | while(cin >> n && n) { 18 | vector v; 19 | for(int i = 0; i < n; i++) { 20 | vector tmp(3); 21 | cin >> tmp[0] >> tmp[1] >> tmp[2]; 22 | sort(tmp.begin(), tmp.end()); 23 | do{ 24 | v.push_back({tmp[0], tmp[1], tmp[2]}); 25 | } while(next_permutation(tmp.begin(), tmp.end())); 26 | } sort(v.begin(), v.end()); 27 | n = v.size(); ll ans = 0; 28 | for(int i = 0; i < n; i++) { 29 | dp[i] = v[i].z; 30 | for(int j = 0; j < i; j++) 31 | if((v[i].x > v[j].x && v[i].y > v[j].y) || 32 | (v[i].y > v[j].x && v[i].x > v[j].y)) 33 | dp[i] = max(dp[i], dp[j] + v[i].z); 34 | ans = max(ans, dp[i]); 35 | } cout << "Case " << ++co << ": maximum height = " << ans << endl; 36 | } 37 | } -------------------------------------------------------------------------------- /Easy Problems/Exercises/Timus 1025 - Democracy in Danger.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: Timus 1025 - Democracy in Danger 3 | Author: sjsakib 4 | """ 5 | 6 | n = int(input()) 7 | 8 | print(sum(sorted(map(lambda x: int(x)//2 + 1, input().split()))[:n//2 + 1])) 9 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/Timus 1079 - Maximum.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: Timus 1079 - Maximum 3 | * Author: sjsakib 4 | * 5 | **/ 6 | #include 7 | 8 | #define MAX 99999 9 | 10 | using namespace std; 11 | 12 | int arr[MAX+5]; 13 | 14 | void cal() { 15 | arr[0] = 1; 16 | arr[1] = 1; 17 | for (int i = 2; i <= MAX; i++) { 18 | if(i&1) arr[i] = arr[i/2] + arr[i/2 + 1]; 19 | else arr[i] = arr[i/2]; 20 | } 21 | for (int i = 2; i <= MAX; i++) arr[i] = max(arr[i], arr[i-1]); 22 | } 23 | 24 | int main() { 25 | cal(); 26 | int n; 27 | while(scanf("%d", &n) && n != 0) printf("%d\n", arr[n]); 28 | } -------------------------------------------------------------------------------- /Easy Problems/Exercises/Timus 1149 - Sinus Dances.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: Timus 1149 - Sinus Dances 3 | * Author: sjsakib 4 | * 5 | **/ 6 | #include 7 | 8 | #define MAX 100 9 | 10 | using namespace std; 11 | 12 | string a[MAX+5]; 13 | 14 | string get_a(int n) { 15 | string ret = "sin(" + to_string(n) + ")"; 16 | while(--n) { 17 | ret = "sin(" + to_string(n) + (n&1?"-":"+") + ret + ")"; 18 | } 19 | return ret; 20 | } 21 | 22 | string get_s(int n) { 23 | string ret = "sin(1)+" + to_string(n); 24 | for (int i = 2,j = n-1; i <= n; i++,j--) { 25 | ret = "(" + ret + ")" + get_a(i) + "+" + to_string(j); 26 | } 27 | return ret; 28 | } 29 | 30 | int main() { 31 | int n; 32 | scanf("%d", &n); 33 | printf("%s\n", get_s(n).c_str()); 34 | } -------------------------------------------------------------------------------- /Easy Problems/Exercises/Timus 1313 - Some Words about Sports.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: Timus 1313 - Some Words about Sports 3 | Author: sjsakib 4 | """ 5 | from sys import stdin 6 | 7 | n = int(input()) 8 | 9 | arr = [] 10 | 11 | for line in stdin: 12 | arr.append(line.split()) 13 | 14 | for i in range(n*2): 15 | j = max(i-n+1, 0) 16 | i = min(i, n-1) 17 | while i >= 0 and j < n: 18 | end = '\n' if (i == n-1 and j == n-1) else ' ' 19 | print(arr[i][j], end=end) 20 | i -= 1 21 | j += 1 22 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/Timus 1319 - Hotel.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: Timus 1319 - Hotel 3 | Author: sjsakib 4 | """ 5 | n = int(input()) 6 | 7 | table = [[0]*n for j in range(n)] 8 | 9 | k = 1 10 | for i in range(n-1, -n-1, -1): 11 | j = max(i, 0) 12 | i = max(0, i*-1) 13 | while i < n and j < n: 14 | table[i][j] = str(k) 15 | k += 1 16 | i += 1 17 | j += 1 18 | 19 | print('\n'.join([' '.join(line) for line in table])) 20 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 10340 - All in All.cpp: -------------------------------------------------------------------------------- 1 | // Author: Jony Bepary 2 | // 2022 3 | // @jbeary 4 | // http://jony-blog.github.io/ 5 | 6 | #include 7 | using namespace std; 8 | typedef long long ll; 9 | typedef unsigned long long ull; 10 | 11 | int main() 12 | { 13 | string t, p; 14 | while (cin >> t >> p) 15 | { 16 | 17 | int i = 0, j = 0; 18 | while (i < p.size() && j < t.size()) 19 | { 20 | if (t[j] == p[i]) 21 | { 22 | i++; 23 | j++; 24 | } 25 | else 26 | { 27 | i++; 28 | } 29 | } 30 | // cout << j << " : " << t.size(); 31 | if (j == t.size()) 32 | cout << "Yes" << endl; 33 | else 34 | cout << "No" << endl; 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 12412 - A Typical Homework.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 12412 A Typical Homework 3 | Author: sjsakib 4 | """ 5 | from collections import OrderedDict 6 | 7 | 8 | class Student: 9 | 10 | def __init__(self, sid, cid, name, ch, mat, en, pro): 11 | self.sid = sid 12 | self.cid = cid 13 | self.name = name 14 | self.ch = ch 15 | self.mat = mat 16 | self.en = en 17 | self.pro = pro 18 | 19 | self.total = ch + mat + en + pro 20 | self.average = "{:.2f}".format(self.total/4 + 1e-5) 21 | self.passed = (ch >= 60) + (mat >= 60) + (en >= 60) + (pro >= 60) 22 | self.rank = 0 23 | 24 | def __str__(self): 25 | return "{} {} {} {} {} {} {} {} {}".format(self.rank, self.sid, self.cid, self.ch, self.mat, 26 | self.en, self.pro, self.total, self.average) 27 | 28 | 29 | db = OrderedDict() 30 | 31 | 32 | def printMainMenu(): 33 | print("Welcome to Student Performance Management System (SPMS).\n") 34 | print("1 - Add") 35 | print("2 - Remove") 36 | print("3 - Query") 37 | print("4 - Show ranking") 38 | print("5 - Show Statistics") 39 | print("0 - Exit\n") 40 | 41 | 42 | def update_index(): 43 | all = sorted(db.values(), key=lambda s: s.total, reverse=True) 44 | rank = 1 45 | for i, s in enumerate(all): 46 | if i and s.total < all[i-1].total: 47 | s.rank = i + 1 48 | rank = i + 1 49 | else: 50 | s.rank = rank 51 | 52 | 53 | def add(): 54 | while True: 55 | print("Please enter the SID, CID, name and four scores. Enter 0 to finish.") 56 | inp = input().strip() 57 | if inp is '0': 58 | break 59 | inp = inp.split() 60 | sid, cid, name = inp[:3] 61 | ch, mat, en, pro = map(int, inp[3:]) 62 | if db.get(sid) is None: 63 | db[sid] = Student(sid, cid, name, ch, mat, en, pro) 64 | else: 65 | print("Duplicated SID.") 66 | update_index() 67 | 68 | 69 | def remove(): 70 | while True: 71 | print("Please enter SID or name. Enter 0 to finish.") 72 | inp = input().strip() 73 | if inp == '0': 74 | break 75 | count = 0 76 | if db.get(inp) is not None: 77 | del db[inp] 78 | count = 1 79 | for s in list(db): 80 | if db[s].name == inp: 81 | del db[s] 82 | count += 1 83 | print("{} student(s) removed.".format(count)) 84 | update_index() 85 | 86 | 87 | def query(): 88 | while True: 89 | print("Please enter SID or name. Enter 0 to finish.") 90 | inp = input().strip() 91 | if inp == '0': 92 | break 93 | if db.get(inp) is not None: 94 | print(db[inp]) 95 | for s in db.values(): 96 | if s.name == inp: 97 | print(s) 98 | 99 | 100 | def show_statistics(): 101 | ov = [0]*5 102 | ch = [0]*3 103 | mat = [0]*3 104 | en = [0]*3 105 | pro = [0]*3 106 | count = 0 107 | print("Please enter class ID, 0 for the whole statistics.") 108 | cid = input().strip() 109 | for s in db.values(): 110 | if (int(cid) and s.cid == cid) or not int(cid): 111 | ov[s.passed] += 1 112 | count += 1 113 | 114 | mat[0] += s.mat 115 | mat[1] += s.mat >= 60 116 | mat[2] += s.mat < 60 117 | 118 | pro[0] += s.pro 119 | pro[1] += s.pro >= 60 120 | pro[2] += s.pro < 60 121 | 122 | ch[0] += s.ch 123 | ch[1] += s.ch >= 60 124 | ch[2] += s.ch < 60 125 | 126 | en[0] += s.en 127 | en[1] += s.en >= 60 128 | en[2] += s.en < 60 129 | if count != 0: 130 | mat[0] = "{:.2f}".format(mat[0]/count + 1e-5) 131 | ch[0] = "{:.2f}".format(ch[0]/count + 1e-5) 132 | en[0] = "{:.2f}".format(en[0]/count + 1e-5) 133 | pro[0] = "{:.2f}".format(pro[0]/count + 1e-5) 134 | else: 135 | mat[0] = "-nan" 136 | ch[0] = "-nan" 137 | en[0] = "-nan" 138 | pro[0] = "-nan" 139 | 140 | print("Chinese") 141 | print("Average Score:", ch[0]) 142 | print("Number of passed students:", ch[1]) 143 | print("Number of failed students:", ch[2]) 144 | print("") 145 | 146 | print("Mathematics") 147 | print("Average Score:", mat[0]) 148 | print("Number of passed students:", mat[1]) 149 | print("Number of failed students:", mat[2]) 150 | print("") 151 | 152 | print("English") 153 | print("Average Score:", en[0]) 154 | print("Number of passed students:", en[1]) 155 | print("Number of failed students:", en[2]) 156 | print("") 157 | 158 | print("Programming") 159 | print("Average Score:", pro[0]) 160 | print("Number of passed students:", pro[1]) 161 | print("Number of failed students:", pro[2]) 162 | print("") 163 | 164 | print("Overall:") 165 | print("Number of students who passed all subjects:", ov[4]) 166 | print("Number of students who passed 3 or more subjects:", sum(ov[3:])) 167 | print("Number of students who passed 2 or more subjects:", sum(ov[2:])) 168 | print("Number of students who passed 1 or more subjects:", sum(ov[1:])) 169 | print("Number of students who failed all subjects:", ov[0]) 170 | print("") 171 | 172 | 173 | while True: 174 | printMainMenu() 175 | cmd = int(input()) 176 | if cmd == 0: 177 | break 178 | elif cmd == 1: 179 | add() 180 | elif cmd == 2: 181 | remove() 182 | elif cmd == 3: 183 | query() 184 | elif cmd == 4: 185 | print("Showing the ranklist hurts students' self-esteem. Don't do that.") 186 | elif cmd == 5: 187 | show_statistics() 188 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 1583 - Digit Generator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 1583 Digit Generator 3 | Author: sjsakib 4 | 5 | We go through all numbers from 0 to MAX and calculate it's digit_sum. Then we save the number as one of the 6 | digit_sums generator. Then for all input we return the minimum of it's saved generators 7 | 8 | A generator can never be greater than the number itself. So if we get a digit_sum greater than 9 | MAX, we don't need to save it 10 | """ 11 | 12 | from sys import stdin 13 | 14 | MAX = 100010 15 | 16 | 17 | def digit_sum(n): 18 | ret = n 19 | while n: 20 | ret += n % 10 21 | n //= 10 22 | return ret 23 | 24 | 25 | input() 26 | ans = [[] for i in range(MAX)] 27 | for i in range(MAX): 28 | try: 29 | ans[digit_sum(i)].append(i) 30 | except IndexError: # digit_sum(i) is greater than MAX 31 | pass 32 | 33 | for line in stdin: 34 | x = int(line) 35 | try: 36 | print(min(ans[x])) 37 | except ValueError: 38 | print(0) 39 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 1584 - Circular Sequence.cpp: -------------------------------------------------------------------------------- 1 | // Author: Jony Bepary 2 | // 2022 3 | // @jbeary 4 | // http://jony-blog.github.io/ 5 | 6 | #include 7 | using namespace std; 8 | typedef long long ll; 9 | typedef unsigned long long ull; 10 | queue q; 11 | 12 | // প্রতিবার স্ট্রিং থেকে লেক্সোগ্রাফিক্যালি ছোট বর্নের ইন্ডেক্স গুলা 13 | // Queue তে পুশ করে 14 | void the_smallest(string &str) 15 | { 16 | q = {}; 17 | int small = 0; 18 | for (int i = 1; i < str.size(); i++) 19 | { 20 | if (str[small] > str[i]) 21 | { 22 | small = i; 23 | } 24 | } 25 | for (int i = 0; i < str.size(); i++) 26 | { 27 | 28 | if (str[small] == str[i]) 29 | { 30 | q.push(i); 31 | } 32 | } 33 | // cout << small << endl; 34 | } 35 | 36 | // the_smallest() ফাংশন থেকে জেনারেট করা একই রকম smallest letter এর ইন্ডেক্স গুলার queue 37 | // থেকে যেই কয়টা ইন্ডেক্স আছে তার প্রতিটি সাবসিকুয়েন্ট স্ট্রিং গুলা চেক ও এলিমিনেট করে লেক্সোগ্রাফিক্যালি 38 | // সবচেয়ে ছোট সাবসিকুয়েন্ট স্ট্রিং এর স্টার্টিং ইন্ডেক্স রিটার্ন করে 39 | 40 | int picking_worthy(string &str) 41 | { 42 | 43 | int s = q.front(), sz = str.size(), sx, qx; 44 | q.pop(); 45 | int i = 1; 46 | 47 | // if all the subsequence string are same return S/0 48 | // eg: AAAA, BBBB, A, B 49 | if ((q.size() + 1) == str.size()) 50 | { 51 | return s; 52 | } 53 | // if not তাহলে খোজাখুজি শুরু 54 | while (!q.empty()) 55 | { 56 | // নিচের sx qx আসলে ফরমুলা দিয়ে ইন্ডেক্স নাম্বার জেনারেট করতেসে 57 | // কারন array এর মাথা আর পাছা কানেক্টেড 58 | sx = (s + i) - floor((s + i) / sz) * sz; 59 | qx = (q.front() + i) - floor((q.front() + i) / sz) * sz; 60 | 61 | if (str[sx] == str[qx]) // যদি সমান তাহলে পরের letter চেক করবে 62 | { 63 | i++; 64 | } 65 | else if (str[sx] < str[qx]) // যদি বড় হয় তাহলে স্ট্রিং টা বাদ দিয়া দেবে 66 | { 67 | q.pop(); 68 | i = 0; 69 | } 70 | // যদি ছোট হয় তাহলে চেকিং "সাবসিকুয়েন্ট স্ট্রিং এর স্টার্টিং ইন্ডেক্স" তাহলে 71 | // current smallest "সাবসিকুয়েন্ট স্ট্রিং এর স্টার্টিং ইন্ডেক্স" টার সাথে swap করবে 72 | // ও কিউ থেকে নেক্সট "সাবসিকুয়েন্ট স্ট্রিং এর স্টার্টিং ইন্ডেক্স" pick করবে 73 | else if (str[sx] > str[qx]) 74 | { 75 | s = q.front(); // swap 76 | q.pop(); // pick 77 | i = 0; 78 | } 79 | } 80 | return s; 81 | } 82 | int main() 83 | { 84 | string str; 85 | ll re, t; 86 | cin >> t; 87 | while (t--) 88 | { 89 | cin >> str; 90 | //লেক্সোগ্রাফিক্যালি ছোট বর্নের ইন্ডেক্স গুলা বাছাই করে নিচ্ছে 91 | the_smallest(str); 92 | //বাছাই করা ইন্ডেক্সগুলো একটা আরেক্টার সাথে কম্পেয়ার 93 | //তুলোনা মুলকলেক্সোগ্রাফিক্যালি ছোট word এর ইন্ডেক্স গ্রিডিলি সিলেক্ট করে রিটার্ন করবে 94 | re = picking_worthy(str); 95 | // cout << re << " : "; 96 | if (re == 0) 97 | { 98 | cout << str << endl; 99 | continue; 100 | } 101 | 102 | // রিটার্নকৃত সবচেয়ে ছোট সাবসিকুয়েন্ট স্ট্রিং এর স্টার্টিং ইন্ডেক্স 103 | // ধরে পুরো স্ট্রিং ওই অর্ডার এ প্রিন্ট করতাসে 104 | for (int i = re; 1; i++) 105 | { 106 | if (i == re - 1) 107 | { 108 | cout << str[i]; 109 | break; 110 | } 111 | else if (i == str.size()) 112 | { 113 | i = -1; 114 | continue; 115 | } 116 | cout << str[i]; 117 | } 118 | cout << endl; 119 | } 120 | return 0; 121 | } 122 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 1589 - Xiangqi.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 1589 Xiangqi 3 | Author: sjsakib 4 | 5 | We mark all the positions attacked by the given pieces and then check if it's a checkmate 6 | """ 7 | dr = [0, 0, 1, -1] 8 | dc = [1, -1, 0, 0] 9 | 10 | 11 | def inside(r, c): 12 | return r > 0 and r <= 10 and c > 0 and c <= 9 13 | 14 | 15 | def palace(r, c, pos): 16 | if pos == 1: 17 | return r > 0 and r < 4 and c > 3 and c < 7 18 | return r < 11 and r > 7 and c > 3 and c < 7 19 | 20 | 21 | def blank(r, c): 22 | return board[r][c][0] == 'X' or board[r][c][0] == '-' 23 | 24 | 25 | def general(r, c): 26 | for ri, ci in zip(dr, dc): 27 | for j in range(1, 11): 28 | rr = r + ri*j 29 | cc = c + ci*j 30 | if not inside(rr, cc): 31 | break 32 | elif not blank(rr, cc): 33 | board[rr][cc] += 'X' 34 | break 35 | else: 36 | board[rr][cc] = 'X' 37 | 38 | 39 | def canon(r, c): 40 | for ri, ci in zip(dr, dc): 41 | found = 0 42 | for j in range(1, 11): 43 | rr = r + ri*j 44 | cc = c + ci*j 45 | if not inside(rr, cc): 46 | break 47 | elif (not blank(rr, cc) and found == 1): 48 | board[rr][cc] += 'X' 49 | break 50 | elif (not blank(rr, cc) and found == 0): 51 | found = 1 52 | elif found == 1: 53 | board[rr][cc] = 'X' 54 | 55 | 56 | def horse(r, c): 57 | for ri, ci in zip(dr, dc): 58 | rr, cc = r + ri, c + ci 59 | if blank(rr, cc): 60 | rr += ri 61 | cc += ci 62 | if not inside(rr, cc): 63 | break 64 | rrr, ccc = rr + ci, cc + ri 65 | if inside(rrr, ccc) and blank(rrr, ccc): 66 | board[rrr][ccc] = 'X' 67 | elif inside(rrr, ccc): 68 | board[rrr][ccc] += 'X' 69 | rrr, ccc = rr - ci, cc - ri 70 | if inside(rrr, ccc) and blank(rrr, ccc): 71 | board[rrr][ccc] = 'X' 72 | elif inside(rrr, ccc): 73 | board[rrr][ccc] += 'X' 74 | 75 | 76 | def checkmate(r, c): 77 | if r > 5: 78 | pos = -1 79 | else: 80 | pos = 1 81 | for ri, ci in zip(dr, dc): 82 | rr, cc = r + ri, c + ci 83 | if inside(rr, cc) and palace(rr, cc, pos) and board[rr][cc][-1] != 'X': 84 | return False 85 | for i in range(1, 10): 86 | rr = r + (i*pos) 87 | if inside(rr, c) and board[rr][c][0] == 'G': 88 | return False 89 | if inside(rr, c) and not blank(rr, c): 90 | break 91 | return True 92 | 93 | 94 | while True: 95 | board = [['-']*10 for i in range(11)] 96 | n, gr, gc = map(int, input().split()) 97 | if n == 0: 98 | break 99 | pcs = [] 100 | for i in range(n): 101 | pcs.append(input().split()) 102 | r = int(pcs[-1][1]) 103 | c = int(pcs[-1][2]) 104 | board[r][c] = pcs[-1][0] 105 | pcs[-1][1] = r 106 | pcs[-1][2] = c 107 | for p in pcs: 108 | if p[0] == 'G': 109 | general(*p[1:]) 110 | elif p[0] == 'R': 111 | general(*p[1:]) 112 | elif p[0] == 'H': 113 | horse(*p[1:]) 114 | else: 115 | canon(*p[1:]) 116 | print("YES" if checkmate(gr, gc) else "NO") 117 | input() 118 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 1590 - IP Networks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 1590 IP networks 3 | Author: sjsakib 4 | 5 | We need to find the bit until which all the IP addresses are same. We'll then take a number with all bits on (-1) 6 | and turn off all the bits after that bit. That's our mask. And the network address is mask & any of 7 | the addresses 8 | """ 9 | from math import log2 10 | 11 | 12 | def to_decimal(ip): 13 | return sum([int(b) << ((3-i)*8) for i, b in enumerate(ip.split('.'))]) 14 | 15 | 16 | def to_ip(n): 17 | return '.'.join([str(n >> (i*8) & 255) for i in range(3, -1, -1)]) 18 | 19 | 20 | while True: 21 | try: 22 | n = int(input()) 23 | except EOFError: 24 | break 25 | 26 | first = to_decimal(input()) 27 | diff = 0 28 | 29 | for i in range(n-1): 30 | c = to_decimal(input()) 31 | diff |= (first ^ c) 32 | try: 33 | mask = ((1 << int(log2(diff)+1)) - 1) ^ -1 34 | except ValueError: 35 | mask = ~diff 36 | print(to_ip(first & mask)) 37 | print(to_ip(mask)) 38 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 1591 - Data Mining.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 1591 Data Mining 3 | Author: sjsakib 4 | 5 | We will go through all possible combinations of A and B and generate Qofs for maximum Pofs ( (N-1)*Sp ) 6 | and then we'll see which of them is the smallest, but greater than or equal (N-1)*Sq 7 | """ 8 | from sys import stdin 9 | 10 | for line in stdin: 11 | n, sp, sq = map(int, line.split()) 12 | minK = 1e10 13 | a = 0 14 | b = 0 15 | for i in range(35): 16 | for j in range(35): 17 | pofs = (n-1)*sp 18 | curK = (pofs + (pofs << i)) >> j 19 | if curK >= sq*(n-1) and curK < minK: 20 | minK = curK 21 | a = i 22 | b = j 23 | print(minK+sq, a, b) 24 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 201 - Squares.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 201 Squares 3 | Author: sjsakib 4 | """ 5 | case = 1 6 | 7 | while True: 8 | try: 9 | n = int(input()) 10 | m = int(input()) 11 | except EOFError: 12 | break 13 | except ValueError: 14 | break 15 | lines = [[[False, False] for i in range(n)] for j in range(n)] 16 | 17 | for k in range(m): 18 | d, i, j = input().split() 19 | i = int(i) - 1 20 | j = int(j) - 1 21 | if d == 'H': 22 | lines[i][j][0] = True 23 | else: 24 | lines[j][i][1] = True 25 | 26 | ans = [0]*n 27 | 28 | for i in range(n): 29 | for j in range(n): 30 | for k in range(1, n-max(i, j)): 31 | for x in range(k): 32 | if not (lines[i][j+x][0] and lines[i+k][j+x][0] and lines[i+x][j][1] and lines[i+x][j+k][1]): 33 | break 34 | else: 35 | ans[k-1] += 1 36 | if case != 1: 37 | print("\n**********************************\n") 38 | 39 | print("Problem #", case, '\n', sep='') 40 | 41 | if sum(ans) == 0: 42 | print("No completed squares can be found.") 43 | else: 44 | for i, v in enumerate(ans): 45 | if v: 46 | print(v, "square (s) of size", i+1) 47 | 48 | case += 1 49 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 213 - Message Decoding.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 213 Message Decoding 3 | Author: sjsakib 4 | """ 5 | k_count = [2*(2**i - 1) - i for i in range(8)] # k_count[i] holds how many keys are there of size i or less than i 6 | 7 | 8 | def extend_line(line, cur, k): 9 | while cur + k > len(line): 10 | line += input() 11 | return line[cur:], 0 12 | 13 | 14 | while True: 15 | try: 16 | header = input() 17 | except EOFError: 18 | break 19 | 20 | line = '' 21 | cur = 0 22 | message = '' 23 | 24 | while True: 25 | line, cur = extend_line(line, cur, 3) 26 | k = int(line[cur:cur+3], 2) 27 | if k == 0: 28 | break 29 | cur += 3 30 | while True: 31 | line, cur = extend_line(line, cur, k) 32 | key = int(line[cur:cur+k], 2) 33 | cur += k 34 | if key == 2**k - 1: 35 | break 36 | else: 37 | message += header[k_count[k-1] + key] 38 | print(message) 39 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 220 - Othello.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 220 - Othello 3 | * Author: sjsakib 4 | * 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int t; 11 | char board[9][9]; 12 | char cp; 13 | int dx[] = {1,1,0,-1,-1,-1,0,1}; 14 | int dy[] = {0,1,1,1,0,-1,-1,-1}; 15 | 16 | void read() { 17 | for (int i = 0; i < 8; i++) { 18 | scanf("%s\n", board[i]); 19 | } 20 | } 21 | 22 | bool inside(int r, int c) { 23 | return r >=0 && r < 8 && c >= 0 && c < 8; 24 | } 25 | 26 | void show() { 27 | for (int i = 0; i < 8; i++) { 28 | printf("%s\n", board[i]); 29 | } 30 | } 31 | 32 | void toggle_p() { 33 | if(cp == 'B') cp = 'W'; 34 | else cp = 'B'; 35 | } 36 | 37 | bool check_line(int r, int c, int dx, int dy) { 38 | int k = 1; 39 | bool found = 0; // found opponent color 40 | while(1) { 41 | int rr = r + dx*k; 42 | int cc = c + dy*k; 43 | char c = board[rr][cc]; 44 | if(!inside(rr,cc) || c == '-' || (!found && c == cp)) return 0; 45 | else if(c != cp) found = 1; 46 | else if(c == cp && found) return 1; 47 | 48 | k++; 49 | } 50 | } 51 | 52 | void fill_line(int r, int c, int dx, int dy) { 53 | int k = 1; 54 | while(1) { 55 | int rr = r + dx*k; 56 | int cc = c + dy*k; 57 | if(board[rr][cc] == cp) return; 58 | board[rr][cc] = cp; 59 | k++; 60 | } 61 | } 62 | 63 | bool valid(int r, int c) { 64 | if(board[r][c] != '-') return 0; 65 | for (int i = 0; i < 8; i++) { 66 | if (check_line(r, c, dx[i], dy[i])) return 1; 67 | } 68 | return 0; 69 | } 70 | 71 | void lst() { 72 | bool found = 0; // found valid move 73 | for (int i = 0; i < 8; i++) { 74 | for (int j = 0; j < 8; j++) { 75 | if(valid(i,j)) { 76 | if(found) printf(" "); 77 | printf("(%d,%d)", i+1, j+1); 78 | found = 1; 79 | } 80 | } 81 | } 82 | if(!found) { 83 | printf("No legal move.\n"); 84 | } 85 | else printf("\n"); 86 | } 87 | 88 | void move() { 89 | char r,c; 90 | scanf("%c%c\n", &r, &c); 91 | r = r - '0' - 1; 92 | c = c - '0' - 1; 93 | if(!valid(r,c)) toggle_p(); 94 | board[(int) r][(int) c] = cp; 95 | for (int i = 0; i < 8; i++) { 96 | if(check_line(r, c, dx[i], dy[i])) { 97 | fill_line(r, c, dx[i], dy[i]); 98 | } 99 | } 100 | int b = 0,w = 0; 101 | for (int i = 0; i < 8; i++) { 102 | for (int j = 0; j < 8; j++) { 103 | if(board[i][j] == 'B') b++; 104 | else if(board[i][j] == 'W') w++; 105 | } 106 | } 107 | printf("Black - %2d White - %2d\n", b, w); 108 | toggle_p(); 109 | } 110 | 111 | int main() { 112 | scanf("%d\n", &t); 113 | for (int i = 0; i < t; i++) { 114 | if(i != 0) printf("\n"); 115 | read(); 116 | char c; 117 | scanf("%c\n", &cp); 118 | while(1) { 119 | scanf("%c\n", &c); 120 | if( c == 'Q' ) { 121 | show(); 122 | break; 123 | } 124 | else if( c == 'L') lst(); 125 | else move(); 126 | } 127 | } 128 | return 0; 129 | } -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 232 - Corssword Answers.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 232 - Crossword Answers 3 | Author: sjsakib 4 | """ 5 | case = 1 6 | while True: 7 | try: 8 | r, c = map(int, input().split()) 9 | except ValueError: 10 | break 11 | 12 | board = [] 13 | board.append('*'*(c+2)) 14 | for i in range(r): 15 | board.append('*'+input()+'*') 16 | board.append('*'*(c+2)) 17 | 18 | across = [] 19 | down = [] 20 | 21 | cnt = 0 22 | for i in range(1, r+1): 23 | for j in range(1, c+1): 24 | if (board[i][j-1] == '*' or board[i-1][j] == '*') and board[i][j] != '*': 25 | cnt += 1 26 | else: 27 | continue 28 | w = '' 29 | if board[i][j-1] == '*': 30 | k = j 31 | while(board[i][k] != '*'): 32 | w += board[i][k] 33 | k += 1 34 | across.append('{:3}.{}'.format(cnt, w)) 35 | w = '' 36 | if board[i-1][j] == '*': 37 | k = i 38 | while(board[k][j] != '*'): 39 | w += board[k][j] 40 | k += 1 41 | down.append('{:3}.{}'.format(cnt, w)) 42 | if case != 1: 43 | print('') 44 | print("puzzle #{}:".format(case)) 45 | print("Across") 46 | if len(across): 47 | print('\n'.join(across)) 48 | print("Down") 49 | if len(down): 50 | print('\n'.join(down)) 51 | case += 1 52 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 272 - TEX Quotes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 272 - TEX Quotes 3 | Author: sjsakib 4 | """ 5 | from sys import stdin 6 | 7 | text = stdin.read().split('"') 8 | new_text = '' 9 | 10 | for i, part in enumerate(text): 11 | if(i != len(text)-1): 12 | new_text += part + ("''" if i & 1 else "``") 13 | else: 14 | new_text += part 15 | 16 | print(new_text, end='') 17 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 340 - Master-Mind Hints.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 340 - Master-Mind Hints 3 | * Author: sjsakib 4 | * 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | void solve(int n) { 11 | int arr[n]; 12 | 13 | for (int i = 0; i < n; i++) { 14 | scanf("%d", &arr[i]); 15 | } 16 | 17 | while (1) { 18 | int g; 19 | map mp; 20 | bool strong[n]; 21 | memset(strong, 0, sizeof(strong[0])*n); 22 | int s=0,w=0; 23 | for (int i = 0; i < n; i++) { 24 | scanf("%d", &g); 25 | if(g == arr[i]) { 26 | s += 1; 27 | strong[i]++; 28 | } 29 | else mp[g]++; 30 | } 31 | if (g == 0) return; 32 | for (int i = 0; i < n; i++) { 33 | if(!strong[i] && mp.find(arr[i]) != mp.end() && mp[arr[i]]) { 34 | mp[arr[i]]--; 35 | w++; 36 | } 37 | } 38 | printf(" (%d,%d)\n", s, w); 39 | } 40 | } 41 | 42 | int main() { 43 | int t=1,n; 44 | while(scanf("%d", &n) && n != 0) { 45 | printf("Game %d:\n", t++); 46 | solve(n); 47 | } 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 508 - Morese Mismatches.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 508 - Morse Mismatch 3 | * Author: sjsakib 4 | * 5 | * Tip: Just ignore the second sentence from the fourth paragraph 6 | **/ 7 | #include 8 | 9 | using namespace std; 10 | 11 | map mp; 12 | map dict; 13 | 14 | string get_code(string s) { 15 | int k = 0; 16 | string code; 17 | while(s[k] != '\0') { 18 | code += mp[s[k]]; 19 | k++; 20 | } 21 | return code; 22 | } 23 | 24 | void read() { 25 | string s1,s2; 26 | while(cin>>s1 && s1 != "*") { 27 | cin>>s2; 28 | mp[s1[0]] = string(s2); 29 | } 30 | while(cin>>s1 && s1 != "*") { 31 | dict[s1] = get_code(s1); 32 | } 33 | } 34 | 35 | int get_diff(string s1, string s2) { 36 | int k = 0; 37 | while(s1[k] == s2[k] && s1[k] != '\0' && s2[k] != '\0') k++; 38 | 39 | if ( k < (int) min(s1.length(), s2.length())) return -1; 40 | 41 | return max(s1.length(), s2.length()) - k; 42 | } 43 | 44 | void answer() { 45 | string code; 46 | while(cin>>code && code != "*") { 47 | int mn = 1e8; 48 | string ans; 49 | for (auto w: dict) { 50 | 51 | int diff = get_diff(w.second, code); 52 | if (diff == -1) continue; 53 | if (diff < mn) { 54 | mn = diff; 55 | ans = w.first; 56 | } else if(mn == 0 && mn == diff) { 57 | ans += '!'; 58 | break; 59 | } 60 | } 61 | if(mn) ans += '?'; 62 | cout< 7 | 8 | using namespace std; 9 | 10 | char disks[8][6410]; 11 | int d, s, b; 12 | bool parity; 13 | 14 | bool read() { 15 | char p; 16 | scanf("%d %d %d\n%c\n", &d, &s, &b, &p); 17 | if (d == 0) return 0; 18 | 19 | parity = (p == 'O'); 20 | 21 | for (int i = 0; i < d; i++) { 22 | scanf("%s", disks[i]); 23 | } 24 | return 1; 25 | } 26 | 27 | bool valid() { 28 | for (int i = 0; i < s*b; i++) { 29 | int k = 0, lost = -1; 30 | for (int j = 0; j < d; j++) { 31 | char &c = disks[j][i]; 32 | if (c == '1') k ^= 1; 33 | else if ( c == 'x') { 34 | if (lost != -1) return 0; 35 | lost = j; 36 | } 37 | } 38 | if ( lost == -1 && k != parity ) return 0; 39 | if (lost != -1) disks[lost][i] = (parity != k) + '0'; 40 | } 41 | return 1; 42 | } 43 | 44 | void printData() { 45 | int n = 0, cnt = 0; 46 | for (int i = 0; i < b; i++) { 47 | for (int j = 0; j < d; j++) { 48 | if (j == i % d) continue; 49 | for (int k = 0; k < s; k++) { 50 | if (disks[j][i*s + k] == '1') n += 1; 51 | if(++cnt == 4) { 52 | printf("%X", n); 53 | n = 0; 54 | cnt = 0; 55 | } else { 56 | n <<= 1; 57 | } 58 | } 59 | } 60 | } 61 | if (cnt) { 62 | n <<= (3-cnt); 63 | printf("%X", n); 64 | } 65 | printf("\n"); 66 | } 67 | 68 | int main() { 69 | int setno = 1; 70 | while ( read() ) { 71 | printf("Disk set %d is ", setno++); 72 | if ( valid() ) { 73 | printf("valid, contents are: "); 74 | printData(); 75 | } else printf("invalid.\n"); 76 | } 77 | return 0; 78 | } -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 512 - Spreadsheet Tracking.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 201 Squares 3 | Author: sjsakib 4 | """ 5 | 6 | 7 | def inp(): 8 | try: 9 | i = input() 10 | while not i: 11 | i = input() 12 | return i 13 | except EOFError: 14 | return -1 15 | 16 | 17 | def find(r, c): 18 | for i, row in enumerate(tb): 19 | try: 20 | j = row.index((r, c)) 21 | return i+1, j+1 22 | except ValueError: 23 | pass 24 | return -1, -1 25 | 26 | 27 | def exchange(r1, c1, r2, c2): 28 | tb[r1-1][c1-1], tb[r2-1][c2-1] = tb[r2-1][c2-1], tb[r1-1][c1-1] 29 | 30 | 31 | def insert_col(cols): 32 | global col 33 | for i, c in enumerate(cols): 34 | for j in range(row): 35 | tb[j].insert(c+i-1, (0, 0)) 36 | col += len(cols) 37 | 38 | 39 | def delete_col(cols): 40 | global col 41 | for i, c in enumerate(cols): 42 | for j in range(row): 43 | del tb[j][c-i-1] 44 | col -= len(cols) 45 | 46 | 47 | def insert_row(rows): 48 | global row 49 | for i, r in enumerate(rows): 50 | tb.insert(r+i-1, [(0, 0) for j in range(col)]) 51 | row += len(rows) 52 | 53 | 54 | def delete_row(rows): 55 | global row 56 | for i, r in enumerate(rows): 57 | del tb[r-i-1] 58 | row -= len(rows) 59 | 60 | 61 | case = 1 62 | 63 | while True: 64 | row, col = map(int, inp().split()) 65 | if row == 0: 66 | break 67 | 68 | tb = [[(j+1, i+1) for i in range(col)] for j in range(row)] 69 | 70 | n = int(inp()) 71 | 72 | for i in range(n): 73 | op = inp().split() 74 | cmd = op[0] 75 | args = list(map(int, op[1:])) 76 | 77 | if cmd == "EX": 78 | exchange(*args) 79 | continue 80 | args = sorted(args[1:]) 81 | if cmd == 'DR': 82 | delete_row(args) 83 | elif cmd == 'DC': 84 | delete_col(args) 85 | elif cmd == 'IC': 86 | insert_col(args) 87 | elif cmd == 'IR': 88 | insert_row(args) 89 | 90 | x = int(inp()) 91 | 92 | if case != 1: 93 | print('') 94 | print("Spreadsheet #", case, sep='') 95 | for i in range(x): 96 | r, c = map(int, inp().split()) 97 | 98 | nr, nc = find(r, c) 99 | if nr == -1: 100 | ans = 'GONE' 101 | else: 102 | ans = "moved to ({},{})".format(nr, nc) 103 | print("Cell data in ({},{})".format(r, c), ans) 104 | case += 1 105 | -------------------------------------------------------------------------------- /Easy Problems/Exercises/UVa 815 - Flooded.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: UVa 815 Flooded! 3 | Author: sjsakib 4 | 5 | We will sort the blocks according to height and keep pouring water until we run out of water or all the blocks 6 | are drowned. 7 | """ 8 | case = 1 9 | 10 | while True: 11 | n, m = map(int, input().split()) 12 | if n == 0 and m == 0: 13 | break 14 | blocks = [] 15 | for i in range(n): 16 | blocks.extend(list(map(int, input().split()))) 17 | total = int(input()) 18 | blocks.sort() 19 | blocks.append(1e10) 20 | 21 | idx = 0 22 | height = blocks[0] 23 | drowned = 0 24 | 25 | while True: 26 | if idx > n*m: 27 | break 28 | while blocks[idx+1] == blocks[idx]: 29 | idx += 1 30 | 31 | h = blocks[idx+1] - blocks[idx] 32 | if(h*100*(idx+1) <= total): 33 | total -= h*100*(idx+1) 34 | drowned = idx + 1 35 | height += h 36 | idx += 1 37 | elif total > 0: 38 | drowned = idx+1 39 | height += total/(100*(idx+1)) 40 | break 41 | else: 42 | break 43 | print("Region {}\nWater level is {:.2f} meters.\n{:.2f} percent of the region is under water.\n" 44 | .format(case, height, drowned/(n*m)*100)) 45 | case += 1 46 | -------------------------------------------------------------------------------- /Easy Problems/Timus 1000 - A+B Problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char const *argv[]) { 5 | int a, b; 6 | scanf("%d %d", &a, &b); 7 | printf("%d\n", a + b); 8 | } 9 | -------------------------------------------------------------------------------- /Easy Problems/Timus 1005 - Stone Pile v1.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: Timus 1005 Stone Pile 3 | * author: sjsakib 4 | * approach: backtracking - O(2^n) 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int n; 11 | int arr[22]; 12 | int sum = 0; 13 | int ans; 14 | 15 | void backtrack(int i, int s) { 16 | if(i == n) { 17 | ans = min(ans, abs(sum - s*2)); 18 | return; 19 | } 20 | backtrack(i+1, s); 21 | backtrack(i+1, s+arr[i]); 22 | } 23 | 24 | 25 | int main() { 26 | scanf("%d", &n); 27 | for (int i = 0; i < n; ++i) { 28 | scanf("%d", &arr[i]); 29 | sum += arr[i]; 30 | } 31 | ans = sum; 32 | backtrack(0, 0); 33 | printf("%d\n",ans); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Easy Problems/Timus 1005 - Stone Pile v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: Timus 1005 Stone Pile 3 | * author: sjsakib 4 | * approach: coin change dp time: O(total*n) 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | int n; 12 | int arr[22]; 13 | int sum = 0; 14 | 15 | scanf("%d", &n); 16 | for (int i = 0; i < n; ++i) { 17 | scanf("%d", &arr[i]); 18 | sum += arr[i]; 19 | } 20 | 21 | int ans = sum; 22 | bool dp[sum+1]; 23 | memset(dp, 0, sum); 24 | dp[0] = 1; 25 | for (int j = 1; j < n; j++) { 26 | for (int i = sum; i >= 1; i--) { 27 | if(i >= arr[j] && dp[i - arr[j]]) { 28 | dp[i] = 1; 29 | ans = min(ans, abs(sum- i*2)); 30 | } 31 | } 32 | } 33 | printf("%d\n",ans); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /Easy Problems/Timus 1005 - Stone Pile v3.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: Timus 1005 Stone Pile 3 | * author: sjsakib 4 | * approach: bitmask with memorization time: O(2^n), mem: O(2^n) 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int n, num[22], sum=0, ans; 11 | 12 | int main() { 13 | scanf("%d", &n); 14 | for (int i = 0; i < n; ++i) { 15 | scanf("%d", &num[i]); 16 | sum += num[i]; 17 | } 18 | ans = sum; 19 | int mem[(1< 7 | 8 | using namespace std; 9 | 10 | int n, num[22], sum=0, ans; 11 | 12 | int main() { 13 | scanf("%d", &n); 14 | for (int i = 0; i < n; ++i) { 15 | scanf("%d", &num[i]); 16 | sum += num[i]; 17 | } 18 | ans = sum; 19 | for (int mask = 0; mask < (1< 7 | 8 | using namespace std; 9 | 10 | int n; 11 | 12 | int main() { 13 | scanf("%d", &n); 14 | vector ans; 15 | if(n == 1) { 16 | printf("1\n"); 17 | return 0; 18 | } else if(n == 0) { 19 | printf("10\n"); 20 | return 0; 21 | } 22 | for(int i = 9;i >= 2;--i) { 23 | while(n % i == 0) { 24 | n /= i; 25 | ans.push_back(i); 26 | } 27 | } 28 | if(n == 1) { 29 | for (int i = ans.size()-1; i >= 0; --i) { 30 | printf("%d", ans[i]); 31 | } 32 | printf("\n"); 33 | } else { 34 | printf("-1\n"); 35 | } 36 | return 0; 37 | } -------------------------------------------------------------------------------- /Easy Problems/Timus 1020 - Rope.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: Timus 1020 Rope 3 | * author: sjsakib 4 | * approach: 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | float pi = 3.1415926; 11 | 12 | float dist(float x1, float y1, float x2, float y2) { 13 | float dx = x1-x2; 14 | float dy = y1-y2; 15 | return sqrt(dx*dx + dy*dy); 16 | } 17 | 18 | int main() { 19 | int n; 20 | float r; 21 | scanf("%d %f", &n, &r); 22 | float len=0, points[n][2]; 23 | for (int i = 0; i < n; ++i) { 24 | scanf("%f %f", &points[i][0], &points[i][1]); 25 | if(i>0) len += dist(points[i][0], points[i][1], points[i-1][0], points[i-1][1]); 26 | } 27 | len += dist(points[0][0], points[0][1], points[n-1][0], points[n-1][1]); 28 | len += 2.0*pi*r; 29 | printf("%.2f\n", len); 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Easy Problems/Timus 1044 - Lucky Tickets (Easy).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: Timus 1044 Lucky Tickets. Easy 3 | * author: sjsakib 4 | * approach: 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int pow(int a, int x) { 11 | int ret = 1; 12 | for (int i = 0; i < x; ++i) { 13 | ret *= a; 14 | } 15 | return ret; 16 | } 17 | 18 | int digitsum(int n) { 19 | int sum = 0; 20 | while(n > 0) { 21 | sum += n % 10; 22 | n /= 10; 23 | } 24 | return sum; 25 | } 26 | 27 | int n; 28 | int mem[38]; 29 | 30 | int main() { 31 | scanf("%d", &n); 32 | for (int i = 0; i < pow(10, n/2); ++i) { 33 | int s = digitsum(i); 34 | mem[s]++; 35 | } 36 | int ans = 0; 37 | for (int i = 0; i < pow(10, n/2); ++i) { 38 | int s = digitsum(i); 39 | ans += mem[s]; 40 | } 41 | printf("%d\n", ans); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Easy Problems/Timus 1197 - Lonesome Knight.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: Timus 1197 Lonesome Knight 3 | * author: sjsakib 4 | * approach: implementation 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int dx[] = {2, -2, 2, -2, 1, -1, 1, -1}; 11 | int dy[] = {1, 1, -1, -1, 2, 2, -2, -2}; 12 | 13 | bool inside(int x, int y) { 14 | return x >= 0 && y >= 0 && x < 8 && y < 8; 15 | } 16 | 17 | 18 | int main() { 19 | int n,ans; 20 | char s[3]; 21 | scanf("%d\n", &n); 22 | for (int i = 0; i < n; ++i) { 23 | ans = 0; 24 | scanf("%s\n", s); 25 | int x = s[0] - 'a'; 26 | int y = s[1] - '1'; 27 | for (int j = 0; j < 8; ++j) { 28 | ans += inside(x+dx[j], y+dy[j]); 29 | } 30 | printf("%d\n", ans); 31 | 32 | } 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Easy Problems/UVa 12108 - Extraordinarily Tired Students.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: UVa 12108 Extraordinarily Tired Students 3 | * author: sjsakib 4 | * time: lcm(a[i]+b[i])*n 5 | * mem: n 6 | **/ 7 | #include 8 | 9 | using namespace std; 10 | 11 | int gcd(int a, int b) { 12 | if(a % b == 0) return b; 13 | else return gcd(b,a%b); 14 | } 15 | 16 | int lcm(int a, int b) { 17 | return a*b/gcd(a,b); 18 | } 19 | 20 | int n; 21 | int arr[13][3]; 22 | int status[13]; 23 | 24 | //Checks how many students are awake and updates their status 25 | //returns true if everyone is awake, false otherwise 26 | bool update() { 27 | int count = 0; 28 | for (int i = 0; i < n; i++) { 29 | if(status[i] <= arr[i][0]) count++; 30 | } 31 | if(count == n) return true; 32 | for(int i = 0;i <= n; i++) { 33 | if(status[i] == arr[i][0]+arr[i][1] || (status[i] == arr[i][0] && n <= count*2)) status[i] = 1; 34 | else status[i]++; 35 | } 36 | return false; 37 | } 38 | 39 | int main() { 40 | int caseno = 1; 41 | while(1) { 42 | scanf("%d", &n); 43 | if(n == 0) break; 44 | 45 | int l = 1; //to hold lcm 46 | 47 | for(int i = 0; i < n; i++) { 48 | scanf("%d %d %d", &arr[i][0], &arr[i][1], &arr[i][2]); 49 | status[i] = arr[i][2]; 50 | l = lcm(l, arr[i][0]+arr[i][1]); 51 | } 52 | 53 | bool found; 54 | for( int t = 1; t <= l; t++) { 55 | found = update(); 56 | if(found) { 57 | printf("Case %d: %d\n", caseno++, t); 58 | break; 59 | } 60 | } 61 | if(!found) { 62 | printf("Case %d: -1\n", caseno++); 63 | } 64 | } 65 | return 0; 66 | } -------------------------------------------------------------------------------- /Easy Problems/UVa 202 - Repeating Decimals.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: UVa 202 Repeating Decimals 3 | * author: sjsakib 4 | * approach: 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int mem[30007]; 11 | vector v; 12 | 13 | void repeating(int a, int x) { 14 | memset(mem, -1, sizeof(mem[0])*3007); 15 | v.clear(); 16 | 17 | printf("%d/%d = ", a, x); 18 | printf("%d.", a/x); 19 | 20 | a = a % x; 21 | mem[a] = 1; 22 | 23 | while(1) { 24 | a *= 10; 25 | bool found = false; 26 | while(a && a/x == 0) { 27 | v.push_back(0); 28 | if(mem[a] == -1) mem[a] = v.size() + 1; 29 | else { 30 | found = true; 31 | break; 32 | } 33 | a *= 10; 34 | } 35 | if(found) break; 36 | v.push_back(a/x); 37 | a = a % x; 38 | if(mem[a] != -1) { 39 | break; 40 | } else mem[a] = v.size() + 1; 41 | } 42 | 43 | for (int i = 0; i < v.size(); ++i) { 44 | if(i == mem[a]-1) printf("("); 45 | printf("%d",v[i]); 46 | if(i == 49 && v.size() != 50) { 47 | printf("...)\n"); 48 | break; 49 | } else if(i == v.size()-1) printf(")\n"); 50 | } 51 | printf(" %d = number of digits in repeating cycle\n\n", (int) v.size()-mem[a]+1); 52 | } 53 | 54 | int main() { 55 | int a, x; 56 | while(scanf("%d %d", &a, &x) != EOF) { 57 | repeating(a, x); 58 | } 59 | return 0; 60 | } -------------------------------------------------------------------------------- /Easy Problems/UVa 253 - Cube Painting.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: UVa 253 Cube painting 3 | * author: sjsakib 4 | **/ 5 | #include 6 | 7 | using namespace std; 8 | 9 | char s[14]; 10 | 11 | bool eq() { 12 | for(int i = 0;i<6;i++) { 13 | if(s[i] != s[i+6]) return false; 14 | } 15 | return true; 16 | } 17 | void rotateZ() { 18 | char tmp = s[1]; 19 | s[1] = s[3]; 20 | s[3] = s[4]; 21 | s[4] = s[2]; 22 | s[2] = tmp; 23 | } 24 | void rotateX() { 25 | char tmp = s[0]; 26 | s[0] = s[1]; 27 | s[1] = s[5]; 28 | s[5] = s[4]; 29 | s[4] = tmp; 30 | } 31 | 32 | int main() { 33 | while(scanf("%s\n", s) != EOF) { 34 | bool same; 35 | for(int i = 0; i < 6; i++) { 36 | same = eq(); 37 | if(same) break; 38 | else if(i < 4) rotateX(); 39 | else if(i == 4) { 40 | rotateZ(); 41 | rotateX(); 42 | } else { 43 | rotateX(); 44 | rotateX(); 45 | } 46 | for(int j = 0;j < 4; j++) { 47 | same = eq(); 48 | 49 | if(same) break; 50 | else rotateZ(); 51 | } 52 | if(same) break; 53 | } 54 | if(same) printf("TRUE\n"); 55 | else printf("FALSE\n"); 56 | } 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Geometry/UVa 10283 - The Kissing Circles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define PI 2.0*acos(0.0) 5 | #define SIN(x) sin(x * PI / 180.0) 6 | #define COS(x) cos(x * PI / 180.0) 7 | 8 | int main() { 9 | int R, n; while( cin >> R >>n ) { 10 | if(n == 1) { 11 | printf("%.10f %.10f %.10f\n", (double) R, 0, 0); 12 | continue; 13 | } 14 | double theta = 180.0 / n; 15 | double r = R * SIN(theta) / (1.0 + SIN(theta)); 16 | double blue = n * ( (R - r) * COS(theta) * r - (90-theta) / 180 * PI * r * r); 17 | double rest = PI * R * R - blue - n * PI * r * r; 18 | printf("%.10f %.10f %.10f\n", r, blue, rest); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Graph Theory/UVa 10048 - Audiophobia.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int inf = 1e9; 5 | int g[105][105]; 6 | 7 | int main() { 8 | bool flag = false; int co=0; 9 | while(1) { 10 | int c, l, q; 11 | scanf("%d %d %d", &c, &l, &q); 12 | if(!c && !l && !q) break; 13 | 14 | for(int i = 0; i <= c; i++){ 15 | for(int j = 0; j <= c; j++){ 16 | g[i][j] = inf; 17 | } 18 | } 19 | int a, b, cost; 20 | for(int i = 0; i < l; i++) { 21 | scanf("%d %d %d", &a, &b, &cost); 22 | g[a][b] = g[b][a] = cost; 23 | } 24 | 25 | for(int k = 1;k <= c; k++) 26 | for(int i = 1;i <= c; i++) 27 | for(int j = 1;j <= c; j++) 28 | g[i][j] = min(g[i][j], max(g[i][k], g[k][j])); 29 | 30 | if(flag) puts(""); 31 | flag = true; 32 | 33 | printf("Case #%d\n",++co); 34 | 35 | for(int i = 0;i < q; i++) { 36 | scanf("%d %d", &a, &b); 37 | if(g[a][b] == inf) puts("no path"); 38 | else printf("%d\n", g[a][b]); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Greedy/CF 26B - Regular Bracket Sequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | typedef pair ii; 6 | 7 | int main(int argc, char const *argv[]) { 8 | #ifdef LOCAL_TESTING 9 | freopen("in", "r", stdin); 10 | #endif 11 | string s; cin >> s; 12 | int cnt = 0, ans = 0; 13 | for(char c : s) { 14 | if(c == '(') cnt++; 15 | else if(cnt) cnt--, ans += 2; 16 | } cout << ans << endl; 17 | } 18 | -------------------------------------------------------------------------------- /Mathematics/UVA 12169 - Disgruntled Judge.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | #define int long long 7 | 8 | int mul(int a, int b, int M) {return ((a % M) * (b % M)) % M;} 9 | // ax + by = g 10 | int egcd(int a, int b, int &x, int &y) { 11 | 12 | if ( b == 0) { 13 | x = 1; 14 | y = 0; 15 | return a; 16 | } 17 | 18 | int x1, y1; 19 | int d = egcd(b, a % b, x1, y1); 20 | x = y1; 21 | y = x1 - y1 * (a / b); 22 | return d; 23 | } 24 | 25 | signed main() { 26 | int n; cin >> n; 27 | 28 | vector v(2 * n + 1); 29 | for (int i = 1; i <= 2 * n - 1; i += 2) { 30 | cin >> v[i]; 31 | } 32 | if (n == 1) { 33 | // a = 0 34 | // b = 0 35 | cout << 0 << endl; 36 | return 0; 37 | } 38 | for (int a = 0; a <= 10000; a++) { 39 | // v[3] = a^2*v[1] + b(a + 1) + 10001c 40 | // b(a + 1) + 10001c = v[3] - a^2*v[1] 41 | // bp + cq = r 42 | // x = b, y = c 43 | // px + qy = r 44 | 45 | // smallest linear combination of p and q 46 | // px_ + qy_ = g ---> g = gcd(p, q) 47 | // kpx_ + kqy_ = r ---> k = r / g 48 | // b = kx_ = (r / g)*x_ 49 | 50 | // we can find x_ from extented gcd 51 | int p = a + 1; 52 | int q = 10001; 53 | int r = v[3] - (a * a * v[1]); 54 | 55 | int x , y; 56 | 57 | int g = egcd(p, q, x, y); 58 | 59 | int b = x; 60 | b *= (r / g); 61 | bool ok = 1; 62 | 63 | 64 | for (int i = 5; i <= 2 * n; i += 2) { 65 | int tmp = (mul(mul(a, a, q), v[i - 2], q) + mul(b, p, q)) % q; 66 | if (tmp != v[i]) { 67 | ok = 0; 68 | // it is not valid (a, b) 69 | break; 70 | } 71 | } 72 | if (ok) { 73 | // found valid a , b for all given v[1], v[3],... v[2*n-1] 74 | 75 | // cout << r << " " << g << endl; 76 | // cout << a << " " << b << endl; 77 | 78 | // printing v[2], v[4], ... v[2*n] 79 | for (int i = 2; i <= 2 * n; i += 2) { 80 | int tmp = (mul(a, v[i - 1], q) + b) % 10001; 81 | cout << tmp << endl; 82 | 83 | } 84 | return 0; 85 | } 86 | 87 | 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /Mathematics/UVa 10375 - Choose and divide.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(int argc, char const *argv[]) { 5 | int p, q, r, s; 6 | while(scanf("%d %d %d %d", &p, &q, &r, &s) != EOF) { 7 | long double ans = 1.0; 8 | q = min(q, p - q); p = p - q + 1; 9 | s = min(s, r - s); r = r - s + 1; 10 | for(int i = 1; i <= q; i++, p++) 11 | ans *= (double) p, 12 | ans /= (double) i; 13 | for(int i = 1; i <= s; i++, r++) 14 | ans *= (double) i, 15 | ans /= (double) r; 16 | cout << fixed << setprecision(5) << ans << endl; 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /Mathematics/UVa 11582 - Colossal Fibonacci Numbers!.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: sjsakib 3 | * Problem: UVa 11582 - Colossal Fibonacci Numbers! 4 | * Approach: Cycle + Matrix Exponent + DP 5 | * এখানে ম্যাট্রিক্স এক্সপোনেন্টের বদলে একটি ফর্মুলা ব্যবহার করা হয়েছে যেটি ম্যাট্রিক্স এক্সপোনেন্ট থেকে পাওয়া যায়। 6 | * কম্প্লেক্সিটি এক হলেও এটার কোড অনেক সিম্পল। 7 | **/ 8 | #include 9 | #include 10 | #include 11 | 12 | #define MAX 1000 13 | 14 | using namespace std; 15 | 16 | vector cycles[MAX+10]; 17 | 18 | int mem[3009][1009]; 19 | 20 | int bigmod(unsigned long long a, unsigned long long b, int n) { 21 | a = a % n; 22 | int ret = 1; 23 | while (b > 0) { 24 | if (b & 1) ret = (ret * a) % n; 25 | a = (a*a) % n; 26 | b /= 2; 27 | } 28 | return ret; 29 | } 30 | 31 | int fib(int i, int n) { 32 | if(i == 0) return 0; 33 | if (i<3) return 1; 34 | if (mem[i][n] != -1) return mem[i][n]; 35 | int k; 36 | int ret; 37 | if(!(i&1)) { 38 | k = i/2; 39 | int fk = fib(k, n); 40 | ret = ((2*fib(k-1, n) + fk)*fk) % n; 41 | } else { 42 | k = (i+1)/2; 43 | int fk1 = fib(k-1, n); 44 | int fk = fib(k, n); 45 | ret = (fk*fk + fk1*fk1) % n; 46 | } 47 | mem[i][n] = ret; 48 | return ret; 49 | } 50 | 51 | void gen_cycles() { 52 | memset(mem, -1, sizeof(mem[0])*3009); 53 | cycles[1].push_back(0); 54 | for (int n = 2; n <= MAX; n++) { 55 | int i = 0; 56 | cycles[n].push_back(fib(i++, n)); 57 | cycles[n].push_back(fib(i++, n)); 58 | cycles[n].push_back(fib(i++, n)); 59 | while(!(cycles[n][0] == cycles[n][cycles[n].size()-2] && cycles[n][1] == cycles[n].back())) { 60 | cycles[n].push_back(fib(i++, n)); 61 | } 62 | cycles[n].pop_back(); 63 | cycles[n].pop_back(); 64 | } 65 | } 66 | 67 | int main() { 68 | int t,n; 69 | unsigned long long a,b; 70 | gen_cycles(); 71 | scanf("%d", &t); 72 | for (int i = 0; i < t; i++) { 73 | scanf("%llu %llu %d", &a, &b, &n); 74 | int c = cycles[n].size(); 75 | printf("%d\n", cycles[n][bigmod(a, b, c)]); 76 | } 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /STL/Exercises/UVa 10763 - Foreign Exchange v2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 10763 - Foreign Exchange 3 | * Author: sjsakib 4 | * Approach: Vector 5 | * Number of incoming and outgoing students of a location have to be equal. 6 | **/ 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | int main() { 14 | int n,h,d; 15 | while (1) { 16 | scanf("%d", &n); 17 | if (n == 0) break; 18 | vector > v; 19 | vector > rv; 20 | for (int i = 0; i < n; i++) { 21 | scanf("%d %d", &h, &d); 22 | v.push_back(make_pair(h, d)); 23 | rv.push_back(make_pair(d,h)); 24 | } 25 | sort(v.begin(), v.end()); 26 | sort(rv.begin(), rv.end()); 27 | if (v == rv) printf("YES\n"); 28 | else printf("NO\n"); 29 | } 30 | return 0; 31 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 10763 - Foreign Exchange.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 10763 - Foreign Exchange 3 | * Author: sjsakib 4 | * Approach: Map 5 | * Number of incoming and outgoing students of a location have to be equal. 6 | **/ 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | int main() { 13 | int n,h,d; 14 | while (1) { 15 | scanf("%d", &n); 16 | if (n == 0) break; 17 | map in; 18 | map out; 19 | for (int i = 0; i < n; i++) { 20 | scanf("%d %d", &h, &d); 21 | in[h]++; 22 | out[d]++; 23 | } 24 | if (in == out) printf("YES\n"); 25 | else printf("NO\n"); 26 | } 27 | return 0; 28 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 10935 - Throwing Cards Away I.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 10935 - Throwing Cards Away I 3 | * Author: sjsakib 4 | * Approach: Deque 5 | **/ 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | int main() { 12 | int n; 13 | while (scanf("%d", &n) && n != 0) { 14 | deque dq; 15 | for (int i = 0; i < n; i++) { 16 | dq.push_back(i+1); 17 | } 18 | printf("Discarded cards:"); 19 | while (dq.size() > 1) { 20 | printf(" %d", dq.front()); 21 | dq.pop_front(); 22 | if(dq.size() != 1) printf(","); 23 | dq.push_back(dq.front()); 24 | dq.pop_front(); 25 | } 26 | printf("\nRemaining card: %d\n", dq.front()); 27 | } 28 | return 0; 29 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 12333 - Revenge of Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 12333 - Revenge of Fibonacci 3 | * Author: sjsakib 4 | * Approach: Bruteforce 5 | * Takes almost a minute on my own machine, but somehow manages to get ac 6 | **/ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | map fibs; 16 | 17 | string add(string& a, string& b) { 18 | int i = (int) a.length() - 1; 19 | int j = (int) b.length() - 1; 20 | int k = max(i,j); 21 | int x,y,rem=0; 22 | string res(k+1, '0'); 23 | while(i >= 0 && j >= 0) { 24 | x = a[i] - '0'; 25 | y = b[j] - '0'; 26 | res[k] = (char) ((x+y+rem)%10 + '0'); 27 | rem = (x+y+rem)/10; 28 | i--; 29 | j--; 30 | k--; 31 | } 32 | while (i >= 0) { 33 | x = a[i] - '0'; 34 | res[k] = (char) ((x+rem)%10 + '0'); 35 | rem = (x+rem)/10; 36 | i--; 37 | k--; 38 | } 39 | while (j >= 0) { 40 | x = b[j] - '0'; 41 | res[k] = (char) ((x+rem)%10 + '0'); 42 | rem = (x+rem)/10; 43 | j--; 44 | k--; 45 | } 46 | if(rem) res = (char) (rem + '0') + res; 47 | return res; 48 | 49 | } 50 | 51 | void gen_fibs() { 52 | string a = "1", b = "1"; 53 | string f; 54 | fibs["1"] = 0; 55 | for (int i = 2; i < 100000; i++) { 56 | f = add(a, b); 57 | a = b; 58 | b = f; 59 | for (int j = 0; j < 51; j++) { 60 | if(j > (int) f.length()) break; 61 | string sub = f.substr(0,j); 62 | if(fibs.count(sub) == 0) fibs[sub] = i; 63 | } 64 | } 65 | } 66 | 67 | int main() { 68 | gen_fibs(); 69 | int t; 70 | scanf("%d", &t); 71 | char s[55]; 72 | for (int i = 0; i < t; i++) { 73 | printf("Case #%d: ", i+1); 74 | scanf("%s", s); 75 | if(fibs.count(s) != 0) printf("%d\n", fibs[s]); 76 | else printf("-1\n"); 77 | } 78 | return 0; 79 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 12504 - Updating a Dictionary.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 12504 - Updating a Dictionary 3 | * Author: sjsakib 4 | * Approach: Implementation 5 | **/ 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | void read_map(map &mp) { 13 | char buff[103]; 14 | scanf("%s", buff); 15 | int i = 1; 16 | while(buff[i] != '\0' && buff[i] != '}'){ 17 | string key; 18 | while(buff[i] != ':') { 19 | key += buff[i++]; 20 | } 21 | i++; 22 | string val; 23 | while(buff[i] != ',' && buff[i] != '}') { 24 | val += buff[i++]; 25 | } 26 | mp[key] = val; 27 | i++; 28 | } 29 | 30 | } 31 | 32 | void print_diff(map &mp1, map &mp2) { 33 | int count = 0,total; 34 | for (auto item: mp2) { 35 | if(mp1.count(item.first) == 0) { 36 | if(count == 0) printf("+"); 37 | else printf(","); 38 | printf("%s", item.first.c_str()); 39 | count++; 40 | } 41 | } 42 | if(count) printf("\n"); 43 | total = count; 44 | count = 0; 45 | for (auto item: mp1) { 46 | if(mp2.count(item.first) == 0) { 47 | if(count == 0) printf("-"); 48 | else printf(","); 49 | printf("%s", item.first.c_str()); 50 | count++; 51 | } 52 | } 53 | if(count) printf("\n"); 54 | total += count; 55 | count = 0; 56 | for (auto item: mp2) { 57 | if(mp1.count(item.first) != 0 && mp1[item.first] != mp2[item.first]) { 58 | if(count == 0) printf("*"); 59 | else printf(","); 60 | printf("%s", item.first.c_str()); 61 | count++; 62 | } 63 | } 64 | if(count) printf("\n"); 65 | total += count; 66 | if(!total) printf("No changes\n"); 67 | printf("\n"); 68 | } 69 | 70 | int main() { 71 | int t; 72 | scanf("%d", &t); 73 | for (int i = 0; i < t; i++) { 74 | map mp1; 75 | map mp2; 76 | read_map(mp1); 77 | read_map(mp2); 78 | print_diff(mp1,mp2); 79 | } 80 | return 0; 81 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 1593 - Alignment of Code.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 1593 - Alignment of Code 3 | * Author: sjsakib 4 | * Approach: C++ STL 5 | **/ 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | vector lines[1000]; 13 | int width[185]; 14 | 15 | int main() { 16 | char buff[185]; 17 | int i = 0; 18 | while(gets(buff) != NULL) { 19 | istringstream is(buff); 20 | string word; 21 | int k = 0; 22 | while(is >> word) { 23 | lines[i].push_back(word); 24 | width[k] = max(width[k], (int) word.length()); 25 | k++; 26 | } 27 | i++; 28 | } 29 | for (int k = 0; k < i; k++) { 30 | for(int l = 0; l < (int) lines[k].size(); l++) { 31 | int w = l!=lines[k].size()-1?width[l]+1:lines[k][l].size(); 32 | printf("%-*s",w, lines[k][l].c_str()); 33 | } 34 | printf("\n"); 35 | } 36 | return 0; 37 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 1594 - Ducci Sequence.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 1594 - Ducci Sequence 3 | * Author: sjsakib 4 | * Approach: Simple Loop 5 | * We get our cycle in 50 steps if we are to get. But why? I just gave up. Please let me know if you find out. 6 | **/ 7 | #include 8 | #include 9 | 10 | int arr[16]; 11 | 12 | int main() { 13 | int t,n,head; 14 | int all; 15 | scanf("%d", &t); 16 | for (int i = 0; i < t; i++) { 17 | scanf("%d", &n); 18 | for (int j = 0; j < n; j++) { 19 | scanf("%d", &arr[j]); 20 | } 21 | for (int j = 0; j < 50; j++) { 22 | all = 1; 23 | head = arr[0]; 24 | for (int k = 0; k < n-1; k++) { 25 | arr[k] = abs(arr[k] - arr[(k+1) % n]); 26 | all &= !arr[k]; 27 | } 28 | arr[n-1] = abs(arr[n-1] - head); 29 | all &= !arr[n-1]; 30 | if(all) break; 31 | } 32 | if(!all) printf("LOOP\n"); 33 | else printf("ZERO\n"); 34 | } 35 | 36 | return 0; 37 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 1595 - Symmetry.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 1595 - Symmetry 3 | * Author: sjsakib 4 | * Approach: Vector 5 | * 6 | **/ 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | int main() { 14 | int t,n,x,y; 15 | scanf("%d", &t); 16 | for (int i = 0; i < t; i++) { 17 | scanf("%d", &n); 18 | vector > v(n); 19 | for (int j = 0; j < n; j++) { 20 | scanf("%d %d", &x, &y); 21 | v[j] = make_pair(x*2, y); // multiplying by 2 to avoid fraction later 22 | } 23 | sort(v.begin(), v.end()); 24 | int mid = v[0].first + (v[n-1].first - v[0].first)/2; 25 | int mx = v[n-1].first; 26 | int mn = v[0].first; 27 | vector > vl,vr; 28 | for (int j = 0; j < n; j++) { 29 | if(v[j].first < mid) vl.push_back(make_pair(v[j].first-mn, v[j].second)); 30 | else if(v[j].first > mid) vr.push_back(make_pair(mx-v[j].first, v[j].second)); 31 | } 32 | sort(vr.begin(), vr.end()); 33 | if(vl == vr) printf("YES\n"); 34 | else printf("NO\n"); 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /STL/Exercises/UVa 1596 - Bug Hunt.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 1596 - Bug Hunt 3 | * Author: sjsakib 4 | * Approach: Implementation 5 | **/ 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | struct arr { int len; map values; }; 14 | 15 | map all; 16 | 17 | long evaluate(char* line, int &i) { 18 | if(isdigit(line[i])) { 19 | int n = line[i++] - '0'; 20 | while(isdigit(line[i])) { 21 | n = n*10 + (line[i++] - '0'); 22 | } 23 | return n; 24 | } 25 | char sym = line[i]; 26 | i+=2; 27 | long n = evaluate(line, i); 28 | i++; 29 | if(all[sym].len > n && all[sym].values.find(n) != all[sym].values.end()) return all[sym].values[n]; 30 | else return -1; 31 | } 32 | 33 | int main() { 34 | char line[85]; 35 | int l=1,err=0; 36 | while(fgets(line, 84, stdin)) { 37 | if (line[0] == '.') { 38 | if(l == 1) break; 39 | printf("%d\n", err); 40 | all.clear(); 41 | l=1; 42 | err=0; 43 | continue; 44 | } 45 | if(err) continue; 46 | char sym = line[0]; 47 | int i = 2; 48 | long n = evaluate(line, i); 49 | if(n == -1) { 50 | err = l; 51 | continue; 52 | } 53 | if (line[++i] == '=') { 54 | if(n >= all[sym].len) { 55 | err = l; 56 | continue; 57 | } 58 | long val = evaluate(line, ++i); 59 | if(val == -1) { 60 | err = l; 61 | continue; 62 | } 63 | all[sym].values[n] = val; 64 | } 65 | else { 66 | all[sym] = arr(); 67 | all[sym].len = n; 68 | } 69 | l++; 70 | } 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /STL/Exercises/UVa 212 - Use of Hospital Facilities.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 212 - Use of Hospital Facilities 3 | * Author: sjsakib 4 | * Approach: OOP/Bruteforce 5 | * Description provided in UVa in a little unclear. A clearer description in available 6 | * [here](spoj.com/problems/HOSPITAL/) 7 | **/ 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | using namespace std; 14 | 15 | struct Patient { 16 | string name; 17 | int i; // Index 18 | int surg; // surgery time 19 | int rec; // recovery time 20 | int op_r; // operation room 21 | int rec_r; // recovery room 22 | int op_s; // operation start time 23 | 24 | Patient() { } 25 | Patient(int i_, string name_, int surg_, int rec_) { 26 | i = i_; 27 | name = name_; 28 | surg = surg_; 29 | rec = rec_; 30 | op_s = -1; 31 | } 32 | 33 | bool operator<(Patient rhs) { 34 | return op_r < rhs.op_r; 35 | } 36 | }; 37 | 38 | struct Room { 39 | int used; // Number of minutes used 40 | int busy; // busy until 41 | Room() { 42 | used = 0; 43 | busy = -1; 44 | } 45 | }; 46 | 47 | vector v; 48 | Patient pats[110]; 49 | Room oprooms[15]; 50 | Room recrooms[35]; 51 | 52 | int op_rs, rec_rs, s_hour, o2r, pre_op, pre_rec, n_pat; 53 | 54 | void assign_room(Patient &pat, int t) { 55 | for(int i = 0; i < op_rs; i++) { 56 | Room &room = oprooms[i]; 57 | if(room.busy <= t) { 58 | room.used += pat.surg; 59 | room.busy = t + pat.surg + pre_op; 60 | pat.op_s = t; 61 | pat.op_r = i+1; 62 | break; 63 | } 64 | } 65 | } 66 | 67 | void assign_bed(Patient &pat, int t) { 68 | for(int i = 0; i < rec_rs; i++) { 69 | Room &room = recrooms[i]; 70 | if(room.busy <= t) { 71 | room.used += pat.rec; 72 | room.busy = t + pat.rec + o2r + pre_rec; 73 | pats[pat.i].rec_r = i+1; 74 | break; 75 | } 76 | } 77 | } 78 | 79 | int main() { 80 | while(scanf("%d %d %d %d %d %d %d", &op_rs, &rec_rs, &s_hour, &o2r, &pre_op, &pre_rec, &n_pat) == 7) { 81 | char name[15]; 82 | int surg, rec; 83 | for (int i = 0; i < n_pat; i++) { 84 | scanf("%s %d %d", name, &surg, &rec); 85 | pats[i] = Patient(i, name, surg, rec); 86 | } 87 | int t = s_hour*60; // Current time 88 | int finished = 0; 89 | while (1) { 90 | for(int i = 0; i < n_pat; i++) { 91 | Patient &pat = pats[i]; 92 | if(pat.op_s == -1) { 93 | assign_room(pat, t); 94 | } else if (pat.op_s != -1 && pat.op_s + pat.surg == t) { 95 | v.push_back(pat); 96 | } else if (pat.op_s != -1 && pat.op_s + pat.surg + o2r + pat.rec == t) { 97 | finished++; 98 | } 99 | } 100 | sort(v.begin(), v.end()); 101 | for(auto p: v) { 102 | assign_bed(p, t); 103 | } 104 | v.clear(); 105 | if ( finished == n_pat) break; 106 | t+=1; 107 | } 108 | 109 | 110 | puts(" Patient Operating Room Recovery Room"); 111 | puts(" # Name Room# Begin End Bed# Begin End"); 112 | puts(" ------------------------------------------------------"); 113 | for (int i = 0; i < n_pat; i++) { 114 | Patient &pat = pats[i]; 115 | int op_end = pat.op_s + pat.surg; 116 | int rec_start = op_end + o2r; 117 | int rec_end = rec_start + pat.rec; 118 | printf("%2d %-9s %2d %3d:%02d %3d:%02d %3d %3d:%02d %3d:%02d\n", i+1, pat.name.c_str(), 119 | pat.op_r, pat.op_s / 60, pat.op_s % 60, op_end / 60, op_end % 60, 120 | pat.rec_r, rec_start / 60, rec_start % 60, rec_end / 60, rec_end % 60); 121 | } 122 | int t_m = t - s_hour*60; 123 | puts("\nFacility Utilization"); 124 | puts("Type # Minutes % Used"); 125 | puts("-------------------------"); 126 | for (int i = 0; i < op_rs; i++) { 127 | printf("%-4s %2d %7d %7.2lf\n","Room", i+1, oprooms[i].used, (double) oprooms[i].used*100/t_m); 128 | oprooms[i].used = 0; 129 | oprooms[i].busy = -1; 130 | } 131 | for (int i = 0; i < rec_rs; i++) { 132 | printf("%-4s %2d %7d %7.2lf\n","Bed", i+1, recrooms[i].used, (double) recrooms[i].used*100/t_m); 133 | recrooms[i].used = 0; 134 | recrooms[i].busy = -1; 135 | } 136 | puts(""); 137 | } 138 | return 0; 139 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 230 - Borrowers.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 230 - Borrowers 3 | * Author: sjsakib 4 | * Approach: 5 | **/ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | vector > all_books; 15 | map borrowed; 16 | map returned; 17 | 18 | int main() { 19 | char book[85], author[85]; 20 | while (scanf("\"%[^\"]\" by %[^\n]\n", book, author)) { 21 | all_books.push_back(make_pair(author, book)); 22 | borrowed[book] = 0; 23 | returned[book] = 0; 24 | } 25 | sort(all_books.begin(), all_books.end()); 26 | 27 | scanf("%s\n", book); // eating the END 28 | 29 | while (scanf("%s ", book)) { // using 'book' as buffer to read the command 30 | string cmd(book); 31 | if (cmd == "END") break; 32 | if (cmd == "SHELVE") { 33 | string last; 34 | for (auto b: all_books) { 35 | if(!borrowed[b.second]) last = b.second; 36 | else if(returned[b.second]) { 37 | if(last.length()) printf("Put \"%s\" after \"%s\"\n", b.second.c_str(), last.c_str()); 38 | else printf("Put \"%s\" first\n", b.second.c_str()); 39 | borrowed[b.second] = 0; 40 | last = b.second; 41 | } 42 | } 43 | printf("END\n"); 44 | returned.clear(); 45 | continue; 46 | } 47 | scanf("\"%[^\"]\"\n", book); 48 | if (cmd == "BORROW") { 49 | borrowed[book] = 1; 50 | } else if (cmd == "RETURN") { 51 | returned[book] = 1; 52 | } 53 | } 54 | return 0; 55 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 400 - Unix ls.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 400 - Unix ls 3 | * Author: sjsakib 4 | * 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | string lst[1010]; 11 | 12 | int n,max_len; 13 | 14 | void read() { 15 | char buff[62]; 16 | max_len = 0; 17 | for (int i = 0; i < n; i++) { 18 | scanf("%s\n", buff); 19 | lst[i] = string(buff); 20 | max_len = max(max_len, (int) lst[i].length()); 21 | } 22 | sort(lst, lst + n); 23 | } 24 | 25 | void print() { 26 | int cols = 62 / (max_len + 2); 27 | int rows = (int) ceil(n / (float) cols); 28 | printf("------------------------------------------------------------\n"); 29 | for (int i = 0; i < rows; i++) { 30 | for (int j = 0; j < cols; j++) { 31 | int pos = j*rows + i; 32 | int len = ((j == cols-1)?max_len:max_len+2); 33 | if(pos < n) printf("%-*s", len, lst[pos].c_str()); 34 | } 35 | printf("\n"); 36 | } 37 | } 38 | 39 | int main() { 40 | while(scanf("%d", &n) != EOF) { 41 | read(); 42 | print(); 43 | } 44 | } -------------------------------------------------------------------------------- /STL/Exercises/UVa 511 - Do You Know the Way to San Jose?.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 511 - Do You Know the Way to San Jose? 3 | * Author: sjsakib 4 | * Approach: Naive Implementation 5 | **/ 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | using namespace std; 13 | 14 | double eps = 1e-6; 15 | 16 | struct Map { 17 | string name; 18 | double x1,x2,y1,y2; 19 | double ratio; 20 | 21 | Map(string name_, double x1_, double y1_, double x2_, double y2_) { 22 | name = name_; 23 | x1 = max(x1_,x2_); 24 | y1 = max(y1_,y2_); 25 | x2 = min(x1_,x2_); 26 | y2 = min(y1_,y2_); 27 | 28 | ratio = 0.75 - (y1-y2)/(x1-x2); 29 | } 30 | bool operator<(Map rhs) { 31 | return (x1-x2)*(y1-y2) > (rhs.x1-rhs.x2)*(rhs.y1-rhs.y2); 32 | } 33 | }; 34 | 35 | struct Location { 36 | string name; 37 | double x,y; 38 | vector maps; 39 | 40 | Location(string name_, double x_, double y_) { 41 | name = name_; 42 | x = x_; 43 | y = y_; 44 | } 45 | 46 | bool in(Map& mp) { 47 | return x <= mp.x1+eps && x+eps >= mp.x2 && y <= mp.y1+eps && y+eps >= mp.y2; 48 | } 49 | double dist(Map& mp) { 50 | double cx = (mp.x1-mp.x2)/2; 51 | double cy = (mp.y1-mp.y2)/2; 52 | return (x-cx)*(x-cx) + (y-cy)*(y-cy); 53 | } 54 | double cdist(Map& mp) { 55 | return (x-mp.x2)*(x-mp.x2) + (y-mp.y2)*(y-mp.y2); 56 | } 57 | }; 58 | 59 | 60 | vector maps; 61 | vector locations; 62 | 63 | void set_maps() { 64 | for(auto& loc: locations) { 65 | int mpidx = -1; 66 | double dist, ratio, cdist, xcord; 67 | for(int i = 0; i < (int) maps.size(); i++) { 68 | if(loc.in(maps[i])) { 69 | if(mpidx == -1) { 70 | mpidx = i; 71 | dist = loc.dist(maps[i]); 72 | ratio = maps[i].ratio; 73 | cdist = loc.cdist(maps[i]); 74 | xcord = maps[i].x1 - maps[i].x2; 75 | continue; 76 | } 77 | if(maps[mpidx] < maps[i]) { // '<' works as '>'; path to hell 78 | loc.maps.push_back(mpidx); 79 | mpidx = i; 80 | continue; 81 | } 82 | if(loc.dist(maps[i])+eps < dist) { 83 | loc.maps.push_back(mpidx); 84 | mpidx = -1; 85 | continue; 86 | } 87 | if(abs(loc.dist(maps[i]) - dist) < eps && maps[i].ratio+eps < ratio) { 88 | loc.maps.push_back(mpidx); 89 | mpidx = -1; 90 | continue; 91 | } 92 | if(abs(maps[i].ratio - ratio) < eps && loc.cdist(maps[i])+eps < cdist) { 93 | loc.maps.push_back(mpidx); 94 | mpidx = -1; 95 | continue; 96 | } 97 | if(abs(loc.cdist(maps[i]) - cdist) < eps && xcord > (maps[i].x1 - maps[i].x2)) { 98 | loc.maps.push_back(mpidx); 99 | mpidx = -1; 100 | } 101 | } 102 | } 103 | if(mpidx != -1) loc.maps.push_back(mpidx); 104 | } 105 | } 106 | 107 | void print_lev(string name, int lev) { 108 | cout<= lev) { 112 | cout<<"using "<>cmd; 128 | string name; 129 | double x1,x2,y1,y2; 130 | while ((cin>>name) && name != "LOCATIONS") { 131 | cin>>x1>>y1>>x2>>y2; 132 | maps.push_back(Map(name, x1, y1, x2, y2)); 133 | } 134 | sort(maps.begin(), maps.end()); 135 | while ((cin>>name) && name != "REQUESTS") { 136 | cin>>x1>>y1; 137 | locations.push_back(Location(name, x1, y1)); 138 | } 139 | set_maps(); 140 | int lev; 141 | while ((cin>>name) && name != "END") { 142 | cin>>lev; 143 | print_lev(name, lev); 144 | } 145 | return 0; 146 | } 147 | -------------------------------------------------------------------------------- /STL/Exercises/UVa 822 - Queue and A.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Problem: UVa 822 - Queue and A 3 | * Author: sjsakib 4 | * Approach: Bruteforce 5 | **/ 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | struct topic { 12 | int id; 13 | int reqs; // Total number of requests 14 | int next; // When next request will come 15 | int time; // Time required to handle a request 16 | int gap; // Gap between requests 17 | int active; // Active tilL 18 | int waiting; // Number of requests waiting to be handled 19 | 20 | topic(int id_, int num_reqs_, int start_, int time_, int gap_) { 21 | id = id_; 22 | reqs = num_reqs_; 23 | next = start_; 24 | time = time_; 25 | gap = gap_; 26 | waiting = 0; 27 | active = 0; 28 | } 29 | 30 | }; 31 | 32 | struct staff { 33 | int id; 34 | vector topics; 35 | int busy; // Busy till 36 | 37 | staff(int id_) { 38 | id = id_; 39 | busy = 0; 40 | } 41 | }; 42 | vector topics; 43 | vector staffs; 44 | 45 | void assign(topic& tp, int t, bool is_wait) { 46 | int idx = -1; 47 | int pr = 100; // priority 48 | for (int i = 0; i < (int) staffs.size(); i++) { 49 | if(staffs[i].busy > t) continue; 50 | int tpidx = -1; 51 | for (int k = 0; k < (int) staffs[i].topics.size(); k++) { 52 | if (staffs[i].topics[k] == tp.id) { 53 | tpidx = k; 54 | break; 55 | } 56 | } 57 | if(tpidx == -1) continue; 58 | if (tpidx < pr) { 59 | pr = tpidx; 60 | idx = i; 61 | } else if (tpidx == pr) { 62 | if (staffs[i].busy < staffs[idx].busy) { 63 | idx = i; 64 | } 65 | } 66 | } 67 | if(!is_wait) { 68 | tp.next += tp.gap; 69 | tp.reqs--; 70 | } 71 | if(idx == -1 && !is_wait) { 72 | tp.waiting++; 73 | } 74 | if (idx != -1) { 75 | staffs[idx].busy = t + tp.time; 76 | tp.active = t + tp.time; 77 | if(is_wait) tp.waiting--; 78 | } 79 | } 80 | 81 | int main() { 82 | int n; 83 | int id,reqs,start,time,gap,x,tid; 84 | int sen = 1; 85 | while (scanf("%d", &n) && n != 0) { 86 | for (int i = 0; i < n; i++) { 87 | scanf("%d %d %d %d %d", &id, &reqs, &start, &time, &gap); 88 | topics.push_back(topic(id, reqs, start, time, gap)); 89 | } 90 | scanf("%d", &n); 91 | for (int i = 0; i < n; i++) { 92 | scanf("%d %d", &id, &x); 93 | staffs.push_back(staff(id)); 94 | for (int j = 0; j < x; j++) { 95 | scanf("%d", &tid); 96 | staffs.back().topics.push_back(tid); 97 | } 98 | } 99 | int t = 0; 100 | while (1) { 101 | int active = 0; 102 | for (auto &tp: topics) { 103 | if(tp.waiting) { 104 | for (int k = 0; k < tp.waiting; k++) { 105 | assign(tp, t, 1); 106 | } 107 | } 108 | if (tp.next == t && tp.reqs > 0) { 109 | assign(tp, t, 0); 110 | } 111 | if (tp.reqs > 0 || tp.active > t) { 112 | active++; 113 | } 114 | } 115 | if(!active) { 116 | printf("Scenario %d: All requests are serviced within %d minutes.\n", sen++, t); 117 | staffs.clear(); 118 | topics.clear(); 119 | break; 120 | } 121 | t++; 122 | } 123 | } 124 | return 0; 125 | } -------------------------------------------------------------------------------- /STL/Timus 1209 - 1, 10, 100, 1000....py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem: Timus 1209 - 1, 10, 100, 1000... 3 | Author: sjsakib 4 | Approach: Math 5 | """ 6 | from math import sqrt 7 | from sys import stdin 8 | 9 | 10 | def f(s): 11 | return int((sqrt(1 + 8*s) - 1)/2) 12 | 13 | 14 | def ans(k): 15 | k = int(k) 16 | n = f(k) 17 | if k == 1 or k - (n*(n+1))//2 == 1: 18 | return '1' 19 | return '0' 20 | 21 | 22 | n = input() 23 | 24 | print(' '.join(map(ans, stdin.read().split()))) 25 | -------------------------------------------------------------------------------- /STL/UVA 136 - Ugly Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | #ifndef ONLINE_JUDGE 7 | freopen("in.txt","r",stdin); 8 | freopen("out.txt","w",stdout); 9 | #endif 10 | 11 | ios::sync_with_stdio(false); 12 | cin.tie(0);cout.tie(0); 13 | 14 | setnumber; 15 | 16 | number.insert(1); 17 | int cnt(1); 18 | long i; 19 | while(cnt<=1500){ 20 | cnt++; 21 | i = *number.begin(); 22 | // cout< 7 | 8 | using namespace std; 9 | 10 | vector v[28]; 11 | int n, a, b; 12 | 13 | void clearUp(int idx, int pos) { 14 | while(v[idx].size() != pos+1) { 15 | if(v[idx].back() != idx) v[v[idx].back()].push_back(v[idx].back()); 16 | v[idx].pop_back(); 17 | } 18 | } 19 | 20 | void moveOnto(int aIdx, int aPos, int bIdx, int bPos) { 21 | clearUp(aIdx, aPos); 22 | clearUp(bIdx, bPos); 23 | v[aIdx].pop_back(); 24 | v[bIdx].push_back(a); 25 | } 26 | 27 | void moveOver(int aIdx, int aPos, int bIdx, int bPos) { 28 | clearUp(aIdx, aPos); 29 | v[aIdx].pop_back(); 30 | v[bIdx].push_back(a); 31 | } 32 | 33 | void pileOnto(int aIdx, int aPos, int bIdx, int bPos) { 34 | clearUp(bIdx, bPos); 35 | for (int i = aPos; i < v[aIdx].size(); i++) { 36 | v[bIdx].push_back(v[aIdx][i]); 37 | } 38 | while (v[aIdx].size() != aPos) { 39 | v[aIdx].pop_back(); 40 | } 41 | } 42 | 43 | void pileOver(int aIdx, int aPos, int bIdx, int bPos) { 44 | for (int i = aPos; i < v[aIdx].size(); i++) { 45 | v[bIdx].push_back(v[aIdx][i]); 46 | } 47 | while (v[aIdx].size() != aPos) { 48 | v[aIdx].pop_back(); 49 | } 50 | } 51 | 52 | int find(int x, int &pos) { 53 | for (int i = 0; i < n; i++) { 54 | for (int j = 0; j < v[i].size(); j++) { 55 | if(v[i][j] == x) { 56 | pos = j; 57 | return i; 58 | } 59 | } 60 | } 61 | pos = -1; 62 | return -1; 63 | } 64 | 65 | void printStatus() { 66 | for (int i = 0; i < n; i++) { 67 | printf("%d:", i); 68 | if(v[i].size()) printf(" "); 69 | for (int j = 0; j < v[i].size(); j++) { 70 | printf("%d", v[i][j]); 71 | if(j != v[i].size()-1) printf(" "); 72 | } 73 | printf("\n"); 74 | } 75 | } 76 | 77 | int main() { 78 | scanf("%d\n", &n); 79 | for (int i = 0; i < n; i++) { 80 | v[i].push_back(i); 81 | } 82 | char x[5],y[5]; 83 | while(1) { 84 | scanf("%s %d %s %d\n", x, &a, y, &b); 85 | if (strcmp(x, "quit") == 0) break; 86 | int aPos, bPos; 87 | int aIdx = find(a, aPos); 88 | int bIdx = find(b, bPos); 89 | 90 | if(a == b || aIdx == bIdx) continue; 91 | 92 | if(strcmp(x, "move") == 0) { 93 | if(strcmp(y, "onto") == 0) { 94 | moveOnto(aIdx, aPos, bIdx, bPos); 95 | } else { 96 | moveOver(aIdx, aPos, bIdx, bPos); 97 | } 98 | } else if(strcmp(x, "pile") == 0) { 99 | if(strcmp(y, "onto") == 0) { 100 | pileOnto(aIdx, aPos, bIdx, bPos); 101 | } else { 102 | pileOver(aIdx, aPos, bIdx, bPos); 103 | } 104 | } 105 | //printStatus(); 106 | } 107 | printStatus(); 108 | return 0; 109 | } -------------------------------------------------------------------------------- /STL/UVa 10815 - Andy's First Dictionary.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: UVa 10815 Andy's First Dictionary 3 | * author: sjsakib 4 | **/ 5 | #include 6 | 7 | using namespace std; 8 | 9 | void clean(char line[]) { 10 | int i = 0; 11 | while(line[i] != '\0') { 12 | line[i] = tolower(line[i]); 13 | if(!isalpha(line[i])) line[i] = ' '; 14 | i++; 15 | } 16 | } 17 | 18 | 19 | int main() { 20 | ios::sync_with_stdio(false); 21 | char line[210]; 22 | string w; 23 | set dict; 24 | while(gets(line)) { 25 | clean(line); 26 | istringstream iS(line); 27 | while(iS>>w) { 28 | dict.insert(w); 29 | } 30 | } 31 | for(auto w: dict) { 32 | cout< 7 | 8 | using namespace std; 9 | 10 | set operator|(set s1, set s2) { 11 | set ret; 12 | set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), ::inserter(ret,ret.begin())); 13 | return ret; 14 | } 15 | 16 | set operator&(set s1, set s2) { 17 | set ret; 18 | set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), ::inserter(ret,ret.begin())); 19 | return ret; 20 | } 21 | 22 | 23 | map > mp; 24 | map, int> rmp; 25 | stack stc; 26 | 27 | int idCount; 28 | 29 | void push() { 30 | if(idCount == 0) { 31 | set s; 32 | mp[0] = s; 33 | rmp[s] = 0; 34 | } 35 | stc.push(0); 36 | } 37 | 38 | void dup() { 39 | stc.push(stc.top()); 40 | } 41 | 42 | void exec(int op) { 43 | int id1 = stc.top(); 44 | stc.pop(); 45 | int id2 = stc.top(); 46 | stc.pop(); 47 | set s1 = mp[id1]; 48 | set s2 = mp[id2]; 49 | set s; 50 | if (op == 1) s = s1 | s2; 51 | else if (op == 2) s = s1 & s2; 52 | else { 53 | s2.insert(id1); 54 | s = s2; 55 | } 56 | if(rmp.find(s) == rmp.end()) { 57 | stc.push(++idCount); 58 | mp[idCount] = s; 59 | rmp[s] = idCount; 60 | } else { 61 | stc.push(rmp[s]); 62 | } 63 | } 64 | 65 | int main() { 66 | ios::sync_with_stdio(false); 67 | int n,k; 68 | string cmd; 69 | cin>>n; 70 | for (int i = 0; i < n; i++) { 71 | cin>>k; 72 | for (int j = 0; j < k; j++) { 73 | cin>>cmd; 74 | if(cmd == "PUSH") push(); 75 | else if(cmd == "DUP") dup(); 76 | else if(cmd == "UNION") exec(1); 77 | else if(cmd == "INTERSECT") exec(2); 78 | else exec(3); 79 | cout< 7 | #include 8 | 9 | using namespace std; 10 | 11 | struct Job { 12 | int i; 13 | int p; 14 | 15 | Job(int i_, int p_) { 16 | i = i_; 17 | p = p_; 18 | } 19 | }; 20 | 21 | bool operator<(Job a, Job b) { 22 | return a.p < b.p; 23 | } 24 | 25 | priority_queue pq; 26 | queue q; 27 | 28 | int main() { 29 | int t,n,m,p; 30 | scanf("%d", &t); 31 | for (int i = 0; i < t; i++) { 32 | scanf("%d %d", &n, &m); 33 | for (int k = 0; k < n; k++) { 34 | scanf("%d", &p); 35 | Job j(k, p); 36 | q.push(j); 37 | pq.push(j); 38 | } 39 | int t = 0; 40 | while (1) { 41 | if(q.front().p == pq.top().p) { 42 | if(q.front().i == m) break; 43 | q.pop(); 44 | pq.pop(); 45 | t++; 46 | 47 | } else { 48 | q.push(q.front()); 49 | q.pop(); 50 | } 51 | } 52 | printf("%d\n", t+1); 53 | q = queue(); 54 | pq = priority_queue(); 55 | } 56 | return 0; 57 | } -------------------------------------------------------------------------------- /STL/UVa 156 - Anagrams.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * problem: UVa 156 Anagrams 3 | * author: sjsakib 4 | * approach: 5 | **/ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | ios::sync_with_stdio(false); 12 | map count; 13 | string w; 14 | vector words; 15 | while (cin>>w) { 16 | if(w == "#") break; 17 | words.push_back(w); 18 | transform(w.begin(), w.end(), w.begin(), ::tolower); 19 | sort(w.begin(), w.end()); 20 | count[w]++; 21 | } 22 | vector ans; 23 | for(auto word: words) { 24 | string w = word; 25 | transform(w.begin(), w.end(), w.begin(), ::tolower); 26 | sort(w.begin(), w.end()); 27 | if(count[w] == 1) { 28 | ans.push_back(word); 29 | } 30 | } 31 | sort(ans.begin(), ans.end()); 32 | for(auto w: ans) { 33 | cout< 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | typedef pair ii; 6 | 7 | int main(int argc, char const *argv[]) { 8 | int n, co = 0; 9 | while(cin >> n && n) { 10 | queue teamQ[n+1], mainQ; 11 | map teamNo; 12 | for(int i=0; i>m; 14 | while(m--) { 15 | cin>>num; 16 | teamNo[num] = i; 17 | } 18 | } 19 | cout << "Scenario #" << ++co << endl; 20 | string cmd; 21 | while(cin >> cmd) { 22 | if(cmd[0] == 'S') break; 23 | else if(cmd[0] == 'E') { 24 | int id; cin >> id; 25 | int tm = teamNo[id]; 26 | teamQ[tm].push(id); 27 | if(teamQ[tm].size() == 1) 28 | mainQ.push(tm); 29 | } else { 30 | int tm = mainQ.front(); 31 | cout << teamQ[tm].front() << endl; 32 | teamQ[tm].pop(); 33 | if(!teamQ[tm].size()) 34 | mainQ.pop(); 35 | } 36 | } cout << endl; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /UVa 10474 Where is the Marble?.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main(){ 6 | #ifndef ONLINE_JUDGE 7 | freopen("in.txt","r",stdin); 8 | freopen("out.txt","w",stdout); 9 | #endif 10 | 11 | ios::sync_with_stdio(false); 12 | cin.tie(0);cout.tie(0); 13 | 14 | int n,q,t,tc(1); 15 | while(cin>>n>>q and n and q){ 16 | vectorlst; 17 | 18 | cout<<"CASE# "<>t, lst.push_back(t); 22 | 23 | sort(lst.begin(), lst.end()); 24 | 25 | while(q--){ 26 | 27 | cin>>t; 28 | 29 | int pos = find(lst.begin(), lst.end(),t) - lst.begin() +1; 30 | 31 | pos<=n?cout<