[
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Explanations/Cow and Fields Explanation.txt",
    "content": "Let S[i] denote the distance of vertex i from source\n\nLet T[i] denote the distance of vertex i from the target\n\nWe can determine both with a BFS.\n\n-----\n\nvoid bfs(int source, vector <int> &distance)\n{\n    queue <int> Q;\n\n    Q.push(source);\n    distance[source] = 0;\n\n    while(!Q.empty())\n    {\n        int v = Q.front();\n        Q.pop();\n\n        for(int i = 0; i < graph[v].size(); i++)\n        {\n            int child = graph[v][i];\n\n            if(distance[child] >= oo)\n            {\n                distance[child] = distance[v] + 1;\n\n                Q.push(child);\n\n            }\n        }\n    }\n}\n\n-----\n\nWhen we draw an edge between (x, y) the distance between (1, n) becomes\n\nS[x] + 1 + T[y]\n\nWe will draw an edge so as to maximise this distance since we want to maximise the length of the shortest path.\n\nUltimately the shortest path will not be more than S[n]\n\nNote that we can never increase the length of the shortest path.\n\nSo we will choose the edge which maximises the length (S[x] + 1 + T[y])\n\nWe can sort the vertices according to S[x] - T[x]\n\nSince (S[x] + T[y] < S[y] + T[x]). As we visit the vertices in order, for every i, we will take the prefix maximum of T[i]\n\n-----\n\nint main()\n{\n    int no_of_vertices, no_of_edges, no_of_special_vertices;\n    cin >> no_of_vertices >> no_of_edges >> no_of_special_vertices;\n\n    vector <int> special_vertices(no_of_special_vertices);\n    for(int i = 0; i < no_of_special_vertices; i++)\n    {\n        cin >> special_vertices[i];\n    }\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n\n    vector <int> distance_1(no_of_vertices + 1, oo);\n    bfs(1, distance_1);\n\n    vector <int> distance_n(no_of_vertices + 1, oo);\n    bfs(no_of_vertices, distance_n);\n\n    sort(special_vertices.begin(), special_vertices.end(), [&] (int a, int b)\n    {\n        return (distance_1[a] - distance_n[a] < distance_1[b] - distance_n[b]);\n    });\n\n    int maximum_distance = 0;\n    int furthest_1 = distance_1[special_vertices[0]];\n\n    for(int i = 1; i < no_of_special_vertices; i++)\n    {\n        maximum_distance = max(maximum_distance,\n                               furthest_1 + distance_n[special_vertices[i]] + 1);\n\n        furthest_1 = max(furthest_1, distance_1[special_vertices[i]]);\n    }\n\n    maximum_distance = min(maximum_distance, distance_n[1]);\n\n    cout << maximum_distance << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Explanations/Cow and Friend Explanation.txt",
    "content": "First of all, if x exists in the original array, then the answer is 1.\n\nIf there is at least one element A[i] such that is 2A[i]>= x,\nthen we can reach in 2 moves by making a triangle.\n\nIf even the greatest element x 2 < x, then we will keep on making linear steps\nof length A[i] till x is within A[i]'s range.\n\nThen if x = A[i], we will take a linear step.\n\nOtherwise, we will make a triangle.\n\nIt is important to check if x [0, 2A[i]] as 2A[i] is the furthest we can get using A[i]\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    long long distance;\n    cin >> no_of_elements >> distance;\n\n    vector <long long> A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    if(binary_search(all(A), distance))\n    {\n        cout << \"1\\n\";\n\n        return;\n    }\n\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        if(A[i] + A[i] >= distance)\n        {\n            cout << \"2\\n\";\n\n            return;\n        }\n    }\n\n    long long steps = distance/A[no_of_elements - 1] + (distance%A[no_of_elements - 1] != 0);\n\n    cout << steps << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Explanations/Cow and Haybales Explanation.txt",
    "content": "We can simulate the process.\n\nOne by one, we will carry the i-th element over to A[2] and then transfer it to A[1]\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, no_of_days;\n    cin >> no_of_elements >> no_of_days;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    for(int i = 2; i <= no_of_elements && no_of_days > 0; i++)\n    {\n        while(A[i] > 0 && no_of_days >= (i - 1))\n        {\n            A[i]--;\n\n            A[1]++;\n\n            no_of_days -= (i - 1);\n        }\n    }\n\n    cout << A[1] << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Explanations/Cow and Message Explanation.txt",
    "content": "Observation - The number of good strings will be equal to the number of pairs\nand single letters.\n\nProof -\n\nIt is clear that every single letter is good.\n\nEvery good string of length > 1, has 2 letters at the beginning\n\nSo, there is a bijection in between the starting pair of any good string and the rest of the string.\n\nWhy cannot the same argument be used to reduce 2 -> 1 ?\n\nIt is because of the property of arithmetic series.\n\nThe difference has to form an arithmetic progression so the first pair uniquely determine the rest of the string.\n\nWhereas, when we look at pairs, they do not correspond to single digits because a single digit by itself\ndoes not have any series and can be added to any digit through the entire array.\n\n-----\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <long long> frequency(NO_OF_ALPHABETS, 0);\n    map <string, long long> pair_frequency;\n\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            char second_letter = (char)('a' + alpha);\n\n            string current_pair;\n\n            current_pair += S[i];\n\n            current_pair += second_letter;\n\n            pair_frequency[current_pair] += frequency[alpha];\n        }\n\n        frequency[S[i] - 'a']++;\n    }\n\n    long long answer = 0;\n    for(auto it = pair_frequency.begin(); it != pair_frequency.end(); it++)\n    {\n        answer = max(answer, it->second);\n    }\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        answer = max(answer, frequency[alpha]);\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Explanations/Cows and Treats Explanation.txt",
    "content": "1. At most 2 cows can come and at most 1 from each side, one from the left, one from the right.\n\n2. Suppose I know that cows {1, 3, 5} are there in the left set.\nThey can only be placed in 1 combination and cannot be changed. Because once one of the cows come, they will block the other cows.\n\n3. We need to iterate over all possibilities. We can do this by iterating on the grass where the left border ends. This will enable us to do the counting. We will see for each sweetness, the possible endings of cows of that sweetness both on the left and right side\n\n-----\n\nWe will count the number of cows that can go inside the left border.\nLet it be L\n\nWe will count the number of cows that can go inside the right border.\nLet it be R.\n\nThen the number of pairs will be L*R - min(L, R)\n\nThe reason is that the same cow cannot go both on the left and on the right.\n\nSo, whichever is minimum among (L, R), those are cows which go on both sides and they can only go in one.\n\n-----\n\nint main()\n{\n    int no_of_grass, no_of_cows;\n    cin >> no_of_grass >> no_of_cows;\n\n    vector <int> sweetness(no_of_grass + 1);\n    for(int i = 1; i <= no_of_grass; i++)\n    {\n        cin >> sweetness[i];\n    }\n\n    vector <vector <int> > cows(no_of_grass + 1);\n    for(int i = 1; i <= no_of_cows; i++)\n    {\n        int sweet, hunger;\n        cin >> sweet >> hunger;\n\n        cows[sweet].push_back(hunger);\n    }\n\n    for(int i = 1; i <= no_of_grass; i++)\n    {\n        sort(cows[i].begin(), cows[i].end());\n    }\n\n    const int MOD = 1e9 + 7;\n    int happy_cows = 0;\n    long long no_of_ways = 1;\n\n    for(int cut = 0; cut <= no_of_grass; cut++)\n    {\n        vector <int> left(no_of_grass + 1, 0);\n        vector <int> right(no_of_grass + 1, 0);\n        for(int i = 1; i <= cut; i++)\n        {\n            left[sweetness[i]]++;\n        }\n\n        for(int i = cut + 1; i <= no_of_grass; i++)\n        {\n            right[sweetness[i]]++;\n        }\n\n        int left_ending = (cut == 0 ? -1 : sweetness[cut]);\n\n        int happy_cows_here = 0;\n        long long no_of_ways_here = 1;\n\n        for(int i = 1; i <= no_of_grass; i++)\n        {\n            if(i == left_ending)\n            {\n                if(binary_search(cows[i].begin(), cows[i].end(), left[i]))\n                {\n                    happy_cows_here++;\n                }\n                else\n                {\n                    happy_cows_here = 0;\n                    break;\n                }\n\n                int right_choices = 0;\n\n                for(int j = 0; j < cows[i].size(); j++)\n                {\n                    if(cows[i][j] != left[i] && cows[i][j] <= right[i])\n                    {\n                        right_choices++;\n                    }\n                }\n\n                if(right_choices >= 1)\n                {\n                    happy_cows_here++;\n                    no_of_ways_here *= right_choices;\n                }\n            }\n            else\n            {\n                int left_choices = 0, right_choices = 0;\n\n                for(int j = 0; j < cows[i].size(); j++)\n                {\n                    if(cows[i][j] <= left[i])\n                    {\n                        left_choices++;\n                    }\n                    if(cows[i][j] <= right[i])\n                    {\n                        right_choices++;\n                    }\n                }\n\n                int no_of_pairs = (left_choices*right_choices) - min(left_choices, right_choices);\n\n                if(no_of_pairs > 0)\n                {\n                    happy_cows_here += 2;\n\n                    no_of_ways_here *= no_of_pairs;\n                }\n                else if(left_choices > 0 || right_choices > 0)\n                {\n                    happy_cows_here++;\n\n                    no_of_ways_here *= (left_choices + right_choices);\n                }\n            }\n\n            no_of_ways_here %= MOD;\n        }\n\n        if(happy_cows_here > happy_cows)\n        {\n            happy_cows = happy_cows_here;\n            no_of_ways = no_of_ways_here;\n        }\n        else if(happy_cows_here == happy_cows && happy_cows_here > 0)\n        {\n            no_of_ways += no_of_ways_here;\n\n            no_of_ways %= MOD;\n        }\n    }\n\n    cout << happy_cows << \" \" << no_of_ways << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Programs/Cow and Fields.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5, oo = 1e9 + 9;\nvector <int> graph[MAX_N];\n\nvoid bfs(int source, vector <int> &distance)\n{\n    queue <int> Q;\n    \n    Q.push(source);\n    distance[source] = 0;\n    \n    while(!Q.empty())\n    {\n        int v = Q.front();\n        Q.pop();\n        \n        for(int i = 0; i < graph[v].size(); i++)\n        {\n            int child = graph[v][i];\n            \n            if(distance[child] >= oo)\n            {\n                distance[child] = distance[v] + 1;\n                \n                Q.push(child);\n                \n                //cout << \"Child = \" << child << \" Distance = \" << distance[child] << \"\\n\";\n            }\n        }\n    }\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges, no_of_special_vertices;\n    cin >> no_of_vertices >> no_of_edges >> no_of_special_vertices;\n    \n    vector <int> special_vertices(no_of_special_vertices);\n    for(int i = 0; i < no_of_special_vertices; i++)\n    {\n        cin >> special_vertices[i];\n    }\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n    \n    vector <int> distance_1(no_of_vertices + 1, oo);\n    bfs(1, distance_1);\n    \n    vector <int> distance_n(no_of_vertices + 1, oo);\n    bfs(no_of_vertices, distance_n);\n    \n    sort(special_vertices.begin(), special_vertices.end(), [&] (int a, int b)\n    {\n        return (distance_1[a] - distance_n[a] < distance_1[b] - distance_n[b]);\n    });\n    \n    int maximum_distance = 0;\n    int furthest_1 = distance_1[special_vertices[0]];\n    \n    for(int i = 1; i < no_of_special_vertices; i++)\n    {\n        maximum_distance = max(maximum_distance,\n                               furthest_1 + distance_n[special_vertices[i]] + 1);\n        \n        //cout << special_vertices[i] << \"\\n\";\n        //cout << \"Distance n = \" << distance_n[special_vertices[i]] << \" Furthest 1 = \" << furthest_1 << \"\\n\";\n        //cout << \"Maximum Distance = \" << maximum_distance << \"\\n\";\n        furthest_1 = max(furthest_1, distance_1[special_vertices[i]]);\n    }\n    \n    maximum_distance = min(maximum_distance, distance_n[1]);\n    \n    cout << maximum_distance << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Programs/Cow and Haybales.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, no_of_days;\n    cin >> no_of_elements >> no_of_days;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n    \n    for(int i = 2; i <= no_of_elements && no_of_days > 0; i++)\n    {\n        while(A[i] > 0 && no_of_days >= (i - 1))\n        {\n            A[i]--;\n            \n            A[1]++;\n            \n            no_of_days -= (i - 1);\n        }\n    }\n    \n    cout << A[1] << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Programs/Cow and Message.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint main()\n{\n    string S;\n    cin >> S;\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <long long> frequency(NO_OF_ALPHABETS, 0);\n    map <string, long long> pair_frequency;\n    \n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            char second_letter = (char)('a' + alpha);\n            \n            string current_pair;\n            \n            current_pair += S[i];\n            \n            current_pair += second_letter;\n            \n            pair_frequency[current_pair] += frequency[alpha];\n            \n            //cout << \"Pair = \" << current_pair << \" Second Frequency = \" << frequency[alpha] << \"\\n\";\n        }\n        \n        frequency[S[i] - 'a']++;\n    }\n    \n    long long answer = 0;\n    for(auto it = pair_frequency.begin(); it != pair_frequency.end(); it++)\n    {\n        answer = max(answer, it->second);\n    }\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        answer = max(answer, frequency[alpha]);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/621 Div 1 + 2/Programs/Cows and Treats.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_grass, no_of_cows;\n    cin >> no_of_grass >> no_of_cows;\n    \n    vector <int> sweetness(no_of_grass + 1);\n    for(int i = 1; i <= no_of_grass; i++)\n    {\n        cin >> sweetness[i];\n    }\n    \n    vector <vector <int> > cows(no_of_grass + 1);\n    for(int i = 1; i <= no_of_cows; i++)\n    {\n        int sweet, hunger;\n        cin >> sweet >> hunger;\n        \n        cows[sweet].push_back(hunger);\n    }\n    \n    for(int i = 1; i <= no_of_grass; i++)\n    {\n        sort(cows[i].begin(), cows[i].end());\n    }\n    \n    const int MOD = 1e9 + 7;\n    int happy_cows = 0;\n    long long no_of_ways = 1;\n    \n    for(int cut = 0; cut <= no_of_grass; cut++)\n    {\n        vector <int> left(no_of_grass + 1, 0);\n        vector <int> right(no_of_grass + 1, 0);\n        for(int i = 1; i <= cut; i++)\n        {\n            left[sweetness[i]]++;\n        }\n        \n        for(int i = cut + 1; i <= no_of_grass; i++)\n        {\n            right[sweetness[i]]++;\n        }\n        \n        int left_ending = (cut == 0 ? -1 : sweetness[cut]);\n        \n        int happy_cows_here = 0;\n        long long no_of_ways_here = 1;\n        \n        for(int i = 1; i <= no_of_grass; i++)\n        {\n            if(i == left_ending)\n            {\n                if(binary_search(cows[i].begin(), cows[i].end(), left[i]))\n                {\n                    happy_cows_here++;\n                }\n                else\n                {\n                    happy_cows_here = 0;\n                    break;\n                }\n                \n                int right_choices = 0;\n                \n                for(int j = 0; j < cows[i].size(); j++)\n                {\n                    if(cows[i][j] != left[i] && cows[i][j] <= right[i])\n                    {\n                        right_choices++;\n                    }\n                }\n                \n                if(right_choices >= 1)\n                {   //cout << \"Left = \" << left[i] << \"\\n\";\n                    //cout << \"Right Choices = \" << right_choices << \"\\n\";\n                    happy_cows_here++;\n                    no_of_ways_here *= right_choices;\n                }\n            }\n            else\n            {\n                int left_choices = 0, right_choices = 0;\n                \n                for(int j = 0; j < cows[i].size(); j++)\n                {\n                    if(cows[i][j] <= left[i])\n                    {\n                        left_choices++;\n                    }\n                    if(cows[i][j] <= right[i])\n                    {\n                        right_choices++;\n                    }\n                }\n                \n                //cout << \"Sweetness = \" << i << \" L = \" << left_choices << \" R = \" << right_choices << \"\\n\";\n                int no_of_pairs = (left_choices*right_choices) - min(left_choices, right_choices);\n                \n                if(no_of_pairs > 0)\n                {\n                    happy_cows_here += 2;\n                    \n                    no_of_ways_here *= no_of_pairs;\n                }\n                else if(left_choices > 0 || right_choices > 0)\n                {\n                    happy_cows_here++;\n                    \n                    no_of_ways_here *= (left_choices + right_choices);\n                    \n                    //cout << \"Reached and No of Ways = \" << no_of_ways_here << \"\\n\";\n                }\n            }\n            \n            no_of_ways_here %= MOD;\n        }\n        \n        if(happy_cows_here > happy_cows)\n        {\n            happy_cows = happy_cows_here;\n            no_of_ways = no_of_ways_here;\n        }\n        else if(happy_cows_here == happy_cows && happy_cows_here > 0)\n        {\n            no_of_ways += no_of_ways_here;\n            \n            no_of_ways %= MOD;\n        }\n        \n        //cout << \"Cut = \" << cut << \" Maximum = \" << happy_cows << \" No of ways = \" << no_of_ways << \"\\n\";\n    }\n    \n    cout << happy_cows << \" \" << no_of_ways << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Explanations/Bad Ugly Numbers Explanation.txt",
    "content": "Let us think of the divisibility rules of each number.\n\nA number is divisible by 5 only if the last digit if 5 or 0\n\nSo, we can make every digit except the last = 5\n\nWhat do we put as the last digit ?\n\nWe will put 4, as a number is divisible by 4 if it's last 2 digits are a multiple of 4\nand 54 is not a multiple of 4\n\n-----\n\nAnother solution is that we can have a string of (n - 1) 3s and 1 2.\n\nJust avoid putting 2 in the last position\n\nThis way the integer will not be even and the sum of digits = 2 (mod 3) so it will\nnot be a multiple of 3\n\n-----\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    if(n == 1)\n    {\n        cout << \"-1\\n\";\n\n        return;\n    }\n\n    for(int i = 1; i <= n - 1; i++)\n    {\n        cout << \"5\";\n    }\n\n    cout << \"4\\n\";\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Explanations/Maximums Explanation.txt",
    "content": "We will just simulate the process.\n\nWe will keep track of the maximum element in B[1, ... , i]\n\nA[i] = B[i] + prefix_max[i]\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    vector <int> A(no_of_elements + 1);\n    vector <int> prefix_max(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = B[i] + prefix_max[i];\n\n        prefix_max[i + 1] = max(prefix_max[i], A[i]);\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Explanations/Permutation Partitions Explanation.txt",
    "content": "Ultimately, the K greatest integers will be the best sum\nIt is always possible to make segments in such a way the K greatest integers are chosen.\n\nLet us re-write the array and put a 1 if A[i] is one of the K greatest integers and a 0\notherwise\n\nSuppose we have\n\n1 0 0 0 1\n\nNow, here are the possible divisions\n\n1 | 0 0 0 1\n1 0 | 0 0 1\n1 0 0 | 0 1\n1 0 0 0 | 1\n\nAll of these divisions satisfy the condition\n\n-----\n\nWe will keep track of all the indices of the k greatest integers.\n\nSuppose the consecutive indices are I[i] and I[i + 1], then the i-th barrier has\n\nI[i] - I[i - 1] ways and the first barrier is at A[1] and the last barrier is at A[n]\n\nWe will simply multiply the number of ways to place the other (K - 1) barriers\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long get_sum(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nint main()\n{\n    int no_of_elements, no_of_parts;\n    cin >> no_of_elements >> no_of_parts;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> indices;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] > no_of_elements - no_of_parts)\n        {\n            indices.push_back(i);\n        }\n    }\n\n    sort(all(indices));\n\n    long long best_sum = get_sum(no_of_elements) - get_sum(no_of_elements - no_of_parts);\n\n    long long no_of_ways = 1;\n\n    const long long MOD = 998244353;\n\n    for(int i = 1; i < no_of_parts; i++)\n    {\n        no_of_ways *= (indices[i] - indices[i - 1]);\n\n        no_of_ways %= MOD;\n    }\n\n    cout << best_sum << \" \" << no_of_ways << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Explanations/Prefix Suffix Palindrome (Easy Version) Explanation.txt",
    "content": "The optimal string consists of\n\n1. Some set of matching prefix and suffix of the string\n2. And then some palindrome that is either completely in the prefix or completely in the suffix.\n\n-----\n\nFirst, we will find out the maximum matching part of the prefix and the suffix.\n\nThen, we will calculate the longest palindrome in both the prefix and the suffix using a DP\n\n-----\n\npair <int, int> get_prefix_suffix(string S)\n{\n    for(int length = 1; length <= S.size(); length++)\n    {\n        for(int left = 0, right = left + length - 1; right < S.size(); left++, right++)\n        {\n            max_palindrome_in[left][right] = 0;\n\n            if(length == 1)\n            {\n                max_palindrome_in[left][right] = 1;\n                continue;\n            }\n\n            if(length == 2)\n            {\n                max_palindrome_in[left][right] = (S[left] == S[right] ? 2 : 0);\n                continue;\n            }\n\n            if(S[left] == S[right] && max_palindrome_in[left + 1][right - 1] != 0)\n            {\n                max_palindrome_in[left][right] = 2 + max_palindrome_in[left + 1][right - 1];\n            }\n        }\n    }\n\n    int best_prefix = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        best_prefix = max(best_prefix, max_palindrome_in[0][i]);\n    }\n\n    int best_suffix = 0;\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        best_suffix = max(best_suffix, max_palindrome_in[i][S.size() - 1]);\n    }\n\n    return make_pair(best_prefix, best_suffix);\n}\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    int matching_part = 0, prefix_palindrome = 0, suffix_palindrome = 0;\n    for(int i = 0, j = S.size() - 1; i < j; i++, j--)\n    {\n        if(S[i] == S[j])\n        {\n            matching_part++;\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    string remaining_S;\n    for(int i = matching_part; i < S.size() - matching_part; i++)\n    {\n        remaining_S += S[i];\n    }\n    //cout << \"Remaining = \" << remaining_S << \"\\n\";\n    pair <int, int> prefix_suffix = get_prefix_suffix(remaining_S);\n    prefix_palindrome = prefix_suffix.first;\n    suffix_palindrome = prefix_suffix.second;\n\n    if(prefix_palindrome > suffix_palindrome)\n    {\n        suffix_palindrome = 0;\n    }\n    else\n    {\n        prefix_palindrome = 0;\n    }\n\n    string answer;\n    for(int i = 0; i < matching_part; i++)\n    {\n        answer += S[i];\n    }\n\n    for(int i = 0; i < prefix_palindrome; i++)\n    {\n        answer += remaining_S[i];\n    }\n\n    for(int i = remaining_S.size() - suffix_palindrome; i < remaining_S.size(); i++)\n    {\n        answer += remaining_S[i];\n    }\n\n    for(int i = S.size() - matching_part; i < S.size(); i++)\n    {\n        answer += S[i];\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Programs/Bad Ugly Numbers.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    if(n == 1)\n    {\n        cout << \"-1\\n\";\n        \n        return;\n    }\n    \n    for(int i = 1; i <= n - 1; i++)\n    {\n        cout << \"5\";\n    }\n    \n    cout << \"4\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Programs/Maximums.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n    \n    vector <int> A(no_of_elements + 1);\n    vector <int> prefix_max(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = B[i] + prefix_max[i];\n        \n        prefix_max[i + 1] = max(prefix_max[i], A[i]);\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Programs/Permutation Partitions.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long get_sum(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nint main()\n{\n    int no_of_elements, no_of_parts;\n    cin >> no_of_elements >> no_of_parts;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> indices;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] > no_of_elements - no_of_parts)\n        {\n            indices.push_back(i);\n        }\n    }\n    \n    sort(all(indices));\n    \n    long long best_sum = get_sum(no_of_elements) - get_sum(no_of_elements - no_of_parts);\n    \n    long long no_of_ways = 1;\n    \n    const long long MOD = 998244353;\n    \n    for(int i = 1; i < no_of_parts; i++)\n    {   \n        no_of_ways *= (indices[i] - indices[i - 1]);\n        \n        no_of_ways %= MOD;\n    }\n    \n    cout << best_sum << \" \" << no_of_ways << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/CodeForces Global Round 7/Programs/Prefix Suffix Palindrome (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 5005;\nint max_palindrome_in[MAX_N][MAX_N];\n\npair <int, int> get_prefix_suffix(string S)\n{\n    for(int length = 1; length <= S.size(); length++)\n    {\n        for(int left = 0, right = left + length - 1; right < S.size(); left++, right++)\n        {\n            max_palindrome_in[left][right] = 0;\n            \n            if(length == 1)\n            {\n                max_palindrome_in[left][right] = 1;\n                continue;\n            }\n            \n            if(length == 2)\n            {\n                max_palindrome_in[left][right] = (S[left] == S[right] ? 2 : 0);\n                continue;\n            }\n            \n            if(S[left] == S[right] && max_palindrome_in[left + 1][right - 1] != 0)\n            {\n                max_palindrome_in[left][right] = 2 + max_palindrome_in[left + 1][right - 1];\n            }\n        }\n    }\n    \n    int best_prefix = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        best_prefix = max(best_prefix, max_palindrome_in[0][i]);\n    }\n    \n    int best_suffix = 0;\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        best_suffix = max(best_suffix, max_palindrome_in[i][S.size() - 1]);\n    }\n    \n    return make_pair(best_prefix, best_suffix);\n}\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    int matching_part = 0, prefix_palindrome = 0, suffix_palindrome = 0;\n    for(int i = 0, j = S.size() - 1; i < j; i++, j--)\n    {\n        if(S[i] == S[j])\n        {\n            matching_part++;\n        }\n        else\n        {\n            break;\n        }\n    }\n    \n    string remaining_S;\n    for(int i = matching_part; i < S.size() - matching_part; i++)\n    {\n        remaining_S += S[i];\n    }\n    //cout << \"Remaining = \" << remaining_S << \"\\n\";\n    pair <int, int> prefix_suffix = get_prefix_suffix(remaining_S);\n    prefix_palindrome = prefix_suffix.first;\n    suffix_palindrome = prefix_suffix.second;\n    \n    if(prefix_palindrome > suffix_palindrome)\n    {\n        suffix_palindrome = 0;\n    }\n    else\n    {\n        prefix_palindrome = 0;\n    }\n    \n    string answer;\n    for(int i = 0; i < matching_part; i++)\n    {\n        answer += S[i];\n    }\n    \n    for(int i = 0; i < prefix_palindrome; i++)\n    {\n        answer += remaining_S[i];\n    }\n    \n    for(int i = remaining_S.size() - suffix_palindrome; i < remaining_S.size(); i++)\n    {\n        answer += remaining_S[i];\n    }\n    \n    for(int i = S.size() - matching_part; i < S.size(); i++)\n    {\n        answer += S[i];\n    }\n   \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Explanations/Kuroni and Impossible Calculation Explanation.txt",
    "content": "If there are two integers A[i] and A[j] such that (A[i] = A[j] (mod m))\n\nThen (A[i] - A[j] = 0) (mod m)\n\nThere are only m possible remainders mod m = {0, 1, ... , m - 1}\n\nBy the Pigeonhole Principle, if there are more than m integers, at least 2 will have the same remainder.\n\nThis means, the answer will be 0 as 1 term (A[i] - A[j]) = 0 (mod m)\n\n-----\n\nIf there are less than m terms, then there are less than 1000 terms and we can\nfind the answer in O(n^2) time\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, modulo;\n    cin >> no_of_elements >> modulo;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    if(no_of_elements > modulo)\n    {\n        cout << \"0\\n\";\n\n        return 0;\n    }\n\n    long long product = 1;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = i + 1; j <= no_of_elements; j++)\n        {\n            product *= abs(A[i] - A[j]);\n\n            product %= modulo;\n        }\n    }\n\n    cout << product << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Explanations/Kuroni and Punishment Explanation.txt",
    "content": "Firstly, we will notice that the answer will never be more than N.\n\nWe can always use at most one move for each element and make them all even.\n\nSo, the answer is always <= N\n\n------\n\nIf the answer is < N, then at least one element is unchanged.\n\nThis means that the final gcd will be a divisor of one of the original no_of_elements\n\nThe number of distinct divisors will not be too many.\n\nUnfortunately, we do not have enough time to factorise all the integers.\n\nInstead, we will randomly pick around 100 of them and\ntake all the distinct prime factors of (A[i] - 1, A[i], A[i] + 1)\n\n------\n\n1. Ultimately we will change each element by some amount \n\n2. We can always just make every integer even. This means that the total change is at most N. \n\n3. If the total change <= N, then how many elements change by more than 1 ? \nAt most N/2 element change by more than 1 !\nIn other words, at least N/2 elements change by at most 1 \n\n4. That means there are at least N/2 elements for which the 'best' factor is a divisor is one of the divisors of (A[I] - 1, A[I], A[I] + 1) \n\n5. There are two types of elements - Those that change by at most 1 and those that change by more than 1. \nThere are at least N/2 of the former. The probability of a random element belonging to the first set is at least 1/2\nIf we sample 100 elements randomly, the probability is 1/2^{100}\n\n------\n\n#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nvoid factorise(set <long long> &F, long long n)\n{\n    if(n <= 1)\n    {\n        return;\n    }\n    //cout << \"N = \" << n << \"\\n\";\n\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            F.insert(i);\n\n            while(n%i == 0)\n            {\n                n /= i;\n            }\n        }\n    }\n\n    if(n > 1)\n    {\n        F.insert(n);\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int MAX_TRIES = 100;\n    random_shuffle(A.begin() + 1, A.end());\n\n    set <long long> factors;\n    for(int i = 1; i <= MAX_TRIES && i <= no_of_elements; i++)\n    {\n        factorise(factors, A[i]);\n        factorise(factors, A[i] - 1);\n        factorise(factors, A[i] + 1);\n    }\n\n    long long minimum_moves = no_of_elements;\n    for(auto it = factors.begin(); it != factors.end(); it++)\n    {\n        long long x = *it; //cout << \"X = \" << x << \"\\n\";\n\n        long long moves_here = 0;\n\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            long long moves_for_this_elements = (x - A[i]%x);\n\n            if(A[i] >= x)\n            {\n                moves_for_this_elements = min(moves_for_this_elements, A[i]%x);\n            }\n\n            moves_here += moves_for_this_elements; //cout << \"Moves = \" << moves_for_this_elements << \"\\n\";\n        }\n\n        minimum_moves = min(minimum_moves, moves_here);\n    }\n\n    cout << minimum_moves << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Explanations/Kuroni and Simple Strings Explanation.txt",
    "content": "It is best to be greedy.\n\nWe will remove '(' from the left.\n\nAnd for each '(', we will look for an ')', as much to the right as possible\n\nWe will do as many such 'sweeps' as we can\n\nWhile printing it, we will sort the indices in each 'sweep'\n\n-----\n\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    vector <vector <int> >indices;\n    vector <int> available(S.size() + 1, true);\n    for(int attempts = 1; attempts <= S.size(); attempts++)\n    {\n        vector <int> indices_here;\n\n        for(int front = 0, back = S.size() - 1; front < back;)\n        {\n            while(true)\n            {\n                if(front >= back)\n                {\n                    break;\n                }\n\n                if(!available[front] || S[front] != '(')\n                {\n                    front++;\n                    continue;\n                }\n\n                break;\n            }\n\n            if(front >= back || S[front] != '(')\n            {\n                break;\n            }\n\n            while(true)\n            {\n                if(back <= front)\n                {\n                    break;\n                }\n\n                if(!available[back] || S[back] != ')')\n                {\n                    back--;\n                    continue;\n                }\n\n                break;\n            }\n\n            if(back <= front || S[back] != ')')\n            {\n                break;\n            }\n\n            available[front] = false;\n            available[back] = false;\n\n            indices_here.push_back(front + 1);\n            indices_here.push_back(back + 1);\n        }\n\n        if(indices_here.size() > 0)\n        {\n            indices.push_back(indices_here);\n        }\n    }\n\n    cout << indices.size() << \"\\n\";\n    for(int i = 0; i < indices.size(); i++)\n    {\n        cout << indices[i].size() << \"\\n\";\n\n        sort(all(indices[i]));\n\n        for(int j = 0; j < indices[i].size(); j++)\n        {\n            cout << indices[i][j] << \" \";\n        }\n\n        cout << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Explanations/Kuroni and the Celebration Explanation.txt",
    "content": "Let us keep all the leaves in a vector.\n\nWe will pick out two leaves u and v and query their LCA\n\nIf LCA(u, v) = u or v, then u or v is the root of the tree\n\nIf LCA(u, v) = w and w =/= u and w =/= v, then we will erase all vertices\nin the path from (u, w) and all vertices in the path from (v, w)\n\nIn the process of doing this if w becomes a leaf, we will add it to our vector.\n\nIf at any point, the leaf vector has only 1 element, then it will be the root.\n\nIn every query, the size of the tree reduces by at least 2. So, the number of queries will not exceed (n/2)\n\n-----\n\n\nvector <set <int> > tree;\nset <int> leaves;\n\nvoid erase_till(int v, int child, int destination)\n{\n    if(leaves.find(v) != leaves.end())\n    {\n        leaves.erase(v);\n    }\n\n    for(auto it = tree[v].begin(); it != tree[v].end(); it++)\n    {\n        int parent = *it;\n\n        if(parent == child)\n        {\n            continue;\n        }\n\n        if(parent == destination)\n        {\n            tree[destination].erase(v);\n\n            continue;\n        }\n\n        if(tree[parent].size() > 0)\n        {\n            erase_till(parent, v, destination);\n        }\n    }\n\n    tree[v].clear();\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n\n    tree.resize(no_of_vertices + 1);\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].insert(v);\n        tree[v].insert(u);\n    }\n\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        if(tree[v].size() == 1)\n        {\n            leaves.insert(v);\n        }\n    }\n\n    int root = 0;\n    while(leaves.size() > 1)\n    {\n        int u = *(leaves.begin()); leaves.erase(u);\n        int v = *(leaves.begin()); leaves.erase(v);\n\n        int w;\n        cout << \"? \" << u << \" \" << v << \"\\n\" << flush;\n        cin >> w;\n\n        if(w == u || w == v)\n        {\n            root = w;\n            break;\n        }\n\n        erase_till(u, 0, w);\n        erase_till(v, 0, w);\n\n        if(tree[w].size() <= 1)\n        {\n            leaves.insert(w);\n        }\n    }\n\n    if(root == 0)\n    {\n        root = *(leaves.begin());\n    }\n\n    cout << \"! \" << root << \"\\n\" << flush;\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Explanations/Kuroni and the Gifts Explanation.txt",
    "content": "The elements of both A and B are distinct.\n\nThe smallest possible sum is A[1] + B[1]\n\nWe will sort the elements and (A[i] + B[i]) as each element.\n\nAs (A[i + 1] > A[i]) and (B[i + 1] > B[i]), this means\n\n(A[i + 1] + B[i + 1]) > (A[i] + B[i])\n\nThis helps us prove that the entire array is distinct \n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    sort(all(B));\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << B[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Programs/Kuroni and Impossible Calculation.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, modulo;\n    cin >> no_of_elements >> modulo;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    if(no_of_elements > modulo)\n    {\n        cout << \"0\\n\";\n        \n        return 0;\n    }\n    \n    long long product = 1;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = i + 1; j <= no_of_elements; j++)\n        {\n            product *= abs(A[i] - A[j]);\n            \n            product %= modulo;\n        }\n    }\n    \n    cout << product << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Programs/Kuroni and Punishment.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n#include <random>\n\nusing namespace std;\n\nvoid factorise(set <long long> &F, long long n)\n{\n    if(n <= 1)\n    {\n        return;\n    }\n    //cout << \"N = \" << n << \"\\n\";\n    \n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            F.insert(i);\n            \n            while(n%i == 0)\n            {\n                n /= i;\n            }\n        }\n    }\n    \n    if(n > 1)\n    {\n        F.insert(n);\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int MAX_TRIES = 100;\n    random_shuffle(A.begin() + 1, A.end());\n    \n    set <long long> factors;\n    for(int i = 1; i <= MAX_TRIES && i <= no_of_elements; i++)\n    {\n        factorise(factors, A[i]);\n        factorise(factors, A[i] - 1);\n        factorise(factors, A[i] + 1);\n    }\n    \n    long long minimum_moves = no_of_elements;\n    for(auto it = factors.begin(); it != factors.end(); it++)\n    {\n        long long x = *it; //cout << \"X = \" << x << \"\\n\";\n        \n        long long moves_here = 0;\n        \n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            long long moves_for_this_elements = (x - A[i]%x);\n            \n            if(A[i] >= x)\n            {\n                moves_for_this_elements = min(moves_for_this_elements, A[i]%x);\n            }\n            \n            moves_here += moves_for_this_elements; //cout << \"Moves = \" << moves_for_this_elements << \"\\n\";\n        }\n        \n        minimum_moves = min(minimum_moves, moves_here);\n    }\n    \n    cout << minimum_moves << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Programs/Kuroni and Simple Strings.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    string S;\n    cin >> S;\n    \n    vector <vector <int> >indices;\n    vector <int> available(S.size() + 1, true);\n    for(int attempts = 1; attempts <= S.size(); attempts++)\n    {\n        vector <int> indices_here;\n        \n        for(int front = 0, back = S.size() - 1; front < back;)\n        {\n            while(true)\n            {\n                if(front >= back)\n                {\n                    break;\n                }\n                \n                if(!available[front] || S[front] != '(')\n                {\n                    front++;\n                    continue;\n                }\n                \n                break;\n            }\n            \n            if(front >= back || S[front] != '(')\n            {\n                break;\n            }\n            \n            while(true)\n            {\n                if(back <= front)\n                {\n                    break;\n                }\n                \n                if(!available[back] || S[back] != ')')\n                {\n                    back--;\n                    continue;\n                }\n                \n                break;\n            }\n            \n            if(back <= front || S[back] != ')')\n            {\n                break;\n            }\n            \n            available[front] = false;\n            available[back] = false;\n            \n            indices_here.push_back(front + 1);\n            indices_here.push_back(back + 1);\n        }\n        \n        if(indices_here.size() > 0)\n        {\n            indices.push_back(indices_here);\n        }\n    }\n    \n    cout << indices.size() << \"\\n\";\n    for(int i = 0; i < indices.size(); i++)\n    {\n        cout << indices[i].size() << \"\\n\";\n        \n        sort(all(indices[i]));\n        \n        for(int j = 0; j < indices[i].size(); j++)\n        {\n            cout << indices[i][j] << \" \";\n        }\n        \n        cout << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Programs/Kuroni and the Celebration.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nvector <set <int> > tree;\nset <int> leaves;\n\nvoid erase_till(int v, int child, int destination)\n{\n    if(leaves.find(v) != leaves.end())\n    {\n        leaves.erase(v);\n    }\n    \n    for(auto it = tree[v].begin(); it != tree[v].end(); it++)\n    {\n        int parent = *it;\n        \n        if(parent == child)\n        {\n            continue;\n        }\n        \n        if(parent == destination)\n        {\n            tree[destination].erase(v);\n            \n            continue;\n        }\n        \n        if(tree[parent].size() > 0)\n        {\n            erase_till(parent, v, destination);\n        }\n    }\n    \n    tree[v].clear();\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    tree.resize(no_of_vertices + 1);\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].insert(v);\n        tree[v].insert(u);\n    }\n    \n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        if(tree[v].size() == 1)\n        {\n            leaves.insert(v);\n        }\n    }\n    \n    int root = 0;\n    while(leaves.size() > 1)\n    {\n        int u = *(leaves.begin()); leaves.erase(u);\n        int v = *(leaves.begin()); leaves.erase(v);\n        \n        int w;\n        cout << \"? \" << u << \" \" << v << \"\\n\" << flush;\n        cin >> w;\n        \n        if(w == u || w == v)\n        {\n            root = w;\n            break;\n        }\n        \n        erase_till(u, 0, w);\n        erase_till(v, 0, w);\n        \n        if(tree[w].size() <= 1)\n        {\n            leaves.insert(w);\n        }\n    }\n    \n    if(root == 0)\n    {\n        root = *(leaves.begin());\n    }\n    \n    cout << \"! \" << root << \"\\n\" << flush;\n    return 0;\n}\n"
  },
  {
    "path": "2020/Combined Divisions/Ozone Tech Challenge 2020/Programs/Kuroni and the Gifts.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    \n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n    \n    sort(all(B));\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << B[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while (no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/606 Div 2 Technocup 2020 Elimination Round 4/Explanations/As Simple as One and Two Explanation.txt",
    "content": "We will make 2 passes through the string. \n\n1. In Pass 1, we will remove all the 'o' which are common to both \"one\" and \"two\".\n2. In Pass 2, we will remove any one of the letters for either \"one\" or \"two\".\n\n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    vector <int> answer;\n    for(int i = 4; i < S.size(); i++)\n    {\n        if(S[i] == 'e' and S[i - 1] == 'n' and S[i - 2] == 'o' \n            and S[i - 3] == 'w' and S[i - 4] == 't')\n        {\n            S[i - 2] = 'x';\n            \n            answer.push_back(i - 2 + 1);\n        }\n        \n    }\n    \n    for(int i = 2; i < S.size(); i++)\n    {\n        if(S[i] == 'o' and S[i - 1] == 'w' && S[i - 2] == 't')\n        {\n            answer.push_back(i - 1 + 1);\n        }\n        \n        if(S[i] == 'e' and S[i - 1] == 'n' && S[i - 2] == 'o')\n        {\n            answer.push_back(i - 1 + 1);\n        }\n    }\n    \n    cout << answer.size() << \"\\n\";\n    \n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/606 Div 2 Technocup 2020 Elimination Round 4/Explanations/Happy Birthday Polycarp Explanation.txt",
    "content": "If the number has d digits, then all strings upto length (d - 1) are automatically good.\n\nSo the answer is initially 9(d - 1).\n\nWe will try all 9 D digit numbers and check how many of them are < n.\n\n-----\n\nint no_of_digits(int n)\n{\n    int digits = 0;\n\n    while(n > 0)\n    {\n        n /= 10;\n        digits++;\n    }\n\n    return digits;\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    int answer = 9*(no_of_digits(n) - 1);\n\n    for(int i = 1, x = 0; i <= 9; i++)\n    {\n        x = 0;\n\n        for(int d = 1; d <= no_of_digits(n); d++)\n        {\n            x = x*10 + i;\n        }\n\n        if(x > n)\n        {\n            break;\n        }\n\n        answer++;\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/606 Div 2 Technocup 2020 Elimination Round 4/Explanations/Make Them Odd Explanation.txt",
    "content": "In every step, we will keep dividing the largest element till it becomes odd.\n\nUse a set to hit only distinct elements.\n\nThis also takes care of the situation when x/2 is already there in the array.\n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    set <int> S;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n\n        if(x%2 == 0)\n        {\n            S.insert(x);\n        }\n    }\n\n    int no_of_steps = 0;\n    while(!S.empty())\n    {\n        int maximum = *(S.rbegin());\n\n        while(maximum%2 == 0)\n        {\n            if(S.find(maximum) != S.end())\n            {\n                S.erase(S.find(maximum));\n            }\n\n            maximum /= 2;\n\n            no_of_steps++;\n        }\n    }\n\n    cout << no_of_steps << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/606 Div 2 Technocup 2020 Elimination Round 4/Programs/As Simple as One and Two.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    vector <int> answer;\n    for(int i = 4; i < S.size(); i++)\n    {\n        if(S[i] == 'e' and S[i - 1] == 'n' and S[i - 2] == 'o' \n            and S[i - 3] == 'w' and S[i - 4] == 't')\n        {\n            S[i - 2] = 'x';\n            \n            answer.push_back(i - 2 + 1);\n        }\n        \n    }\n    \n    for(int i = 2; i < S.size(); i++)\n    {\n        if(S[i] == 'o' and S[i - 1] == 'w' && S[i - 2] == 't')\n        {\n            answer.push_back(i - 1 + 1);\n        }\n        \n        if(S[i] == 'e' and S[i - 1] == 'n' && S[i - 2] == 'o')\n        {\n            answer.push_back(i - 1 + 1);\n        }\n    }\n    \n    cout << answer.size() << \"\\n\";\n    \n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/606 Div 2 Technocup 2020 Elimination Round 4/Programs/Happy Birthday Polycarp.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint no_of_digits(int n)\n{\n    int digits = 0;\n    \n    while(n > 0)\n    {\n        n /= 10;\n        digits++;\n    }\n    \n    return digits;\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int answer = 9*(no_of_digits(n) - 1);\n    \n    for(int i = 1, x = 0; i <= 9; i++)\n    {\n        x = 0;\n        \n        for(int d = 1; d <= no_of_digits(n); d++)\n        {\n            x = x*10 + i;\n        }\n        \n        if(x > n)\n        {\n            break;\n        }\n        \n        answer++;\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/606 Div 2 Technocup 2020 Elimination Round 4/Programs/Make Them Odd.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    set <int> S;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n        \n        if(x%2 == 0)\n        {\n            S.insert(x);\n        }\n    }\n    \n    int no_of_steps = 0;\n    while(!S.empty())\n    {\n        int maximum = *(S.rbegin());\n        \n        while(maximum%2 == 0)\n        {\n            if(S.find(maximum) != S.end())\n            {\n                S.erase(S.find(maximum));\n            }\n            \n            maximum /= 2;\n            \n            no_of_steps++;\n        }\n    }\n    \n    cout << no_of_steps << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Explanations/Domino for Young Explanation.txt",
    "content": "We can think of it as a chessboard.Each domino covers one square of each colour.\n\nThe answer is whichever is minimum - black or white squares.\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_columns;\n    cin >> no_of_columns;\n\n    long long black = 0, white = 0;\n    for(int i = 1; i <= no_of_columns; i++)\n    {\n        int no_of_rows;\n        cin >> no_of_rows;\n\n        black += (no_of_rows/2) + (no_of_rows%2 == 1 && i%2 == 0);\n        white += (no_of_rows/2) + (no_of_rows%2 == 1 && i%2 == 1);\n    }\n\n    long long dominos = min(black, white);\n    cout << dominos << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Explanations/Equation Explanation.txt",
    "content": "We can just print 9n and 8n.\n\ngcd(8, 9) = 1 and 9n - 8n = 1\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    cout << 9*n << \" \" << 8*n << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Explanations/Long Beautiful Integer Explanation.txt",
    "content": "The first k characters determine the entire string.\nWe will first set B[i] = B[i%k] for every i.\n\nIf B >= A like this, then we are done.\nThis is the smallest beautiful integer as it matches the longest prefix.\n\nOtherwise if B < A, then, we will look at the last digit which is not 9 in the prefix.\nWe will increment it and make all the 9's from there till k = 0\n\nNow, B > A and has the longest matching prefix.\n\n-----\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_digits, k;\n    string S;\n    cin >> no_of_digits >> k >> S;\n\n    string answer = S;\n    for(int i = k; i < no_of_digits; i++)\n    {\n        answer[i] = answer[i%k];\n    }\n\n    int is_lesser = false;\n    for(int i = 0; i < no_of_digits; i++)\n    {\n        if(answer[i] > S[i])\n        {\n            break;\n        }\n\n        if(answer[i] < S[i])\n        {\n            is_lesser = true;\n            break;\n        }\n    }\n\n    if(!is_lesser)\n    {\n        cout << no_of_digits << \"\\n\" << answer << \"\\n\";\n        return 0;\n    }\n\n    int change_point = -1;\n    for(int i = k - 1; i >= 0; i--)\n    {\n        if(S[i] != '9')\n        {\n            change_point = i;\n            answer[i] = answer[i] + 1;\n            break;\n        }\n    }\n\n    for(int i = change_point + 1; change_point != -1 && i < k; i++)\n    {\n        answer[i] = '0';\n    }\n\n    for(int i = k; i < no_of_digits; i++)\n    {\n        answer[i] = answer[i%k];\n    }\n\n    cout << no_of_digits << \"\\n\" << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Explanations/Modulo Equality Explanation.txt",
    "content": "Let us check all possible candidates that we can add to A to make it equal to B.\n\nWhen A = B, then A[1] is equal to some element in B.\n\nWe will iterate over all B, and check if x = (B[i] - A[1]) satisfies the condition.\n\nWe will add x to the entire array A and then check if A = B.\n\nThis can be done by comparing the sorted arrays A and B.\n\n-----\n\nint add_and_check_equality(vector <int> A, vector <int> B, int m, int x)\n{\n    for(int i = 1; i < A.size(); i++)\n    {\n        A[i] = (A[i] + x)%m;\n    }\n\n    sort(all(A));\n\n    for(int i = 1; i < B.size(); i++)\n    {\n        if(A[i] != B[i])\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nint main()\n{\n    int no_of_elements, m;\n    cin >> no_of_elements >> m;\n\n    vector <int> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        A[i] %= m;\n    }\n\n    vector <int> B(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n\n        B[i] %= m;\n    }\n\n    sort(all(B));\n\n    int minimum_moves = m;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int to_add = (B[i] - A[1] + m)%m;\n\n        if(add_and_check_equality(A, B, m, to_add))\n        {\n            minimum_moves = min(minimum_moves, to_add);\n        }\n    }\n\n    cout << minimum_moves << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Programs/Domino for Young.cpp",
    "content": "#include <iostream>\n \nusing namespace std;\n \nint main()\n{\n    int no_of_columns;\n    cin >> no_of_columns;\n    \n    long long black = 0, white = 0;\n    for(int i = 1; i <= no_of_columns; i++)\n    {\n        int no_of_rows;\n        cin >> no_of_rows;\n        \n        black += (no_of_rows/2) + (no_of_rows%2 == 1 && i%2 == 0);\n        white += (no_of_rows/2) + (no_of_rows%2 == 1 && i%2 == 1);\n    }\n    \n    long long dominos = min(black, white);\n    cout << dominos << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Programs/Equation.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n    \n    cout << 9*n << \" \" << 8*n << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Programs/Long Beautiful Integer.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_digits, k;\n    string S;\n    cin >> no_of_digits >> k >> S;\n    \n    string answer = S;\n    for(int i = k; i < no_of_digits; i++)\n    {\n        answer[i] = answer[i%k];\n    }\n    \n    int is_lesser = false;\n    for(int i = 0; i < no_of_digits; i++)\n    {\n        if(answer[i] > S[i])\n        {\n            break;\n        }\n        \n        if(answer[i] < S[i])\n        {\n            is_lesser = true;\n            break;\n        }\n    }\n    \n    if(!is_lesser)\n    {\n        cout << no_of_digits << \"\\n\" << answer << \"\\n\";\n        return 0;\n    }\n    \n    int change_point = -1;\n    for(int i = k - 1; i >= 0; i--)\n    {\n        if(S[i] != '9')\n        {\n            change_point = i;\n            answer[i] = answer[i] + 1;\n            break;\n        }\n    }\n    \n    for(int i = change_point + 1; change_point != -1 && i < k; i++)\n    {\n        answer[i] = '0';\n    }\n    \n    for(int i = k; i < no_of_digits; i++)\n    {\n        answer[i] = answer[i%k];\n    }\n    \n    cout << no_of_digits << \"\\n\" << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/609 Div 2/Programs/Modulo Equality.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint add_and_check_equality(vector <int> A, vector <int> B, int m, int x)\n{\n    for(int i = 1; i < A.size(); i++)\n    {\n        A[i] = (A[i] + x)%m;\n    }\n    \n    sort(all(A));\n    \n    for(int i = 1; i < B.size(); i++)\n    {\n        if(A[i] != B[i])\n        {\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nint main()\n{\n    int no_of_elements, m;\n    cin >> no_of_elements >> m;\n    \n    vector <int> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        A[i] %= m;\n    }\n    \n    vector <int> B(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n        \n        B[i] %= m;\n    }\n    \n    sort(all(B));\n    \n    int minimum_moves = m;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int to_add = (B[i] - A[1] + m)%m;\n        \n        if(add_and_check_equality(A, B, m, to_add))\n        {\n            minimum_moves = min(minimum_moves, to_add);\n        }\n    }\n    \n    cout << minimum_moves << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/612 Div 2/Explanations/Angry Students Explanation.txt",
    "content": "The prefix of P's will not be changed.\n\nFor every other P, the amount of time taken to change it is equal to the distance of the leftmost A.\n\nWe can compute this in one linear sweep.\n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    const int oo = 1e7;\n    vector <int> nearest_a(length + 1, oo);\n    nearest_a[0] = (S[0] == 'A' ? 0 : oo);\n\n    for(int i = 1; i < length; i++)\n    {\n        nearest_a[i] = (S[i] == 'A' ? 0 : nearest_a[i - 1] + 1);\n    }\n\n    int answer = 0;\n    for(int i = 0; i < length; i++)\n    {\n        //Skip the prefix\n        if(nearest_a[i] >= oo)\n        {\n            continue;\n        }\n\n        answer = max(answer, nearest_a[i]);\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/612 Div 2/Explanations/Hyperset Explanation.txt",
    "content": "Let us notice something. \n\nSuppose we fix 2 strings A and B. \n\nThere can only be 1 string C, such that (A, B, C) is a set. \n\nFor each of the K positions, if \n\nA[i] = B[i], then C[i] also has to be = A[i]\n\nIf A[i] != B[i], then C[i] must be the third character not equal to both (A[i], B[i]). \n\n-----\n\nLet us iterate over every pair of strings. The third string C is only one.\n\nFor every pair (A[i], A[j]), add the frequency of Complement(A[i], A[j]) to the answer. \n\nThe only observation is that every triplet (A, B, C) is counted three times. \n\n1. When we fix (A, B)\n2. When we fix (B, C)\n3. When we fix (C, A)\n\nSo, we will divide the number of triplets by 3. \n\n----\n\nWe need to notice something. What about identical triplets - when all three strings are the same - (A, A, A) ? \n\nIf we add it in the same way, then we will be counting such triplets 6 times. \n\nWhen we fix (A, A) and add frequency of Complement(A, A) = A to the answer, the answer overcounts by 2. \n\nEach such triplet is counted 3x2 = 6 times. \n\nThat is why, in my solution I count same triplets first, and then different triplets seperately. \n\n----\n\nNote that we do not have to deal with the condition where A = B =/= C because of the definition of the triplet :)\n\n----\n\nchar get_third(char a, char b)\n{\n    switch(a)\n    {\n        case 'S' : return (b == 'E' ? 'T' : 'E');\n        case 'E' : return (b == 'T' ? 'S' : 'T');\n        case 'T' : return (b == 'S' ? 'E' : 'S');\n    }\n    \n    return 0;\n}\n\nlong  long choose_3(long long n)\n{\n    long long numerator = n*(n - 1)*(n - 2);\n    long long denominator = 3*2*1;\n    \n    return numerator/denominator;\n}\n\nint main()\n{\n    int no_of_cards, no_of_features;\n    cin >> no_of_cards >> no_of_features;\n    \n    vector <string> card(no_of_cards + 1);\n    map <string, int> frequency;\n    for(int i = 1; i <= no_of_cards; i++)\n    {\n        cin >> card[i];\n        \n        frequency[card[i]]++;\n    }\n    \n    long long same_triplets = 0;\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\n    {\n        same_triplets += choose_3(it->second);\n    }\n    \n    long long different_triplets = 0;\n    for(int i = 1; i <= no_of_cards; i++)\n    {\n        for(int j = i + 1; j <= no_of_cards; j++)\n        {\n            if(card[i] == card[j])\n            {\n                continue;\n            }\n            \n            string complement;\n            \n            for(int k = 0; k < no_of_features; k++)\n            {\n                if(card[i][k] == card[j][k])\n                {\n                    complement += card[i][k];\n                }\n                else\n                {\n                    complement += get_third(card[i][k], card[j][k]);\n                }\n            }\n            \n            different_triplets += frequency[complement];\n        }\n    }\n    \n    different_triplets /= 3;\n    \n    long long no_of_triplets = same_triplets + different_triplets;\n    \n    cout << no_of_triplets << \"\\n\";\n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Div 2/612 Div 2/Explanations/Madhouse (Easy Version) Explanation.txt",
    "content": "Let us do this.\n\nSince we are given random permutations of every substring, we will collect a vector of length 26\ndenoting the frequency of each of the alphabets instead of the actual string.\n\nWe will first get all the substrings of length [1, n].\n\nWe will then get all the substrings of length [2, n].\n\nWe will store all the vectors of length 26 inside a multiset.\nWe will delete all the vectors from [2, n] that are present.\n\nThis leaves us with n substrings -\n\n[1, 1], [1, 2], [1, 3], ... , [1, n].\n\n----\n\nNotice that [1, 1] is the only letter.\n\nTo get the second letter, we must search for which letter is there in [1, 2] but not in [1, 1].\n\nSimilarly, we will repeat this process. To get the i-th alphabet, we will search for which letter\nis there in [1, i] but not there in [1, i - 1].\n\n-----\n\nint sort_by_frequency(vector <int> &A, vector <int> &B)\n{\n    const int NO_OF_ALPHABETS = 26;\n\n    int a_sum = 0, b_sum = 0;\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\n    {\n        a_sum += A[i];\n        b_sum += B[i];\n    }\n\n    return (b_sum > a_sum);\n}\n\nint main()\n{\n    int length;\n    cin >> length;\n\n    const int NO_OF_ALPHABETS = 26;\n    cout << \"? 1 \" << length << endl;\n\n    multiset <vector <int> >subarray;\n    for(int i = 1; i <= length; i++)\n    {\n        for(int j = i; j <= length; j++)\n        {\n            string S;\n            cin >> S;\n\n            if(length == 1)\n            {\n                cout << \"! \" << S << endl;\n\n                return 0;\n            }\n\n            vector <int> frequency(NO_OF_ALPHABETS, 0);\n            for(int k = 0; k < S.size(); k++)\n            {\n                frequency[S[k] - 'a']++;\n            }\n\n            subarray.insert(frequency);\n        }\n    }\n\n    cout << \"? 2 \" << length << endl;\n    for(int i = 2; i <= length; i++)\n    {\n        for(int j = i; j <= length; j++)\n        {\n            string S;\n            cin >> S;\n\n            vector <int> frequency(NO_OF_ALPHABETS, 0);\n            for(int k = 0; k < S.size(); k++)\n            {\n                frequency[S[k] - 'a']++;\n            }\n\n            subarray.erase(subarray.find((frequency)));\n        }\n    }\n\n    vector <vector <int> >subarrays_from_1;\n    for(auto it = subarray.begin(); it != subarray.end(); it++)\n    {\n        subarrays_from_1.push_back(*it);\n    }\n\n    sort(all(subarrays_from_1), sort_by_frequency);\n\n    string answer;\n\n    vector <int> current_frequency(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < length; i++)\n    {\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            if(subarrays_from_1[i][alpha] > current_frequency[alpha])\n            {\n                answer += (char)('a' + alpha);\n\n                current_frequency[alpha]++;\n            }\n        }\n    }\n\n    cout << \"! \" << answer << endl;\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/612 Div 2/Programs/Angry Students.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    const int oo = 1e7;\n    vector <int> nearest_a(length + 1, oo);\n    nearest_a[0] = (S[0] == 'A' ? 0 : oo);\n    \n    for(int i = 1; i < length; i++)\n    {\n        nearest_a[i] = (S[i] == 'A' ? 0 : nearest_a[i - 1] + 1);\n    }\n    \n    int answer = 0;\n    for(int i = 0; i < length; i++)\n    {\n        //Skip the prefix\n        if(nearest_a[i] >= oo)\n        {\n            continue;\n        }\n        \n        answer = max(answer, nearest_a[i]);\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/612 Div 2/Programs/Hyperset.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nchar get_third(char a, char b)\n{\n    switch(a)\n    {\n        case 'S' : return (b == 'E' ? 'T' : 'E');\n        case 'E' : return (b == 'T' ? 'S' : 'T');\n        case 'T' : return (b == 'S' ? 'E' : 'S');\n    }\n    \n    return 0;\n}\n\nlong  long choose_3(long long n)\n{\n    long long numerator = n*(n - 1)*(n - 2);\n    long long denominator = 3*2*1;\n    \n    return numerator/denominator;\n}\n\nint main()\n{\n    int no_of_cards, no_of_features;\n    cin >> no_of_cards >> no_of_features;\n    \n    vector <string> card(no_of_cards + 1);\n    map <string, int> frequency;\n    for(int i = 1; i <= no_of_cards; i++)\n    {\n        cin >> card[i];\n        \n        frequency[card[i]]++;\n    }\n    \n    long long same_triplets = 0;\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\n    {\n        same_triplets += choose_3(it->second);\n    }\n    \n    long long different_triplets = 0;\n    for(int i = 1; i <= no_of_cards; i++)\n    {\n        for(int j = i + 1; j <= no_of_cards; j++)\n        {\n            if(card[i] == card[j])\n            {\n                continue;\n            }\n            \n            string complement;\n            \n            for(int k = 0; k < no_of_features; k++)\n            {\n                if(card[i][k] == card[j][k])\n                {\n                    complement += card[i][k];\n                }\n                else\n                {\n                    complement += get_third(card[i][k], card[j][k]);\n                }\n            }\n            \n            different_triplets += frequency[complement];\n        }\n    }\n    \n    different_triplets /= 3;\n    \n    long long no_of_triplets = same_triplets + different_triplets;\n    \n    cout << no_of_triplets << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/612 Div 2/Programs/Madhouse (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <set>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint sort_by_frequency(vector <int> &A, vector <int> &B)\n{\n    const int NO_OF_ALPHABETS = 26;\n    \n    int a_sum = 0, b_sum = 0;\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\n    {\n        a_sum += A[i];\n        b_sum += B[i];\n    }\n    \n    return (b_sum > a_sum);\n}\n\nint main()\n{\n    int length;\n    cin >> length;\n    \n    const int NO_OF_ALPHABETS = 26;\n    cout << \"? 1 \" << length << endl;\n    \n    multiset <vector <int> >subarray;\n    for(int i = 1; i <= length; i++)\n    {\n        for(int j = i; j <= length; j++)\n        {\n            string S;\n            cin >> S;\n            \n            if(length == 1)\n            {\n                cout << \"! \" << S << endl;\n                \n                return 0;\n            }\n            \n            vector <int> frequency(NO_OF_ALPHABETS, 0);\n            for(int k = 0; k < S.size(); k++)\n            {\n                frequency[S[k] - 'a']++;\n            }\n            \n            subarray.insert(frequency);\n        }\n    }\n    \n    cout << \"? 2 \" << length << endl;\n    for(int i = 2; i <= length; i++)\n    {\n        for(int j = i; j <= length; j++)\n        {\n            string S;\n            cin >> S;\n            \n            vector <int> frequency(NO_OF_ALPHABETS, 0);\n            for(int k = 0; k < S.size(); k++)\n            {\n                frequency[S[k] - 'a']++;\n            }\n            \n            subarray.erase(subarray.find((frequency)));\n        }\n    }\n    \n    vector <vector <int> >subarrays_from_1;\n    for(auto it = subarray.begin(); it != subarray.end(); it++)\n    {\n        subarrays_from_1.push_back(*it);\n    }\n    \n    sort(all(subarrays_from_1), sort_by_frequency);\n    \n    string answer;\n    \n    vector <int> current_frequency(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < length; i++)\n    {\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            if(subarrays_from_1[i][alpha] > current_frequency[alpha])\n            {\n                answer += (char)('a' + alpha);\n                \n                current_frequency[alpha]++;\n            }\n        }\n    }\n    \n    cout << \"! \" << answer << endl;\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Explanations/Dr Evil Underscores Explanation.txt",
    "content": "If all the integers have a 1 in a bit position or a 0 in a bit position, \nthen the answer will have a 0 there if we put a bit in X.\n\nIf some integers have a 1 and some integers have a 0, then the answer will have\nthat bit set in answer regardless of what we put in X.\n\n-----\n\nSuppose we are dealing with bit b,\n\nWhat we will do is put all the integers with that bit set in A,\nWe will put all the integers with that bit unset in B\n\nWe will solve the problem for the remaining bits in A and B seperately and add it to 2^b\n\n-----\n\n\nlong long solve(int bit, vector <long long> &A)\n{\n    if(bit < 0 || A.size() == 0)\n    {\n        return 0;\n    }\n\n    vector <long long> set, unset;\n    for(int i = 0; i < A.size(); i++)\n    {\n        if(is_bit_set(A[i], bit))\n        {\n            set.push_back(A[i]);\n        }\n        else\n        {\n            unset.push_back(A[i]);\n        }\n    }\n\n    if(set.size() == 0)\n    {\n        return solve(bit - 1, unset);\n    }\n\n    if(unset.size() == 0)\n    {\n        return solve(bit - 1, set);\n    }\n\n    return ( (1LL << bit) + min(solve(bit - 1, set), solve(bit - 1, unset)) );\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Explanations/Fadi and LCM Explanation.txt",
    "content": "Let us notice something.\n\nSuppose p is a prime integer.\n\nThe LCM of (p^a, p^b) is p^{max(a, b)}\n\nIf X = p1^a1 p2^a2 ... pn^an\n\nIf we have to split their prime factors among a and b.\n\nWe must give p1^a1 to at least one of (a, b).\n\nSince we want to minimise the maximum, we will give p1^a1 to one of them and 1 to the other.\n\nIn the given range, the number of distinct prime factors is not too much (Around 11).\n\nWe will use bitmasks to check how many of the 11 factors we give to a and how many we give to b and choose the best pair.\n\n------\n\nint main()\n{\n    long long n;\n    cin >> n;\n\n    vector <long long> prime_factors;\n    factorise(n, prime_factors);\n\n    long long best_x = 1, best_y = n;\n    int number_of_uniques = prime_factors.size();\n    for(long long mask = 0; mask < (1LL << number_of_uniques); mask++)\n    {\n        long long x = 1, y = 1;\n        for(int bit = 0; bit < number_of_uniques; bit++)\n        {\n            if(is_bit_set(mask, bit))\n            {\n               x *= prime_factors[bit];\n            }\n            else\n            {\n                y *= prime_factors[bit];\n            }\n        }\n\n        if(max(x, y) < max(best_x, best_y))\n        {\n            best_x = x;\n            best_y = y;\n        }\n    }\n\n    cout << best_x << \" \" << best_y << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Explanations/Just Eat It Explanation.txt",
    "content": "We will use Kandane's Algorithm to find out the best segment that can be chosen at each point.\n\nThe only exception is when we are at the last element.\n\nWe have to be careful that the segment we are choosing at the last element is not the entire array.\n\nWe will check that if we are at the last element, the best segment sum is not the entire prefix sum.\nThe only way we are allowed to take a sum = the entire prefix sum at i = n is if there is some point where prefix[i] = 0\n\nThen, prefix[n] - prefix[i] = prefix[n]\n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    int is_zero = false;\n    vector <long long> prefix_sum(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = A[i] + prefix_sum[i - 1];\n\n        if(prefix_sum[i] == 0)\n        {\n            is_zero = true;\n        }\n    }\n\n    long long best_choice = -1e10;\n    vector <long long> max_sum(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        max_sum[i] = max(A[i], A[i] + max_sum[i - 1]);\n\n        if(i == no_of_elements && max_sum[i] == prefix_sum[i] && is_zero == false)\n        {\n            continue;\n        }\n\n        best_choice = max(best_choice, max_sum[i]);\n    }\n\n    cout << (prefix_sum[no_of_elements] > best_choice  ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Explanations/Mezo Playing Zoma Explanation.txt",
    "content": "If there are L lefts and R rights, then we can end up anywhere between [-L, R]\n\nThe answer = (L + R + 1)\n\n------\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    int lefts = 0, rights = 0;\n    for(int i = 0; i < length; i++)\n    {\n        switch(S[i])\n        {\n            case 'L' : lefts++; break;\n            case 'R' : rights++; break;\n        }\n    }\n\n    int answer = (lefts + rights + 1);\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Programs/Dr Evil Underscores.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0 );\n}\n\nlong long solve(int bit, vector <long long> &A)\n{\n    if(bit < 0 || A.size() == 0)\n    {\n        return 0;\n    }\n    \n    vector <long long> set, unset;\n    for(int i = 0; i < A.size(); i++)\n    {\n        if(is_bit_set(A[i], bit))\n        {\n            set.push_back(A[i]);\n        }\n        else\n        {\n            unset.push_back(A[i]);\n        }\n    }\n    \n    if(set.size() == 0)\n    {\n        return solve(bit - 1, unset);\n    }\n    \n    if(unset.size() == 0)\n    {\n        return solve(bit - 1, set);\n    }\n    \n    return ( (1LL << bit) + min(solve(bit - 1, set), solve(bit - 1, unset)) );\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long answer = solve(31, A);\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Programs/Fadi and LCM.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( ( n&(1LL << bit) ) != 0);\n}\n\nvoid factorise(long long x, vector <long long> &P)\n{\n    for(long long i = 2; i*i <= x; i++)\n    {\n        if(x%i == 0)\n        {\n            long long p = 1;\n            \n            while(x%i == 0)\n            {\n                x /= i;\n                \n                p *= i;\n            }\n            \n            P.push_back(p);\n        }\n    }\n    \n    if(x > 1)\n    {\n        P.push_back(x);\n    }\n}\n\nint main()\n{\n    long long n;\n    cin >> n;\n    \n    vector <long long> prime_factors;\n    factorise(n, prime_factors);\n    \n    long long best_x = 1, best_y = n;\n    int number_of_uniques = prime_factors.size();\n    for(long long mask = 0; mask < (1LL << number_of_uniques); mask++)\n    {\n        long long x = 1, y = 1;\n        for(int bit = 0; bit < number_of_uniques; bit++)\n        {\n            if(is_bit_set(mask, bit))\n            {\n               x *= prime_factors[bit];\n            }\n            else\n            {\n                y *= prime_factors[bit];\n            }\n        }\n        \n        if(max(x, y) < max(best_x, best_y))\n        {\n            best_x = x;\n            best_y = y;\n        }\n    }\n    \n    cout << best_x << \" \" << best_y << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Programs/Just Eat It.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int is_zero = false;\n    vector <long long> prefix_sum(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = A[i] + prefix_sum[i - 1];\n        \n        if(prefix_sum[i] == 0)\n        {\n            is_zero = true;\n        }\n    }\n    \n    long long best_choice = -1e10;\n    vector <long long> max_sum(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        max_sum[i] = max(A[i], A[i] + max_sum[i - 1]);\n       \n        if(i == no_of_elements && max_sum[i] == prefix_sum[i] && is_zero == false)\n        {\n            continue;\n        }\n            \n        best_choice = max(best_choice, max_sum[i]);\n    }\n    \n    cout << (prefix_sum[no_of_elements] > best_choice  ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/613 Div 2/Programs/Mezo Playing Zoma.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    int lefts = 0, rights = 0;\n    for(int i = 0; i < length; i++)\n    {\n        switch(S[i])\n        {\n            case 'L' : lefts++; break;\n            case 'R' : rights++; break;\n        }\n    }\n    \n    int answer = (lefts + rights + 1);\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/616 Div 2/Explanations/Array Sharpening Explanation.txt",
    "content": "Let us make an observation here\n\nIf it is possible to make (A[1] < A[2] < A[3] < ... < A[k]),\n\nthen it is possible to make them = (0 < 1 < 2 < ... < (k - 1))\n\nWe can do this by simply subtracting more.\n\nLet prefix[i] = true, if it is possible to make [1, i] = (0, 1, ... , i - 1)\n\nLet suffix[i] = true, if it is possible to make [i, n] = (n - i, ... , 2, 1, 0)\n\nWe will then go through the entire array and see if we can find an i such that\n\nprefix[i - 1] = true and suffix[i + 1] = true and A[i] >= max(i - 1, n - i)\n\nThen, we have got our array if even there is a single i that satisfies this condition !\n\n-----\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> prefix_possible(no_of_elements + 1, false);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] < i - 1)\n        {\n            break;\n        }\n\n        prefix_possible[i] = true;\n    }\n\n    vector <int> suffix_possible(no_of_elements + 1, false);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        if(A[i] < (no_of_elements - i))\n        {\n            break;\n        }\n\n        suffix_possible[i] = true;\n    }\n\n    int possible = (no_of_elements == 1 ? true : false);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(i == 1)\n        {\n            if(A[i] >= (no_of_elements - i) && suffix_possible[i + 1])\n            {\n                possible = true;\n                break;\n            }\n        }\n\n        if(i == no_of_elements)\n        {\n            if(A[i] >= (i - 1) && prefix_possible[i - 1])\n            {\n                possible = true;\n                break;\n            }\n        }\n\n        if(A[i] >= (i - 1) && prefix_possible[i - 1] && A[i] >= (no_of_elements - i) && suffix_possible[i + 1])\n        {\n            possible = true;\n            break;\n        }\n    }\n\n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/616 Div 2/Explanations/Even But Not Even Explanation.txt",
    "content": "The sum of 2 odd numbers is even.\n\nIf there are at least 2 odd numbers, we will print them in order\n\nOtherwise, it is not possible.\n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n\n    cin >> length >> S;\n\n    int odd_count = 0;\n    for(int i = 0; i < length; i++)\n    {\n        odd_count += (S[i] - '0')%2;\n    }\n\n    if(odd_count < 2)\n    {\n        cout << \"-1\\n\";\n\n        return;\n    }\n\n    string answer;\n    for(int i = 0; i < length && answer.size() < 2; i++)\n    {\n        if( (S[i] - '0')%2 == 1)\n        {\n            answer += S[i];\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/616 Div 2/Explanations/Mind Control Explanation.txt",
    "content": "1. Suppose there are (k - 1) people in front of you. \nUltimately, we will have p elements taken from the prefix and s elements taken from the suffix where (p + x = k - 1)\n\n2. Suppose we can control C people. \nOut of these C people, we will make some of them take the prefix and some of them take the suffix. \nOut of the U people we can't control, u people will take the prefix and (U - u) will take the suffix.\n\n3. Let us say we make c people out of C take the prefix. \nThe U people we can't control will make their choice so as to minimise our sum. \n\n4. We will iterate over all possibilities. We will first fix that we will choose c people to take the prefix and (C - c) to take the suffix. \nThe U people we can't control will make their choice in such a way as to minimise our sum. \n\n5. We will choose the value of (c, u) that gives us our maximum sum.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, position, controlled;\n    cin >> no_of_elements >> position >> controlled;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    controlled = min(controlled, position - 1);\n    int uncontrolled = (position - 1) - controlled;\n    \n    int best_answer = 0;\n    for(int c = 0; c <= controlled; c++)\n    {\n        int best_answer_for_c = 1e9 + 5;\n        \n        for(int i = 0; i <= uncontrolled; i++)\n        {\n            int prefix = c + i, suffix = no_of_elements - (controlled - c) - (uncontrolled - i) + 1;//Last element is n, not (n - 1) so add +1\n            \n            int answer_here = max(A[prefix + 1], A[suffix - 1]);\n           \n            best_answer_for_c = min(answer_here, best_answer_for_c);\n        }\n        \n        best_answer = max(best_answer, best_answer_for_c);\n    }\n    \n    cout << best_answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/616 Div 2/Programs/Array Sharpening.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> prefix_possible(no_of_elements + 1, false);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] < i - 1)\n        {\n            break;\n        }\n        \n        prefix_possible[i] = true;\n    }\n    \n    vector <int> suffix_possible(no_of_elements + 1, false);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        if(A[i] < (no_of_elements - i))\n        {\n            break;\n        }\n        \n        suffix_possible[i] = true;\n    }\n    \n    int possible = (no_of_elements == 1 ? true : false);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(i == 1)\n        {\n            if(A[i] >= (no_of_elements - i) && suffix_possible[i + 1])\n            {\n                possible = true;\n                break;\n            }\n        }\n        \n        if(i == no_of_elements)\n        {\n            if(A[i] >= (i - 1) && prefix_possible[i - 1])\n            {\n                possible = true;\n                break;\n            }\n        }\n        \n        if(A[i] >= (i - 1) && prefix_possible[i - 1] && A[i] >= (no_of_elements - i) && suffix_possible[i + 1])\n        {\n            possible = true;\n            break;\n        }\n    }\n    \n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/616 Div 2/Programs/Even But Not Even.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    \n    cin >> length >> S;\n    \n    int odd_count = 0;\n    for(int i = 0; i < length; i++)\n    {\n        odd_count += (S[i] - '0')%2;\n    }\n    \n    if(odd_count < 2)\n    {\n        cout << \"-1\\n\";\n        \n        return;\n    }\n    \n    string answer;\n    for(int i = 0; i < length && answer.size() < 2; i++)\n    {\n        if( (S[i] - '0')%2 == 1)\n        {\n            answer += S[i];\n        }\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/616 Div 2/Programs/Mind Control.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, position, controlled;\n    cin >> no_of_elements >> position >> controlled;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    controlled = min(controlled, position - 1);\n    int uncontrolled = (position - 1) - controlled;\n    \n    int best_answer = 0;\n    for(int c = 0; c <= controlled; c++)\n    {\n        int best_answer_for_c = 1e9 + 5;\n        \n        for(int i = 0; i <= uncontrolled; i++)\n        {\n            int prefix = c + i, suffix = no_of_elements - (controlled - c) - (uncontrolled - i) + 1;//Last element is n, not (n - 1) so add +1\n            \n            int answer_here = max(A[prefix + 1], A[suffix - 1]);\n           \n            best_answer_for_c = min(answer_here, best_answer_for_c);\n        }\n        \n        best_answer = max(best_answer, best_answer_for_c);\n    }\n    \n    cout << best_answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/618 Div 2/Explanations/Anu has a Function Explanation.txt",
    "content": "Observation - f(x, y) will only have the bits that are set in x\n\nEvery bit in y is subtracted so we cannot add any new bits to x, by performing f(x, y)\n\n-----\n\nThis means that the value of a[1], represents the value of the entire function. \n\nFor every A[i], we will calculate the value of the function if we place A[i] at A[1]. \n\nThe answer will have all the bits set that are set only once in A[i] and not in any other array element. \n\nIf any bit is set in some other element A[j], it will get subtracted when we peform f(x, A[j])\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ((n & (1LL << bit)) != 0);\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int NO_OF_BITS = 31;\n    vector <int> bit_frequency(NO_OF_BITS + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int b = 0; b <= NO_OF_BITS; b++)\n        {\n            if(is_bit_set(A[i], b))\n            {\n                bit_frequency[b]++;\n            }\n        }\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long answer_here = 0;\n        \n        for(int b = 0; b <= NO_OF_BITS; b++)\n        {\n            if(is_bit_set(A[i], b) && bit_frequency[b] == 1)\n            {\n                answer_here |= (1LL << b);\n            }\n        }\n        \n        if(answer_here > answer)\n        {\n            swap(A[i], A[1]);\n            \n            answer = answer_here;\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Div 2/618 Div 2/Programs/Anu has a Function.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ((n & (1LL << bit)) != 0);\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int NO_OF_BITS = 31;\n    vector <int> bit_frequency(NO_OF_BITS + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int b = 0; b <= NO_OF_BITS; b++)\n        {\n            if(is_bit_set(A[i], b))\n            {\n                bit_frequency[b]++;\n            }\n        }\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long answer_here = 0;\n        \n        for(int b = 0; b <= NO_OF_BITS; b++)\n        {\n            if(is_bit_set(A[i], b) && bit_frequency[b] == 1)\n            {\n                answer_here |= (1LL << b);\n            }\n        }\n        \n        if(answer_here > answer)\n        {\n            swap(A[i], A[1]);\n            \n            answer = answer_here;\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Explanations/Ayoub's Function Explanation.txt",
    "content": "We need to maximise the number of substrings containing at least 1 one.\nThis is the same as minimizing the number of substrings containing only 0s.\n\nLet us see how to do this with an example.\n\nIf we want to minimize the number of 0s,\nit is best to make each group of 0s as small as possible.\n(2 groups of length 1 is smaller than 1 group of length 2)\n\n0, 0 has 2 substrings\n00 has 3 substrings\n\nSuppose we have 10 0s and 5 1s\n\n00 | 00 | 00 | 00 | 0 | 0\n\nThe best way to distribute them is like this\nIf there are d 1s, then we divide the 0s into (D + 1) parts.\n\n----\n\nFirst, we will divide them equally\n\n0 | 0 | 0 | 0 | 0 | 0\n\n-----\n\nWe will have some remainder.\n\nIn this case 10 (mod 6) = 4\n\nSo, we will add the 4 extra 0s to different parts to keep the sum of 0s minimum\n\nSo 4 segments, will have an extra 0\n\n-----\n\nHow to calculate this ?\n\n1. Find out the length of each 0 segment. The number of 0 substrings will be\nl(l - 1)/2 + l\n2. When we add a 0 to a segment of length z, we will be create (z + 1) new 0-substrings\nEach remainder contributes (z + 1) to the answer, where z is the length of a 0-substring\n\n----\n\nlong long count_substrings(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nvoid solve()\n{\n    long long length, no_of_1s;\n    cin >> length >> no_of_1s;\n\n    long long no_of_0s = (length - no_of_1s);\n\n    long long total_substrings = count_substrings(length);\n\n    long long dividers = (no_of_1s + 1);\n\n    long long full_zero_islands_size = (no_of_0s/dividers);\n\n    long long zero_substrings = dividers*count_substrings(full_zero_islands_size);\n\n    if(no_of_0s%dividers != 0)\n    {\n        long long remaining_zeroes = no_of_0s - dividers*(full_zero_islands_size);\n\n        zero_substrings += remaining_zeroes*(full_zero_islands_size + 1);\n    }\n\n    long long one_substrings = total_substrings - zero_substrings;\n\n    cout << one_substrings << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Explanations/Motarack's Birthday Explanation.txt",
    "content": "Let us look at the elements which -1 is adjacent to.\n\nLet them be {F1, F2, ... , Fm}\n\nThe maximum value of |k - Fi| for some Fi in this set will be either\nwith the smallest or largest element.\n\nSo, the best choice for k is (F1 + Fm)/2 as this is the optimal distance between both\n\nAfter we replace all k's with (F1 + Fm)/2, we will calculate the value of max|A[i] - A[i - 1]|\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> fixed;\n\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        if(A[i - 1] == -1 && A[i] != -1)\n        {\n            fixed.push_back(A[i]);\n        }\n    }\n\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(A[i + 1] == -1 && A[i] != -1)\n        {\n            fixed.push_back(A[i]);\n        }\n    }\n\n    sort(all(fixed));\n\n    long long mid;\n\n    if(fixed.size() == 0)\n    {\n        mid = 0;\n    }\n    else\n    {\n        mid = (fixed[0] + fixed.back())/2;\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] == -1)\n        {\n            A[i] = mid;\n        }\n    }\n\n    long long m = 0;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        m = max(m, abs(A[i] - A[i - 1]));\n    }\n\n    cout << m << \" \" << mid << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Explanations/Three Strings Explanation.txt",
    "content": "For each position i, \n\nWe must swap either (A[i], C[i]) or (B[i], C[i])\n\nThis means that either (B[i] = C[i]) or (A[i] = C[i]) respectively\n\n-----\n\nvoid solve()\n{\n    string A, B, C;\n    cin >> A >> B >> C;\n    \n    for(int i = 0; i < A.size(); i++)\n    {\n        if(A[i] == C[i] || B[i] == C[i])\n        {\n            continue;\n        }\n        \n        cout << \"NO\\n\";\n        \n        return;\n    }\n    \n    cout << \"YES\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Explanations/Time to Run Explanation.txt",
    "content": "We will start from (1, 1)\n\nIn any given row, we will go left till we reach the end of that row.\nThen, we will go UDR, till we reach the first cell of the row.\nThen, we will go to the next row and repeat.\n\nIf we are at the last row, then we will go U till we reach (1, 1).\n\n-----\n\nint range(int max_1, int distance, int size, int &steps)\n{\n    int taken;\n\n    if(distance*size <= steps)\n    {\n        taken = distance;\n    }\n    else\n    {\n        taken = steps/size;\n    }\n\n    steps -= taken*size;\n\n    return taken;\n}\n\nint main()\n{\n    int rows, columns, steps;\n    cin >> rows >> columns >> steps;\n\n    if(steps > 4*rows*columns - 2*rows - 2*columns)\n    {\n        cout << \"NO\\n\";\n\n        return 0;\n    }\n\n    cout << \"YES\\n\";\n    vector < pair <int, string> > journey;\n\n    for(int r = 1; r <= rows && steps > 0; r++)\n    {\n        int steps_taken;\n\n        steps_taken = range(steps, columns - 1, 1, steps);\n\n        if(steps_taken > 0)\n        {\n            journey.push_back(make_pair(steps_taken, \"R\"));\n        }\n\n        if(r < rows)\n        {\n            steps_taken = range(steps, columns - 1, 3, steps);\n\n            if(steps_taken > 0)\n            {\n                journey.push_back(make_pair(steps_taken, \"DUL\"));\n            }\n\n            if(steps_taken < columns - 1 && steps < 3 && steps > 0)\n            {\n                switch(steps)\n                {\n                    case 2 : journey.push_back(make_pair(1, \"DU\")); steps -= 2; break;\n                    case 1 : journey.push_back(make_pair(1, \"D\")); steps--; break;\n                }\n            }\n\n            if(steps > 0)\n            {\n                journey.push_back(make_pair(1, \"D\"));\n\n                steps--;\n            }\n\n            continue;\n        }\n\n        if(r == rows)\n        {\n            steps_taken = range(steps, columns - 1, 1, steps);\n\n            if(steps_taken > 0)\n            {\n                journey.push_back(make_pair(steps_taken, \"L\"));\n            }\n\n            if(steps > 0)\n            {\n                steps_taken = range(steps, rows - 1, 1, steps);\n\n                journey.push_back(make_pair(steps_taken, \"U\"));\n            }\n        }\n    }\n\n    cout << journey.size() << \"\\n\";\n    for(int i = 0; i < journey.size(); i++)\n    {\n        cout << journey[i].first << \" \" << journey[i].second << \"\\n\";\n    }\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Programs/Ayoub's Function.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long count_substrings(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nvoid solve()\n{\n    long long length, no_of_1s;\n    cin >> length >> no_of_1s;\n    \n    long long no_of_0s = (length - no_of_1s);\n    \n    long long total_substrings = count_substrings(length);\n    \n    long long dividers = (no_of_1s + 1);\n    \n    long long full_zero_islands_size = (no_of_0s/dividers);\n    \n    long long zero_substrings = dividers*count_substrings(full_zero_islands_size);\n    \n    if(no_of_0s%dividers != 0)\n    {\n        long long remaining_zeroes = no_of_0s - dividers*(full_zero_islands_size);\n        \n        zero_substrings += remaining_zeroes*(full_zero_islands_size + 1);\n    }\n    \n    long long one_substrings = total_substrings - zero_substrings;\n    \n    cout << one_substrings << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Programs/Motarack's Birthday.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> fixed;\n    \n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        if(A[i - 1] == -1 && A[i] != -1)\n        {\n            fixed.push_back(A[i]);\n        }\n    }\n    \n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(A[i + 1] == -1 && A[i] != -1)\n        {\n            fixed.push_back(A[i]);\n        }\n    }\n    \n    sort(all(fixed));\n    \n    long long mid;\n    \n    if(fixed.size() == 0)\n    {\n        mid = 0;\n    }\n    else\n    {\n        mid = (fixed[0] + fixed.back())/2;\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] == -1)\n        {\n            A[i] = mid;\n        }\n    }\n    \n    long long m = 0;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        m = max(m, abs(A[i] - A[i - 1]));\n    }\n    \n    cout << m << \" \" << mid << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Programs/Three Strings.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    string A, B, C;\n    cin >> A >> B >> C;\n    \n    for(int i = 0; i < A.size(); i++)\n    {\n        if(A[i] == C[i] || B[i] == C[i])\n        {\n            continue;\n        }\n        \n        cout << \"NO\\n\";\n        \n        return;\n    }\n    \n    cout << \"YES\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/619 Div 2/Programs/Time to Run.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint range(int max_1, int distance, int size, int &steps)\n{\n    int taken;\n    \n    if(distance*size <= steps)\n    {\n        taken = distance;\n    }\n    else\n    {\n        taken = steps/size;\n    }\n    \n    steps -= taken*size;\n    \n    return taken;\n}\n\nint main()\n{\n    int rows, columns, steps;\n    cin >> rows >> columns >> steps;\n    \n    if(steps > 4*rows*columns - 2*rows - 2*columns)\n    {\n        cout << \"NO\\n\";\n        \n        return 0;\n    }\n    \n    cout << \"YES\\n\";\n    vector < pair <int, string> > journey;\n    \n    for(int r = 1; r <= rows && steps > 0; r++)\n    {\n        int steps_taken;\n        \n        steps_taken = range(steps, columns - 1, 1, steps);\n        \n        if(steps_taken > 0)\n        {\n            journey.push_back(make_pair(steps_taken, \"R\"));\n        }\n        \n        if(r < rows)\n        {\n            steps_taken = range(steps, columns - 1, 3, steps);\n            \n            if(steps_taken > 0)\n            {\n                journey.push_back(make_pair(steps_taken, \"DUL\"));\n            }\n            \n            if(steps_taken < columns - 1 && steps < 3 && steps > 0)\n            {\n                switch(steps)\n                {\n                    case 2 : journey.push_back(make_pair(1, \"DU\")); steps -= 2; break;\n                    case 1 : journey.push_back(make_pair(1, \"D\")); steps--; break;\n                }\n            }\n            \n            if(steps > 0)\n            {\n                journey.push_back(make_pair(1, \"D\"));\n                \n                steps--;\n            }\n            \n            continue;\n        }\n        \n        if(r == rows)\n        {\n            steps_taken = range(steps, columns - 1, 1, steps);\n            \n            if(steps_taken > 0)\n            {\n                journey.push_back(make_pair(steps_taken, \"L\"));\n            }\n            \n            if(steps > 0)\n            {\n                steps_taken = range(steps, rows - 1, 1, steps);\n                \n                journey.push_back(make_pair(steps_taken, \"U\"));\n            }\n        }\n    }\n\n    cout << journey.size() << \"\\n\";\n    for(int i = 0; i < journey.size(); i++)\n    {\n        cout << journey[i].first << \" \" << journey[i].second << \"\\n\";\n    }\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Explanations/1-Trees and Queries Explanation.txt",
    "content": "There is a crucial insight that we can make here.\nWe can make a 'waiting' move.\n\nAfter we travel from a -> b, we can keep going back and forth on the same edge.\nb-> c -> b\n\nWe can keep going back and forth to one of the neighbours of b.\nThis way, we can make an unlimited number of moves !\n\n----\n\nSuppose we have a path of length L.\nThere is a path of length (L + 2X) for every integer X.\n\n----\n\nNow, there are 3 Simple Paths from (a, b)\n\n1. a -> b\n2. a -> x -> y -> b\n3. a -> y -> x -> b\n\n----\n\nIf any of these path lengths <= k and have the same parity as k,\nthen we can use the required number of waiting moves to go from (a, b) and\nuse exactly k moves.\n\n----\n\nWe can use LCA to calculate the distance between 2 vertices.\nWe can do O(N Log N) precompute and answer each query in O(Log N) time.\n\n-----\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n\n    depth[0] = 0;\n\n    dfs(1, 0);\n\n    precompute_parents(no_of_vertices);\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int x, y, a, b, k;\n        cin >> x >> y >> a >> b >> k;\n\n        int path_1 = distance(a, b);\n        int path_2 = distance(a, x) + distance(b, y) + 1;\n        int path_3 = distance(a, y) + distance(b, x) + 1;\n\n        if( (path_1 <= k && path_1%2 == k%2) ||\n            (path_2 <= k && path_2%2 == k%2) ||\n            (path_3 <= k && path_3%2 == k%2) )\n        {\n            cout << \"YES\\n\";\n        }\n        else\n        {\n            cout << \"NO\\n\";\n        }\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Explanations/Air Conditioner Explanation.txt",
    "content": "We can interpret this problem geometrically and it would help greatly.\n\nLet us visualise the time on the y-axis and the temperature on the x axis.\nWe are given a set of segments and we must determine if it is possible to draw\na line that passes through each of them.\n\nInstead of keeping track of a line, we will keep track of the possible range of the line.\nLet the line always lie between [A, B] on the x axis.\n\nIn the time between two events, the minimum can reduce by at most (T[i] - T[i - 1])\nand the maximum can reduce by at most (T[i] - T[i - 1])\n\nHowever, we have to be careful of one thing.\n\nThe minimum range of the line cannot be lesser than the Left boundary of any event.\nThe maximum range of the line cannot be greater than the Right boundary of any event.\n\nSo at every point, we just have to update the minimum and maximum range of the line.\nWe are keeping the range as large as possible at every step.\nIf a line exists, it has to do so within this range.\n\nThe beauty of this approach is that we don't have to find the actual line. Just knowing it's range is enough. :)\n\n-----\n\nstruct customer\n{\n    int time, left, right;\n\n    customer(){}\n\n    customer(int T, int L, int R)\n    {\n        time = T; left = L; right = R;\n    }\n};\n\nint sort_by_time(customer &A, customer &B)\n{\n    if(A.time == B.time)\n    {\n        return (A.left < B.left);\n    }\n\n    return (A.time < B.time);\n}\n\nvoid solve()\n{\n    int no_of_customers, starting;\n    cin >> no_of_customers >> starting;\n\n    vector <customer> C(no_of_customers, customer(0, 0, 0));\n    for(int i = 0; i < no_of_customers; i++)\n    {\n        cin >> C[i].time >> C[i].left >> C[i].right;\n    }\n\n    sort(all(C), sort_by_time);\n\n    int minimum = starting, maximum = starting;\n    int possible = true;\n\n    for(int i = 0; i < no_of_customers && possible; i++)\n    {\n        if(i == 0)\n        {\n            minimum = starting - C[i].time;\n            maximum = starting + C[i].time;\n        }\n        else\n        {\n            minimum = minimum - (C[i].time - C[i - 1].time);\n            maximum = maximum + (C[i].time - C[i - 1].time);\n        }\n\n        if(minimum > C[i].right || maximum < C[i].left)\n        {\n            possible = false;\n            break;\n        }\n\n        minimum = max(minimum, C[i].left);\n        maximum = min(maximum, C[i].right);\n    }\n\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Explanations/Longest Palindrome Explanation.txt",
    "content": "Let R[S] be the reverse of string S\n\nThe final palindrome looks like this\n\nS1 S2 S3 ... Sm (M)R[Sm] ... R[S3]R[S2]R[S1]\nAnd M is a palindrome that can be placed in the middle.\n\nThe constraints are small enough that we can check every pair of strings.\nFor each string S[i], we will check if it's reverse R(S[i]) is also present in the array.\nWe will store all the strings in one vector and all their reverses in another vector.\n\nSuppose S[i] is the 3rd string in the list of strings we will print,\nthen R(S[i]) is the 3rd last string that we need to print.\n\nLastly, we can have at most 1 palindromic string in the middle.\nWe will check if any of the strings are palindromes.\nIf they are, we will use one in the middle.\n\n-----\n\nint main()\n{\n    int no_of_strings, length;\n    cin >> no_of_strings >> length;\n\n    vector <string> S(no_of_strings + 1);\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        cin >> S[i];\n    }\n\n    vector <int> strings_index;\n    vector <int> reverse_strings_index;\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        for(int j = i + 1; j <= no_of_strings; j++)\n        {\n            if(is_palindrome(S[i] + S[j]))\n            {\n                strings_index.push_back(i);\n                reverse_strings_index.push_back(j);\n            }\n        }\n    }\n\n    string middle;\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        if(is_palindrome(S[i]))\n        {\n            middle = S[i];\n        }\n    }\n\n    int final_length = strings_index.size() + (middle.size() != 0) + reverse_strings_index.size();\n\n    final_length *= length;\n\n    cout << final_length << \"\\n\";\n\n    for(int i = 0; i < strings_index.size(); i++)\n    {\n        cout << S[strings_index[i]];\n    }\n\n    if(middle.size() != 0)\n    {\n        cout << middle;\n    }\n\n    for(int i = reverse_strings_index.size() - 1; i >= 0; i--)\n    {\n        cout << S[reverse_strings_index[i]];\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Explanations/Shortest and Longest LIS Explanation.txt",
    "content": "1. If we want to make the shortest LIS possible, we must make sure 1 comes as late as possible as it matches with every element. Then, 2 must come as much to the right as possible and so on.\n\n2. We will start from the right end and whenever a sequence of <<< is there, we will start filling from 1, 2, 3\n\n3. For making the longest LIS possible, we will fill each digit as much to the left as possible to ensure it has as many digits as possible to match. So, we will start from the left and fill <<< 1,2,3\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    vector <int> longest_chain_from(length + 1, 1);\n    for(int i = length - 1; i >= 1; i--)\n    {\n        if(S[i - 1] == '<')\n        {\n            longest_chain_from[i] = 1 + longest_chain_from[i + 1];\n        }\n    }\n\n    vector <int> shortest_lis(length + 1);\n    for(int i = length, last = 1; i >= 1; last++)\n    {\n        int j = i;\n        for(j = i; j >= 1 && longest_chain_from[j] + 1 == longest_chain_from[j - 1]; j--)\n        {   //cout << \"J = \" << j << \"\\n\";\n            last++;\n        }\n\n        shortest_lis[i] = last;\n\n        //cout << \"J = \" << j << \" i = \" << i << \"\\n\";\n        for(int k = i - 1; k >= j; k--)\n        {\n            shortest_lis[k] = shortest_lis[k + 1] - 1;\n        }\n\n        i = j - 1;\n    }\n\n    for(int i = 1; i <= length; i++)\n    {\n        cout << shortest_lis[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    vector <int> longest_lis(length + 1);\n    for(int i = 1, last = 1; i <= length; i++, last++)\n    {\n        int j = i;\n        for(j = i; (j <= length - 1 && S[j - 1] == '>'); j++)\n        {\n            last++;\n        }\n        //cout << \"J = \" << j << \"\\n\";\n        longest_lis[i] = last;\n        for(int k = i + 1; k <= j; k++)\n        {\n            longest_lis[k] = longest_lis[k - 1] - 1;\n        }\n\n        i = j;\n    }\n\n    for(int i = 1; i <= length; i++)\n    {\n        cout << longest_lis[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Explanations/Two Rabbits Explanation.txt",
    "content": "There are two rabbits.\nThe distance between them reduces by (a + b)\nin 1 second.\nThe total distance to be covered is (x - y).\n\nThe rabbits will meet if (x - y) is a multiple of (a + b).\nOtherwise, they will never complement\n\n-----\n\nvoid solve()\n{\n    long long position_1, position_2, distance_1, distance_2;\n    cin >> position_1 >> position_2 >> distance_1 >> distance_2;\n\n    long long time = ((position_2 - position_1)%(distance_1 + distance_2) == 0 ? (position_2 - position_1)/(distance_1 + distance_2) : -1);\n    cout << time << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Programs/1-Trees and Queries.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MAX_L = 25;\nvector <int> tree[MAX_N];\nint parent[MAX_N][MAX_L], depth[MAX_N];\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0);\n}\n\nvoid dfs(int v, int parent_v)\n{\n    parent[v][0] = parent_v;\n    \n    depth[v] = depth[parent_v] + 1;\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n    }\n}\n\nvoid precompute_parents(int no_of_vertices)\n{\n    for(int l = 1; l < MAX_L; l++)\n    {\n        for(int v = 1; v <= no_of_vertices; v++)\n        {\n            int ancestor = parent[v][l - 1];\n            \n            parent[v][l] = parent[ancestor][l - 1];\n        }\n    }\n}\n\nint LCA(int u, int v)\n{\n    if(depth[v] < depth[u])\n    {\n        swap(u, v);\n    }\n    \n    int difference = depth[v] - depth[u];\n    \n    for(int i = MAX_L - 1; i >= 0; i--)\n    {\n        if(is_bit_set(difference, i))\n        {\n            v = parent[v][i];\n        }\n    }\n    \n    if(u == v)\n    {\n        return v;\n    }\n    \n    for(int i = MAX_L - 1; i >= 0; i--)\n    {\n        if(parent[v][i] != parent[u][i])\n        {\n            v = parent[v][i];\n            u = parent[u][i];\n        }\n    }\n    \n    return parent[v][0];\n}\n\nint distance(int u, int v)\n{\n    int l = LCA(u, v);\n    \n    if(l == u)\n    {\n        return (depth[v] - depth[l]);\n    }\n    \n    if(l == v)\n    {\n        return (depth[u] - depth[l]);\n    }\n    \n    return (depth[v] - depth[l]) + (depth[u] - depth[l]);\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    depth[0] = 0;\n    \n    dfs(1, 0);\n    \n    precompute_parents(no_of_vertices);\n    \n    int no_of_queries;\n    cin >> no_of_queries;\n    \n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int x, y, a, b, k;\n        cin >> x >> y >> a >> b >> k;\n        \n        int path_1 = distance(a, b);\n        int path_2 = distance(a, x) + distance(b, y) + 1;\n        int path_3 = distance(a, y) + distance(b, x) + 1;\n        \n        if( (path_1 <= k && path_1%2 == k%2) ||\n            (path_2 <= k && path_2%2 == k%2) ||\n            (path_3 <= k && path_3%2 == k%2) )\n        {\n            cout << \"YES\\n\";\n        }\n        else\n        {\n            cout << \"NO\\n\";\n        }\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Programs/Air Conditioner.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nstruct customer\n{\n    int time, left, right;\n\n    customer(){}\n    \n    customer(int T, int L, int R)\n    {\n        time = T; left = L; right = R;\n    }\n};\n\nint sort_by_time(customer &A, customer &B)\n{\n    if(A.time == B.time)\n    {\n        return (A.left < B.left);\n    }\n    \n    return (A.time < B.time);\n}\n\nvoid solve()\n{\n    int no_of_customers, starting;\n    cin >> no_of_customers >> starting;\n    \n    vector <customer> C(no_of_customers, customer(0, 0, 0));\n    for(int i = 0; i < no_of_customers; i++)\n    {\n        cin >> C[i].time >> C[i].left >> C[i].right;\n    }\n    \n    sort(all(C), sort_by_time);\n    \n    int minimum = starting, maximum = starting;\n    int possible = true;\n    \n    for(int i = 0; i < no_of_customers && possible; i++)\n    {\n        if(i == 0)\n        {\n            minimum = starting - C[i].time;\n            maximum = starting + C[i].time;\n        }\n        else\n        {\n            minimum = minimum - (C[i].time - C[i - 1].time);\n            maximum = maximum + (C[i].time - C[i - 1].time);\n        }\n        \n        if(minimum > C[i].right || maximum < C[i].left)\n        {\n            possible = false;\n            break;\n        }\n        \n        minimum = max(minimum, C[i].left);\n        maximum = min(maximum, C[i].right);\n    }\n    \n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Programs/Longest Palindrome.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <string>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint is_palindrome(string S)\n{\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] != S[S.size() - 1 - i])\n        {\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nint main()\n{\n    int no_of_strings, length;\n    cin >> no_of_strings >> length;\n    \n    vector <string> S(no_of_strings + 1);\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        cin >> S[i];\n    }\n    \n    vector <int> strings_index;\n    vector <int> reverse_strings_index;\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        for(int j = i + 1; j <= no_of_strings; j++)\n        {\n            if(is_palindrome(S[i] + S[j]))\n            {\n                strings_index.push_back(i);\n                reverse_strings_index.push_back(j);\n            }\n        }\n    }\n    \n    string middle;\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        if(is_palindrome(S[i]))\n        {\n            middle = S[i];\n        }\n    }\n    \n    int final_length = strings_index.size() + (middle.size() != 0) + reverse_strings_index.size();\n    \n    final_length *= length;\n    \n    cout << final_length << \"\\n\";\n    \n    for(int i = 0; i < strings_index.size(); i++)\n    {\n        cout << S[strings_index[i]];\n    }\n    \n    if(middle.size() != 0)\n    {\n        cout << middle;\n    }\n    \n    for(int i = reverse_strings_index.size() - 1; i >= 0; i--)\n    {\n        cout << S[reverse_strings_index[i]];\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Programs/Shortest and Longest LIS.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    vector <int> longest_chain_from(length + 1, 1);\n    for(int i = length - 1; i >= 1; i--)\n    {\n        if(S[i - 1] == '<')\n        {\n            longest_chain_from[i] = 1 + longest_chain_from[i + 1];\n        }\n    }\n    \n    vector <int> shortest_lis(length + 1);\n    for(int i = length, last = 1; i >= 1; last++)\n    {\n        int j = i;\n        for(j = i; j >= 1 && longest_chain_from[j] + 1 == longest_chain_from[j - 1]; j--)\n        {   //cout << \"J = \" << j << \"\\n\";\n            last++;\n        }\n        \n        shortest_lis[i] = last;\n        \n        //cout << \"J = \" << j << \" i = \" << i << \"\\n\";\n        for(int k = i - 1; k >= j; k--)\n        {\n            shortest_lis[k] = shortest_lis[k + 1] - 1;\n        }\n        \n        i = j - 1;\n    }\n    \n    for(int i = 1; i <= length; i++)\n    {\n        cout << shortest_lis[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    vector <int> longest_lis(length + 1);\n    for(int i = 1, last = 1; i <= length; i++, last++)\n    {\n        int j = i;\n        for(j = i; (j <= length - 1 && S[j - 1] == '>'); j++)\n        {\n            last++;\n        }\n        //cout << \"J = \" << j << \"\\n\";\n        longest_lis[i] = last;\n        for(int k = i + 1; k <= j; k++)\n        {\n            longest_lis[k] = longest_lis[k - 1] - 1;\n        }\n            \n        i = j;\n    }\n    \n    for(int i = 1; i <= length; i++)\n    {\n        cout << longest_lis[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/620 Div 2/Programs/Two Rabbits.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long position_1, position_2, distance_1, distance_2;\n    cin >> position_1 >> position_2 >> distance_1 >> distance_2;\n    \n    long long time = ((position_2 - position_1)%(distance_1 + distance_2) == 0 ? (position_2 - position_1)/(distance_1 + distance_2) : -1);\n    cout << time << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/622 Div 2/Explanations/Fast Food Restaurant Explanation.txt",
    "content": "We will have a bitmask corresponding to each possibility.\n\nHere is our strategy \n\n001\n010\n100\n011\n101\n110\n111\n\n-----\n\nSo, we will go through all the submasks and find out which masks correspond to \npossible meals.\n\n-----\n\nvoid solve()\n{\n    const int NO_OF_FOOD = 3;\n    vector <int> portions(NO_OF_FOOD);\n    for(int i = 0; i < NO_OF_FOOD; i++)\n    {\n        cin >> portions[i];\n    }\n    \n    sort(all(portions));\n    reverse(all(portions));\n    \n    int max_mask = (1 << NO_OF_FOOD);\n    int no_of_meals = 0;\n    \n    for(int m = 1; m < max_mask; m++)\n    {\n        int good_mask = true;\n        for(int i = 0; i < NO_OF_FOOD; i++)\n        {\n            if(is_bit_set(m, i) && portions[i] <= 0)\n            {   //cout << \"No \" << i << \"\\n\";\n                good_mask = false;\n            }\n        }\n        //cout << \"Mask = \" << m << \"\\n\";\n        if(!good_mask)\n        {\n            continue;\n        }\n        //cout << \"Good \\n\";\n        for(int i = 0; i < NO_OF_FOOD; i++)\n        {\n            if(is_bit_set(m, i))\n            {\n                portions[i]--;\n            }\n        }\n        \n        no_of_meals++;\n    }\n    \n    cout << no_of_meals << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/622 Div 2/Explanations/Sky Scrapers (Hard Version) Explanation.txt",
    "content": "This is the same as the Easy Version\n\nFor every A[i], we will calculate the total height if this were the peak.\n\nHere, is what we will do if A[i] is the peak\n\nWe will make all A[j] = A[i], where j < i and A[j] >= A[i]\ntill we find a j such that A[j] < A[i]\n\nWe will do the same in both the left and right directions.\n\n-----\n\nFor every A[i], we need to find the first j, such that A[j] < A[i]\n\nWe can do this with a Stack in O(1) time\n\n1. Initially Stack is empty\n2. When we reach A[i], we will pop all elements from the stack\nas long as A[stack.top()] >= A[i]\n3. Then, stack.top() will be the nearest element < A[i]\nAnd we will put A[i] in the stack after this\n\nThis is optimal for the future steps as well.\n\n-----\n\nint main()\n{\n    int no_of_plots;\n    cin >> no_of_plots;\n\n    vector <long long> max_height(no_of_plots + 5);\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cin >> max_height[i];\n    }\n\n    stack <long long> greater_than;\n    greater_than.push(0);\n\n    vector <long long> left_contribution(no_of_plots + 1);\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        while(max_height[greater_than.top()] > max_height[i])\n        {\n            greater_than.pop();\n        }\n\n        left_contribution[i] = max_height[i]*(i - greater_than.top()) + left_contribution[greater_than.top()];\n\n        //cout << \"Left \" << i << \" = \" << left_contribution[i] << \"\\n\";\n\n        greater_than.push(i);\n    }\n\n    greater_than.pop();\n\n    greater_than.push(no_of_plots + 1);\n    vector <long long> right_contribution(no_of_plots + 5);\n    for(int i = no_of_plots; i >= 1; i--)\n    {\n        while(max_height[greater_than.top()] > max_height[i])\n        {\n            greater_than.pop();\n        }\n\n        right_contribution[i] = max_height[i]*(greater_than.top() - i) + right_contribution[greater_than.top()];\n\n        greater_than.push(i);\n\n        //cout << \"Right \" << i << \" = \" << right_contribution[i] << \"\\n\";\n    }\n\n    long long answer = 0;\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        answer = max(answer, left_contribution[i] + right_contribution[i] - max_height[i]);\n    }\n\n    //cout << answer << \"\\n\";\n    int peak = 0;\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        if(answer == left_contribution[i] + right_contribution[i] - max_height[i])\n        {\n            peak = i;\n            break;\n        }\n    }\n\n    vector <long long> height(no_of_plots + 1);\n\n    height[peak] = max_height[peak];\n\n    for(int i = peak - 1; i >= 1; i--)\n    {\n        height[i] = min(max_height[i], height[i + 1]);\n    }\n\n    for(int i = peak + 1;i <= no_of_plots; i++)\n    {\n        height[i] = min(max_height[i], height[i - 1]);\n    }\n\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cout << height[i] << \" \";\n    }\n\n    cout <<\"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/622 Div 2/Explanations/Skyscrapers (Easy Version) Explanation.txt",
    "content": "The array will be ascending for some time and then descending.\n\nWe will iterate over all N plots and find the total if the i-th plot is the peak.\n\n-----\n\nlong long count(int P, vector <int> &limit, vector <int> &A)\n{\n    A[P] = limit[P];\n\n    for(int i = P - 1; i >= 1; i--)\n    {\n        A[i] = min(limit[i], A[i + 1]);\n    }\n\n    for(int i = P + 1; i < limit.size(); i++)\n    {\n        A[i] = min(limit[i], A[i - 1]);\n    }\n\n    long long total = 0;\n    for(int i = 1; i < limit.size(); i++)\n    {\n        total += A[i];\n    }\n\n    return total;\n}\n\nint main()\n{\n    int no_of_plots;\n    cin >> no_of_plots;\n\n    vector <int> max_height(no_of_plots + 1);\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cin >> max_height[i];\n    }\n\n    long long max_count = 0;\n    vector <int> answer(no_of_plots + 1);\n    vector <int> this_answer(no_of_plots + 1);\n\n    for(int peak = 1; peak <= no_of_plots; peak++)\n    {\n        if(count(peak, max_height, this_answer) > max_count)\n        {\n            max_count = count(peak, max_height, this_answer);\n\n            answer = this_answer;\n        }\n    }\n\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/622 Div 2/Programs/Fast Food Restaurants.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1 << bit)) != 0) ;\n}\n\nvoid solve()\n{\n    const int NO_OF_FOOD = 3;\n    vector <int> portions(NO_OF_FOOD);\n    for(int i = 0; i < NO_OF_FOOD; i++)\n    {\n        cin >> portions[i];\n    }\n    \n    sort(all(portions));\n    reverse(all(portions));\n    \n    int max_mask = (1 << NO_OF_FOOD);\n    int no_of_meals = 0;\n    \n    for(int m = 1; m < max_mask; m++)\n    {\n        int good_mask = true;\n        for(int i = 0; i < NO_OF_FOOD; i++)\n        {\n            if(is_bit_set(m, i) && portions[i] <= 0)\n            {\n                good_mask = false;\n            }\n        }\n        \n        if(!good_mask)\n        {\n            continue;\n        }\n       \n        for(int i = 0; i < NO_OF_FOOD; i++)\n        {\n            if(is_bit_set(m, i))\n            {\n                portions[i]--;\n            }\n        }\n        \n        no_of_meals++;\n    }\n    \n    cout << no_of_meals << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/622 Div 2/Programs/Skyscrapers (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long count(int P, vector <int> &limit, vector <int> &A)\n{\n    A[P] = limit[P];\n    \n    for(int i = P - 1; i >= 1; i--)\n    {\n        A[i] = min(limit[i], A[i + 1]);\n    }\n    \n    for(int i = P + 1; i < limit.size(); i++)\n    {\n        A[i] = min(limit[i], A[i - 1]);\n    }\n    \n    long long total = 0;\n    for(int i = 1; i < limit.size(); i++)\n    {\n        total += A[i];\n    }\n    \n    return total;\n}\n\nint main()\n{\n    int no_of_plots;\n    cin >> no_of_plots;\n    \n    vector <int> max_height(no_of_plots + 1);\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cin >> max_height[i];\n    }\n    \n    long long max_count = 0;\n    vector <int> answer(no_of_plots + 1);\n    vector <int> this_answer(no_of_plots + 1);\n    \n    for(int peak = 1; peak <= no_of_plots; peak++)\n    {\n        if(count(peak, max_height, this_answer) > max_count)\n        {\n            max_count = count(peak, max_height, this_answer);\n            \n            answer = this_answer;\n        }\n    }\n    \n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/622 Div 2/Programs/Skyscrapers (Hard Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <stack>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_plots;\n    cin >> no_of_plots;\n    \n    vector <long long> max_height(no_of_plots + 5);\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cin >> max_height[i];\n    }\n    \n    stack <long long> greater_than;\n    greater_than.push(0);\n    \n    vector <long long> left_contribution(no_of_plots + 1);\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        while(max_height[greater_than.top()] > max_height[i])\n        {\n            greater_than.pop();\n        }\n        \n        left_contribution[i] = max_height[i]*(i - greater_than.top()) + left_contribution[greater_than.top()];\n        \n        //cout << \"Left \" << i << \" = \" << left_contribution[i] << \"\\n\";\n        \n        greater_than.push(i);\n    }\n    \n    greater_than.pop();\n    \n    greater_than.push(no_of_plots + 1);\n    vector <long long> right_contribution(no_of_plots + 5);\n    for(int i = no_of_plots; i >= 1; i--)\n    {\n        while(max_height[greater_than.top()] > max_height[i])\n        {\n            greater_than.pop();\n        }\n        \n        right_contribution[i] = max_height[i]*(greater_than.top() - i) + right_contribution[greater_than.top()];\n        \n        greater_than.push(i);\n        \n        //cout << \"Right \" << i << \" = \" << right_contribution[i] << \"\\n\";\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        answer = max(answer, left_contribution[i] + right_contribution[i] - max_height[i]);\n    }\n    \n    //cout << answer << \"\\n\";\n    int peak = 0;\n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        if(answer == left_contribution[i] + right_contribution[i] - max_height[i])\n        {\n            peak = i;\n            break;\n        }\n    }\n    \n    vector <long long> height(no_of_plots + 1);\n    \n    height[peak] = max_height[peak];\n    \n    for(int i = peak - 1; i >= 1; i--)\n    {\n        height[i] = min(max_height[i], height[i + 1]);\n    }\n    \n    for(int i = peak + 1;i <= no_of_plots; i++)\n    {\n        height[i] = min(max_height[i], height[i - 1]);\n    }\n    \n    for(int i = 1; i <= no_of_plots; i++)\n    {\n        cout << height[i] << \" \";\n    }\n    \n    cout <<\"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Explanations/Dead Pixel Explanation.txt",
    "content": "There are 4 possible areas\n\n(x - 1)b\n(a - x)b\na(y - 1)\na(b - y)\n\nWe will choose the maximum of the 4 areas\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int a, b, x, y;\n    cin >> a >> b >> x >> y;\n\n    x++; y++;\n    int area_1, area_2;\n\n    if(x > a/2)\n    {\n        area_1 = (x - 1)*b;\n    }\n    else\n    {\n        area_1 = (a - x)*b;\n    }\n\n    if(y > b/2)\n    {\n        area_2 = a*(y - 1);\n    }\n    else\n    {\n        area_2 = a*(b - y);\n    }\n\n    int answer = max(area_1, area_2);\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Explanations/Homecoming Explanation.txt",
    "content": "This is a tricky problem because of the condition that we will not\nneed to go anywhere from the last station.\n\nWe will scan the array from right to left.\n\nWhenever we encounter a change in segments, we will see if the price range is in our budget.\n\nIf no, then we need to reach the (i + 1)-th spot by foot\n\n-----\n\nvoid solve()\n{\n    int bus, tram, budget;\n    cin >> bus >> tram >> budget;\n\n    string city;\n    cin >> city;\n\n    int index = 0, money_so_far = 0;\n    for(int i = city.size() - 2; i >= 0; i--)\n    {\n        if(i == city.size() - 2 || (city[i] != city[i + 1]))\n        {\n            int money_here = (city[i] == 'A' ? bus : tram);\n\n            //cout << \"Money at \" << i + 1 << \" = \" << money_here << \" T = \" << money_so_far + money_here << \"\\n\";\n            if(money_so_far + money_here > budget)\n            {\n                index = (i + 1);\n                break;\n            }\n\n            money_so_far += money_here;\n        }\n    }\n\n    cout << index + 1 << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Explanations/Recommendations Explanation.txt",
    "content": "The only operation that we are allowed is addition.\n\nLet us start processing the elements in ascending order.\n\nAt any point in time A[1] is the smallest integer.\n\nIf A[1] < A[2], we can remove A[1] from the array and solve the same problem from\n[2, n]\n\nOtherwise, A[1] = A[2] = ... = A[i]\n\nIn this case, we have to increment (i - 1) elements no matter what.\n\nSo, we will increment all values except that which has the highest cost.\n\nAnd we will discard the element with the largest cost and now we will have\n\nA[1], A[2] + 1, A[3] + 1, ... , A[i] + 1\n\nWe have to check if (A[i + 1] == A[i] + 1)\n\nIf yes, then we will add the cost of (A[i] + 1) to our multiset of costs\nand once again increment everything except the largest value.\n\nOtherwise, we will repeat the same process till the multiset is empty.\n\n-----\n\nI have used a variable called current minima which keeps track of the current minimum\nAnd a multiset which keeps track of all the costs of the current minimum.\n\nAt any one step, we will discard the largest cost.\nAnd increment all the other equal elements by 1.\nWe will update the total cost incurred so far.\nAnd we will add (A[i] + 1) cost into our multiset if current minima = (A[i] + 1)\n\nAnd when the multiset is empty, we will make current minima = A[i] again\nThis is to prevent it from timing out by getting stuck\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_magazines;\n    cin >> no_of_magazines;\n\n    vector <pair <int, long long> > M(no_of_magazines);\n\n    for(int i = 0; i < no_of_magazines; i++)\n    {\n        cin >> M[i].first;\n    }\n\n    for(int i = 0; i < no_of_magazines; i++)\n    {\n        cin >> M[i].second;\n    }\n\n    sort(all(M));\n\n    multiset <long long> equal_segment;\n\n    long long current_minima = 0, i = 0;\n\n    long long total_cost = 0, equal_segment_sum = 0;\n    while(i < M.size() || equal_segment.size() > 0)\n    {\n        while(i < M.size() && M[i].first == current_minima)\n        {\n            equal_segment.insert(M[i].second);\n            equal_segment_sum += M[i].second;\n            i++;\n        }\n\n        if(equal_segment.size() > 0)\n        {\n            auto it = equal_segment.rbegin();\n            long long largest = *it;\n\n            equal_segment.erase(equal_segment.find(largest)); //Erases only one instance of largest\n            equal_segment_sum -= largest;\n\n            total_cost += equal_segment_sum;\n\n            current_minima++;\n        }\n        else\n        {\n            current_minima = M[i].first;\n        }\n    }\n\n    cout << total_cost << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Explanations/Restoring Permutation Explanation.txt",
    "content": "We will be greedy.\n\nWe will keep a set of all integers not used so far.\n\nFor each B[i], we will take the smallest integer > B[i] which is available\nand place it in A[2i]\n\nIf there is no such element, then we will declare it is not possible.\n\nWe have to erase the element after we use it\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    set <int> available;\n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        available.insert(i);\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        available.erase(B[i]);\n    }\n\n    int possible = true;\n\n    vector <int> A(2*no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        auto it = available.lower_bound(B[i]);\n\n        if(it == available.end())\n        {\n            possible = false;\n            break;\n        }\n\n        A[2*i - 1] = B[i];\n        A[2*i] = *(it);\n\n        available.erase(it);\n    }\n\n    if(!possible)\n    {\n        cout << \"-1\\n\";\n\n        return;\n    }\n\n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Programs/Dead Pixel.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int a, b, x, y;\n    cin >> a >> b >> x >> y;\n    \n    x++; y++;\n    int area_1, area_2;\n    \n    if(x > a/2)\n    {\n        area_1 = (x - 1)*b;\n    }\n    else\n    {\n        area_1 = (a - x)*b;\n    }\n    \n    if(y > b/2)\n    {\n        area_2 = a*(y - 1);\n    }\n    else\n    {\n        area_2 = a*(b - y);\n    }\n    \n    int answer = max(area_1, area_2);\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Programs/Homecoming.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int bus, tram, budget;\n    cin >> bus >> tram >> budget;\n    \n    string city;\n    cin >> city;\n    \n    int index = 0, money_so_far = 0;\n    for(int i = city.size() - 2; i >= 0; i--)\n    {\n        if(i == city.size() - 2 || (city[i] != city[i + 1]))\n        {\n            int money_here = (city[i] == 'A' ? bus : tram);\n            \n            //cout << \"Money at \" << i + 1 << \" = \" << money_here << \" T = \" << money_so_far + money_here << \"\\n\";\n            if(money_so_far + money_here > budget)\n            {\n                index = (i + 1);\n                break;\n            }\n            \n            money_so_far += money_here;\n        }\n    }\n    \n    cout << index + 1 << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Programs/Recommendations.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_magazines;\n    cin >> no_of_magazines;\n    \n    vector <pair <int, long long> > M(no_of_magazines);\n    \n    for(int i = 0; i < no_of_magazines; i++)\n    {\n        cin >> M[i].first;\n    }\n    \n    for(int i = 0; i < no_of_magazines; i++)\n    {\n        cin >> M[i].second;\n    }\n    \n    sort(all(M));\n    \n    multiset <long long> equal_segment;\n    \n    long long current_minima = 0, i = 0;\n    \n    long long total_cost = 0, equal_segment_sum = 0;\n    while(i < M.size() || equal_segment.size() > 0)\n    {\n        while(i < M.size() && M[i].first == current_minima)\n        {\n            equal_segment.insert(M[i].second);\n            equal_segment_sum += M[i].second;\n            i++;\n        }\n        \n        if(equal_segment.size() > 0)\n        {\n            auto it = equal_segment.rbegin();\n            long long largest = *it;\n            \n            equal_segment.erase(equal_segment.find(largest)); //Erases only one instance of largest\n            equal_segment_sum -= largest;\n            \n            total_cost += equal_segment_sum;\n            \n            current_minima++;\n        }\n        else\n        {\n            current_minima = M[i].first;\n        }\n    }\n    \n    cout << total_cost << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/623 Div 2/Programs/Restoring Permutations.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n    \n    set <int> available;\n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        available.insert(i);\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        available.erase(B[i]);\n    }\n    \n    int possible = true;\n    \n    vector <int> A(2*no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        auto it = available.lower_bound(B[i]);\n        \n        if(it == available.end())\n        {\n            possible = false;\n            break;\n        }\n        \n        A[2*i - 1] = B[i];\n        A[2*i] = *(it);\n        \n        available.erase(it);\n    }\n    \n    if(!possible)\n    {\n        cout << \"-1\\n\";\n        \n        return;\n    }\n    \n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Explanations/Contest for Robots Explanation.txt",
    "content": "Let us count the number of problems, A, which A solves and B does not\nAnd B = The number of problems B solves which A does not\n\nIf (A = 0), then it is impossible to make A win\n\nIf (A > B), then we can give each problem 1 point and A wins\n\nIf (A < B), then we can give each problem A solves (B/A) number of points\nand each problem B solves 1 point.\nThen, we will start giving problems 1 extra point till their total is > B\n\nThe answer = (B/A) + 1\n\n-----\n\nint main()\n{\n    int no_of_robots;\n    cin >> no_of_robots;\n\n    vector <int> A(no_of_robots + 1);\n    for(int i = 1; i <= no_of_robots; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> B(no_of_robots + 1);\n    for(int i = 1; i <= no_of_robots; i++)\n    {\n        cin >> B[i];\n    }\n\n    int a_points = 0, b_points = 0;\n    for(int i = 1; i <= no_of_robots; i++)\n    {\n        if(A[i] != 0 && B[i] == 0)\n        {\n            a_points++;\n        }\n        else if(A[i] == 0 && B[i] != 0)\n        {\n            b_points++;\n        }\n    }\n\n    int answer = 0;\n\n    if(a_points == 0)\n    {\n        answer = -1;\n    }\n    else if(a_points > b_points)\n    {\n        answer = 1;\n    }\n    else\n    {\n        answer = (b_points/a_points) + 1;\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Explanations/Journey Planning Explanation.txt",
    "content": "We are told that if we move from i to j, then \n\nj - i = A[j] - A[i]\n\nA[i] - i = A[j] - j\n\nThis insight is easier to come upon if we think of the problem geometrically \nand think of the indices as X-axis and the values as Y-axis \n\nThe value of (A[i] - i) is invariant for a subsequence. \n\nSo, we will find out the total sum of all possible (A[i] - i) and then give the maximum\n\n------\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> beauty(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> beauty[i];\n    }\n    \n    map <int, long long> answer_for;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        answer_for[i - beauty[i]] += beauty[i];\n    }\n    \n    long long answer = 0;\n    for(auto it = answer_for.begin(); it != answer_for.end(); it++)\n    {\n        answer = max(answer, it->second);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Explanations/Navigation System Explanation.txt",
    "content": "Let us find the shortest distance of each vertex from the source.\nLet it be in D\n\nTo find D in a directed graph, we have to do BFS on the transpose graph\n\n-----\n\nvoid bfs(int source)\n{\n    queue <int> Q;\n\n    Q.push(source);\n    D[source] = 0;\n\n    while(!Q.empty())\n    {\n        int v = Q.front();\n        Q.pop();\n\n        for(int i = 0; i < transpose_graph[v].size(); i++)\n        {\n            int child = transpose_graph[v][i];\n\n            if(D[child] == -1)\n            {\n                D[child] = D[v] + 1;\n\n                Q.push(child);\n            }\n        }\n    }\n}\n\n-----\n\nLet us go through the stops in order.\n\nSuppose we are at stop i,\n\n1. If D[next] + 1 =/= D[v],\nThen the path will be forced to rebuild\nThis will increase both the minimum and maximum paths by 1\n\n2. If D[next] + 1 = D[v],\nWe will count the number of options\nIf there is more than 1 valid option from v, then\nThe maximum number of paths will increase by 1\n\n-----\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].push_back(v);\n        transpose_graph[v].push_back(u);\n    }\n\n    int no_of_stops;\n    cin >> no_of_stops;\n\n    vector <int> stops(no_of_stops + 1, 0);\n    for(int i = 1; i <= no_of_stops; i++)\n    {\n        cin >> stops[i];\n    }\n\n    int source = stops[no_of_stops];\n    bfs(source);\n\n    int minimum_paths = 0, maximum_paths = 0;\n    for(int i = 1; i < no_of_stops; i++)\n    {\n        if(D[stops[i + 1]] + 1 != D[stops[i]])\n        {\n            minimum_paths++;\n            maximum_paths++;\n            continue;\n        }\n\n        int no_of_options = 0;\n        for(int j = 0; j < graph[stops[i]].size(); j++)\n        {\n            int next = graph[stops[i]][j];\n\n            if(D[next] + 1 == D[stops[i]])\n            {\n                no_of_options++;\n            }\n        }\n\n        if(no_of_options > 1)\n        {\n            maximum_paths++;\n        }\n    }\n\n    cout << minimum_paths << \" \" << maximum_paths << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Explanations/Remove Adjacent Explanation.txt",
    "content": "We can be greedy and start removing alphabets one by one from Z to A\n\nWe need S[i - 1] to remove S[i]. We do not need any other alphabets.\n\nSo, we will remove alphabets starting from the greatest to the least\n\n-----\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    int removed = 0;\n    for(int alpha = 'z'; alpha > 'a'; alpha--)\n    {\n        for(int attempts = 1; attempts <= length; attempts++)\n        {\n            for(int i = 0; i < length; i++)\n            {\n                if( (i + 1) < length && S[i] == alpha && S[i] == S[i + 1] + 1)\n                {\n                    S.erase(i, 1);\n                    removed++;\n\n                    continue;\n                }\n\n                if( (i - 1) >= 0 && S[i] == alpha && S[i] == S[i - 1] + 1)\n                {\n                    S.erase(i, 1);\n                    removed++;\n                }\n            }\n        }\n    }\n\n    cout << removed << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Programs/Contest for Robotos.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_robots;\n    cin >> no_of_robots;\n    \n    vector <int> A(no_of_robots + 1);\n    for(int i = 1; i <= no_of_robots; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_robots + 1);\n    for(int i = 1; i <= no_of_robots; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int a_points = 0, b_points = 0;\n    for(int i = 1; i <= no_of_robots; i++)\n    {\n        if(A[i] != 0 && B[i] == 0)\n        {\n            a_points++;\n        }\n        else if(A[i] == 0 && B[i] != 0)\n        {\n            b_points++;\n        }\n    }\n    \n    int answer = 0;\n    \n    if(a_points == 0)\n    {\n        answer = -1;\n    }\n    else if(a_points > b_points)\n    {\n        answer = 1;\n    }\n    else\n    {\n        answer = (b_points/a_points) + 1;\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Programs/Journey Planning.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> beauty(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> beauty[i];\n    }\n    \n    map <int, long long> answer_for;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        answer_for[i - beauty[i]] += beauty[i];\n    }\n    \n    long long answer = 0;\n    for(auto it = answer_for.begin(); it != answer_for.end(); it++)\n    {\n        answer = max(answer, it->second);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Programs/Navigation System.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nvector <int> graph[MAX_N];\nvector <int> transpose_graph[MAX_N];\nvector <int> D(MAX_N, -1);\n\nvoid bfs(int source)\n{\n    queue <int> Q;\n    \n    Q.push(source);\n    D[source] = 0;\n    \n    while(!Q.empty())\n    {\n        int v = Q.front();\n        Q.pop();\n        \n        for(int i = 0; i < transpose_graph[v].size(); i++)\n        {\n            int child = transpose_graph[v][i];\n            \n            if(D[child] == -1)\n            {\n                D[child] = D[v] + 1;\n                \n                Q.push(child);\n            }\n        }\n    }\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        transpose_graph[v].push_back(u);\n    }\n    \n    int no_of_stops;\n    cin >> no_of_stops;\n    \n    vector <int> stops(no_of_stops + 1, 0);\n    for(int i = 1; i <= no_of_stops; i++)\n    {\n        cin >> stops[i];\n    }\n    \n    int source = stops[no_of_stops];\n    bfs(source);\n    \n    int minimum_paths = 0, maximum_paths = 0;\n    for(int i = 1; i < no_of_stops; i++)\n    {\n        if(D[stops[i + 1]] + 1 != D[stops[i]])\n        {\n            minimum_paths++;\n            maximum_paths++;\n            continue;\n        }\n        \n        int no_of_options = 0;\n        for(int j = 0; j < graph[stops[i]].size(); j++)\n        {\n            int next = graph[stops[i]][j];\n            \n            if(D[next] + 1 == D[stops[i]])\n            {\n                no_of_options++;\n            }\n        }\n        \n        if(no_of_options > 1)\n        {\n            maximum_paths++;\n        }\n    }\n    \n    cout << minimum_paths << \" \" << maximum_paths << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/625 Div 2/Programs/Remove Adjacent.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    int removed = 0;\n    for(int alpha = 'z'; alpha > 'a'; alpha--)\n    {\n        for(int attempts = 1; attempts <= length; attempts++)\n        {\n            for(int i = 0; i < length; i++)\n            {\n                if( (i + 1) < length && S[i] == alpha && S[i] == S[i + 1] + 1)\n                {\n                    S.erase(i, 1);\n                    removed++;\n                    \n                    continue;\n                }\n                \n                if( (i - 1) >= 0 && S[i] == alpha && S[i] == S[i - 1] + 1)\n                {\n                    S.erase(i, 1);\n                    removed++;\n                }\n            }\n        }\n    }\n    \n    cout << removed << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/626 Div 2/Explanations/Count Subrectangles Explanation.txt",
    "content": "1. If A[i] = 0, then the whole i-th row is 0. \nIf B[j] = 0, the whole column j is 0\n\n-----\n\n2. Ultimately, the matrix consists of some islands (rectangles) of ones seperated by entire lines of 0s.\nWe will keep track of the length of the consecutive segments of 1's both \nrow-wise and column-wise.\n\nint rows, columns, area;\n    cin >> rows >> columns >> area;\n    \n    vector <int> A(rows + 5, 0);\n    for(int i = 1; i <= rows; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(columns + 5, 0);\n    for(int i = 1; i <= columns; i++)\n    {\n        cin >> B[i];\n    }\n    \n    vector <int> row_segments;\n    row_segments.push_back(0);\n    int segment = 0;\n    for(int i = 1; i <= rows + 1; i++)\n    {\n        if(A[i] == 0 || i == rows + 1)\n        {\n            row_segments.push_back(segment);\n            \n            segment = 0;\n            \n            continue;\n        }\n        \n        segment++;\n    }\n    \n    sort(all(row_segments));\n    \n    vector <long long> row_sum(row_segments.size(), 0);\n    for(int i = 1; i < row_segments.size(); i++)\n    {\n        row_sum[i] = row_sum[i - 1] + row_segments[i];\n    }\n    \n    vector <int> column_segments;\n    column_segments.push_back(0);\n    segment = 0;\n    for(int i = 1; i <= columns + 1; i++)\n    {\n        if(B[i] == 0 || i == columns + 1)\n        {\n            column_segments.push_back(segment);\n            \n            segment = 0;\n            \n            continue;\n        }\n        \n        segment++;\n    }\n    \n    sort(all(column_segments));\n    \n    vector <long long> column_sum(column_segments.size(), 0);\n    for(int i = 1; i < column_segments.size(); i++)\n    {\n        column_sum[i] = column_sum[i - 1] + column_segments[i];\n    }\n\n-----\n\n3. Iterate over all factors (f1, f2) of K. \nLet us count the number of 'row segments' which are more than K \nand the number of 'column segments' which are more than K\n\nSuppose (f1 = 5, f2 = 3)\n\nLet us count the number of ways of selecting a row of 5 continuous ones \n\nSuppose the lengths of the row segments are - {1, 3, 5, 7, 9}\n\nThe number of ways of choosing a row segment of length 5 is \n= (5 - 5 + 1) + (7 - 5 + 1) + (9 - 5 + 1) \n= 1 + 3 + 4 \n= 8\n\nSo, we need to know \n\n1. The number of elements >= 5\n2. The sum of elements >= 5\n\nThen, the number of ways = (9 + 7 + 5) - 3(5 - 1)\n\nlong long no_of_subrectangles = 0;\n    for(long long i = 1; i*i <= area; i++)\n    {\n        if(area%i == 0)\n        {\n            long long f1 = i, f2 = area/i;\n            \n            long long row_contribution = 0;\n            \n            if(f1 <= row_segments.back())\n            {\n                int j = upper_bound(all(row_segments), f1 - 1) - row_segments.begin();\n                \n                row_contribution = (row_sum.back() - row_sum[j - 1]) -\n                    (row_segments.size() - 1 - (j - 1))*(f1 - 1);\n                \n                //cout << \"Sum = \" << (row_sum.back() - row_sum[j - 1]) << \" - \"\n                 //<< (row_segments.size() - 1 - (j - 1))*(f2 - 1) << \"\\n\";\n            }\n            \n            long long column_contribution = 0;\n            \n            if(f2 <= column_segments.back())\n            {\n                int j = upper_bound(all(column_segments), f2 - 1) - column_segments.begin();\n                \n                column_contribution = (column_sum.back() - column_sum[j - 1]) -\n                    (column_segments.size() - 1 - (j - 1))*(f2 - 1);\n            }\n            //cout << \"Fr = \" << f1 << \" Fc = \" << f2 << \" = \";\n            no_of_subrectangles += row_contribution*column_contribution;\n            //cout << no_of_subrectangles << \" = \" << row_contribution << \"x\" << column_contribution << \"\\n\";\n            \n            if(f1 == f2)\n            {\n                continue;\n            }\n            \n            column_contribution = 0;\n            \n            if(f1 <= column_segments.back())\n            {\n                int j = upper_bound(all(column_segments), f1 - 1) - column_segments.begin();\n                \n                column_contribution = (column_sum.back() - column_sum[j - 1]) -\n                    (column_segments.size() - 1 - (j - 1))*(f1 - 1);\n            }\n            \n            row_contribution = 0;\n            //cout << \"F2 = \" << f2 << \" Back = \" << row_segments.back() << \"\\n\";\n            \n            if(f2 <= row_segments.back())\n            {\n                int j = upper_bound(all(row_segments), f2 - 1) - row_segments.begin();\n                \n                row_contribution = (row_sum.back() - row_sum[j - 1]) -\n                    (row_segments.size() - 1 - (j - 1))*(f2 - 1);\n                \n                //cout << \"Sum = \" << (row_sum.back() - row_sum[j - 1]) << \" - \"\n                 //<< (row_segments.size() - 1 - (j - 1))*(f2 - 1) << \"\\n\";\n            }\n            \n            //cout << \"Fr = \" << f2 << \" Fc = \" << f1 << \" = \";\n            no_of_subrectangles += row_contribution*column_contribution;\n            //cout << no_of_subrectangles << \" = \" << row_contribution << \"x\" << column_contribution << \"\\n\";\n        }\n    }\n    \n    cout << no_of_subrectangles << \"\\n\";\n    return 0;\n"
  },
  {
    "path": "2020/Div 2/626 Div 2/Explanations/Even Subset Sum Problem Explanation.txt",
    "content": "We will either print 1 even integer or 2 odd integers\n\nIf there is only 1 odd integer, it is not possible\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> odd;\n    vector <int> even;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n\n        if(x%2 == 1)\n        {\n            odd.push_back(i);\n        }\n        else\n        {\n            even.push_back(i);\n        }\n    }\n\n    if(odd.size() >= 2)\n    {\n        cout << \"2\\n\";\n        cout << odd[0] << \" \" << odd[1] << \"\\n\";\n\n        return;\n    }\n\n    if(even.size() >= 1)\n    {\n        cout << \"1\\n\";\n        cout << even[0] << \"\\n\";\n\n        return;\n    }\n\n    cout << \"-1\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/626 Div 2/Explanations/Unusual Competitions Explanation.txt",
    "content": "Let us replace the '(' by +1  and the ')' by -1\n\nWe will keep track of the prefix sum\n\nIf at some point, the sum goes below 0, then we will start our segment from there\nWe will close the segment as soon as the sum reaches 0\n\nThis greedy solution works because we ensure each segment is as small as possible\n\n-----\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    int sum = 0;\n    int answer = 0;\n    for(int left = -1, right = 0; right < length; right++)\n    {\n        sum += (S[right] == '(' ? 1 : -1);\n\n        if(sum == -1 && left == -1)\n        {\n            left = right;\n            continue;\n        }\n\n        if(sum == 0)\n        {\n            if(left != -1)\n            {\n                answer += (right - (left - 1));\n\n                left = -1;\n\n                continue;\n            }\n        }\n    }\n\n    if(sum != 0)\n    {\n        answer = -1;\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/626 Div 2/Programs/Counting Subrectangles.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int rows, columns, area;\n    cin >> rows >> columns >> area;\n    \n    vector <int> A(rows + 5, 0);\n    for(int i = 1; i <= rows; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(columns + 5, 0);\n    for(int i = 1; i <= columns; i++)\n    {\n        cin >> B[i];\n    }\n    \n    map <int, int> row_frequency;\n    vector <int> row_segments;\n    row_segments.push_back(0);\n    int segment = 0;\n    for(int i = 1; i <= rows + 1; i++)\n    {\n        if(A[i] == 0 || i == rows + 1)\n        {\n            row_frequency[segment]++;\n            \n            row_segments.push_back(segment);\n            \n            segment = 0;\n            \n            continue;\n        }\n        \n        segment++;\n    }\n    \n    sort(all(row_segments));\n    \n    vector <long long> row_sum(row_segments.size(), 0);\n    for(int i = 1; i < row_segments.size(); i++)\n    {\n        row_sum[i] = row_sum[i - 1] + row_segments[i];\n    }\n    \n    map <int, int> column_frequency;\n    vector <int> column_segments;\n    column_segments.push_back(0);\n    segment = 0;\n    for(int i = 1; i <= columns + 1; i++)\n    {\n        if(B[i] == 0 || i == columns + 1)\n        {\n            column_frequency[segment]++;\n            \n            column_segments.push_back(segment);\n            \n            segment = 0;\n            \n            continue;\n        }\n        \n        segment++;\n    }\n    \n    sort(all(column_segments));\n    \n    vector <long long> column_sum(column_segments.size(), 0);\n    for(int i = 1; i < column_segments.size(); i++)\n    {\n        column_sum[i] = column_sum[i - 1] + column_segments[i];\n    }\n    \n    long long no_of_subrectangles = 0;\n    for(long long i = 1; i*i <= area; i++)\n    {\n        if(area%i == 0)\n        {\n            long long f1 = i, f2 = area/i;\n            \n            long long row_contribution = 0;\n            \n            if(f1 <= row_segments.back())\n            {\n                int j = upper_bound(all(row_segments), f1 - 1) - row_segments.begin();\n                \n                row_contribution = (row_sum.back() - row_sum[j - 1]) -\n                    (row_segments.size() - 1 - (j - 1))*(f1 - 1);\n                \n                //cout << \"Sum = \" << (row_sum.back() - row_sum[j - 1]) << \" - \"\n                 //<< (row_segments.size() - 1 - (j - 1))*(f2 - 1) << \"\\n\";\n            }\n            \n            long long column_contribution = 0;\n            \n            if(f2 <= column_segments.back())\n            {\n                int j = upper_bound(all(column_segments), f2 - 1) - column_segments.begin();\n                \n                column_contribution = (column_sum.back() - column_sum[j - 1]) -\n                    (column_segments.size() - 1 - (j - 1))*(f2 - 1);\n            }\n            //cout << \"Fr = \" << f1 << \" Fc = \" << f2 << \" = \";\n            no_of_subrectangles += row_contribution*column_contribution;\n            //cout << no_of_subrectangles << \" = \" << row_contribution << \"x\" << column_contribution << \"\\n\";\n            \n            if(f1 == f2)\n            {\n                continue;\n            }\n            \n            column_contribution = 0;\n            \n            if(f1 <= column_segments.back())\n            {\n                int j = upper_bound(all(column_segments), f1 - 1) - column_segments.begin();\n                \n                column_contribution = (column_sum.back() - column_sum[j - 1]) -\n                    (column_segments.size() - 1 - (j - 1))*(f1 - 1);\n            }\n            \n            row_contribution = 0;\n            //cout << \"F2 = \" << f2 << \" Back = \" << row_segments.back() << \"\\n\";\n            \n            if(f2 <= row_segments.back())\n            {\n                int j = upper_bound(all(row_segments), f2 - 1) - row_segments.begin();\n                \n                row_contribution = (row_sum.back() - row_sum[j - 1]) -\n                    (row_segments.size() - 1 - (j - 1))*(f2 - 1);\n                \n                //cout << \"Sum = \" << (row_sum.back() - row_sum[j - 1]) << \" - \"\n                 //<< (row_segments.size() - 1 - (j - 1))*(f2 - 1) << \"\\n\";\n            }\n            \n            //cout << \"Fr = \" << f2 << \" Fc = \" << f1 << \" = \";\n            no_of_subrectangles += row_contribution*column_contribution;\n            //cout << no_of_subrectangles << \" = \" << row_contribution << \"x\" << column_contribution << \"\\n\";\n        }\n    }\n    \n    cout << no_of_subrectangles << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/626 Div 2/Programs/Even Subset Sum Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> odd;\n    vector <int> even;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n        \n        if(x%2 == 1)\n        {\n            odd.push_back(i);\n        }\n        else\n        {\n            even.push_back(i);\n        }\n    }\n    \n    if(odd.size() >= 2)\n    {\n        cout << \"2\\n\";\n        cout << odd[0] << \" \" << odd[1] << \"\\n\";\n        \n        return;\n    }\n    \n    if(even.size() >= 1)\n    {\n        cout << \"1\\n\";\n        cout << even[0] << \"\\n\";\n        \n        return;\n    }\n    \n    cout << \"-1\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/626 Div 2/Programs/Unusual Competitions.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    int sum = 0;\n    int answer = 0;\n    for(int left = -1, right = 0; right < length; right++)\n    {\n        sum += (S[right] == '(' ? 1 : -1);\n        \n        if(sum == -1 && left == -1)\n        {\n            left = right;\n            continue;\n        }\n        \n        if(sum == 0)\n        {\n            if(left != -1)\n            {\n                answer += (right - (left - 1));\n                \n                left = -1;\n                \n                continue;\n            }\n        }\n    }\n    \n    if(sum != 0)\n    {\n        answer = -1;\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Explanations/Copy Copy Copy Copy Copy Explanation.txt",
    "content": "We concatenate the array N times with itself\n\nWe can pick all the distinct elements of the array and that will be the longest increasing subsequence\n\nThe length of the Longest increasing subsequence cannot be more than the number of distinct elements\n\nAs there is no element greater than the maximum element\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    set <int> distinct;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        distinct.insert(A[i]);\n    }\n\n    cout << distinct.size() << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Explanations/Ehab and GCD Explanation.txt",
    "content": "We can use (1, x - 1)\n\ngcd(1, x - 1) = 1\nlcm(1, x - 1) = x - 1\n\ngcd(1, x - 1) + lcm(1, x - 1) = x\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long x;\n    cin >> x;\n\n    cout << \"1 \" << x - 1 << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Explanations/Ehab and Path-etic MEX Explanation.txt",
    "content": "The crucial insight here is that there will always be a path running through\nany 2 edges.\n\nSo, there will always be a path that runs through both 0 and 1 and will have MEX = 2\n\nNow, is there a way, we can avoid having 2 on the same path as (0, 1) ?\nThe only way to do this is if some vertex had degree >= 3 and we label it 0, 1, 2\n\nThe mex of every path not containing 0 or 1 will be 0 or 1\nThe mex of every path containing both 0 and 1 will be 2\n\n------\n\nMy strategy was to start with the leaves and maintain a queue of them.\nAfter labelling an edge (u, v), we delete the edge and add u to our queue if u is now a leaf\n\nIf the tree has at least 3 leaves,\nthen it ensures that there is no path passing through (0, 1, 2)\nsince there can be no path that hits 3 leaves.\n\nIf the tree has only 2 leaves, then it is a bamboo and any labelling we do won't matter\n\n----\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Explanations/Ehab and XORcist Explanation.txt",
    "content": "Suppose\n\nU = 110001 V = 1100001\n\nI will keep track of the frequency of all 64 bits\n\nSo initially, it will be U = 110001\n\nNow, the sum I have to still make is V - U = 110000\n\nSo here is what I will do\nFirst 4 bits nothing\n\nThen, I'll go to the fifth bit\n\n[11:34 PM, 3/14/2020] Saikat: Presently, my answer is 110001\n\nThe sum has a 2^5 in the fifth spot\n I cannot make it 120001\nThe reason is the XOR in that spot is 1\n\nSo instead of adding 2^5, I will add two 2^4's\n\n11 2 001\nThen, I will go to the sixth bit\n\nI can't add a 1 in there.\nHere are my options -\n\n(2) 12001\n1 (3) 2001\n11 (6) 001\n112 (8) 01\n1120 (16) 1\n11200 (32)\n\n Among all these options, 1 3 2001 is the best\n\n -----\n\n 1. Keep track of frequency of each bit\n\n2. Initially, set it to XOR\n\n3. Then, look at the remaining sum\n\n4. After that go bit by bit. If the i-th bit is set in the remaining sum, then we can either\n\nAdd 2 bits of (i - 1)\nAdd 4 bits of (i - 2)\nAdd 8 bits of (i - 3)\nAdd 16 bits of (i - 4)\n.\n.\nAdd 2^m bits of (i - m)\n\nAll these choices add an even number of summands so XOR does not change\n\nAmong all these options,\nwe will choose the one which minimises the number of summands\n\n-----\n\nIt is not possible if (u > v) or if u =!= v (mod 2)\n\nThe reason is that the bits in the last position must be either even or odd and can't be both\n\nIf u = v = 0, then the answer is 0\n\nElse if u = v, the answer is 1\n\n-----\n\nThere is a simpler solution\n\nIf the answer is possible and not 0 or 1, then it is always at most 3\n\n(u + v)/2, (u - v)/2, v works\n\n-----\n\nint some_non_zero(vector <int> &A)\n{\n    for(int i = 0; i < A.size(); i++)\n    {\n        if(A[i] > 0)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0);\n}\n\nint main()\n{\n    long long array_xor, array_sum;\n    cin >> array_xor >> array_sum;\n\n    if(array_xor > array_sum || (array_xor%2 != array_sum%2))\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    if(array_xor == array_sum)\n    {\n        if(array_xor == 0)\n        {\n            cout << \"0\\n\";\n        }\n        else\n        {\n            cout << \"1\\n\";\n            cout << array_xor << \"\\n\";\n        }\n\n        return 0;\n    }\n\n    const int MAX_BITS = 63;\n    vector <int> frequency(MAX_BITS, 0);\n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(is_bit_set(array_xor, bit))\n        {\n            array_sum -= (1LL << bit);\n\n            frequency[bit]++;\n        }\n    }\n\n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(is_bit_set(array_sum, bit))\n        {\n            int best_spot = max(bit - 1, 0);\n            long long best_no_of_terms = frequency[best_spot] + 2;\n\n            for(int i = bit - 1; i >= 0; i--)\n            {\n                if(frequency[i] + (1LL << (bit - i)) <= best_no_of_terms)\n                {\n                    best_no_of_terms = frequency[i] + (1LL << (bit - i));\n\n                    best_spot = i;\n                }\n            }\n\n            frequency[best_spot] += (1LL << (bit - best_spot));\n\n            array_sum -= (1LL << bit);\n        }\n    }\n\n    vector <long long> A;\n    while(some_non_zero(frequency))\n    {\n        long long current = 0;\n\n        for(int bit = 0; bit < MAX_BITS; bit++)\n        {\n            if(frequency[bit] > 0)\n            {\n                current |= (1LL << bit);\n\n                frequency[bit]--;\n            }\n        }\n\n        A.push_back(current);\n    }\n\n    long long xorr = 0, sum = 0;\n    cout << A.size() << \"\\n\";\n    for(int i = 0; i < A.size(); i++)\n    {\n        cout << A[i] << \" \";\n        xorr ^= A[i];\n        sum += A[i];\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Programs/Copy Copy Copy Copy Copy.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    set <int> distinct;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        distinct.insert(A[i]);\n    }\n    \n    cout << distinct.size() << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Programs/Ehab and GCD.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long x;\n    cin >> x;\n    \n    cout << \"1 \" << x - 1 << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Programs/Ehab and Pathetic MEX.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <queue>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5;\nvector <set <int> > tree;\nqueue <int> leaves;\n\nvoid remove(int u, int v)\n{\n    tree[u].erase(v);\n    tree[v].erase(u);\n    \n    if(tree[u].size() == 1)\n    {\n        leaves.push(u);\n    }\n    \n    if(tree[v].size() == 1)\n    {\n        leaves.push(v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    int no_of_edges = no_of_vertices - 1;\n    tree.resize(no_of_vertices + 1);\n    map <pair <int, int>, int> edge_no;\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].insert(v);\n        tree[v].insert(u);\n        \n        edge_no[make_pair(u, v)] = i;\n        edge_no[make_pair(v, u)] = i;\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(tree[i].size() == 1)\n        {\n            leaves.push(i);\n        }\n    }\n    \n    int last_label = 0;\n    vector <int> label(no_of_edges + 1, 0);\n    while(leaves.size() > 0)\n    {\n        int current_v = leaves.front();\n        \n        leaves.pop();\n        \n        auto v_it = tree[current_v].begin();\n        \n        int current_u = *v_it;\n        \n        remove(current_u, current_v);\n        \n       /* cout << \"L = \" << current_v << \",\" << current_u\n        << \" Edge No = \" << edge_no[make_pair(current_u, current_v)] <<\n        \" edgeLabel = \" << last_label << \"\\n\";*/\n        label[edge_no[make_pair(current_u, current_v)]] = last_label++;\n    }\n    \n    \n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        cout << label[i] << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/628 Div 2/Programs/Ehab and XORcist.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint some_non_zero(vector <int> &A)\n{\n    for(int i = 0; i < A.size(); i++)\n    {\n        if(A[i] > 0)\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0);\n}\n\nint main()\n{\n    long long array_xor, array_sum;\n    cin >> array_xor >> array_sum;\n    \n    if(array_xor > array_sum || (array_xor%2 != array_sum%2))\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    if(array_xor == array_sum)\n    {\n        if(array_xor == 0)\n        {\n            cout << \"0\\n\";\n        }\n        else\n        {\n            cout << \"1\\n\";\n            cout << array_xor << \"\\n\";\n        }\n       \n        return 0;\n    }\n    \n    const int MAX_BITS = 63;\n    vector <int> frequency(MAX_BITS, 0);\n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(is_bit_set(array_xor, bit))\n        {\n            array_sum -= (1LL << bit);\n            \n            frequency[bit]++;\n        }\n    }\n    \n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(is_bit_set(array_sum, bit))\n        {\n            int best_spot = max(bit - 1, 0);\n            long long best_no_of_terms = frequency[best_spot] + 2;\n            \n            for(int i = bit - 1; i >= 0; i--)\n            {\n                if(frequency[i] + (1LL << (bit - i)) <= best_no_of_terms)\n                {\n                    best_no_of_terms = frequency[i] + (1LL << (bit - i));\n                    \n                    best_spot = i;\n                }\n            }\n            \n            frequency[best_spot] += (1LL << (bit - best_spot));\n            \n            array_sum -= (1LL << bit);\n        }\n    }\n    \n    vector <long long> A;\n    while(some_non_zero(frequency))\n    {\n        long long current = 0;\n        \n        for(int bit = 0; bit < MAX_BITS; bit++)\n        {\n            if(frequency[bit] > 0)\n            {\n                current |= (1LL << bit);\n                \n                frequency[bit]--;\n            }\n        }\n        \n        A.push_back(current);\n    }\n    \n    long long xorr = 0, sum = 0;\n    cout << A.size() << \"\\n\";\n    for(int i = 0; i < A.size(); i++)\n    {\n        cout << A[i] << \" \";\n        xorr ^= A[i];\n        sum += A[i];\n    }\n   \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Explanations/Composite Coloring Explanation.txt",
    "content": "We need to make 1 observation\nIf a number is smaller than 1000, it must have at least 1 prime factor <= 31\n\nIf a number has 2 prime factors > 31, then it's product will be\nat least 37*37 > 1000\n\nThis means that the smallest prime factor of n will be one of\n{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}\n\nWe will colour all integers with the same 'smallest prime factor'\nthe same colour\n\nThis guarantees that two integers with the same 'smallest prime factor'\nare not coprime as their gcd = common smallest prime factor\n\n-----\n\nvoid precompute(vector <int> &lowest_prime_factor, int N)\n{\n    for(long long i = 2; i < N; i++)\n    {\n        if(lowest_prime_factor[i] != 0)\n        {\n            continue;\n        }\n\n        for(long long multiple = i; multiple < N; multiple += i)\n        {\n            if(lowest_prime_factor[multiple] == 0)\n            {\n                lowest_prime_factor[multiple] = i;\n            }\n        }\n    }\n}\n\nvoid solve(vector <int> &lowest_prime_factor)\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> position({2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 31});\n    vector <int> colour(no_of_elements + 1, 0);\n\n    set <int> distinct;\n    vector <int> distinct_colours;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        colour[i] = upper_bound(position.begin(), position.end(), lowest_prime_factor[A[i]]) - position.begin();\n\n        if(distinct.find(colour[i]) == distinct.end())\n        {\n            distinct.insert(colour[i]);\n\n            distinct_colours.push_back(colour[i]);\n        }\n    }\n\n    sort(distinct_colours.begin(), distinct_colours.end());\n\n    int no_of_colours = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        colour[i] = upper_bound(distinct_colours.begin(), distinct_colours.end(), colour[i]) - distinct_colours.begin();\n\n        no_of_colours = max(no_of_colours, colour[i]);\n    }\n\n    cout << no_of_colours << \"\\n\";\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << colour[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n\nint main()\n{\n    const int MAX_N = 1001;\n    vector <int> lowest_prime_factor(MAX_N, 0);\n    precompute(lowest_prime_factor, MAX_N);\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n    {\n        solve(lowest_prime_factor);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Explanations/Exercising Walk Explanation.txt",
    "content": "The X and Y axes are independent of each other.\n\nThe optimal solution is to use a 'waiting' move.\n\nKeep going [L, R] till there is only one path left and then follow it\n\nIt has to be within [X1, X2] and [Y1, Y2]\n\nWe have to check the case where (X1 = X2) or (Y1 = Y2) seperately as it is not possible to make even 1 move\n\n-----\n\nvoid solve()\n{\n    long long up, down, left, right;\n    cin >> left >> right >> down >> up;\n\n    long long x, y, x1, y1, x2, y2;\n    cin >> x >> y >> x1 >> y1 >> x2 >> y2;\n\n    if(x1 == x2)\n    {\n        if(left + right > 0)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    else\n    {\n        long long end = x - left + right;\n\n        if(end < x1 || x2 < end)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n\n    if(y1 == y2)\n    {\n        if(up + down > 0)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    else\n    {\n        long long end = y - down + up;\n\n        if(end < y1 || y2 < end)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n\n    cout << \"Yes\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Explanations/Height All The Same Explanation.txt",
    "content": "We have to make 2 crucial observations\n\n1. The integer doesn't matter. Only the parity matters.\nWe can make all integers of the same parity equal.\n\n2. It is possible to flip the parities of two cells u and v on the board,\nno matter where they are !\n\nSuppose there is a path from u to v\n\nu t1 t2 t3 ... tk v\n\nWe will apply the second operation to\n(u, t1)\n(t1, t2)\n.\n.\n,\n(tk, v)\n\nu and v increase by 1 whereas all others increase by 2.\nThis means that we can flip the parities of any two cells together.\n\n-----\n\nIf there are an even number of even cells, we can make them all odd\n\nIf there are an even number of odd cells, we can make them all even\n\nThe only situation where we can't make all integers equal is when\nthere are an odd number of even as well odd number of odd cells\n\n-----\n\nNow, let us try to count the number of boards.\n\nLet G = MN\nLet the number of ways to fill a cell be R - (L - 1) = N\n\nNow, if G is odd, then there must be either an even number of odd cells or an even number of even cells\n\nSo every board is good.\n\nIn that case, the answer = N^G\n\n------\n\nWhat is G is even ?\n\nWe want the cases where either there are an even number of Even cells or even number of Odd cells\n\nLet the number of ways to fill a cell with an even number be E\nLet the number of ways to fill a cell with an odd number be O\n\nWe want\n\nC(G, 0) E^0 O^G + C(G, 2) E^2 O^{G - 2} + ... + C(G, G) E^G O^0\n\nThere is a beautiful combinatoric trick for this\n\nThis is basically the expansion of (O + E)^G with the odd terms removed\n\nLet us look at the expansion of (O + E)^G !\n\nHere, all the odd terms have a negative sign !\n\nSo, (O + E)^G + (O + E)^G gives us twice the number we want.\n\nSo, we have to divide this by 2.\n\nWe have to be careful that we are dealing it via MOD, so we have to multiply with inverse(2) rather than divide by 2\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long MOD)\n{\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2)\n            result = (result*x)%MOD;\n\n        x = (x*x)%MOD;\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nlong long inverse(long long x, long long MOD)\n{\n    return power_mod(x, MOD - 2, MOD);\n}\n\nint main()\n{\n    long long rows, columns, left, right;\n    cin >> rows >> columns >> left >> right;\n\n    long long grid = rows*columns;\n\n    long long answer = 1;\n\n    const int MOD = 998244353;\n\n    if(grid%2 == 1)\n    {\n        long long one_cell = right - (left - 1);\n\n        answer = power_mod(one_cell, grid, MOD);\n    }\n    else\n    {\n        long long even_cells = right/2 - (left - 1)/2;\n        long long odd_cells = (right - (left - 1)) - even_cells;\n\n        answer = (power_mod(odd_cells + even_cells, grid, MOD) + power_mod(even_cells - odd_cells, grid, MOD))%MOD;\n        answer *= inverse(2, MOD);\n\n        answer %= MOD;\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Explanations/K Complete Word Explanation.txt",
    "content": "Let f(i, alpha) be the frequency of alphabet 'alpha' in positions = i (mod k)\n\nWe will compute this first.\n\nNow, the character at 0 (mod k) must be the same character at K - 1 (mod k)\n\n-----\n\nWe will go through all positions mod k and find the cost of making it = alpha\n\nThe number of steps in making all positions = i and j (mod k) = alpha is\n\ntotal_i - frequency(i, alpha) + total_j - frequency(j, alpha)\n\n-----\n\nvoid solve()\n{\n    const int NO_OF_ALPHABETS = 26;\n\n    int length, period;\n    cin >> length >> period;\n\n    vector <vector <int> > frequency(period, vector <int> (NO_OF_ALPHABETS + 1, 0));\n    string S;\n    cin >> S;\n\n    for(int i = 0; i < length; i++)\n    {\n        frequency[i%period][S[i] - 'a']++;\n    }\n\n    int minimum_moves = 0;\n    for(int i = 0, j = period - 1; i <= j; i++, j--)\n    {\n        int moves_here = length;\n\n        if(i == j)\n        {\n            int total = length/period + (length%period >= i && i > 0);\n\n            for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n            {\n                moves_here = min(moves_here, total - frequency[i][alpha]);\n            }\n        }\n        else\n        {\n            int total_i = length/period + (length%period >= i && i > 0);\n            int total_j = length/period + (length%period >= j);\n\n            for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n            {\n                moves_here = min(moves_here, total_i - frequency[i][alpha] + total_j - frequency[j][alpha]);\n            }\n        }\n        //cout << \"I = \" << i << \" J = \" << j << \" Moves = \" << moves_here << \"\\n\";\n        minimum_moves += moves_here;\n    }\n\n    cout << minimum_moves << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Explanations/Walk on Matrix Explanation.txt",
    "content": "Here is the basic idea -\n\nWe will make a matrix such that the DP matrix gives 0 as the answer and the actual answer\nis k.\n\nHere, is what we will do.\n\nSuppose, k = 10101\n\nWe need 3 integers\n\n1. The 'Full Form' = 111111\n2. The MSB = 100000\n3. Complement = 101010\n\nHere is the 3x3 matrix we will create -\n\n111111 010101 101010\n100000 010101 101010\n111111 111111 010101\n\n-----\n\nHere is the DP Matrix\n\n111111 010101 000000\n100000 010101 000000\n100000 100000 000000\n\n-----\n\nThe Answer in the DP Matrix is 0, and the answer in the original matrix is 010101,\n\nWhich is what is required.\n\n-----\n\nk = 0 is a special case where we will print a single integer\n\n-----\n\nHow do we get this idea ?\n\nLook at the example test case given.\nWe must create a matrix where following the DP path will always gives 0.\nWe do this by adding an additional bit and setting it so it has no bit in common with k\nAnd then try to create a path in such a way that the DP path will give the answer = 0\n\nThe DP Path makes the answer 0\nThe optimal path gives us the answer k\n\n-----\n\nint is_bit_set(int n, int bit)\n{\n    return ((n&(1LL << bit)) != 0);\n}\n\nint all_ones(int n)\n{\n    return ( (n&(n + 1)) == 0);\n}\n\nint get_msb(int n)\n{\n    for(int bit = MAX_BITS; bit >= 0; bit--)\n    {\n        if(is_bit_set(n, bit))\n        {\n            return bit;\n        }\n    }\n\n    return 0;\n}\n\nint complete(int n)\n{\n    int most_significant_bit = get_msb(n);\n\n    int complete_n = 0;\n    for(int bit = most_significant_bit; bit >= 0; bit--)\n    {\n        complete_n |= (1LL << bit);\n    }\n\n    return complete_n;\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    if(n == 0)\n    {\n        cout << \"1 1\\n\";\n\n        cout << \"1\\n\";\n\n        return 0;\n    }\n\n    int full_form = (all_ones(n) ? 4*n + 3: 2*complete(n) + 1);\n    int complement = full_form - n;\n    int msb = (1 << get_msb(full_form));\n\n    matrix[1][1] = full_form; matrix[1][2] = n; matrix[1][3] = complement;\n    matrix[2][1] = msb;       matrix[2][2] = n; matrix[2][3] = complement;\n    matrix[3][1] = full_form; matrix[3][2] = full_form; matrix[3][3] = n;\n\n    cout << \"3 3\\n\";\n    for(int i = 1; i <= 3; i++)\n    {\n        for(int j = 1; j <= 3; j++)\n        {\n            cout << matrix[i][j] << \" \";\n        }\n\n        cout << \"\\n\";\n    }\n\n    /*dp[0][1] = matrix[1][1];\n    for(int i = 1; i <= 3; i++)\n    {\n        for(int j = 1; j <= 3; j++)\n        {\n            dp[i][j] = max(matrix[i][j]&dp[i - 1][j], matrix[i][j]&dp[i][j - 1]);\n\n            cout << dp[i][j] << \" \";\n        }\n\n        cout << \"\\n\";\n    }*/\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Programs/Composite Coloring.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nvoid precompute(vector <int> &lowest_prime_factor, int N)\n{\n    for(long long i = 2; i < N; i++)\n    {\n        if(lowest_prime_factor[i] != 0)\n        {\n            continue;\n        }\n        \n        for(long long multiple = i; multiple < N; multiple += i)\n        {\n            if(lowest_prime_factor[multiple] == 0)\n            {\n                lowest_prime_factor[multiple] = i;\n            }\n        }\n    }\n}\n\nvoid solve(vector <int> &lowest_prime_factor)\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> position({2, 3, 5, 7, 11, 13, 17, 19, 23, 27, 31});\n    vector <int> colour(no_of_elements + 1, 0);\n    \n    set <int> distinct;\n    vector <int> distinct_colours;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        colour[i] = upper_bound(position.begin(), position.end(), lowest_prime_factor[A[i]]) - position.begin();\n        \n        if(distinct.find(colour[i]) == distinct.end())\n        {\n            distinct.insert(colour[i]);\n            \n            distinct_colours.push_back(colour[i]);\n        }\n    }\n    \n    sort(distinct_colours.begin(), distinct_colours.end());\n    \n    int no_of_colours = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        colour[i] = upper_bound(distinct_colours.begin(), distinct_colours.end(), colour[i]) - distinct_colours.begin();\n        \n        no_of_colours = max(no_of_colours, colour[i]);\n    }\n    \n    cout << no_of_colours << \"\\n\";\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << colour[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    const int MAX_N = 1001;\n    vector <int> lowest_prime_factor(MAX_N, 0);\n    precompute(lowest_prime_factor, MAX_N);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n    {\n        solve(lowest_prime_factor);\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Programs/Exercising Walk.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long up, down, left, right;\n    cin >> left >> right >> down >> up;\n    \n    long long x, y, x1, y1, x2, y2;\n    cin >> x >> y >> x1 >> y1 >> x2 >> y2;\n    \n    if(x1 == x2)\n    {\n        if(left + right > 0)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    else\n    {\n        long long end = x - left + right;\n        \n        if(end < x1 || x2 < end)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    \n    if(y1 == y2)\n    {\n        if(up + down > 0)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    else\n    {\n        long long end = y - down + up;\n        \n        if(end < y1 || y2 < end)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    \n    cout << \"Yes\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Programs/Height All the Same.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long MOD)\n{\n    long long result = 1;\n    \n    while(power)\n    {\n        if(power%2)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nlong long inverse(long long x, long long MOD)\n{\n    return power_mod(x, MOD - 2, MOD);\n}\n\nint main()\n{\n    long long rows, columns, left, right;\n    cin >> rows >> columns >> left >> right;\n    \n    long long grid = rows*columns;\n    \n    long long answer = 1;\n    \n    const int MOD = 998244353;\n    \n    if(grid%2 == 1)\n    {\n        long long one_cell = right - (left - 1);\n        \n        answer = power_mod(one_cell, grid, MOD);\n    }\n    else\n    {\n        long long one_cell = (right - (left - 1));\n        long long even_cells = right/2 - (left - 1)/2;\n        long long odd_cells = (right - (left - 1)) - even_cells;\n        \n        if(one_cell%2 == 0)\n        {\n            answer = power_mod(one_cell, grid, MOD);\n        }\n        else\n        {\n            answer = power_mod(one_cell, grid, MOD) + 1;\n        }\n        //answer = (power_mod(odd_cells + even_cells, grid, MOD) + power_mod(even_cells - odd_cells, grid, MOD))%MOD;\n        answer *= inverse(2, MOD);\n        \n        answer %= MOD;\n    }\n    \n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Programs/K Complete Word.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    const int NO_OF_ALPHABETS = 26;\n    \n    int length, period;\n    cin >> length >> period;\n    \n    vector <vector <int> > frequency(period, vector <int> (NO_OF_ALPHABETS + 1, 0));\n    string S;\n    cin >> S;\n    \n    for(int i = 0; i < length; i++)\n    {\n        frequency[i%period][S[i] - 'a']++;\n    }\n    \n    int minimum_moves = 0;\n    for(int i = 0, j = period - 1; i <= j; i++, j--)\n    {\n        int moves_here = length;\n        \n        if(i == j)\n        {\n            int total = length/period + (length%period >= i && i > 0);\n            \n            for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n            {\n                moves_here = min(moves_here, total - frequency[i][alpha]);\n            }\n        }\n        else\n        {\n            int total_i = length/period + (length%period >= i && i > 0);\n            int total_j = length/period + (length%period >= j);\n            \n            for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n            {\n                moves_here = min(moves_here, total_i - frequency[i][alpha] + total_j - frequency[j][alpha]);\n            }\n        }\n        //cout << \"I = \" << i << \" J = \" << j << \" Moves = \" << moves_here << \"\\n\";\n        minimum_moves += moves_here;\n    }\n    \n    cout << minimum_moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/630 Div 2/Programs/Walk on Matrix.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nconst int MAX_N = 3 + 2, MAX_BITS = 25;\nint matrix[MAX_N][MAX_N], dp[MAX_N][MAX_N];\n\nint is_bit_set(int n, int bit)\n{\n    return ((n&(1LL << bit)) != 0);\n}\n\nint all_ones(int n)\n{\n    return ( (n&(n + 1)) == 0);\n}\n\nint get_msb(int n)\n{\n    for(int bit = MAX_BITS; bit >= 0; bit--)\n    {\n        if(is_bit_set(n, bit))\n        {\n            return bit;\n        }\n    }\n    \n    return 0;\n}\n\nint complete(int n)\n{\n    int most_significant_bit = get_msb(n);\n    \n    int complete_n = 0;\n    for(int bit = most_significant_bit; bit >= 0; bit--)\n    {\n        complete_n |= (1LL << bit);\n    }\n    \n    return complete_n;\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n    \n    if(n == 0)\n    {\n        cout << \"1 1\\n\";\n        \n        cout << \"1\\n\";\n        \n        return 0;\n    }\n    \n    int full_form = (all_ones(n) ? 4*n + 3: 2*complete(n) + 1);\n    int complement = full_form - n;\n    int msb = (1 << get_msb(full_form));\n                     \n    matrix[1][1] = full_form; matrix[1][2] = n; matrix[1][3] = complement;\n    matrix[2][1] = msb;       matrix[2][2] = n; matrix[2][3] = complement;\n    matrix[3][1] = full_form; matrix[3][2] = full_form; matrix[3][3] = n;\n    \n    cout << \"3 3\\n\";\n    for(int i = 1; i <= 3; i++)\n    {\n        for(int j = 1; j <= 3; j++)\n        {\n            cout << matrix[i][j] << \" \";\n        }\n        \n        cout << \"\\n\";\n    }\n    \n    /*dp[0][1] = matrix[1][1];\n    for(int i = 1; i <= 3; i++)\n    {\n        for(int j = 1; j <= 3; j++)\n        {\n            dp[i][j] = max(matrix[i][j]&dp[i - 1][j], matrix[i][j]&dp[i][j - 1]);\n            \n            cout << dp[i][j] << \" \";\n        }\n        \n        cout << \"\\n\";\n    }*/\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Explanations/Dreamoon Likes Coloring Explanation.txt",
    "content": "Firstly, if the sum is less than N, it is not possible\n\nSecondly, if any A[i] > (n - i), then it means that it must begin in one of\nthe first (i - 1) squares.\n\nThis means it would over write one of the (i - 1) colours.\n\n-----\n\nSuppose, these two conditions are not there, then it is always possible.\n\nWhen we paint the i-th colour, we want to be able to paint the entire thing.\n\nSo, the i-th colour cannot start < i,\nbecause (i - 1) colours have been used and they each have at least 1 colour each.\n\nWe also want to paint the whole thing, so A[i] should not start before\n\n(N - suffix_sum[i]) otherwise we can't paint the whole thing.\n\ni-th colour should start at max(i, N - suffix_sum[i])\n\n-----\n\nNow, if i starts at a position > i, we can be sure all the cells before it are coloured\n\nSince the (i - 1)-th colour started at a point where suffix_sum(i - 1) was enough to cover the entire thing\n\n-----\n\nint main()\n{\n    int no_of_cells, no_of_elements;\n    cin >> no_of_cells >> no_of_elements;\n\n    vector <int> A(no_of_elements + 5);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] + i - 1 > no_of_cells)\n        {\n            cout << \"-1\\n\";\n\n            return 0;\n        }\n    }\n\n    vector <long long> suffix_sum(no_of_elements + 5, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        suffix_sum[i] = A[i] + suffix_sum[i + 1];\n    }\n\n    if(suffix_sum[1] < no_of_cells)\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    for(long long i = 1; i <= no_of_elements; i++)\n    {\n        cout << max(i, no_of_cells - suffix_sum[i] + 1) << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Explanations/Dreamoon Likes Permutations Explanation.txt",
    "content": "1. Let p[i] represent the smallest integer which is not present in A[1, i]\n\n2. Let s[i] represent the smallest integer which is not present in A[i, n]\n\n3. We will precompute this in O(N log N) time.\n\n4. (i, n - i) is good if p[i] = (i + 1) and s[i + 1] = (n - i) + 1\n\n5. Count the number of i which satisfy the above condition\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    set <int> S;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        S.insert(i);\n    }\n\n    vector <int> prefix_mex(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(S.find(A[i]) != S.end())\n        {\n            S.erase(A[i]);\n        }\n\n        prefix_mex[i] = *(S.begin());\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        S.insert(i);\n    }\n\n    vector <int> suffix_mex(no_of_elements + 1);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        if(S.find(A[i]) != S.end())\n        {\n            S.erase(A[i]);\n        }\n\n        suffix_mex[i] = *(S.begin());\n    }\n\n    vector <pair <int, int> > answer;\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(prefix_mex[i] == i + 1 && suffix_mex[i + 1] == no_of_elements - i + 1)\n        {\n            answer.push_back(make_pair(i, no_of_elements - i));\n        }\n    }\n\n    cout << answer.size() << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i].first << \" \" << answer[i].second << \"\\n\";\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Explanations/Dreamoon Likes Sequences Explanation.txt",
    "content": "Fact - Two consecutive integers in the sequence cannot have the same MSB\n\nSuppose, we have 2 elements A[i] and A[i + 1] that have the same MSB - b\n\nThen, the prefix XOR (i + 1) will not have the b-th bit set.\n\nThis means that A[i] > B[i + 1], which should not happen.\n\n-----\n\nThe integers must be in ascending order.\n\nLet b(i) be the number of integers with MSB = i\n\nThen, the number of sequences of length 3 for example is\n\nb(1) b(2) b(3)\nb(1) b(2) b(4)\nb(1) b(2) b(5)\n.\n.\nand so on till\n\nb(28) b(29) b(30)\n\n-----\n\nWe can compute the number of sequences of length i with a DP\n\nLet f(i, last) be the number of sequences of length i having b(last) in the i-th position\n\nThis is = sum{b(last)*f(i - 1, second_last)},\n\nFor all seecond_last < last\n\n-----\n\nThe only thing left to do is to calculate B(i)\n\nif i = MSB, then b(i) = n - (2^i) + 1\n\nFor example, if n = 1001001,\nThen all integers in [1 000000, 1 001001] should count, which is why\n\nB(6) = n - 2^6 + 1\n\nIf i < MSB, then b(i) = 2^i, as every combination of the last (i - 1) bits is allowed\n\n----\n\nvoid solve()\n{\n    int d, mod;\n    cin >> d >> mod;\n\n    const int MAX_BITS = 31;\n    vector < vector <long long> > no_of_ways(MAX_BITS + 1,\n                                             vector <long long> (MAX_BITS + 1, 0));\n\n    vector <long long> frequency(MAX_BITS + 1, 0);\n    for(int msb = false, bit = MAX_BITS; bit >= 0; bit--)\n    {\n        if(msb)\n        {\n            frequency[bit] = (1LL << bit);\n\n            //cout << \"Frequency \" << bit << \" = \" << frequency[bit] << \"\\n\";\n\n            continue;\n        }\n\n        if(is_bit_set(d, bit))\n        {\n            if(!msb)\n            {\n                msb = true;\n\n                frequency[bit] = d - (1 << bit) + 1;\n\n                //cout << \"Frequency \" << bit << \" = \" << frequency[bit] << \"\\n\";\n            }\n\n            continue;\n        }\n    }\n\n    for(int length = 1; length <= min(d, MAX_BITS); length++)\n    {\n        for(int last = 0; last <= MAX_BITS; last++)\n        {\n            if(length == 1)\n            {\n                no_of_ways[length][last] = frequency[last];\n\n                //cout << \"F(\" << length << \",\" << last << \") = \" << no_of_ways[length][last] << \"\\n\";\n\n                continue;\n            }\n\n            for(int second_last = 0; second_last <= last - 1; second_last++)\n            {\n                no_of_ways[length][last] += (frequency[last]*no_of_ways[length - 1][second_last])%mod;\n\n                no_of_ways[length][last] %= mod;\n            }\n\n            //cout << \"F(\" << length << \",\" << last << \") = \" << no_of_ways[length][last] << \"\\n\";\n        }\n    }\n\n    long long answer = 0;\n    for(int length = 1; length <= MAX_BITS; length++)\n    {\n        for(int bit = 0; bit <= MAX_BITS; bit++)\n        {\n            answer += no_of_ways[length][bit];\n\n            answer %= mod;\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Explanations/Dreamoon and Ranking Collection Explanation.txt",
    "content": "The question is basically this\n\nAdd x elements to the array and give the greatest integer v such that\nall integers from [1, v] are there in this array of length (n + x)\n\nWe will maintain a boolean array of which elements are already there in the array.\nWe will go from 1 to as large an integer as we can and fill up the first x 'empty' spots.\n\n------\n\nvoid solve()\n{\n    int no_of_elements, x;\n    cin >> no_of_elements >> x;\n\n    const int MAX = 1e5;\n    vector <int> used(MAX, false);\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        used[A[i]] = true;\n    }\n\n    int answer = 0;\n    for(int i = 1; i < MAX; i++)\n    {\n        if(!used[i])\n        {\n            if(x == 0)\n            {\n                answer = i - 1;\n                break;\n            }\n            else\n            {\n                x--;\n                used[i] = true;\n            }\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Programs/Dreamoon Likes Coloring.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_cells, no_of_elements;\n    cin >> no_of_cells >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 5);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] + i - 1 > no_of_cells)\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n    }\n    \n    vector <long long> suffix_sum(no_of_elements + 5, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        suffix_sum[i] = A[i] + suffix_sum[i + 1];\n    }\n    \n    if(suffix_sum[1] < no_of_cells)\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    for(long long i = 1; i <= no_of_elements; i++)\n    {\n        cout << max(i, no_of_cells - suffix_sum[i] + 1) << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Programs/Dreamoon Likes Permutations.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    set <int> S;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        S.insert(i);\n    }\n    \n    vector <int> prefix_mex(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(S.find(A[i]) != S.end())\n        {\n            S.erase(A[i]);\n        }\n        \n        prefix_mex[i] = *(S.begin());\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        S.insert(i);\n    }\n    \n    vector <int> suffix_mex(no_of_elements + 1);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        if(S.find(A[i]) != S.end())\n        {\n            S.erase(A[i]);\n        }\n        \n        suffix_mex[i] = *(S.begin());\n    }\n    \n    vector <pair <int, int> > answer;\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(prefix_mex[i] == i + 1 && suffix_mex[i + 1] == no_of_elements - i + 1)\n        {\n            answer.push_back(make_pair(i, no_of_elements - i));\n        }\n    }\n    \n    cout << answer.size() << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i].first << \" \" << answer[i].second << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Programs/Dreamoon Likes Sequences.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0 );\n}\n\nvoid solve()\n{\n    int d, mod;\n    cin >> d >> mod;\n    \n    const int MAX_BITS = 31;\n    vector < vector <long long> > no_of_ways(MAX_BITS + 1,\n                                             vector <long long> (MAX_BITS + 1, 0));\n    \n    vector <long long> frequency(MAX_BITS + 1, 0);\n    for(int msb = false, bit = MAX_BITS; bit >= 0; bit--)\n    {\n        if(msb)\n        {\n            frequency[bit] = (1LL << bit);\n            \n            continue;\n        }\n        \n        if(is_bit_set(d, bit))\n        {\n            if(!msb)\n            {\n                msb = true;\n                \n                frequency[bit] = d - (1 << bit) + 1;\n            }\n            \n            continue;\n        }\n    }\n    \n    for(int length = 1; length <= min(d, MAX_BITS); length++)\n    {\n        for(int last = 0; last <= MAX_BITS; last++)\n        {\n            if(length == 1)\n            {\n                no_of_ways[length][last] = frequency[last];\n                \n                continue;\n            }\n            \n            for(int second_last = 0; second_last <= last - 1; second_last++)\n            {\n                no_of_ways[length][last] += (frequency[last]*no_of_ways[length - 1][second_last])%mod;\n                \n                no_of_ways[length][last] %= mod;\n            }\n            \n       }\n    }\n    \n    long long answer = 0;\n    for(int length = 1; length <= MAX_BITS; length++)\n    {\n        for(int bit = 0; bit <= MAX_BITS; bit++)\n        {\n            answer += no_of_ways[length][bit];\n            \n            answer %= mod;\n        }\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/631 Div 2/Programs/Dreamoon and Ranking Collection.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, x;\n    cin >> no_of_elements >> x;\n    \n    const int MAX = 1e5;\n    vector <int> used(MAX, false);\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        used[A[i]] = true;\n    }\n    \n    int answer = 0;\n    for(int i = 1; i < MAX; i++)\n    {\n        if(!used[i])\n        {\n            if(x == 0)\n            {\n                answer = i - 1;\n                break;\n            }\n            else\n            {\n                x--;\n                used[i] = true;\n            }\n        }\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Explanations/Eugene and Array Explanation.txt",
    "content": "We will iterate from i = 1 to N, and count the number of good subarrays\nending at each i\n\nLet [L1, R1], [L2, R2], ... , [Lk, Rk] be all the subarrays upto i, such that\ntheir sum is 0.\n\nLet Lk be the greatest of all the Lk's\n\nThen,\n[Lk + 1, i]\n[Lk + 2, i]\n[Lk + 3, i]\n.\n.\n.\n[i, i]\n\nare all good subarrays as there is no subarrays inside such that the sum is 0.\n\n-----\n\nNow, the only question is how do we find the largest end_point L_k ? \n\nLet us make an observation \n\nIf Sum[L, R] = 0, then Sum[R] - Sum[L - 1] = 0 \n\nSum[R] = Sum[L - 1]\n\nWe will keep track of the prefix sum and the last occurrence of every Sum[i]\n\nNow, when we are at i, we will check if Sum[i] has occurred before by checking \nit's frequency !\n\nIf frequency[Sum[i]] > 0, then it means it has occurred before, \nwe will look at the rightmost position where Sum[i] has occurred \n\n-----\n\nLet it be L \n\nThen, end point = max(end_point, L + 2)\n\nWhy L + 2 ? \n\nBecause Sum[i] = Sum[L] \n\nSo Sum[L + 1, i] = 0 \n\nFrom [L + 2, i] is the first (possibly) good array)\n\nThat is why end point = max(end_point, L + 2)\n\n-----\n\nFor every i, we have updated end_point, so end_point always is the point from which\n\n[end_point, i] is a good array. \n\nNow, we have to ensure that end_point <= i \n\nThe number of good arrays ending at i is (i - end_point + 1)\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> prefix_sum(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\n    }\n    \n    int end_point = 0;\n    \n    map <long long, int> frequency;\n    map <long long, int> last_occurence;\n    frequency[0] = 1;\n    long long answer = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(frequency[prefix_sum[i]] != 0)\n        {\n            end_point = max(end_point, last_occurence[prefix_sum[i]] + 2);\n        }\n        \n        last_occurence[prefix_sum[i]] = i;\n        \n        frequency[prefix_sum[i]] = i;\n        \n        int distance = (end_point == 0 ? i : i - end_point + 1);\n    \n        answer += (distance > 0 ? distance : 0);\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Explanations/Kate and Imperfection Explanation.txt",
    "content": "Here is the optimal approach\n\n1. We will use all the prime numbers first. The imperfection remains 1\n\n2. Once we are done, we must use a composite integer. And the imperfection will increase\n\nWe will put 4 next, and then we will put in 6 so that the gcd becomes 3\n\nIf we put 8, the gcd becomes 4\n\n3. The editorial has a very nice proof.\n\nSuppose we have k integers in our set - {A1, A2, ... , Ak}, then\nfor every integer Ai, all it's divisors are also there.\n\nLet us suppose for some Ai, there is a divisor of Ai = x that is not in the set\nWe can remove Ai from the set and put in x\n\nThe gcd will not increase and the answer will remain the same\n\nSo, we can use the following constructive idea\n\nAn integer will be added to the set after all it's divisors have been added\n\n-----\n\nHow do we do this ?\n\nWe can use a sieve to find out the greatest divisor of all the integers\n\nThen, we will sort them by their greatest divisor\n\nFor the answer for k, we will choose the first k elements\n\nThe gcd will be equal to the greatest divisor of A[k] since it's divisor is already in the set\n\n-----\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    vector <int> largest_divisor(n + 1, 1);\n    for(int i = 1; i <= n; i++)\n    {\n        for(int multiple = 2*i; multiple <= n; multiple += i)\n        {\n            largest_divisor[multiple] = i;\n        }\n    }\n\n    sort(largest_divisor.begin(), largest_divisor.end());\n    for(int i = 2; i <= n; i++)\n    {\n        cout << largest_divisor[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Explanations/Kind Anton Explanation.txt",
    "content": "The important constraint here is that the condition (j < i) is maintained\n\nSo, we will start transforming A from the last element to the first\n\nWhile at i, we will check if (A[i] < B[i]), and see if there is a +1 in the prefix_sum\n\nAnd if (A[i] > B[i]), we will check if there is a -1 in the prefix\n\nWe will go through the array and check if these conditions are maintained\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1), B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    int positive = false, negative = false, possible = true;;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] < B[i])\n        {\n            if(!positive)\n            {\n                possible = false;\n            }\n        }\n\n        if(A[i] > B[i])\n        {\n            if(!negative)\n            {\n                possible = false;\n            }\n        }\n\n        if(A[i] == 1)\n        {\n            positive = true;\n        }\n\n        if(A[i] == -1)\n        {\n            negative = true;\n        }\n    }\n\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Explanations/Little Artem Explanation.txt",
    "content": "Case 1 - Suppose M, N are both odd\n\nWe will colour the board like a chessboard with the first square being black\nThe number of squares is odd so there is 1 more black cell than white cell.\n\nSo, B = W + 1 is satisfied\n\n-----\n\nCase 2 - One of M, N is even\n\nThe square at the [M][N] is white and the number of black and white cells are\nequal.\n\nWe will just back the last cell [M][N] = 'B'\n\nThis will reduce the number of good white cells by 1 and keep\nthe number of good black cells constant so B = W + 1 is maintained\n\n-----\n\nCase 3 - Both M, N are even\n\nNow [M][N] = B anyway so we will make cell [M][1] = B\n\nThis reduces the number of good white cells by 1 and the number of black cells constant\n\nB = W + 1 is maintained\n\nThis satisfies all the cases\n\n----\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            switch((i + j)%2)\n            {\n                case 0 : grid[i][j] = 'B'; break;\n                case 1 : grid[i][j] = 'W'; break;\n            }\n        }\n    }\n\n    grid[rows][columns] = 'B';\n\n    if(rows%2 == 0 && columns%2 == 0)\n    {\n        grid[rows][1] = 'B';\n    }\n\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            cout << grid[i][j];\n        }\n\n        cout << \"\\n\";\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Programs/Eugene and Array.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> prefix_sum(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\n    }\n    \n    int end_point = 0;\n    \n    map <long long, int> frequency;\n    map <long long, int> last_occurence;\n    frequency[0] = 1;\n    long long answer = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(frequency[prefix_sum[i]] != 0)\n        {\n            end_point = max(end_point, last_occurence[prefix_sum[i]] + 2);\n        }\n        \n        last_occurence[prefix_sum[i]] = i;\n        \n        frequency[prefix_sum[i]] = i;\n        \n        int distance = (end_point == 0 ? i : i - end_point + 1);\n    \n        answer += (distance > 0 ? distance : 0);\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Programs/Kate and Imperfection.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n    \n    vector <int> largest_divisor(n + 1, 1);\n    for(int i = 1; i <= n; i++)\n    {\n        for(int multiple = 2*i; multiple <= n; multiple += i)\n        {\n            largest_divisor[multiple] = i;\n        }\n    }\n    \n    sort(largest_divisor.begin(), largest_divisor.end());\n    for(int i = 2; i <= n; i++)\n    {\n        cout << largest_divisor[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Programs/Kind Anton.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1), B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int positive = false, negative = false, possible = true;;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] < B[i])\n        {\n            if(!positive)\n            {\n                possible = false;\n            }\n        }\n        \n        if(A[i] > B[i])\n        {\n            if(!negative)\n            {\n                possible = false;\n            }\n        }\n        \n        if(A[i] == 1)\n        {\n            positive = true;\n        }\n        \n        if(A[i] == -1)\n        {\n            negative = true;\n        }\n    }\n    \n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while (no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Div 2/632 Div 2/Programs/Little Artem.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nconst int MAX_N = 105;\nchar grid[MAX_N][MAX_N];\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            switch((i + j)%2)\n            {\n                case 0 : grid[i][j] = 'B'; break;\n                case 1 : grid[i][j] = 'W'; break;\n            }\n        }\n    }\n    \n    grid[rows][columns] = 'B';\n    \n    if(rows%2 == 0 && columns%2 == 0)\n    {\n        grid[rows][1] = 'B';\n    }\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            cout << grid[i][j];\n        }\n        \n        cout << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while (no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/633 Div 2/Explanations/Filling Diamonds Explanation.txt",
    "content": "It is difficult to explain this without drawing a diagram. \n\nThe main idea is that if we place a diamond vertically, the rest of the positions are forced. \n\nIn a diagram of (4n - 2) triangles, there are n positions where we can place a vertical diamond\n\nThe arrangement before and after the vertical triangle are fixed\n\nSo, the answer is always n\n\n-----\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    cout << n << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/633 Div 2/Explanations/Powered Addition Explanation.txt",
    "content": "1. We will keep track of the Prefix Maximum as we go from i = 1 to N\n\n2. At every i, we will check if A[i] < prefix_max\n\n3. If yes, we will add just enough to make A[i] = prefix_max\nThe time taken = msb(prefix_max - A[i])\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    int time_required = 0;\n    long long max_so_far = A[1];\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] >= max_so_far)\n        {\n            max_so_far = A[i];\n            continue;\n        }\n\n        long long required = max_so_far - A[i];\n        time_required = max(time_required, msb(required) + 1);\n\n        max_so_far = A[i] + required;\n    }\n\n    cout << time_required << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/633 Div 2/Explanations/Sorted Adjacent Differences Explanation.txt",
    "content": "What is the biggest difference ? A[1] - A[n]\n\nIf we replace, A[1] by any other element, it will get smaller and if we replace A[n] by any other element, it will get smaller\nThis means, the array ends with (A[1], A[n])\n\nNow, what should be the third last element ? It should be the second largest difference. This means that A[1] should be paired with A[n - 1].\n\nIf we exchange A[n - 1] with something else, the difference will get smaller\n\n-----\n\nAfter sorting the array,\n\nWe will make the array like this\n\nA[1] A[n]\n\nA[n - 1] A[1] A[n]\n\nA[2] A[n - 1] A[1] A[n]\n\nand so on\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(A.begin() + 1, A.end());\n\n    vector <int> answer(no_of_elements + 1);\n    for(int i = no_of_elements, front = 1, back = no_of_elements; i >= 1; i--)\n    {\n        if(i%2 == no_of_elements%2)\n        {\n            answer[i] = A[back--];\n        }\n        else\n        {\n            answer[i] = A[front++];\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/633 Div 2/Programs/Filling Diamonds.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    cout << n << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n    {\n        solve();\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/633 Div 2/Programs/Powered Addition.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0);\n}\n\nint msb(long long n)\n{\n    const int MAX_BIT = 63;\n    for(int bit = MAX_BIT; bit >= 0; bit--)\n    {\n        if(is_bit_set(n, bit))\n        {\n            return bit;\n        }\n    }\n    \n    return 0;\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int time_required = 0;\n    long long max_so_far = A[1];\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] >= max_so_far)\n        {\n            max_so_far = A[i];\n            continue;\n        }\n        \n        long long required = max_so_far - A[i]; \n        time_required = max(time_required, msb(required) + 1);\n        \n        max_so_far = A[i] + required;\n    }\n    \n    cout << time_required << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/633 Div 2/Programs/Sorted Adjacent Differences.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(A.begin() + 1, A.end());\n    \n    vector <int> answer(no_of_elements + 1);\n    for(int i = no_of_elements, front = 1, back = no_of_elements; i >= 1; i--)\n    {\n        if(i%2 == no_of_elements%2)\n        {\n            answer[i] = A[back--];\n        }\n        else\n        {\n            answer[i] = A[front++];\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Explanations/Ichime and Triangle Explanation.txt",
    "content": "The triangle inequality says (a + b > c)\n\nSo, we can just print b c c\n\nb + c > c\nc + c > b\n\n-----\n\nvoid solve()\n{\n    int a, b, c, d;\n    cin >> a >> b >> c >> d;\n\n    cout << b << \" \" << c << \" \" << c << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Explanations/Kana and Dragon Quest Game Explanation.txt",
    "content": "The net reduction is H/2 or 10\n\nAs long as H/2 > 10, it is always better to do the first operation\n\nAnd then, we can do the second operation to the maximum extent\n\nWe will check if the value is still > 0 after these operations\n\nAnd give the answer accordingly\n\n-----\n\nvoid solve()\n{\n    int total, type_1, type_2;\n    cin >> total >> type_1 >> type_2;\n\n    while(total/2 + total%2 > 10 && type_1 > 0)\n    {\n        total = total/2 + 10;\n        type_1--;\n    }\n\n    total -= 10*type_2;\n\n    cout << (total <= 0 ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Explanations/Linova and Kingdom Explanation.txt",
    "content": "Let us try to calculate the contribution of a vertex to the sum if we add it.\n\n-----\n\nFirstly, it is always optimal to choose the first 'unpicked' vertex in a given chain.\n\nIf we choose some other vertex v instead of u and depth[u] < depth[v]\nand u and v are in the same chain (lca(u, v) = u),\n\nthen we can choose v instead of u and get a bigger sum.\n\n-----\n\nWhen we choose a leaf vertex, it contributes depth[v] to the sum.\n\nWhat happens when we choose a non-leaf vertex v ?\n\nThe happiness of the v-th vertex is depth[v],\n\nbut the happiness of every vertex in the subtree[v] reduces by 1.\n\n(Since v is now an industrial town).\n\nSo, if v is added to our set, it contributes (depth[v] - subtree_size[v])\n\nSo the contribution[v] = (depth[v] - subtree_size[v])\n\n-----\n\nWe will sort the contribution of all the vertices and choose the greatest K vertices\n\n-----\n\nvoid dfs(int v, int parent_v)\n{\n    if(depth[v] != 0)\n    {\n        return;\n    }\n\n    depth[v] = 1 + depth[parent_v];\n\n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        dfs(child_v, v);\n\n        subtree_from[v] += (1 + subtree_from[child_v]);\n    }\n}\n\nint main()\n{\n    int no_of_vertices, chosen_vertices;\n    cin >> no_of_vertices >> chosen_vertices;\n\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n\n    depth[0] = -1;\n    dfs(1, 0);\n\n    vector <long long> contribution;\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        contribution.push_back(depth[v] - subtree_from[v]);\n    }\n\n    sort(all(contribution));\n    reverse(all(contribution));\n\n    long long sum = 0;\n    for(int i = 0; i < chosen_vertices; i++)\n    {\n        sum += contribution[i];\n    }\n\n    cout << sum << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Explanations/Xenia and Colourful Gems Explanation.txt",
    "content": "Let us imagine that X <= Y <= Z\n\nWe will iterate over the middle element.\n\nIf we fix Y, then we will look for the closest X <= Y and the closest Z >= Y\n\nThis is the optimal pairing.\nThe reason is with a y fixed, replacing either the x with a smaller x\nor the z with a larger z will increase the sum\n\n----\n\nIf we fix either the first or the third element, the exchange argument doesn't hold.\n\nFor example,\n3\n3 4\n6\n\nIf we fix the smallest element (3, 3, 6) is the triplet\nBut we can do better by increasing 3 to 4 (3, 3, 4) gives us 14 which is smaller than 18\n\n-----\n\nWe will check all 6 possibilities with each of the arrays given a chance to be X, Y and Z\n\n-----\n\nvoid find_best(vector <long long> &X, vector <long long> &Y, vector <long long> &Z, long long &answer)\n{\n    for(int j = 1; j < Y.size(); j++)\n    {\n        int i = lower_bound(all(X), Y[j]) - X.begin();\n\n        int k = lower_bound(all(Z), Y[j]) - Z.begin();\n\n        if(i != X.size() && k != Z.size())\n        {\n            answer = min(answer, square(X[i] - Y[j]) + square(Y[j] - Z[k]) + square(Z[k] - X[i]));\n        }\n\n        if(i > 1 && k != Z.size())\n        {\n            i--;\n\n            answer = min(answer, square(X[i] - Y[j]) + square(Y[j] - Z[k]) + square(Z[k] - X[i]));\n        }\n    }\n}\n\nvoid solve()\n{\n    int no_of_red, no_of_green, no_of_blue;\n    cin >> no_of_red >> no_of_green >> no_of_blue;\n\n    vector <long long> R(no_of_red + 1);\n    for(int i = 1; i <= no_of_red; i++)\n    {\n        cin >> R[i];\n    }\n    sort(all(R));\n\n    vector <long long> G(no_of_green + 1);\n    for(int i = 1; i <= no_of_green; i++)\n    {\n        cin >> G[i];\n    }\n    sort(all(G));\n\n    vector <long long> B(no_of_blue + 1);\n    for(int i = 1; i <= no_of_blue; i++)\n    {\n        cin >> B[i];\n    }\n    sort(all(B));\n\n    long long answer = LLONG_MAX; //cout << answer << \"\\n\";\n    find_best(R, G, B, answer); find_best(R, B, G, answer);\n\n    find_best(G, R, B, answer); find_best(G, B, R, answer);\n\n    find_best(B, G, R, answer); find_best(B, R, G, answer);\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Programs/Ichihime and Triangle.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int a, b, c, d;\n    cin >> a >> b >> c >> d;\n    \n    cout << b << \" \" << c << \" \" << c << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Programs/Kana and Dragon Quest game.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int total, type_1, type_2;\n    cin >> total >> type_1 >> type_2;\n    \n    while(total/2 + total%2 > 10 && type_1 > 0)\n    {\n        total = total/2 + 10;\n        type_1--;\n    }\n    \n    total -= 10*type_2;\n    \n    cout << (total <= 0 ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Programs/Linova and Kingdom.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n#define all(v) (v).begin(), (v).end()\n\nconst int MAX_N = 3e5 + 5;\nvector <int> tree[MAX_N];\nvector <int> depth(MAX_N, 0);\nvector <int> subtree_from(MAX_N, 0);\n\nvoid dfs(int v, int parent_v)\n{\n    if(depth[v] != 0)\n    {\n        return;\n    }\n    \n    depth[v] = 1 + depth[parent_v];\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n        \n        subtree_from[v] += (1 + subtree_from[child_v]);\n    }\n}\n\nint main()\n{\n    int no_of_vertices, chosen_vertices;\n    cin >> no_of_vertices >> chosen_vertices;\n    \n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    depth[0] = -1;\n    dfs(1, 0);\n    \n    vector <long long> contribution;\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        contribution.push_back(depth[v] - subtree_from[v]);\n    }\n    \n    sort(all(contribution));\n    reverse(all(contribution));\n    \n    long long sum = 0;\n    for(int i = 0; i < chosen_vertices; i++)\n    {\n        sum += contribution[i];\n    }\n    \n    cout << sum << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/635 Div 2/Programs/Xenia and Colourful Gems.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <climits>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long square(long long n)\n{\n    return n*n;\n}\n\nvoid find_best(vector <long long> &X, vector <long long> &Y, vector <long long> &Z, long long &answer)\n{\n    for(int j = 1; j < Y.size(); j++)\n    {\n        int i = lower_bound(all(X), Y[j]) - X.begin();\n        \n        int k = lower_bound(all(Z), Y[j]) - Z.begin();\n        \n        if(i != X.size() && k != Z.size())\n        {\n            answer = min(answer, square(X[i] - Y[j]) + square(Y[j] - Z[k]) + square(Z[k] - X[i]));\n        }\n        \n        if(i > 1 && k != Z.size())\n        {\n            i--;\n            \n            answer = min(answer, square(X[i] - Y[j]) + square(Y[j] - Z[k]) + square(Z[k] - X[i]));\n        }\n    }\n}\n\nvoid solve()\n{\n    int no_of_red, no_of_green, no_of_blue;\n    cin >> no_of_red >> no_of_green >> no_of_blue;\n    \n    vector <long long> R(no_of_red + 1);\n    for(int i = 1; i <= no_of_red; i++)\n    {\n        cin >> R[i];\n    }\n    sort(all(R));\n    \n    vector <long long> G(no_of_green + 1);\n    for(int i = 1; i <= no_of_green; i++)\n    {\n        cin >> G[i];\n    }\n    sort(all(G));\n    \n    vector <long long> B(no_of_blue + 1);\n    for(int i = 1; i <= no_of_blue; i++)\n    {\n        cin >> B[i];\n    }\n    sort(all(B));\n    \n    long long answer = LLONG_MAX; //cout << answer << \"\\n\";\n    find_best(R, G, B, answer); find_best(R, B, G, answer);\n    \n    find_best(G, R, B, answer); find_best(G, B, R, answer);\n    \n    find_best(B, G, R, answer); find_best(B, R, G, answer);\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Explanations/Nastya and Door Explanation.txt",
    "content": "Let us make another array where P[i] = true, if A[i] is a peak and false otherwise\n\nWe will make a prefix sum of peaks\n\nThen, for each query, we will retrun Sum[R - 1] - Sum[L]\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> is_peak(no_of_elements + 1, false);\n    for(int i = 2; i < no_of_elements; i++)\n    {\n        if(A[i - 1] < A[i] && A[i] > A[i + 1])\n        {\n            is_peak[i] = true;\n        }\n    }\n\n    vector <int> peak_sum(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        peak_sum[i] = peak_sum[i - 1] + is_peak[i];\n    }\n\n    int max_peaks = 0, left_border = 1;\n    for(int i = k; i <= no_of_elements; i++)\n    {\n        int right = i - 1, left = i - k + 1;\n        int peaks_here = peak_sum[right] - peak_sum[left];\n\n        if(peaks_here > max_peaks)\n        {\n            max_peaks = peaks_here;\n            left_border = left;\n        }\n    }\n\n    int max_parts = max_peaks + 1;\n    cout << max_parts << \" \" << left_border << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Explanations/Nastya and Rice Explanation.txt",
    "content": "The minimum weight we can make n(a - b) and the maximum weight we can make n(a + b)\n\nWe must check if the maximum weight is not < minimum capacity and that the\nminimum weight is not < maximum capacity\n\n-----\n\nvoid solve()\n{\n    int no_of_grains, a, b, c, d;\n    cin >> no_of_grains >> a >> b >> c >> d;\n\n    int minimum_weight = no_of_grains*(a - b);\n    int maximum_weight = no_of_grains*(a + b);\n\n    int minimum_capacity = (c - d);\n    int maximum_capacity = (c + d);\n\n    cout << (minimum_weight > maximum_capacity || maximum_weight < minimum_capacity ? \"No\\n\" : \"Yes\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Explanations/Nastya and Scoreboard Explanation.txt",
    "content": "Here is the best strategy -\n\nWe will try to make the left most strings as large an integer as possible.\n\nSuppose we have 100 operations in total.\n\nIf we use 2 operations for A[1] to 9, then we have 98 operations for [2, 100].\nWe have to know if this is possible.\n\nSimilarly, if we use 3 operations for A[1] to 8, then we have 97 operations for [3, 100]\nWe have to know if this is exactly possible.\n\n-----\n\n1. We will make a DP\n\nLet f(i, j) be true if it is possible to make A[i, ... , n] a valid string with exactly j operations\nand false otherwise\n\nTo calculate the transition, we will go over all 10 digits and\nif we need to use 'd' operations to make A[i] = d,\n\nf(i, j) = true if f(i + 1, j - d) is true\n\n2. We will check all 10 digits and not stop when we first get a 'true'.\nThe reason is there might be a situation when we set\nA[i] to 7 instead of 9 in order to make the entire number a valid string.\n\n-----\n\nmemset(is_possible, false, sizeof(is_possible));\n\n    is_possible[no_of_digits][0] = true;\n    for(int i = no_of_digits - 1; i >= 0; i--)\n    {\n        for(int steps = 0; steps <= switched_off_stick; steps++)\n        {\n            for(int d = 0; d < DIGITS; d++)\n            {\n                int remaining_steps = steps - steps_to_convert(state[i], d);\n\n                if(remaining_steps >= 0 && is_possible[i + 1][remaining_steps])\n                {\n                    //cout << \"F(\" << i << \",\" << steps << \") = for \" << d << \" is possible\\n\";\n                    //cout << \"Remaining Steps = \" << remaining_steps << \" And to Convert = \" << steps_to_convert(state[i], d) << \"\\n\";\n                    is_possible[i][steps] = true;\n                }\n            }\n        }\n    }\n\n-----\n\nHow to construct the optimal string ?\n\nWe will go from i = 0 to N - 1\n\nFor each position, we will try to be greedy and place as high a digit as possible\n\nif(!is_possible[0][switched_off_stick])\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    int steps_remaining = switched_off_stick;\n    string final_integer;\n    for(int i = 0 ; i < no_of_digits; i++)\n    {\n        for(int d = 9; d >= 0; d--)\n        {\n            int steps_for_suffix = steps_remaining - steps_to_convert(state[i], d);\n\n            if(steps_for_suffix >= 0 && is_possible[i + 1][steps_for_suffix])\n            {\n                final_integer.push_back('0' + d);\n\n                steps_remaining -= steps_to_convert(state[i], d);\n\n                break;\n            }\n        }\n    }\n\n    cout << final_integer << \"\\n\";\n\n-----\n\nHow to check how many steps are required to make A[i] = d, for each d from 0 to 9 ?\n\nWe will have to 'hard-code' the values of 0 to 9 and then check\n\nvoid hardcode()\n{\n    digits.push_back(\"1110111\"); //0\n    digits.push_back(\"0010010\"); //1\n    digits.push_back(\"1011101\"); //2\n    digits.push_back(\"1011011\"); //3\n    digits.push_back(\"0111010\"); //4\n    digits.push_back(\"1101011\"); //5\n    digits.push_back(\"1101111\"); //6\n    digits.push_back(\"1010010\"); //7\n    digits.push_back(\"1111111\"); //8\n    digits.push_back(\"1111011\"); //9\n}\n\nint steps_to_convert(string &current, int number)\n{\n    int steps = 0;\n    string ending = digits[number];\n\n    for(int i = 0; i < NO_OF_SEGMENTS; i++)\n    {\n        if(current[i] == '1' && ending[i] == '0')\n        {\n            return oo;\n        }\n\n        if(current[i] == '0' && ending[i] == '1')\n        {\n            steps++;\n        }\n\n        //Otherwise current[i] = ending[i]\n    }\n\n    return steps;\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Explanations/Nastya and Strange Generator Explanation.txt",
    "content": "Let us try to simulate the process -\n\nWe start with an empty array.\n\n_ _ 1 _ _\n\nNow, for the next step, we have to put 2 in the spot next to the 1\n\n_ _ 1 2 _\n\nAnd now, the digit 3 can only be placed in the last position\n\n-----\n\nClaim - The final array can be broken into subarrays consisting of consecutive integers in ascending order\n\nFor example\n\nx (x + 1) (x + 2) | y (y + 1) (y + 2) (y + 3) | z (z + 1) (z + 2) (z + 3)\n\n----\n\nProof - We can prove this in with induction over the number of 'segments' already placed\n\nWe have shown the base case that the first segment will cover the entire suffix\n\n-----\n\nLet us assume the 'k' segments are already placed and the suffix is already placed\n\nLet x be the first unplaced digit\n\nWe can place x in any of the first empty places in the prefix\n\n(x + 1) has to be a neighbour to x\n(x + 2) has to be a neighbour to (x + 1)\nand so on till the entire prefix is over. \n\n-----\n\n void solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> P(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> P[i];\n    }\n\n    int possible = true;\n    for(int i = no_of_elements; i > 1; i--)\n    {\n        if(P[i - 1] < P[i])\n        {\n            if(P[i - 1] != P[i] - 1)\n            {\n                possible = false;\n                break;\n            }\n\n            continue;\n        }\n    }\n\n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Programs/Nastya and Door.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> is_peak(no_of_elements + 1, false);\n    for(int i = 2; i < no_of_elements; i++)\n    {\n        if(A[i - 1] < A[i] && A[i] > A[i + 1])\n        {\n            is_peak[i] = true;\n        }\n    }\n    \n    vector <int> peak_sum(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        peak_sum[i] = peak_sum[i - 1] + is_peak[i];\n    }\n    \n    int max_peaks = 0, left_border = 1;\n    for(int i = k; i <= no_of_elements; i++)\n    {\n        int right = i - 1, left = i - k + 1;\n        int peaks_here = peak_sum[right] - peak_sum[left];\n        \n        if(peaks_here > max_peaks)\n        {\n            max_peaks = peaks_here;\n            left_border = left;\n        }\n    }\n    \n    int max_parts = max_peaks + 1;\n    cout << max_parts << \" \" << left_border << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Programs/Nastya and Rice.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_grains, a, b, c, d;\n    cin >> no_of_grains >> a >> b >> c >> d;\n    \n    int minimum_weight = no_of_grains*(a - b);\n    int maximum_weight = no_of_grains*(a + b);\n    \n    int minimum_capacity = (c - d);\n    int maximum_capacity = (c + d);\n    \n    cout << (minimum_weight > maximum_capacity || maximum_weight < minimum_capacity ? \"No\\n\" : \"Yes\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Programs/Nastya and Scoreboard.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 2015, DIGITS = 10, NO_OF_SEGMENTS = 7, oo = 1e9;\nint is_possible[MAX_N][MAX_N];\nvector <string> digits;\n\nvoid hardcode()\n{\n    digits.push_back(\"1110111\"); //0\n    digits.push_back(\"0010010\"); //1\n    digits.push_back(\"1011101\"); //2\n    digits.push_back(\"1011011\"); //3\n    digits.push_back(\"0111010\"); //4\n    digits.push_back(\"1101011\"); //5\n    digits.push_back(\"1101111\"); //6\n    digits.push_back(\"1010010\"); //7\n    digits.push_back(\"1111111\"); //8\n    digits.push_back(\"1111011\"); //9\n}\n\nint steps_to_convert(string &current, int number)\n{\n    int steps = 0;\n    string ending = digits[number];\n   \n    for(int i = 0; i < NO_OF_SEGMENTS; i++)\n    {\n        if(current[i] == '1' && ending[i] == '0')\n        {\n            return oo;\n        }\n        \n        if(current[i] == '0' && ending[i] == '1')\n        {\n            steps++;\n        }\n        \n        //Otherwise current[i] = ending[i]\n    }\n    \n    return steps;\n}\n\nint main()\n{\n    hardcode();\n    \n    int no_of_digits, switched_off_stick;\n    cin >> no_of_digits >> switched_off_stick;\n    \n    vector <string> state(no_of_digits);\n    for(int i = 0; i < no_of_digits; i++)\n    {\n        cin >> state[i];\n    }\n    \n    memset(is_possible, false, sizeof(is_possible));\n    \n    is_possible[no_of_digits][0] = true;\n    for(int i = no_of_digits - 1; i >= 0; i--)\n    {\n        for(int steps = 0; steps <= switched_off_stick; steps++)\n        {\n            for(int d = 0; d < DIGITS; d++)\n            {\n                int remaining_steps = steps - steps_to_convert(state[i], d);\n                \n                if(remaining_steps >= 0 && is_possible[i + 1][remaining_steps])\n                {\n                    //cout << \"F(\" << i << \",\" << steps << \") = for \" << d << \" is possible\\n\";\n                    //cout << \"Remaining Steps = \" << remaining_steps << \" And to Convert = \" << steps_to_convert(state[i], d) << \"\\n\";\n                    is_possible[i][steps] = true;\n                }\n            }\n        }\n    }\n    \n    if(!is_possible[0][switched_off_stick])\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    int steps_remaining = switched_off_stick;\n    string final_integer;\n    for(int i = 0 ; i < no_of_digits; i++)\n    {\n        for(int d = 9; d >= 0; d--)\n        {\n            int steps_for_suffix = steps_remaining - steps_to_convert(state[i], d);\n        \n            if(steps_for_suffix >= 0 && is_possible[i + 1][steps_for_suffix])\n            {\n                final_integer.push_back('0' + d);\n                \n                steps_remaining -= steps_to_convert(state[i], d);\n                \n                break;\n            }\n        }\n    }\n    \n    cout << final_integer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/637 Div 2/Programs/Nastya and Strange Generator.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> P(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> P[i];\n    }\n    \n    int possible = true;\n    for(int i = no_of_elements; i > 1; i--)\n    {\n        if(P[i - 1] < P[i])\n        {\n            if(P[i - 1] != P[i] - 1)\n            {\n                possible = false;\n                break;\n            }\n            \n            continue;\n        }\n    }\n    \n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/638 Div 2/Explanations/Pheonix and Balance Explanation.txt",
    "content": "We can use 1 fact about binary integers and powers of 2\n\n2^i = (2^{i - 1} + 2^{i - 2} + ... + 2^1 + 2^0) + 1\n\nSo 2^n is greater than all other powers of 2 combined.\n\nSo, 2^n will be in one pile along with the lightest (n/2 - 1) coins\n\nAll the other coins will be in the other pile.\n\n-----\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    int heavy_pile = (1 << n);\n    for(int i = 1; i < n/2; i++)\n    {\n        heavy_pile += (1 << i);\n    }\n\n    int light_pile = 0;\n    for(int i = n/2; i < n; i++)\n    {\n        light_pile += (1 << i);\n    }\n\n    cout << (heavy_pile - light_pile) << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/638 Div 2/Programs/Pheonix and Balance.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int heavy_pile = (1 << n);\n    for(int i = 1; i < n/2; i++)\n    {\n        heavy_pile += (1 << i);\n    }\n    \n    int light_pile = 0;\n    for(int i = n/2; i < n; i++)\n    {\n        light_pile += (1 << i);\n    }\n    \n    cout << (heavy_pile - light_pile) << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/638 Div 2/Programs/Phoenix and Balance.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int heavy_pile = (1 << n);\n    for(int i = 1; i < n/2; i++)\n    {\n        heavy_pile += (1 << i);\n    }\n    \n    int light_pile = 0;\n    for(int i = n/2; i < n; i++)\n    {\n        light_pile += (1 << i);\n    }\n    \n    cout << (heavy_pile - light_pile) << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Card Construction Explanation.txt",
    "content": "Let us try to build a recurrence between the number of cards required for H levels and (H - 1) levels\n\nWe will use 2H cards in the base triangles and (H - 1) cards for the base and then f(H - 1) cards above it\n\nf(H) = 2H + (H - 1) + f(H - 1)\n\n-----\n\nAfter precomputing this, let us see the number of pyramids we can make with H cards\n\nWe can use binary search and find out the smallest number <= H\n\nThen reduce H by it\n\nAnd continue to do so till no more pyramids can be made with H cards\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 1e9;\nvector <long long> cards;\n\nvoid precompute()\n{\n    cards.push_back(0);\n\n    while(cards.back() < MAX_N)\n    {\n        int level = cards.size();\n\n        long long next = 2*level + level - 1 + cards.back();\n\n        cards.push_back(next);\n    }\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    int no_of_pyramids = 0;\n\n    while(true)\n    {\n        int current_pyramid_size = lower_bound(all(cards), n) - cards.begin();\n\n        if(cards[current_pyramid_size] > n)\n        {\n            current_pyramid_size--;\n        }\n\n        n -= cards[current_pyramid_size];\n\n        if(current_pyramid_size == 0)\n        {\n            break;\n        }\n\n        no_of_pyramids++;\n    }\n\n    cout << no_of_pyramids << \"\\n\";\n}\n\nint main()\n{\n    precompute();\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Hilbert Hotel Explanation.txt",
    "content": "Two integers i and j will intersect if\n\ni + A[i] = j + A[j] (mod N)\n\nSo, we have to ensure that all N moduli - (0 + A[0]), (1 + A[1]), ... , (N - 1 + A[N - 1]) are unique\n\nIf any two of them are equal, there will be a collision.\n\nWe have to ensure that each modulus occurs exactly one time.\n\nIf any modulus between [0, N - 1] does not occur, then by the Pigeonhole Principle,\nsome other modulus will occur at least twice\n\nBe careful to handle negative integers properly and ensure all the moduli are positive\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> frequency_mod(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        A[i] %= no_of_elements;\n\n        if(A[i] < 0)\n        {\n            A[i] += 2*no_of_elements;\n\n            A[i] %= no_of_elements;\n        }\n\n        frequency_mod[ (i + A[i])%no_of_elements ]++;\n    }\n\n    int all_unique = true;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        if(frequency_mod[i] != 1)\n        {\n            all_unique = false;\n        }\n    }\n\n    cout << (all_unique ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Monopole Magnets Explanation.txt",
    "content": "There can be no row or column with more than 1 black segment\n\nThe reason is that if there is a row with more than 1 black segment,\nthen we can force a North Pole to reach the white squares between them.\n\nNorth Magnets can visit every black square so they should be able to visit both black segments\nWhich means both black segments have a South Magnet which attracts the North Magnet in the other segment\n\n-----\n\nIf there is a row with 0 black cells and is all white,\nthe South Magnet has to be placed in a column with 0 black cells.\n\nIf there is a row with 0 black cells and is all white and we place it in a column which has black cells,\nit will make the North Magnet visit the white cell which we don't want.\n\nSo, a South Magnet should be placed at the intersection of a white row and white column\n\n-----\n\nIf these two conditions are met, then we can see that it is sufficient to have 1 North Magnet per component\n\nAs there is a South Magnet in every row and every column, it will help us to get the North Magnet into every black cell of the segment\n\n-----\n\n1. Each row and Column has at most 1 black segment\n2. If there is an all white row, there has to be an all white column\n3. Otherwise, we will count the number of components in the graph\n\n-----\n\n#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 1005, NO_OF_NEIGHOURS = 4;\nconst char BLACK = '#', WHITE = '.';\nchar grid[MAX_N][MAX_N];\nint visited[MAX_N][MAX_N];\nint next_r[NO_OF_NEIGHOURS] = {-1, 0, 0, 1};\nint next_c[NO_OF_NEIGHOURS] = {0, 1, -1, 0};\nint rows, columns;\n\nint inside_grid(int x, int y)\n{\n    return (1 <= x && x <= rows && 1 <= y && y <= columns);\n}\n\nvoid dfs(int x, int y)\n{\n    visited[x][y] = true;\n\n    for(int n = 0; n < NO_OF_NEIGHOURS; n++)\n    {\n        int next_x = x + next_r[n];\n        int next_y = y + next_c[n];\n\n        if(inside_grid(next_x, next_y) && grid[next_x][next_y] == BLACK && !visited[next_x][next_y])\n        {\n            dfs(next_x, next_y);\n        }\n    }\n}\n\nint main()\n{\n    scanf(\"%d %d\", &rows, &columns);\n\n    for(int i = 1; i <= rows; i++)\n    {\n        scanf(\"%s\", grid[i] + 1);\n    }\n\n    vector <int> row_frequency(rows + 1);\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                row_frequency[i]++;\n            }\n        }\n    }\n\n    vector <int> column_frequency(columns + 1);\n    for(int j = 1; j <= columns; j++)\n    {\n        for(int i = 1; i <= rows; i++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                column_frequency[j]++;\n            }\n        }\n    }\n\n    int possible = true, all_white_row = false, all_white_column = false;\n    for(int i = 1; i <= rows; i++)\n    {\n        int black_cells = 0;\n\n        for(int j = 1; j <= columns; j++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                black_cells++;\n\n                if(j + 1 <= columns && grid[i][j + 1] == WHITE && black_cells != row_frequency[i])\n                {\n                    possible = false;\n                    break;\n                }\n            }\n        }\n\n        if(row_frequency[i] == 0)\n        {\n            all_white_row = true;\n        }\n    }\n\n    for(int j = 1; j <= columns; j++)\n    {\n        int black_cells = 0;\n\n        for(int i = 1; i <= rows; i++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                black_cells++;\n\n                if(i + 1 <= rows && grid[i + 1][j] == WHITE && black_cells != column_frequency[j])\n                {\n                    possible = false;\n                    break;\n                }\n            }\n        }\n\n        if(column_frequency[j] == 0)\n        {\n            all_white_column = true;\n        }\n    }\n\n    if( (all_white_row && !all_white_column) || (!all_white_row && all_white_column) )\n    {\n        possible = false;\n    }\n\n    if(!possible)\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    int no_of_components = 0;\n    memset(visited, false, sizeof(visited));\n\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(grid[i][j] == BLACK && !visited[i][j])\n            {\n                dfs(i, j);\n                no_of_components++;\n            }\n        }\n    }\n\n    cout << no_of_components << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Puzzle Pieces Explanation.txt",
    "content": "If we have only 1 row or 1 column, we can achieve any length of it \n\nOtherwise, we can only achieve 2x2 and no other combination \n\n-----\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    if(min(rows, columns) == 1)\n    {\n        cout << \"YES\\n\";\n        return;\n    }\n    \n    cout << (max(rows, columns) <= 2 ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Quantifier Question Explanation.txt",
    "content": "Let us draw an edge between every pair of vertices (u, v) if (u < v)\n\nThis will give us a directed graph.\n\nIt is important to notice that each connected component can have exactly 1 Universal Identifier.\nAll other vertices in this component must be an Existential Identifier as they are 'forced'.\n\nIf there are any cycles in this graph, then we cannot have any valid assignment\n\n-----\n\nOne thing to be careful of in this problem\n\nThis is a directed graph.\n\nSo, when we visit an unvisited graph, it is not enough to only do DFS\nWe must also do DFS on the reverse graph.\n\nSuppose the graph is like\n\n5 -> 4 -> 1 -> 2 -> 3\n\nIf we do DFS from 1, we will only be marking 2 and 3\nBut, we should mark 4 and 5 too\n\nThis is why we must maintain two vectors -\nVisited and Visited Reverse to mark all vertices in the same component.\n\n-----\n\nTo check if there is a cycle in either the DFS or Reverse DFS,\nwe will maintain another vector to keep track of whether a variable is still on the DFS Stack.\nIf we visit a vertex on the DFS Stack, it means there is a cycle.\nOtherwise, there is not.\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nvector <int> graph[MAX_N], reverse_graph[MAX_N];\nvector <int> visited(MAX_N, false);\nvector <int> on_stack(MAX_N, false);\nvector <int> visited_reverse(MAX_N, false), on_stack_reverse(MAX_N, 0);\n\nint dfs_cycle_reverse(int v)\n{\n    visited_reverse[v] = true;\n    on_stack_reverse[v] = true;\n\n    for(int i = 0; i < reverse_graph[v].size(); i++)\n    {\n        int child_v = reverse_graph[v][i];\n\n        if(visited_reverse[child_v] && on_stack_reverse[child_v])\n        {\n            return true;\n        }\n\n        if(!visited_reverse[child_v] && dfs_cycle_reverse(child_v))\n        {\n            return true;\n        }\n    }\n\n    on_stack_reverse[v] = false;\n\n    return false;\n}\n\nint dfs_cycle(int v)\n{\n    visited[v] = true;\n    on_stack[v] = true;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n\n        if(visited[child_v] && on_stack[child_v])\n        {\n            return true;\n        }\n\n        if(!visited[child_v] && dfs_cycle(child_v))\n        {\n            return true;\n        }\n    }\n\n    on_stack[v] = false;\n\n    return false;\n}\n\nint main()\n{\n    int no_of_variables, no_of_inequalities;\n    cin >> no_of_variables >> no_of_inequalities;\n\n    vector <int> indegree(no_of_variables + 1, 0);\n    for(int i = 1; i <= no_of_inequalities; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].push_back(v);\n        reverse_graph[v].push_back(u);\n\n        indegree[v]++; //cout << \"In Degree \" << v << \" = \" << indegree[v] << \"\\n\";\n    }\n\n    int no_of_universals = 0;\n    string answer;\n    for(int i = 1; i <= no_of_variables; i++)\n    {\n        if(!visited[i] && !visited_reverse[i])\n        {\n            no_of_universals++;\n\n            answer += 'A';\n        }\n        else\n        {\n            answer += 'E';\n        }\n\n        if(dfs_cycle(i) || dfs_cycle_reverse(i))\n        {\n            cout << \"-1\\n\";\n\n            return 0;\n        }\n    }\n\n    cout << no_of_universals << \"\\n\";\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Resume Review Explanation.txt",
    "content": "Let us see what happens when we increment some B[i] from (x - 1) to x\n\nThe function changes by |x.(A[i] - x)^2| - |(x - 1).(A[i] - (x - 1))^2|\n\nThis is (A[i] - 3x^2 + 3x - 1)\n\nIt is interesting to note that this function decreases as x >= 1\n\nThe more we increase B[i], the more we decrease this function.\nHowever, we have to add k B[i]'s anyway.\n\nSo, we must try to the greatest values of this update as possible\n\n-----\n\nWe can do this by binary search.\nWe will fix a value of R, and check how many additions we need to process all contributions > R\n\nFor example, if R = 100,\nWe will check how many addition steps we need to do to B such that all contributions > 100 are counted\n\nWe will maintain the invariant that it is always possible for R and not possible for L and stop when (R - L = 1)\n\n-----\n\nlong long left = -3e18, right = 3e18;\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n\n        if(no_of_steps(mid) <= total_steps)\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n\n-----\n\nNow, let us try to answer a different question\n\nGiven an integer X, how many steps do we have to perform if,\nfor every B[i] we set it to a value such that all gains are strictly > x ?\n\nWe can do this with binary search !\n\n---\n\nWe know for a given A[i], if we set B[i] = m, what the last gain will be\n\nIt will be (A[i] - 3m^2 + 3m - 1)\n\nThis is a decreasing function so we can use binary search.\n\nThe invariant we maintain is that\n\nIt is always possible to do L steps and never possible to do R steps.\nInitially, L = 0, R = A[i] + 1\n\nIf (A[i] - 3m^2 + 3m - 1) > x, then set L = m\nOtherwise, set R = m\n\nIn the end, L is the answer that we want -\nThe maximum number of addition steps we can do such that B[i] has all contributions > R counted\n\n---\n\nlong long no_of_steps(long long x)\n{\n    long long steps = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left = 0, right = A[i] + 1;\n\n        //Left is always possible, right is not\n        while(right - left > 1)\n        {\n            long long mid = (left + right)/2;\n\n            long long smallest_contribution = A[i] - 3*mid*mid+ 3*mid - 1;\n\n            if(smallest_contribution > x)\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n\n        B[i] = left;\n\n        steps += left;\n    }\n\n    return steps;\n}\n\n-----\n\nA side note to be made here is that we might not have used exactly K elements\nIf we have used < K elements, then we must increment B[i] such that the gain = x\n\n(It will always be possible that there is an integer increasing which will give us a gain = x\nThis is because of the invariant of our binary search.\n\nIf there is no integer who's contribution is exactly x, then R would have stopped at a lower integer in our binary search.)\n\nR stopped at the minimum integer such that it is possible to make contributions > R\n\n----\n\nlong long final_steps = no_of_steps(right);\n\n    for(int i = 1; i <= no_of_elements && final_steps < total_steps; i++)\n    {\n        if(B[i] == A[i])\n        {\n            continue;\n        }\n\n        long long new_b = B[i] + 1;\n        if(A[i] - 3*new_b*new_b + 3*new_b - 1 == right)\n        {\n            B[i]++;\n            final_steps++;\n        }\n    }\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Explanations/Resume Review.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long no_of_elements, total_steps;\nvector <long long> A, B;\n\nlong long no_of_steps(long long x)\n{\n    long long steps = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left = 0, right = A[i] + 1;\n        \n        //Left is always possible, right is not\n        while(right - left > 1)\n        {\n            long long mid = (left + right)/2;\n            \n            long long smallest_contribution = A[i] - 3*mid*mid+ 3*mid - 1;\n            \n            if(smallest_contribution > x)\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n        \n        B[i] = left;\n        \n        steps += left;\n    }\n    \n    return steps;\n}\n\nint main()\n{\n    cin >> no_of_elements >> total_steps;\n    \n    A.resize(no_of_elements + 1);\n    B.resize(no_of_elements + 1);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    // > Right is always possible, <= Left is never possible\n    long long left = -3e18, right = 3e18;\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n        \n        if(no_of_steps(mid) <= total_steps)\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n    \n    long long final_steps = no_of_steps(right);\n    \n    for(int i = 1; i <= no_of_elements && final_steps < total_steps; i++)\n    {\n        if(B[i] == A[i])\n        {\n            continue;\n        }\n        \n        long long new_b = B[i] + 1;\n        if(A[i] - 3*new_b*new_b + 3*new_b - 1 == right)\n        {\n            B[i]++;\n            final_steps++;\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << B[i] << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Programs/Card Construction.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 1e9;\nvector <long long> cards;\n\nvoid precompute()\n{\n    cards.push_back(0);\n    \n    while(cards.back() < MAX_N)\n    {\n        int level = cards.size();\n        \n        long long next = 2*level + level - 1 + cards.back();\n        \n        cards.push_back(next);\n    }\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int no_of_pyramids = 0;\n    \n    while(true)\n    {\n        int current_pyramid_size = lower_bound(all(cards), n) - cards.begin();\n        \n        if(cards[current_pyramid_size] > n)\n        {\n            current_pyramid_size--;\n        }\n        \n        n -= cards[current_pyramid_size];\n        \n        if(current_pyramid_size == 0)\n        {\n            break;\n        }\n        \n        no_of_pyramids++;\n    }\n    \n    cout << no_of_pyramids << \"\\n\";\n}\n\nint main()\n{\n    precompute();\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Programs/Hilbert Hotel.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> frequency_mod(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        A[i] %= no_of_elements;\n        \n        if(A[i] < 0)\n        {\n            A[i] += 2*no_of_elements;\n        \n            A[i] %= no_of_elements;\n        }\n        \n        frequency_mod[ (i + A[i])%no_of_elements ]++;\n    }\n    \n    int all_unique = true;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        if(frequency_mod[i] != 1)\n        {\n            all_unique = false;\n        }\n    }\n    \n    cout << (all_unique ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Programs/Monopole Magnets.cpp",
    "content": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 1005, NO_OF_NEIGHOURS = 4;\nconst char BLACK = '#', WHITE = '.';\nchar grid[MAX_N][MAX_N];\nint visited[MAX_N][MAX_N];\nint next_r[NO_OF_NEIGHOURS] = {-1, 0, 0, 1};\nint next_c[NO_OF_NEIGHOURS] = {0, 1, -1, 0};\nint rows, columns;\n\nint inside_grid(int x, int y)\n{\n    return (1 <= x && x <= rows && 1 <= y && y <= columns);\n}\n\nvoid dfs(int x, int y)\n{\n    visited[x][y] = true;\n    \n    for(int n = 0; n < NO_OF_NEIGHOURS; n++)\n    {\n        int next_x = x + next_r[n];\n        int next_y = y + next_c[n];\n        \n        if(inside_grid(next_x, next_y) && grid[next_x][next_y] == BLACK && !visited[next_x][next_y])\n        {\n            dfs(next_x, next_y);\n        }\n    }\n}\n\nint main()\n{\n    scanf(\"%d %d\", &rows, &columns);\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        scanf(\"%s\", grid[i] + 1);\n    }\n    \n    vector <int> row_frequency(rows + 1);\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                row_frequency[i]++;\n            }\n        }\n    }\n    \n    vector <int> column_frequency(columns + 1);\n    for(int j = 1; j <= columns; j++)\n    {\n        for(int i = 1; i <= rows; i++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                column_frequency[j]++;\n            }\n        }\n    }\n    \n    int possible = true, all_white_row = false, all_white_column = false;\n    for(int i = 1; i <= rows; i++)\n    {\n        int black_cells = 0;\n        \n        for(int j = 1; j <= columns; j++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                black_cells++;\n                \n                if(j + 1 <= columns && grid[i][j + 1] == WHITE && black_cells != row_frequency[i])\n                {\n                    possible = false;\n                    break;\n                }\n            }\n        }\n        \n        if(row_frequency[i] == 0)\n        {\n            all_white_row = true;\n        }\n    }\n    \n    for(int j = 1; j <= columns; j++)\n    {\n        int black_cells = 0;\n        \n        for(int i = 1; i <= rows; i++)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                black_cells++;\n                \n                if(i + 1 <= rows && grid[i + 1][j] == WHITE && black_cells != column_frequency[j])\n                {\n                    possible = false;\n                    break;\n                }\n            }\n        }\n        \n        if(column_frequency[j] == 0)\n        {\n            all_white_column = true;\n        }\n    }\n    \n    if( (all_white_row && !all_white_column) || (!all_white_row && all_white_column) )\n    {\n        possible = false;\n    }\n    \n    if(!possible)\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    int no_of_components = 0;\n    memset(visited, false, sizeof(visited));\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(grid[i][j] == BLACK && !visited[i][j])\n            {\n                dfs(i, j);\n                no_of_components++;\n            }\n        }\n    }\n    \n    cout << no_of_components << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Programs/Puzzle Pieces.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    if(min(rows, columns) == 1)\n    {\n        cout << \"YES\\n\";\n        return;\n    }\n    \n    cout << (max(rows, columns) <= 2 ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Programs/Quantifier Question.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nvector <int> graph[MAX_N], reverse_graph[MAX_N];\nvector <int> visited(MAX_N, false);\nvector <int> on_stack(MAX_N, false);\nvector <int> visited_reverse(MAX_N, false), on_stack_reverse(MAX_N, 0);\n\nint dfs_cycle_reverse(int v)\n{\n    visited_reverse[v] = true;\n    on_stack_reverse[v] = true;\n    \n    for(int i = 0; i < reverse_graph[v].size(); i++)\n    {\n        int child_v = reverse_graph[v][i];\n        \n        if(visited_reverse[child_v] && on_stack_reverse[child_v])\n        {   \n            return true;\n        }\n        \n        if(!visited_reverse[child_v] && dfs_cycle_reverse(child_v))\n        {\n            return true;\n        }\n    }\n    \n    on_stack_reverse[v] = false;\n    \n    return false;\n}\n\nint dfs_cycle(int v)\n{\n    visited[v] = true;\n    on_stack[v] = true;\n    \n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n        \n        if(visited[child_v] && on_stack[child_v])\n        {\n            return true;\n        }\n        \n        if(!visited[child_v] && dfs_cycle(child_v))\n        {\n            return true;\n        }\n    }\n    \n    on_stack[v] = false;\n    \n    return false;\n}\n\nint main()\n{\n    int no_of_variables, no_of_inequalities;\n    cin >> no_of_variables >> no_of_inequalities;\n    \n    vector <int> indegree(no_of_variables + 1, 0);\n    for(int i = 1; i <= no_of_inequalities; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        reverse_graph[v].push_back(u);\n        \n        indegree[v]++; //cout << \"In Degree \" << v << \" = \" << indegree[v] << \"\\n\";\n    }\n    \n    int no_of_universals = 0;\n    string answer;\n    for(int i = 1; i <= no_of_variables; i++)\n    {\n        if(!visited[i] && !visited_reverse[i])\n        {\n            no_of_universals++;\n            \n            answer += 'A';\n        }\n        else\n        {\n            answer += 'E';\n        }\n        \n        if(dfs_cycle(i) || dfs_cycle_reverse(i))\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n    }\n    \n    cout << no_of_universals << \"\\n\";\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/639 Div 2/Programs/Resume Review.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long no_of_elements, total_steps;\nvector <long long> A, B;\n\nlong long no_of_steps(long long x)\n{\n    long long steps = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left = 0, right = A[i] + 1;\n        \n        //Left is always possible, right is not\n        while(right - left > 1)\n        {\n            long long mid = (left + right)/2;\n            \n            long long smallest_contribution = A[i] - 3*mid*mid+ 3*mid - 1;\n            \n            if(smallest_contribution > x)\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n        \n        B[i] = left;\n        \n        steps += left;\n    }\n    \n    return steps;\n}\n\nint main()\n{\n    cin >> no_of_elements >> total_steps;\n    \n    A.resize(no_of_elements + 1);\n    B.resize(no_of_elements + 1);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    // > Right is always possible, <= Left is never possible\n    long long left = -3e18, right = 3e18;\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n        \n        if(no_of_steps(mid) <= total_steps)\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n    \n    long long final_steps = no_of_steps(right);\n    \n    for(int i = 1; i <= no_of_elements && final_steps < total_steps; i++)\n    {\n        if(B[i] == A[i])\n        {\n            continue;\n        }\n        \n        long long new_b = B[i] + 1;\n        if(A[i] - 3*new_b*new_b + 3*new_b - 1 == right)\n        {\n            B[i]++;\n            final_steps++;\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << B[i] << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/641 Div 2/Explanations/Orac and Factors Explanation.txt",
    "content": "Let us notice that f(n) = 2 for all even integers.\n\nIf n is odd, then (f(n) + n) is even\n\nSo, we can do n = (f(n) + n) for our first step\n\nAnd for the remaining (k - 1) steps, we will just add 2 to n !\n\nThe main idea here is observing that f(n) = 2 for all even\n\n-----\n\nvoid precompute()\n{\n    for(int i = 2; i < MAX_N; i++)\n    {\n        for(long long multiple = i; multiple < MAX_N; multiple += i)\n        {\n            if(smallest_multiple[multiple] == 0)\n            {\n                smallest_multiple[multiple] = i;\n            }\n        }\n    }\n}\n\nvoid solve()\n{\n    long long n, k;\n    cin >> n >> k;\n\n    n += smallest_multiple[n];\n    k--;\n\n    n += k*2;\n\n    cout << n << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/641 Div 2/Explanations/Orac and LCM Explanation.txt",
    "content": "The gcd of this set should divide every element of the set.\n\nLet us look at each prime seperately.\n\n-----\n\nCase 1 - There are at least 2 integers not divisible by P\n\nIn this case, their LCM will also not be divisible by P\n\nSo, the GCD of the set should now have P set in it\n\n-----\n\nCase 2 - There is only 0 or 1 integer not divisible by P\n\nIn this case, the LCM of every pair will have an exponent of P in it\n\nThe lowest exponent of P will be equal to the the second smallest exponent of P in the array\n\n-----\n\nFor each prime, we will count the number of multiples it has\n\nIf the number of multiples >= N - 1,\n\nThen, we will multiply P^{Second Smallest Exponent} to our answer\n\n-----\n\n\nvoid precompute()\n{\n    vector <int> is_prime(MAX_N, true);\n\n    for(int i = 2; i < MAX_N; i++)\n    {\n        if(is_prime[i])\n        {\n            primes.push_back(i);\n        }\n\n        for(int j = 0; j < primes.size() && i*primes[j] < MAX_N; j++)\n        {\n            is_prime[i*primes[j]] = false;\n\n            if(i%primes[j] == 0)\n            {\n                break;\n            }\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    precompute();\n\n    vector <pair <int, int> > minimum_exponents(primes.size() + 1, make_pair(100, 100));\n\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    if(no_of_elements == 2)\n    {\n        cout << (A[1]*A[2])/gcd(A[1], A[2]) << \"\\n\";\n\n        return 0;\n    }\n\n    vector <int> frequency(MAX_N, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n\n    vector <int> no_of_multiples(primes.size() + 1, 0);\n    for(int i = 0; i < primes.size(); i++)\n    {\n        int p = primes[i];\n\n        for(int multiple = p; multiple < MAX_N; multiple += p)\n        {\n            no_of_multiples[i] += frequency[multiple];\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = 0; j < primes.size() && A[i] > 1; j++)\n        {\n            int p = primes[j];\n            int exponent_here = 0;\n\n            if(no_of_multiples[j] <= no_of_elements - 2)\n            {\n                continue;\n            }\n\n            while(A[i]%p == 0)\n            {\n                exponent_here++;\n\n                A[i] /= p;\n            }\n\n            if(exponent_here <= minimum_exponents[j].first)\n            {\n                minimum_exponents[j].second = minimum_exponents[j].first;\n                minimum_exponents[j].first = exponent_here;\n            }\n            else if(exponent_here < minimum_exponents[j].second)\n            {\n                minimum_exponents[j].second = exponent_here;\n            }\n        }\n\n        if(A[i] > 1)\n        {\n            int j = lower_bound(primes.begin(), primes.end(), A[i]) - primes.begin();\n\n            if(no_of_multiples[j] > no_of_elements - 2)\n            {\n                int exponent_here = 1;\n\n                if(exponent_here <= minimum_exponents[j].first)\n                {\n                    minimum_exponents[j].second = minimum_exponents[j].first;\n                    minimum_exponents[j].first = exponent_here;\n                }\n                else if(exponent_here < minimum_exponents[j].second)\n                {\n                    minimum_exponents[j].second = exponent_here;\n                }\n            }\n        }\n    }\n\n    long long answer = 1;\n    for(int p = 0; p < primes.size(); p++)\n    {\n        int exponent = minimum_exponents[p].second;\n        if(no_of_multiples[ p ] <= no_of_elements - 2) continue;\n\n        for(int j = 1; j <= exponent; j++)\n        {\n            answer *= primes[p];\n        }\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/641 Div 2/Explanations/Orac and Models Explanation.txt",
    "content": "Let us modify a sieve logic to get the answer\n\nFor every integer i, we can go from i to some multiple of i\n\nWe will check the transition from i to all of i's multiples and choose the best answer\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> answer_till(no_of_elements + 1, 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int m = i; m <= no_of_elements; m += i)\n        {\n            if(A[i] < A[m])\n            {\n                answer_till[m] = max(answer_till[m], answer_till[i] + 1);\n                //cout << \"Answer \" << m << \" = \" << answer_till[m] << \"\\n\";\n            }\n        }\n    }\n\n    int answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        answer = max(answer, answer_till[i]);\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/641 Div 2/Programs/Orac and Factors.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 1e6 + 5;\nvector <int> smallest_multiple(MAX_N, 0);\n\nvoid precompute()\n{\n    for(int i = 2; i < MAX_N; i++)\n    {\n        for(long long multiple = i; multiple < MAX_N; multiple += i)\n        {\n            if(smallest_multiple[multiple] == 0)\n            {\n                smallest_multiple[multiple] = i;\n            }\n        }\n    }\n}\n\nvoid solve()\n{\n    long long n, k;\n    cin >> n >> k;\n    \n    n += smallest_multiple[n];\n    k--;\n    \n    n += k*2;\n    \n    cout << n << \"\\n\";\n}\n\nint main()\n{\n    precompute();\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/641 Div 2/Programs/Orac and LCM.cpp",
    "content": "void precompute()\n{\n    vector <int> is_prime(MAX_N, true);\n    \n    for(int i = 2; i < MAX_N; i++)\n    {\n        if(is_prime[i])\n        {\n            primes.push_back(i);\n        }\n        \n        for(int j = 0; j < primes.size() && i*primes[j] < MAX_N; j++)\n        {\n            is_prime[i*primes[j]] = false;\n            \n            if(i%primes[j] == 0)\n            {\n                break;\n            }\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    precompute();\n    \n    vector <pair <int, int> > minimum_exponents(primes.size() + 1, make_pair(100, 100));\n    \n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    if(no_of_elements == 2)\n    {\n        cout << (A[1]*A[2])/gcd(A[1], A[2]) << \"\\n\";\n        \n        return 0;\n    }\n    \n    vector <int> frequency(MAX_N, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n    \n    vector <int> no_of_multiples(primes.size() + 1, 0);\n    for(int i = 0; i < primes.size(); i++)\n    {\n        int p = primes[i];\n        \n        for(int multiple = p; multiple < MAX_N; multiple += p)\n        {\n            no_of_multiples[i] += frequency[multiple];\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = 0; j < primes.size() && A[i] > 1; j++)\n        {\n            int p = primes[j];\n            int exponent_here = 0;\n            \n            if(no_of_multiples[j] <= no_of_elements - 2)\n            {\n                continue;\n            }\n            \n            while(A[i]%p == 0)\n            {\n                exponent_here++;\n                \n                A[i] /= p;\n            }\n            \n            if(exponent_here <= minimum_exponents[j].first)\n            {\n                minimum_exponents[j].second = minimum_exponents[j].first;\n                minimum_exponents[j].first = exponent_here;\n            }\n            else if(exponent_here < minimum_exponents[j].second)\n            {\n                minimum_exponents[j].second = exponent_here;\n            }\n        }\n        \n        if(A[i] > 1)\n        {\n            int j = lower_bound(primes.begin(), primes.end(), A[i]) - primes.begin();\n            \n            if(no_of_multiples[j] > no_of_elements - 2)\n            {\n                int exponent_here = 1;\n            \n                if(exponent_here <= minimum_exponents[j].first)\n                {\n                    minimum_exponents[j].second = minimum_exponents[j].first;\n                    minimum_exponents[j].first = exponent_here;\n                }\n                else if(exponent_here < minimum_exponents[j].second)\n                {\n                    minimum_exponents[j].second = exponent_here;\n                }\n            }\n        }\n    }\n    \n    long long answer = 1;\n    for(int p = 0; p < primes.size(); p++)\n    {\n        int exponent = minimum_exponents[p].second;\n        if(no_of_multiples[ p ] <= no_of_elements - 2) continue;\n        \n        for(int j = 1; j <= exponent; j++)\n        {\n            answer *= primes[p];\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/641 Div 2/Programs/Orac and Models.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> answer_till(no_of_elements + 1, 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int m = i; m <= no_of_elements; m += i)\n        {\n            if(A[i] < A[m])\n            {\n                answer_till[m] = max(answer_till[m], answer_till[i] + 1);\n                //cout << \"Answer \" << m << \" = \" << answer_till[m] << \"\\n\";\n            }\n        }\n    }\n    \n    int answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        answer = max(answer, answer_till[i]);\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Explanation/Counting Triangles Explanation.txt.txt",
    "content": "- We know $x < y \\< z$ so we will count the number of triplets where $z < x + y$\r\n- $x + y \\in [A + B, A + C]$\r\n- For every possible sum, we will calculate the number of ways of getting it.\r\n    - If we fix a value of $x$, we can get every value from $x + B \\to x + C$\r\n    - We can do this with a linear sweep.\r\n- For every possible $z$, we will count the number of ways to get any sum $> z$, \r\n\twhich can be gotten using a suffix sum over the number of ways array.\r\n\r\n-----\r\n\r\n\r\nint main()\r\n{\r\n    int A, B, C, D;\r\n    cin >> A >> B >> C >> D;\r\n\r\n    vector <long long> no_of_starts(B + C + 5, 0), no_of_finishes(B + C + 5, 0);\r\n    for(int x = A; x <= B; x++)\r\n    {\r\n        no_of_starts[x + B]++;\r\n        no_of_finishes[x + C + 1]++;\r\n    }\r\n\r\n    vector <long long> no_of_ways(B + C + 5, 0);\r\n    for(int i = B; i <= B + C; i++)\r\n    {\r\n        no_of_ways[i] = no_of_ways[i - 1] + no_of_starts[i] - no_of_finishes[i];\r\n    }\r\n\r\n    vector <long long> suffix_sum(B + C + 5, 0);\r\n    for(int i = B + C; i >= B; i--)\r\n    {\r\n        suffix_sum[i] = suffix_sum[i + 1] + no_of_ways[i];\r\n    }\r\n\r\n    long long no_of_triangles = 0;\r\n    for(int z = C; z <= min(D, B + C); z++)\r\n    {\r\n        no_of_triangles += suffix_sum[z + 1];\r\n    }\r\n\r\n    cout << no_of_triangles << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "2020/Div 2/643 Div 2/Explanation/Game with Array Explanation.txt",
    "content": "A win is always possible if S > 2n\n\nIn the array [2, 2, 2, ... 2, S - 2(n - 1)],\n\nthere is no subarray with sum either 1 or S - 1\n\nIf there exists a subarray who's sum is (S - 1), then the remaining array must\nsum to 1.\nBut, this does not exist.\n\n-----\n\nIf S <= 2n, we can reach every integer in [0, S]\n\nThe array consists of 1's and 2's.\n\n- Let us look at the prefix sums $\\mod S$\n- $P_1, P_2, \\dots , P_n$ are all distinct  since they are all positive.\n- $P_1 + K, P_2 + K, P_3 + K, \\dots , P_n + k$ are also all pairwise distinct.\n- Now, we have $2n$ integers all in the range $[0, S - 1]$. By the Pigeonhole Principle,\nthere must be two that are equal since $S < 2n$\n\n- $P_i = P_j + K \\pmod S$\n    - If $i > j$, then we have a subarray $[j, i]$ who's sum is $K$\n    - Otherwise, we have a subarray $[j, i]$ who's sum is $(S - K)$ since some prefix  $[1, j - 1]$and suffix $[i, n]$  add up to $K$\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, sum;\n    cin >> no_of_elements >> sum;\n\n    if(sum >= 2*no_of_elements)\n    {\n        cout << \"YES\\n\";\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            cout << (i < no_of_elements ? 2 : sum - 2*(no_of_elements - 1)) << \" \";\n        }\n        cout << \"\\n\";\n\n        cout << \"1\\n\";\n    }\n    else\n    {\n        cout << \"NO\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Explanation/Restorer Distance Explanation.txt",
    "content": "What is the cost to make each tower = height H ?\n\nWe can set M = min(M, A + R) because moving a block is the same as\nadding and removing.\n\nFor every height H, we will calculate the number of 'extra' and 'missing' blocks.\nWe can do this using prefix sums and binary search.\n\nWe will first move min(extra, missing).\n\nAfter that, if we still have extra blocks, we will add them.\nIf we still have missing blocks, we will remove them.\n\n-----\n\nIt is a piecewise linear function.\nSo, we can check the value of the function at all H[i], along with 1 additional value\n\n(S/n) - both floor and ceil.\n\nAs this is the point where we 'transition' from having more missing blocks to more extra blocks.\n\n-----\n\nWe can also use ternary search like I did.\n\nBut the proof for unimodality is complicated.\n\n-----\n\nlong long calculate(long long h)\n{\n    int l = lower_bound(all(height), h) - height.begin() - 1;\n    int r = upper_bound(all(height), h) - height.begin();\n\n    long long missing_blocks = l*h - sum_till[l];\n    long long extra_blocks = sum_till[no_of_elements] - sum_till[r - 1] - h*(no_of_elements - r + 1);\n\n    long long cost = relocate*min(missing_blocks, extra_blocks);\n\n    if(missing_blocks > extra_blocks)\n    {\n        cost += add*(missing_blocks - extra_blocks);\n    }\n    else if(extra_blocks > missing_blocks)\n    {\n        cost += destroy*(extra_blocks - missing_blocks);\n    }\n\n    //Overflow\n    if(cost < 0)\n    {\n        cost = oo;\n    }\n\n    return cost;\n}\n\n\n-----\n\nNow, let us perform ternary search and find out the best value of H\n\nint main()\n{\n    cin >> no_of_elements >> add >> destroy >> relocate;\n    relocate = min(relocate, add + destroy);\n\n    height.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> height[i];\n    }\n\n    sort(all(height));\n\n    sum_till.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + height[i];\n    }\n\n    const long long RANGE = 2;\n    long long left = height[1], right = height[no_of_elements];\n    while(right - left > RANGE)\n    {\n        long long mid_1 = left + (right - left)/3, mid_2 = right - (right - left)/3;\n\n        if(calculate(mid_1) > calculate(mid_2))\n        {\n            left = mid_1;\n        }\n        else\n        {\n            right = mid_2;\n        }\n    }\n\n    long long answer = min(calculate(left), calculate(right));\n    for(long long i = left; i <= right; i++)\n    {\n        answer = min(answer, calculate(i));\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Explanation/Sequence with Digits Explanation.txt",
    "content": "We will keep performing the operation till the minimum digit is 0.\n\nThis will always happen. After this, there is no change to n anymore.\n\n-----\n\npair <int, int> max_min_digit(long long n)\n{\n    pair <int, int> max_min = make_pair(0, 10);\n\n    while(n)\n    {\n        int digit = n%10;\n\n        max_min.first = max(max_min.first, digit);\n        max_min.second = min(max_min.second, digit);\n\n        n /= 10;\n    }\n\n    return max_min;\n}\n\nvoid solve()\n{\n    long long n, k;\n    cin >> n >> k;\n\n    for(int i = 2; i <= k && max_min_digit(n).second != 0; i++)\n    {\n        n += max_min_digit(n).first*max_min_digit(n).second;\n    }\n\n    cout << n << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Explanation/Young Explorer Explanation.txt",
    "content": "Let the sorted array be\n\nA[1] < A[2] < ... < A[n]\n\nNow, if A[L, ... R] is a group, then the number of people should be A[R]\n\nHow do we check all possibilities ?\n\nFor every person A[i], let us make A[i] the largest experience in the group.\n\nLet f(i) be the largest number of groups for the first i people.\n\nThere are 2 possibilities\n\n1. i is the last part of a group.\nIn which case, the current group goes from A[i - A[i], i]\n\n2. i is not part of any group.\n\nSo, f(i) = max(1 + f(i - A[i]), f(i - 1))\n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(A.begin(), A.end());\n\n    vector <int> max_groups(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        max_groups[i] = max_groups[i - 1];\n\n        if(i - A[i] >= 0)\n        {\n            max_groups[i] = max(max_groups[i], 1 + max_groups[i - A[i]]);\n        }\n    }\n\n    cout << max_groups[no_of_elements] << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Programs/Counting Triangles.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int A, B, C, D;\r\n    cin >> A >> B >> C >> D;\r\n\r\n    vector <long long> no_of_starts(B + C + 5, 0), no_of_finishes(B + C + 5, 0);\r\n    for(int x = A; x <= B; x++)\r\n    {\r\n        no_of_starts[x + B]++;\r\n        no_of_finishes[x + C + 1]++;\r\n    }\r\n\r\n    vector <long long> no_of_ways(B + C + 5, 0);\r\n    for(int i = B; i <= B + C; i++)\r\n    {\r\n        no_of_ways[i] = no_of_ways[i - 1] + no_of_starts[i] - no_of_finishes[i];\r\n    }\r\n\r\n    vector <long long> suffix_sum(B + C + 5, 0);\r\n    for(int i = B + C; i >= B; i--)\r\n    {\r\n        suffix_sum[i] = suffix_sum[i + 1] + no_of_ways[i];\r\n    }\r\n\r\n    long long no_of_triangles = 0;\r\n    for(int z = C; z <= min(D, B + C); z++)\r\n    {\r\n        no_of_triangles += suffix_sum[z + 1];\r\n    }\r\n\r\n    cout << no_of_triangles << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Programs/Game with Array.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, sum;\n    cin >> no_of_elements >> sum;\n    \n    if(sum >= 2*no_of_elements)\n    {\n        cout << \"YES\\n\";\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            cout << (i < no_of_elements ? 2 : sum - 2*(no_of_elements - 1)) << \" \";\n        }\n        cout << \"\\n\";\n        \n        cout << \"1\\n\";\n    }\n    else\n    {\n        cout << \"NO\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Programs/Restorer Distance.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long no_of_elements, relocate, destroy, add;\nvector <int> height;\nvector <long long> sum_till;\nconst long long oo = 1e18;\n\nlong long calculate(long long h)\n{\n    int l = lower_bound(all(height), h) - height.begin() - 1;\n    int r = upper_bound(all(height), h) - height.begin();\n    \n    long long missing_blocks = l*h - sum_till[l];\n    long long extra_blocks = sum_till[no_of_elements] - sum_till[r - 1] - h*(no_of_elements - r + 1);\n    \n    long long cost = relocate*min(missing_blocks, extra_blocks);\n    \n    if(missing_blocks > extra_blocks)\n    {\n        cost += add*(missing_blocks - extra_blocks);\n    }\n    else if(extra_blocks > missing_blocks)\n    {\n        cost += destroy*(extra_blocks - missing_blocks);\n    }\n    \n    //Overflow\n    if(cost < 0)\n    {\n        cost = oo;\n    }\n    \n    return cost;\n}\n\nint main()\n{\n    cin >> no_of_elements >> add >> destroy >> relocate;\n    relocate = min(relocate, add + destroy);\n    \n    height.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> height[i];\n    }\n    \n    sort(all(height));\n    \n    sum_till.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + height[i];\n    }\n    \n    const long long RANGE = 2;\n    long long left = height[1], right = height[no_of_elements];\n    while(right - left > RANGE)\n    {\n        long long mid_1 = left + (right - left)/3, mid_2 = right - (right - left)/3;\n        \n        if(calculate(mid_1) > calculate(mid_2))\n        {\n            left = mid_1;\n        }\n        else\n        {\n            right = mid_2;\n        }\n    }\n    \n    long long answer = min(calculate(left), calculate(right));\n    for(long long i = left; i <= right; i++)\n    {\n        answer = min(answer, calculate(i));\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Programs/Sequence with Digits.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\npair <int, int> max_min_digit(long long n)\n{\n    pair <int, int> max_min = make_pair(0, 10);\n    \n    while(n)\n    {\n        int digit = n%10;\n        \n        max_min.first = max(max_min.first, digit);\n        max_min.second = min(max_min.second, digit);\n        \n        n /= 10;\n    }\n    \n    return max_min;\n}\n\nvoid solve()\n{\n    long long n, k;\n    cin >> n >> k;\n    \n    for(int i = 2; i <= k && max_min_digit(n).second != 0; i++)\n    {\n        n += max_min_digit(n).first*max_min_digit(n).second;\n    }\n    \n    cout << n << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/643 Div 2/Programs/Young Explorer.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(A.begin(), A.end());\n    \n    vector <int> max_groups(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        max_groups[i] = max_groups[i - 1];\n        \n        if(i - A[i] >= 0)\n        {\n            max_groups[i] = max(max_groups[i], 1 + max_groups[i - A[i]]);\n        }\n    }\n    \n    cout << max_groups[no_of_elements] << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Explanations/Johnny and Ancient Computers Explanation.txt",
    "content": "We can never remove any 1 from an integer. \nThe only operation we can do is append 0 and remove trailing 0's. \n\nSo, without loss of generality, let (a < b), \nIf this is not the case, then swap(a, b)\n\nWe will try to reach a -> b by appending 0's only.\nIf it is possible, we will take as many steps of 3 as possible. \nAnswer = Ceil(Steps/3)\n\n-----\n\nvoid solve()\n{\n    long long a, b;\n    cin >> a >> b;\n    \n    if(a > b)\n    {\n        swap(a, b);\n    }\n    \n    int steps = 0;\n    \n    while(a < b)\n    {\n        a *= 2;\n        steps++;\n    }\n    \n    int actual_steps = (a == b ? ceil(steps, 3) : -1);\n    \n    cout << actual_steps << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Explanations/Johnny and Another Rating Drop Explanation.txt",
    "content": "Let us look at each bit seperately ?\n\nHow much does the last bit contribute to the sum ?\nThe last bit is always 01 01 01\nIt contributes n to the sum as each of the n pairs (out of n + 1 integers), has a difference\n\nLet us look at the second last bit,\nIt toggles 00 11 00 11 0 and so on\nIt contributes ceil(N/2) to the sum\n\nSimilarly, we will count the number of 'blocks', which is (N/2^i) + 1, \nFor N and the I-th bit \n\nThe contribution is (Number of Blocks - 1) as each adjacent pair of blocks contributes 1\nWe have to count the contribution of each of the 63 bits\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n& (1LL << bit)) != 0 );\n}\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n\n    long long answer = 0;\n\n    const int MAX_BITS = 63;\n\n    int msb = 0;\n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(is_bit_set(n, bit))\n        {\n            msb = bit;\n        }\n    }\n\n    for(int bit = 0; bit <= msb; bit++)\n    {\n        long long p = (1LL << bit);\n\n        long long no_of_blocks = n/p + 1;\n        //cout << \"B = \" << bit << \" Contribution Number of BLocks = \" << no_of_blocks << \"\\n\";\n        answer += no_of_blocks - 1;\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Explanations/Johnny and Contribution Explanation.txt",
    "content": "We will model this by a graph.\n\nA blog is a vertex and two vertices will share an edge\nif there is a reference from one to the other.\n\nWe will colour each vertex with it's topic number.\n\nThe problem is to order the vertices in such an order that\nif we colour them in that order,\nmaking each vertex = MEX(neighbours),\nEach vertex will have the colour we desire\n\n-----\n\nWe will start with an uncoloured graph.\n\nClearly, we must colour all vertices with topic = 1 first\nThen, we must colour all vertices with topic = 2\nAnd so on\n\nWe will first sort the vertices by their topic numbers\nThen, we will colour the graph\nWhile colouring the graph with our current colour, we will check the MEX (Neighbours)\n\n-----\n\nIf it is the same as the colour we desire, we will continue.\nOtherwise, we will say it is not possible.\n\n-----\n\nThe correct order is either the sorted order or does not exist\n\n-----\n\nNow, the question is, how do we find out the MEX of it's neighbours quickly ?\nOne method is that When we are colour vertex V, we will check all it's neighbours\nand find out the MEX\n\nThis requires us to keep a set for each vertex and adds an additional log factor.\n\n----\n\nThere is a beautiful approach by which we can remove this log factor.\nInstead of maintaining a set against each vertex, we can maintain an array,\nMEX[N], which contains the MEX of each vertex\n\nInitially, the MEX of each vertex is 0.\nWhen we colour a vertex v, we will update the MEX of all it's neighbours.\n\nThis is a beautiful example in which inverting the order of operations saves time\n\n1. Looking at all the neighbours and calculating MEX takes O(E log E) time for each vertex\n2. Colouring a neighbour and then updating all it's neighbours' MEX takes O(E) time\n\nThis beautiful approach helps us reduce a log factor\n\n----\n\nSuppose U is a neighbour of V,\nIf MEX[u] = Colour[V], Then MEX[u] = Colour[V] + 1\nOtherwise, MEX[u] remains as it is\n\n----\n\n----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5;\nvector <int> graph[MAX_N];\nvector <int> colour(MAX_N, 0);\nvector <int> mex(MAX_N, 1);\nvector <pair <int, int> > desired_colour;\n\nvoid update_mex(int v)\n{\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n        \n        if(mex[child] == colour[v])\n        {\n            mex[child]++;\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n    \n    for(int i = 1 ; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n    \n    desired_colour.resize(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> desired_colour[i].first;\n        \n        desired_colour[i].second = i;\n    }\n    \n    sort(desired_colour.begin() + 1, desired_colour.end());\n    \n    vector <int> best_order(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(mex[desired_colour[i].second] != desired_colour[i].first)\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n        \n        best_order[i] = desired_colour[i].second;\n        \n        colour[desired_colour[i].second] = desired_colour[i].first;\n        \n        update_mex(best_order[i]);\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cout << best_order[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n    \n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Explanations/Johnny and His Hobbies Explanation.txt",
    "content": "Let us try every k in [1, 1024]\nWe will check if each k is good in O( N ) time and stop at the first good k\nk can not be greater than 2^{10}, as that bit is not set in any of the integers\nStore all the integers in a set for convenience\n\n-----\n\nThere is also another idea\n\nXOR(A[i], x) = A[j]\nXOR(A[i], A[j]) = x,\n\nSo, x will have to be one of (N - 1) possible values.\n\n-----\n\nint possible(int k, set <int> &S)\n{\n    for(auto it = S.begin(); it != S.end(); it++)\n    {\n        int x = *it;\n\n        if(S.find(x^k) == S.end())\n        {\n            return false;\n        }\n    }\n\n    return true;\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    set <int> S;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        S.insert(A[i]);\n    }\n\n    const int oo = 1e9, MAX_K = 1025;\n    int best_k = oo;\n    for(int k = 1; k <= MAX_K; k++)\n    {\n        if(possible(k, S))\n        {\n            best_k = min(best_k, k);\n\n            break;\n        }\n    }\n\n    if(best_k == oo)\n    {\n        best_k = -1;\n    }\n\n    cout << best_k << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Programs/Johnny and Ancient Computers.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nvoid solve()\n{\n    long long a, b;\n    cin >> a >> b;\n    \n    if(a > b)\n    {\n        swap(a, b);\n    }\n    \n    int steps = 0;\n    \n    while(a < b)\n    {\n        a *= 2;\n        steps++;\n    }\n    \n    int actual_steps = (a == b ? ceil(steps, 3) : -1);\n    \n    cout << actual_steps << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Programs/Johnny and Another Rating Drop.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n& (1LL << bit)) != 0 );\n}\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    long long answer = 0;\n    \n    const int MAX_BITS = 63;\n    \n    int msb = 0;\n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(is_bit_set(n, bit))\n        {\n            msb = bit;\n        }\n    }\n    \n    for(int bit = 0; bit <= msb; bit++)\n    {\n        long long p = (1LL << bit);\n        \n        long long no_of_blocks = n/p + 1;\n        \n        answer += no_of_blocks - 1;\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Programs/Johnny and Contribution.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5;\nvector <int> graph[MAX_N];\nvector <int> colour(MAX_N, 0);\nvector <int> mex(MAX_N, 1);\nvector <pair <int, int> > desired_colour;\n\nvoid update_mex(int v)\n{\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n        \n        if(mex[child] == colour[v])\n        {\n            mex[child]++;\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n    \n    for(int i = 1 ; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n    \n    desired_colour.resize(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> desired_colour[i].first;\n        \n        desired_colour[i].second = i;\n    }\n    \n    sort(desired_colour.begin() + 1, desired_colour.end());\n    \n    vector <int> best_order(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(mex[desired_colour[i].second] != desired_colour[i].first)\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n        \n        best_order[i] = desired_colour[i].second;\n        \n        colour[desired_colour[i].second] = desired_colour[i].first;\n        \n        update_mex(best_order[i]);\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cout << best_order[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n    \n}\n"
  },
  {
    "path": "2020/Div 2/647 Div 2/Programs/Johnny and His Hobbies.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint possible(int k, set <int> &S)\n{\n    for(auto it = S.begin(); it != S.end(); it++)\n    {\n        int x = *it;\n        \n        if(S.find(x^k) == S.end())\n        {\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    set <int> S;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        S.insert(A[i]);\n    }\n    \n    const int oo = 1e9, MAX_K = 1025;\n    int best_k = oo;\n    for(int k = 1; k <= MAX_K; k++)\n    {\n        if(possible(k, S))\n        {\n            best_k = min(best_k, k);\n            \n            break;\n        }\n    }\n    \n    if(best_k == oo)\n    {\n        best_k = -1;\n    }\n    \n    cout << best_k << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Explanations/Maximum Subsequence Value Explanation.txt",
    "content": "We want a set of integers and want to know the bits that are set in all, but 2 of the integers. \n\nIt can be shown that the optimal set always consists of 3 integers. And the value = OR(A[i], A[j], A[k])\n\nIf We add a new integer Z, to the set {A[i], A[j], A[k]}, then every bit of Z must be set in any 1 of {A[i], A[j], A[k]}\n\nIf Z has a bit set that is greater in value to the bits that are existing, we can just replace one of the 3 integers by Z and get a higher answer\n\nSo, it will never be optimal to have more than 3 integers. \n\nWe just have to check all the triplets \n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long answer = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = i; j <= no_of_elements; j++)\n        {\n            for(int k = j; k <= no_of_elements; k++)\n            {\n                answer = max(answer, A[i]|A[j]|A[k]);\n            }\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Explanations/Secure Password Explanation.txt.txt",
    "content": "# Naive Approach\r\n\r\n- Let us assign a bitmask of $i$ to each of the $n$ elements.\r\n- We will perform $2 \\log n$ queries.\r\n    - Find the OR of all elements with the $b$-th bit set\r\n    - Find the OR of all elements with the $b$-th bit unset\r\n- Suppose we want to find the answer for $10011$\r\n    - We will collect the OR of all elements which have the $2, 3$ bit set and the $0, 1, 4$ bit unset.\r\n    - This ensures that every element is counted at least once.\r\n    - Counting an element more than once does not change the answer.\r\n\r\n---\r\n\r\n# Assigning bitmasks so no $2$ are submasks\r\n\r\n- In the naive approach, we were checking all elements which match the complement of $i$. But, why don't we only check elements which have a $1$ where $i$ has a $0$.\r\n    - This way we only need to collect the bitwise OR of all elements which a bit set in their mask. This takes $\\log n$ queries.\r\n- The problem occurs when one mask is a submask of another. For example, $110000$ is a submask of $111100$\r\n    - If we only query those subsets which have a $1$ where our mask has a $0$, we will never hit $110000$ or any other submask\r\n    - We will assign masks in such a way that no mask is a submask of another mask.\r\n\r\n- Bits which have the same number of bits set can never be a submask of each other. The smallest number of bits for which we can get $1000$ bitmasks is $6$\r\n    - We will collect bitmasks which have $6$ bits set. Assign a mask to each of the $n$ positions. Collect the subset OR of all $13$ bits\r\n    - We can get the value of $P[i]$ by OR-ing all those subsets which have $1$ where it has a $0$\r\n\r\n-----\r\n\r\n \r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n \r\n    const int SET_BITS = 6;\r\n    vector <int> mask(no_of_elements + 1);\r\n    for(int m = 1, i = 1; i <= no_of_elements; m++)\r\n    {\r\n        if(no_of_bits(m) == SET_BITS)\r\n        {\r\n            mask[i] = m;\r\n            i++;\r\n        }\r\n    }\r\n \r\n    const int NO_OF_BITS = 13;\r\n    vector < vector <long long> > subset(NO_OF_BITS + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        for(int bit = 0; bit < NO_OF_BITS; bit++)\r\n        {\r\n            if(is_bit_set(mask[i], bit))\r\n            {\r\n                subset[bit].push_back(i);\r\n            }\r\n        }\r\n    }\r\n \r\n    vector <long long> subset_OR(NO_OF_BITS + 1, 0);\r\n    for(int bit = 0; bit < NO_OF_BITS; bit++)\r\n    {\r\n        if(subset[bit].size() == 0)\r\n        {\r\n            continue;\r\n        }\r\n \r\n        cout << \"? \" << subset[bit].size() << \" \";\r\n \r\n        for(int i = 0; i < subset[bit].size(); i++)\r\n        {\r\n            cout << subset[bit][i] << \" \";\r\n        }\r\n \r\n        cout << \"\\n\";\r\n        cout.flush();\r\n \r\n        cin >> subset_OR[bit];\r\n    }\r\n \r\n    vector <long long> answer(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        for(int bit = 0; bit < NO_OF_BITS; bit++)\r\n        {\r\n            if(!is_bit_set(mask[i], bit))\r\n            {\r\n                answer[i] |= subset_OR[bit];\r\n            }\r\n        }\r\n    }\r\n \r\n    cout << \"! \";\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << answer[i] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n \r\n    return 0;\r\n}"
  },
  {
    "path": "2020/Div 2/648 Div 2/Explanations/Swaps Again Explanation.txt",
    "content": "Let us look at how the array is affected after one operation\n\n- $(a_1, a_2, \\dots , a_i, \\dots , a_{n - i + 1}, a_{n - i + 2}, \\dots , a_n)$\n- $(a_{n - i + 1}, a_{n - i + 2}, \\dots , a_n, \\dots , a_1, a_2 \\dots  a_i)$\n\nThere is a very interesting invariant here. The pairs $(a_i, a_{n - i + 1})$ are always together, but can be swapped.\n\nSo, we will check whether all $n/2$ pairs $(a_i, a_{n - i + 1})$ and see that both arrays have the same pairs.\n\n-----\n\nIf the invariant is met, we can put each element in place in at most 3 steps\n\nSuppose we want to put the correct element in the index $i$. And suppose $a_i$ is in position $p$.\n\n- We will perform $[1, p]$ if $p < n$\n    - Now $a_p$ is the last element.\n- We will perform operation $[1, i]$\n    - Now $a_p$ is in the $i$-th index\n- If $p$ was in the second half of the array, we'd need an extra operation.\n\nIt requires at most $3$ operations for each pair.\n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> B(no_of_elements + 1);\n    for(int j = 1; j <= no_of_elements; j++)\n    {\n        cin >> B[j];\n    }\n\n    map < pair <int, int>, int> frequency_A;\n    for(int i = 1; 2*i <= no_of_elements; i++)\n    {\n        if(A[i] > A[no_of_elements - i + 1])\n        {\n            swap(A[i], A[no_of_elements - i + 1]);\n        }\n\n        frequency_A[make_pair(A[i], A[no_of_elements - i + 1])]++;\n    }\n\n    map < pair <int, int>, int> frequency_B;\n    for(int i = 1; 2*i <= no_of_elements; i++)\n    {\n        if(B[i] > B[no_of_elements - i + 1])\n        {\n            swap(B[i], B[no_of_elements - i + 1]);\n        }\n\n        frequency_B[make_pair(B[i], B[no_of_elements - i + 1])]++;\n    }\n\n    int possible = true;\n\n    if(no_of_elements%2 == 1)\n    {\n        if(A[no_of_elements/2 + 1] != B[no_of_elements/2 + 1])\n        {\n            possible = false;\n        }\n    }\n\n    for(auto it = frequency_A.begin(); it != frequency_A.end(); it++)\n    {\n        pair <int, int> current_pair = it->first;\n\n        if(frequency_A[current_pair] != frequency_B[current_pair])\n        {\n            possible = false;\n        }\n    }\n\n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Programs/Matrix Game.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    vector <int> claimed_row(rows + 1, false), claimed_column(columns + 1, false);\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int cell;\n            cin >> cell;\n            \n            if(cell != 0)\n            {\n                claimed_row[i] = true;\n                claimed_column[j] = true;\n            }\n        }\n    }\n    \n    int row_moves = 0;\n    for(int i = 1; i <= rows; i++)\n    {\n        row_moves += (!claimed_row[i]);\n    }\n    \n    int column_moves = 0;\n    for(int j = 1; j <= columns; j++)\n    {\n        column_moves += (!claimed_column[j]);\n    }\n    \n    int moves = min(row_moves, column_moves);\n    cout << (moves%2 == 0 ? \"Vivek\\n\" : \"Ashish\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Programs/Maximum Subsequence Value.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0 );\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long answer = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = i; j <= no_of_elements; j++)\n        {\n            for(int k = j; k <= no_of_elements; k++)\n            {\n                answer = max(answer, A[i]|A[j]|A[k]);\n            }\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Programs/Rotation Matching.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint calculate_left_shifts(int source, int target, int no_of_elements)\n{\n    if(target < source)\n    {\n        return (source - target);\n    }\n    \n    return (source + (no_of_elements - target));\n}\n\nint calculate_right_shifts(int source, int target, int no_of_elements)\n{\n    if(source < target)\n    {\n        return (target - source);\n    }\n    \n    return ((no_of_elements - source) + target);\n}\n\nint get_matches(vector <int> &A, vector <int> &B)\n{\n    int no_of_elements = A.size() - 1;\n    vector <int> B_index(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        B_index[B[i]] = i;\n    }\n    \n    vector <int> mismatches_after_left_shift(no_of_elements + 1, no_of_elements);\n    vector <int> mismatches_after_right_shift(no_of_elements + 1, no_of_elements);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int j = B_index[A[i]];\n        \n        int left_shifts = calculate_left_shifts(i, j, no_of_elements);\n        int right_shifts = calculate_right_shifts(i, j, no_of_elements);\n        \n        mismatches_after_left_shift[left_shifts]--;\n        mismatches_after_right_shift[right_shifts]--;\n    }\n    \n    vector <int> matches_after_left_shift(no_of_elements + 1, 0);\n    vector <int> matches_after_right_shift(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        matches_after_left_shift[i] = no_of_elements - mismatches_after_left_shift[i];\n        matches_after_right_shift[i] = no_of_elements - mismatches_after_right_shift[i];\n    }\n    \n    int maximum_matches = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        maximum_matches = max(maximum_matches, matches_after_left_shift[i]);\n        maximum_matches = max(maximum_matches, matches_after_right_shift[i]);\n    }\n    \n    return maximum_matches;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int maximum_matches = max(get_matches(A, B), get_matches(B, A));\n    \n    cout << maximum_matches << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Programs/Secure Password.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint no_of_bits(int mask)\r\n{\r\n    int bit = 0;\r\n    while(mask)\r\n    {\r\n        bit += (mask%2);\r\n\r\n        mask /= 2;\r\n    }\r\n\r\n    return bit;\r\n}\r\n\r\nint is_bit_set(long long n, int bit)\r\n{\r\n    return ( (n&(1LL << bit)) != 0);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    const int SET_BITS = 6;\r\n    vector <int> mask(no_of_elements + 1);\r\n    for(int m = 1, i = 1; i <= no_of_elements; m++)\r\n    {\r\n        if(no_of_bits(m) == SET_BITS)\r\n        {\r\n            mask[i] = m;\r\n            i++;\r\n        }\r\n    }\r\n\r\n    const int NO_OF_BITS = 13;\r\n    vector < vector <long long> > subset(NO_OF_BITS + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        for(int bit = 0; bit < NO_OF_BITS; bit++)\r\n        {\r\n            if(is_bit_set(mask[i], bit))\r\n            {\r\n                subset[bit].push_back(i);\r\n            }\r\n        }\r\n    }\r\n\r\n    vector <long long> subset_OR(NO_OF_BITS + 1, 0);\r\n    for(int bit = 0; bit < NO_OF_BITS; bit++)\r\n    {\r\n        if(subset[bit].size() == 0)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        cout << \"? \" << subset[bit].size() << \" \";\r\n\r\n        for(int i = 0; i < subset[bit].size(); i++)\r\n        {\r\n            cout << subset[bit][i] << \" \";\r\n        }\r\n\r\n        cout << \"\\n\";\r\n        cout.flush();\r\n\r\n        cin >> subset_OR[bit];\r\n    }\r\n\r\n    vector <long long> answer(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        for(int bit = 0; bit < NO_OF_BITS; bit++)\r\n        {\r\n            if(!is_bit_set(mask[i], bit))\r\n            {\r\n                answer[i] |= subset_OR[bit];\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"! \";\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << answer[i] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Programs/Swaps Again.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_elements + 1);\n    for(int j = 1; j <= no_of_elements; j++)\n    {\n        cin >> B[j];\n    }\n    \n    map < pair <int, int>, int> frequency_A;\n    for(int i = 1; 2*i <= no_of_elements; i++)\n    {\n        if(A[i] > A[no_of_elements - i + 1])\n        {\n            swap(A[i], A[no_of_elements - i + 1]);\n        }\n        \n        frequency_A[make_pair(A[i], A[no_of_elements - i + 1])]++;\n    }\n    \n    map < pair <int, int>, int> frequency_B;\n    for(int i = 1; 2*i <= no_of_elements; i++)\n    {\n        if(B[i] > B[no_of_elements - i + 1])\n        {\n            swap(B[i], B[no_of_elements - i + 1]);\n        }\n        \n        frequency_B[make_pair(B[i], B[no_of_elements - i + 1])]++;\n    }\n    \n    int possible = true;\n    \n    if(no_of_elements%2 == 1)\n    {\n        if(A[no_of_elements/2 + 1] != B[no_of_elements/2 + 1])\n        {\n            possible = false;\n        }\n    }\n    \n    for(auto it = frequency_A.begin(); it != frequency_A.end(); it++)\n    {\n        pair <int, int> current_pair = it->first;\n        \n        if(frequency_A[current_pair] != frequency_B[current_pair])\n        {\n            possible = false;\n        }\n    }\n    \n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/648 Div 2/Programs/Trouble Sort.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> present(2, false);\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n        \n        present[B[i]] = true;\n    }\n    \n    int sorted = true;\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(A[i] > A[i + 1])\n        {\n            sorted = false;\n        }\n    }\n    \n    cout << (sorted || (present[0] && present[1])? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Explanations/Binary Subsequence Rotation Explanation.txt",
    "content": "This operation does not allow us to add any new characters so the number of 1s and 0s must be equal.\n\nLet us ignore the positions where S[i] = T[i] and delete them from the string\n\nIn one step, we can choose an alternating subsequence - 010101 or 1010101\n\nNow, the question is to count the number of alternating sequences the string can be partitioned into\n\n-----\n\nLet us keep track of the list of available sequences ending with 1 and with 0\n\nWhen we are at S[i], we will check if there are any available sequences ending with it's complement.\n\nIf there are, then we will match S[i] with that and update it accordingly.\n\nFor example, if S[i] = 0, and we have sequence number 3 ending with 1, we will append s[i] to the third sequence\n\n-----\n\nWe will maintain a set of all available sequences ending with both numbers\n\nWhen we process S[i], we will check if it's complement is empty or if there is some available sequence\n\nWe will update it accordingly\n\n-----\n\nint main()\n{\n    int length;\n    string S, T;\n    cin >> length >> S >> T;\n\n    if(no_of_1s(S) != no_of_1s(T))\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    string effective_S;\n    for(int i = 0; i < length; i++)\n    {\n        if(S[i] != T[i])\n        {\n            effective_S += S[i];\n        }\n    }\n\n    int no_of_sequences = 0;\n    set <int> last_sequence[2];\n    for(int i = 0; i < effective_S.size(); i++)\n    {\n        int current = effective_S[i] - '0';\n        int complement = 1 - current;\n\n        if(last_sequence[complement].size() == 0)\n        {\n            no_of_sequences++;\n\n            last_sequence[current].insert(no_of_sequences);\n        }\n        else\n        {\n            auto it = last_sequence[complement].begin();\n\n            last_sequence[current].insert(*it);\n\n            last_sequence[complement].erase(it);\n        }\n    }\n\n    cout << no_of_sequences << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Explanations/GCD Compression Explanation.txt",
    "content": "Keep track of the indices of all the odd and even numbers.\n\nThe sum of any two odd numbers is even.\n\nPair the odd integers with each other and make the sum even at each step.\n\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    vector <int> odd_index, even_index;\n    for(int i = 1; i <= 2*n; i++)\n    {\n        int x;\n        cin >> x;\n\n        if(x%2 == 0)\n        {\n            even_index.push_back(i);\n        }\n        else\n        {\n            odd_index.push_back(i);\n        }\n    }\n\n    vector <int> B;\n    if(odd_index.size()%2 == 1 && even_index.size()%2 == 1)\n    {\n        for(int i = 1; i < odd_index.size(); i += 2)\n        {\n            cout << odd_index[i] << \" \" << odd_index[i + 1] << \"\\n\";\n        }\n\n        for(int i = 1; i < even_index.size(); i += 2)\n        {\n            cout << even_index[i] << \" \" << even_index[i + 1] << \"\\n\";\n        }\n    }\n    else\n    {\n        if(odd_index.size() >= 2)\n        {\n            for(int i = 2; i < odd_index.size(); i += 2)\n            {\n                cout << odd_index[i] << \" \" << odd_index[i + 1] << \"\\n\";\n            }\n            for(int i = 0; i < even_index.size(); i += 2)\n            {\n                cout << even_index[i] << \" \" << even_index[i + 1] << \"\\n\";\n            }\n        }\n        else\n        {\n            for(int i = 0; i < odd_index.size(); i += 2)\n            {\n                cout << odd_index[i] << \" \" << odd_index[i + 1] << \"\\n\";\n            }\n            for(int i = 2; i < even_index.size(); i += 2)\n            {\n                cout << even_index[i] << \" \" << even_index[i + 1] << \"\\n\";\n            }\n        }\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Explanations/Maximum GCD Explanation.txt",
    "content": "void solve()\n{\n    int n;\n    cin >> n;\n\n    cout << n/2 << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Explanations/Number Game Explanation.txt",
    "content": "If N is odd, then we can divide it by the entire integer and first player wins\n(except when N = 1)\n\nIf N is a power of 2, then we must subtract 1 and give our opponent this situation.\n(Except when N = 2)\n\nIf N is even but has odd divisors, then we can divide by an odd divisor and give it to our opponent.\nOut opponent will lose, provided N is a multiple of 4 or more.\nIf our opponent gets 2, he will win\n\nIf our number is of the form 2p, then we will lose if p is prime and win otherwise\n\n-----\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    if(n%4 == 0)\n    {\n        cout << (!is_power_of_2(n) ? \"Ashishgup\\n\" : \"FastestFinger\\n\");\n        return;\n    }\n\n    if(n%2 == 1)\n    {\n        cout << (n > 1 ? \"Ashishgup\\n\" : \"FastestFinger\\n\");\n\n        return;\n    }\n\n    if(n == 2)\n    {\n        cout << \"Ashishgup\\n\";\n\n        return;\n    }\n\n    int no_of_odd_divisors = get_prime_divisor_count(n) - 1;\n\n    cout << (no_of_odd_divisors > 1 ? \"Ashishgup\\n\" : \"FastestFinger\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Explanations/Odd Even Subsequence Explanation.txt",
    "content": "Let us binary search the answer.\n\nIf we want to check if x is possible, we have to search for a sequence of length K\nsuch that either\n\n1. All odd indices are < x\n2. All even indices are < x\n\nWe can do this greedily\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint possible(vector <int> &A, int x, int parity, int total_subsequence_length)\n{\n    int subsequence_length = 0;\n\n    for(int i = 1; i < A.size() && subsequence_length < total_subsequence_length; i++)\n    {\n        if((subsequence_length + 1)%2 != parity)\n        {   //cout << \"Subsequence = \" << subsequence_length << \" i = \" << i << \"\\n\";\n            subsequence_length++;\n        }\n        else\n        {\n            if(A[i] <= x)\n            {   //cout << \"Subsequence = \" << subsequence_length << \" i = \" << i << \"\\n\";\n                subsequence_length++;\n            }\n        }\n    }\n\n    return (subsequence_length == total_subsequence_length);\n}\n\nint main()\n{\n    int no_of_elements, subsequence_length;\n    cin >> no_of_elements >> subsequence_length;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int oo = 1e9 + 9;\n    long long left = 0, right = oo;\n\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2; //cout << \"L = \" << left << \" R = \" << right << \"\\n\";\n\n        if(possible(A, mid, 0, subsequence_length) || possible(A, mid, 1, subsequence_length))\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n\n    cout << right << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Programs/Binary Subsequence Rotation.cpp",
    "content": "#include <iostream>\n#include <set>\n\nusing namespace std;\n\nint no_of_1s(string S)\n{\n    int count = 0;\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        count += (S[i] == '1');\n    }\n    \n    return count;\n}\n\nint main()\n{\n    int length;\n    string S, T;\n    cin >> length >> S >> T;\n    \n    if(no_of_1s(S) != no_of_1s(T))\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    string effective_S;\n    for(int i = 0; i < length; i++)\n    {\n        if(S[i] != T[i])\n        {\n            effective_S += S[i];\n        }\n    }\n    \n    int no_of_sequences = 0;\n    set <int> last_sequence[2];\n    for(int i = 0; i < effective_S.size(); i++)\n    {\n        int current = effective_S[i] - '0';\n        int complement = 1 - current;\n        \n        if(last_sequence[complement].size() == 0)\n        {\n            no_of_sequences++;\n            \n            last_sequence[current].insert(no_of_sequences);\n        }\n        else\n        {\n            auto it = last_sequence[complement].begin();\n            \n            last_sequence[current].insert(*it);\n            \n            last_sequence[complement].erase(it);\n        }\n    }\n    \n    cout << no_of_sequences << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Programs/GCD Compression.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    vector <int> odd_index, even_index;\n    for(int i = 1; i <= 2*n; i++)\n    {\n        int x;\n        cin >> x;\n        \n        if(x%2 == 0)\n        {\n            even_index.push_back(i);\n        }\n        else\n        {\n            odd_index.push_back(i);\n        }\n    }\n    \n    vector <int> B;\n    if(odd_index.size()%2 == 1 && even_index.size()%2 == 1)\n    {\n        for(int i = 1; i < odd_index.size(); i += 2)\n        {\n            cout << odd_index[i] << \" \" << odd_index[i + 1] << \"\\n\";\n        }\n        \n        for(int i = 1; i < even_index.size(); i += 2)\n        {\n            cout << even_index[i] << \" \" << even_index[i + 1] << \"\\n\";\n        }\n    }\n    else\n    {\n        if(odd_index.size() >= 2)\n        {\n            for(int i = 2; i < odd_index.size(); i += 2)\n            {\n                cout << odd_index[i] << \" \" << odd_index[i + 1] << \"\\n\";\n            }\n            for(int i = 0; i < even_index.size(); i += 2)\n            {\n                cout << even_index[i] << \" \" << even_index[i + 1] << \"\\n\";\n            }\n        }\n        else\n        {\n            for(int i = 0; i < odd_index.size(); i += 2)\n            {\n                cout << odd_index[i] << \" \" << odd_index[i + 1] << \"\\n\";\n            }\n            for(int i = 2; i < even_index.size(); i += 2)\n            {\n                cout << even_index[i] << \" \" << even_index[i + 1] << \"\\n\";\n            }\n        }\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Programs/Maximum GCD.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    cout << n/2 << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Programs/Number Game.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint is_power_of_2(int n)\n{\n    return ( (n == 1) || (n&(n - 1)) == 0 );\n}\n\nint get_prime_divisor_count(int n)\n{\n    int count = 0;\n    \n    for(int i = 2; i*i <= n; i++)\n    {\n        while(n%i == 0)\n        {\n            n /= i;\n            \n            count++;\n        }\n    }\n    \n    if(n > 1)\n    {\n        count++;\n    }\n    \n    return count;\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    if(n%4 == 0)\n    {\n        cout << (!is_power_of_2(n) ? \"Ashishgup\\n\" : \"FastestFinger\\n\");\n        return;\n    }\n    \n    if(n%2 == 1)\n    {\n        cout << (n > 1 ? \"Ashishgup\\n\" : \"FastestFinger\\n\");\n        \n        return;\n    }\n    \n    if(n == 2)\n    {\n        cout << \"Ashishgup\\n\";\n        \n        return;\n    }\n    \n    int no_of_odd_divisors = get_prime_divisor_count(n) - 1;\n    \n    cout << (no_of_odd_divisors > 1 ? \"Ashishgup\\n\" : \"FastestFinger\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/651 Div 2/Programs/Odd-Even Subsequence.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint possible(vector <int> &A, int x, int parity, int total_subsequence_length)\n{\n    int subsequence_length = 0;\n    \n    for(int i = 1; i < A.size() && subsequence_length < total_subsequence_length; i++)\n    {\n        if((subsequence_length + 1)%2 != parity)\n        {   //cout << \"Subsequence = \" << subsequence_length << \" i = \" << i << \"\\n\";\n            subsequence_length++;\n        }\n        else\n        {\n            if(A[i] <= x)\n            {   //cout << \"Subsequence = \" << subsequence_length << \" i = \" << i << \"\\n\";\n                subsequence_length++;\n            }\n        }\n    }\n    \n    return (subsequence_length == total_subsequence_length);\n}\n\nint main()\n{\n    int no_of_elements, subsequence_length;\n    cin >> no_of_elements >> subsequence_length;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int oo = 1e9 + 9;\n    long long left = 0, right = oo;\n    \n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2; //cout << \"L = \" << left << \" R = \" << right << \"\\n\";\n        \n        if(possible(A, mid, 0, subsequence_length) || possible(A, mid, 1, subsequence_length))\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n    \n    cout << right << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/658 Div 2/Explanations/Common Subsequence Explanation.txt",
    "content": "Sort the arrays.\n\nGo through every element in A and check if it exists in B\n\nIf there exists a common subsequence, there will be a common subsequence of length 1\n\nIf there is no common subsequnece of length 1, there will be no common subsequence\n\n-----\n\nvoid solve()\n{\n    int n, m;\n    cin >> n >> m;\n\n    vector <int> A(n);\n    for(int i = 0; i < n; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    vector <int> B(m);\n    for(int i = 0; i < m; i++)\n    {\n        cin >> B[i];\n    }\n\n    sort(all(B));\n\n    for(int i = 0; i < A.size(); i++)\n    {\n        if(binary_search(B.begin(), B.end(), A[i]))\n        {\n            cout << \"YES\\n\";\n\n            cout << \"1 \" << A[i] << \"\\n\";\n\n            return;\n        }\n    }\n\n    cout << \"NO\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/658 Div 2/Explanations/Sequential Nim Explanation.txt",
    "content": "Case 1 - The first element is not 1\n\nThe first player always wins\n\nProof - There are two possibilities\n\n(Either the pile of (N - 1) stones is winning for the first player or the second player)\n\n-----\n\nCase 1a -\n\nIf the pile of (N - 1) stones (without the first pile) is winning for the first player,\n\nA - Leaves 1 stone  in the pile\nB - Takes that 1 stone\n\nAnd A is now the first player in the pile of (N - 1) stones\n\nCase 1b -\n\nIf the pile of (N - 1) stones (without the first pile) is winning for the second player,\n\nA - Takes the entire pile\n\nAnd A is now the Second Player in the pile of (N - 1) stones\n\n------\n\nCase 2 - The first element is 1,\n\nThe first player has no choice and has to take it\nIn fact, if there is a prefix of 1's\n\nIf there are an odd number of 1's, the second player has the turn after the 1s are over\nIf there are an even number of 1's, the first player has the turn after the 1s are over\n\nIf there are piles remaining after the prefix of 1's is over, the player who has the turn will win\nOtherwise, the last player who took the last stone will win\n\n------\n\nvoid solve()\n{\n    int no_of_piles;\n    cin >> no_of_piles;\n\n    vector <int> A(no_of_piles + 1);\n    for(int i = 1; i <= no_of_piles; i++)\n    {\n        cin >> A[i];\n    }\n\n    int prefix_1s = 0;\n    for(int i = 1; i <= no_of_piles && A[i] == 1; i++)\n    {\n        prefix_1s++;\n    }\n\n    if(prefix_1s == no_of_piles)\n    {\n        cout << (prefix_1s%2 == 0 ? \"Second\\n\" : \"First\\n\");\n\n        return;\n    }\n\n    cout << (prefix_1s%2 == 0 ? \"First\\n\" : \"Second\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/658 Div 2/Explanations/Unmerge Explanation.txt",
    "content": "Let us suppose P[1] is in A\n\nIf P[2] < P[1], then P[2] will also be in A\nIf P[3] < P[1], then P[3] will also be in A\nAnd so on,\n\nLet P[k] be the first element such that P[k] > P[1],\n\n-----\n\nWe can divide P into sequences\n\nS[1], S[2], S[3], ... , S[k], where\n\nS[1] > S[2]\nS[1] > S[3]\nand so on till\n\nS[1] > S[k]\n\nThe entire sequence has to be in the same set.\nThe reason is if any of these (k - 1) elements are in the other set, then\nS[1] will come after it.\n\n-----\n\nThe 'heads' of these sequences form an increasing sequence\n\nEach sequence can be either in A or in B, but a sequence has to be together.\n\n-----\n\nFor example,\nif P =  {3, 2, 6, 1, 5, 7 , 8, 4}\n\nThen the sequences are\n\n{3, 2}\n{6, 1, 5}\n{7}\n{8, 4}\n\nWe can divide these sequences into two sets such that their sum is 4\n\n-----\n\nA = {3, 2, 8, 4}\nB = {6, 1, 5, 7}\n\nNote that there are other valid partitions.\nWe just need to ensure that the whole sequence is together.\n\nWithin each set, sort the sequences by the chronological order in which they appear in P\n\n-----\n\nA = {3, 2}\nB = {6, 1, 5, 7, 8, 4}\n\nA = {3, 2, 6, 1, 5}\nB = {7, 8, 4}\n\nA = {6, 1, 5}\nB = {3, 2, 7, 8, 4}\n\n-----\n\nLet us take the sequence lengths\n\nL{1}, L{2}, ... , L{k}\n\nWe have to check if they can be partitioned to two sets such that the sums are equal\n\nWe have to check if there exists a subset who's sum is = n\n\nThis can be done with a DP\n\n-----\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    vector <int> P(2*n + 5);\n    for(int i = 1; i <= 2*n; i++)\n    {\n        cin >> P[i];\n    }\n\n    vector <int> sequences;\n    int length = 1, beginning = P[1];\n    for(int i = 2; i <= 2*n; i++)\n    {\n        if(P[i] > beginning)\n        {\n            sequences.push_back(length);\n\n            beginning = P[i];\n            length = 1;\n        }\n        else\n        {\n            length++;\n        }\n    }\n    sequences.push_back(length);\n\n    vector <vector <int> > possible_sums(n + 1, vector <int> (sequences.size() + 1, false));\n    for(int s = 0; s <= n; s++)\n    {\n        for(int i = 0; i < sequences.size(); i++)\n        {\n            if(s == 0)\n            {\n                possible_sums[s][i] = true;\n                continue;\n            }\n\n            if(i == 0)\n            {\n                possible_sums[s][i] = (s == sequences[i] ? true : false);\n\n                continue;\n            }\n\n            possible_sums[s][i] = possible_sums[s][i - 1];\n\n            if(s >= sequences[i])\n            {\n                possible_sums[s][i] = (possible_sums[s][i - 1] ||\n                                       possible_sums[s - sequences[i]][i - 1]);\n            }\n        }\n    }\n\n    cout << (possible_sums[n][sequences.size() - 1] ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/658 Div 2/Programs/Common Subsequence.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int n, m;\n    cin >> n >> m;\n    \n    vector <int> A(n);\n    for(int i = 0; i < n; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    \n    vector <int> B(m);\n    for(int i = 0; i < m; i++)\n    {\n        cin >> B[i];\n    }\n    \n    sort(all(B));\n    \n    for(int i = 0; i < A.size(); i++)\n    {\n        if(binary_search(B.begin(), B.end(), A[i]))\n        {\n            cout << \"YES\\n\";\n            \n            cout << \"1 \" << A[i] << \"\\n\";\n            \n            return;\n        }\n    }\n    \n    cout << \"NO\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/658 Div 2/Programs/Sequential Nim.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_piles;\n    cin >> no_of_piles;\n\n    vector <int> A(no_of_piles + 1);\n    for(int i = 1; i <= no_of_piles; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int prefix_1s = 0;\n    for(int i = 1; i <= no_of_piles && A[i] == 1; i++)\n    {\n        prefix_1s++;\n    }\n    \n    if(prefix_1s == no_of_piles)\n    {\n        cout << (prefix_1s%2 == 0 ? \"Second\\n\" : \"First\\n\");\n        \n        return;\n    }\n    \n    cout << (prefix_1s%2 == 0 ? \"First\\n\" : \"Second\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/658 Div 2/Programs/Unmerge.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    vector <int> P(2*n + 5);\n    for(int i = 1; i <= 2*n; i++)\n    {\n        cin >> P[i];\n    }\n    \n    vector <int> sequences;\n    int length = 1, beginning = P[1];\n    for(int i = 2; i <= 2*n; i++)\n    {\n        if(P[i] > beginning)\n        {\n            sequences.push_back(length);\n            \n            beginning = P[i];\n            length = 1;\n        }\n        else\n        {\n            length++;\n        }\n    }\n    sequences.push_back(length);\n    \n    vector <vector <int> > possible_sums(n + 1, vector <int> (sequences.size() + 1, false));\n    for(int s = 0; s <= n; s++)\n    {\n        for(int i = 0; i < sequences.size(); i++)\n        {\n            if(s == 0)\n            {\n                possible_sums[s][i] = true;\n                continue;\n            }\n            \n            if(i == 0)\n            {\n                possible_sums[s][i] = (s == sequences[i] ? true : false);\n                \n                continue;\n            }\n            \n            possible_sums[s][i] = possible_sums[s][i - 1];\n            \n            if(s >= sequences[i])\n            {\n                possible_sums[s][i] = (possible_sums[s][i - 1] ||\n                                       possible_sums[s - sequences[i]][i - 1]);\n            }\n        }\n    }\n    \n    cout << (possible_sums[n][sequences.size() - 1] ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n\n\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Explanations/Common Prefix Explanation.txt",
    "content": "S[i] should have at least (A[i - 1], A[i]) characters\nIf this value is 0, it should have at least 1 character\n\nWhen we are constructing S[i], we will set the first (A[i - 1]) characters\nto S[i - 1]\n\nWe want to avoid a longer prefix matching, so the remaining characters will be = 'a' + i (mod 25)\nIt is a function of i, so it cannot be equal in both S[i] and S[i - 1] or S[i + 1]\n\nWhen we are in the last string, we should only check A[i - 1]\nIf that is 0, we need to put 1 character on ourselves.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int NO_OF_ALPHABETS = 25;\n    vector <string> S(no_of_elements + 5);\n    for(int i = 1; i <= no_of_elements + 1; i++)\n    {\n        //S[i].resize(max ( max(A[i], 10), A[i - 1] ) );\n\n        for(int j = 0; j < A[i - 1]; j++)\n        {\n            S[i] += S[i - 1][j]; //cout << S[i][j] << \"\\n\";\n        }\n\n        if(i > no_of_elements)\n        {\n            if(S[i].size() == 0)\n            {\n                S[i] += (char)( 'a' + (i)%(NO_OF_ALPHABETS) );\n            }\n            continue;\n        }\n\n\n        for(int j = A[i - 1]; j < max(A[i], 1); j++)\n        {//cout << \"Reached j = \" << (char)('a' + (i)%(NO_OF_ALPHABETS) ) << endl;\n            S[i] += (char)('a' + (i)%(NO_OF_ALPHABETS) );\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements + 1; i++)\n    {\n        cout << S[i] << \"\\n\";\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Explanations/Prefix Flip (Easy Version) Explanation.txt",
    "content": "We can always do it with 3 flips for every unequal position.\n\nIf (A[i] = B[i]), we do nothing.\n\nOtherwise, we will flip and reverse the prefix of length i\nThen, we will flip the first bit,\nThen, we will again flip and reverse the prefix of length i\n\nThis leaves the remaining (i - 1) bits unchanged and flips the i-th bit and now A[i] = B[i]\n\nThis can also be done in O(n) time and we do not need to simulate all 3 flips\n\n-----\n\nvoid solve()\n{\n    string A, B;\n    int length;\n    cin >> length >> A >> B;\n\n    vector <int> moves;\n\n    for(int i = A.size() - 1; i >= 0; i--)\n    {\n        if(A[i] != B[i])\n        {\n            moves.push_back(i + 1);\n            moves.push_back(1);\n            moves.push_back(i + 1);\n        }\n    }\n\n    cout << moves.size() << \" \";\n\n    for(int i = 0; i < moves.size(); i++)\n    {\n        cout << moves[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Explanations/Prefix Flip (Hard Version) Explanation.txt",
    "content": "We will convert A to a string of all 0's and B to a string of all 0's\n\nIf we reverse the order of operations done to B, then we can create B from a string of all 0's.\n\n-----\n\nHow to convert a string S to all 0's ?\n\nLet us append an extra 0 at the end of string S\n\nIf S[i] and S[i + 1] are different, we will flip the prefix of length i\n\nThis maintains the invariant that when we are at position (i + 1), the first i elements are the no_of_special_segments\n\nWhen we finish processing the entire string, it will be all-0's since the last alphabet is 0\n\n-----\n\nvoid solve()\n{\n    string A, B;\n    int length;\n    cin >> length >> A >> B;\n\n    A += '0', B += '0';\n\n    vector <int> moves_A, moves_B;\n\n    for(int i = 1; i <= length; i++)\n    {\n        if(A[i] != A[i - 1])\n        {\n            moves_A.push_back(i);\n        }\n\n        if(B[i] != B[i - 1])\n        {\n            moves_B.push_back(i);\n        }\n    }\n\n    cout << moves_A.size() + moves_B.size() << \" \";\n\n    for(int i = 0; i < moves_A.size(); i++)\n    {\n        cout << moves_A[i] << \" \";\n    }\n\n    for(int i = moves_B.size() - 1; i >= 0; i--)\n    {\n        cout << moves_B[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Explanations/String Transformation 1 Explanation.txt",
    "content": "We will follow the above strategy.\n\nWe will draw an edge between alphabets u and v, if some instance of u should be converted to v\n\nLet {t1, t2, ... , tk} be all the target vertices of vertex v\nand let t1 < t2 < ... < tk\n\nWe will convert all the instances of v to t1 and use only one move.\nWe will also add {t2, t3, ... , tk} to the target set of vertex t1\n\n------\n\nWe will process the vertices in alphabetical order. Each alphabet will include at most 1 move.\nSo, the total number of moves will not be more than 19.\n\nAlso, this always works because a target set of an alphabet becomes empty after we finish processing it.\nWhen we finish processing all 20 alphabets, all the target sets are empty\n\n-----\n\nvoid solve()\n{\n    int length;\n    string A, B;\n    cin >> length >> A >> B;\n\n    for(int i = 0; i < length; i++)\n    {\n        if(A[i] > B[i])\n        {\n            cout << \"-1\\n\";\n\n            return;\n        }\n    }\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <set <int> > replacements(NO_OF_ALPHABETS);\n    for(int i = 0; i < length; i++)\n    {\n        if(A[i] != B[i])\n        {\n            replacements[A[i] - 'a'].insert(B[i] - 'a');\n        }\n    }\n\n    int moves = 0;\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(replacements[alpha].size() == 0)\n        {\n            continue;\n        }\n\n        moves++;\n\n        auto it = replacements[alpha].begin();\n        int next_alpha = *it;\n\n        for(it = replacements[alpha].begin(); it != replacements[alpha].end(); it++)\n        {\n            if(*it != next_alpha)\n            {\n                replacements[next_alpha].insert(*it);\n            }\n        }\n    }\n\n    cout << moves << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Programs/Common Prefixes.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int NO_OF_ALPHABETS = 25;\n    vector <string> S(no_of_elements + 5);\n    for(int i = 1; i <= no_of_elements + 1; i++)\n    {\n        //S[i].resize(max ( max(A[i], 10), A[i - 1] ) );\n                                          \n        for(int j = 0; j < A[i - 1]; j++)\n        {\n            S[i] += S[i - 1][j]; //cout << S[i][j] << \"\\n\";\n        }\n        \n        if(i > no_of_elements)\n        {\n            if(S[i].size() == 0)\n            {\n                S[i] += (char)( 'a' + (i)%(NO_OF_ALPHABETS) );\n            }\n            continue;\n        }\n        \n        \n        for(int j = A[i - 1]; j < max(A[i], 1); j++)\n        {//cout << \"Reached j = \" << (char)('a' + (i)%(NO_OF_ALPHABETS) ) << endl;\n            S[i] += (char)('a' + (i)%(NO_OF_ALPHABETS) );\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements + 1; i++)\n    {\n        cout << S[i] << \"\\n\";\n    }\n}\n\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Programs/Prefix Flip (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    string A, B;\n    int length;\n    cin >> length >> A >> B;\n    \n    vector <int> moves;\n    \n    for(int i = A.size() - 1; i >= 0; i--)\n    {\n        if(A[i] != B[i])\n        {\n            moves.push_back(i + 1);\n            moves.push_back(1);\n            moves.push_back(i + 1);\n        }\n    }\n    \n    cout << moves.size() << \" \";\n    \n    for(int i = 0; i < moves.size(); i++)\n    {\n        cout << moves[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Programs/Prefix Flip (Hard Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    string A, B;\n    int length;\n    cin >> length >> A >> B;\n    \n    A += '0', B += '0';\n    \n    vector <int> moves_A, moves_B;\n    \n    for(int i = 1; i <= length; i++)\n    {\n        if(A[i] != A[i - 1])\n        {\n            moves_A.push_back(i);\n        }\n        \n        if(B[i] != B[i - 1])\n        {\n            moves_B.push_back(i);\n        }\n    }\n    \n    cout << moves_A.size() + moves_B.size() << \" \";\n    \n    for(int i = 0; i < moves_A.size(); i++)\n    {\n        cout << moves_A[i] << \" \";\n    }\n    \n    for(int i = moves_B.size() - 1; i >= 0; i--)\n    {\n        cout << moves_B[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/659 Div 2/Programs/String Transformation 1.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string A, B;\n    cin >> length >> A >> B;\n    \n    for(int i = 0; i < length; i++)\n    {\n        if(A[i] > B[i])\n        {\n            cout << \"-1\\n\";\n            \n            return;\n        }\n    }\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <set <int> > replacements(NO_OF_ALPHABETS);\n    for(int i = 0; i < length; i++)\n    {\n        if(A[i] != B[i])\n        {\n            replacements[A[i] - 'a'].insert(B[i] - 'a');\n        }\n    }\n    \n    int moves = 0;\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(replacements[alpha].size() == 0)\n        {\n            continue;\n        }\n        \n        moves++;\n        \n        auto it = replacements[alpha].begin();\n        int next_alpha = *it;\n        \n        for(it = replacements[alpha].begin(); it != replacements[alpha].end(); it++)\n        {\n            if(*it != next_alpha)\n            {\n                replacements[next_alpha].insert(*it);\n            }\n        }\n    }\n    \n    cout << moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/660 Div 2/Explanations/Captain Flint and Crew Recruitment Explanation.txt",
    "content": "The smallest nearly prime integers are 6, 10, 14\n\nSo, we can give (6, 10, 14, n - 30) if n > 30\n\nThe only condition we have to be careful about is if\n\nn - 30 = 6, 10, 14\n\nWhen n = 36, 40, 44\n\nIn these cases, we will need a different solution.\n\nWe can use (6, 10, 15, n - 31)\n\n-----\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    if(n <= 30)\n    {\n        cout << \"NO\\n\";\n\n        return;\n    }\n\n    cout << \"YES\\n\";\n    switch(n)\n    {\n        case 36 :\n        case 40 :\n        case 44 : cout << \"6 10 15 \" << n - 31 << \"\\n\";\n            return;\n\n        default : cout << \"6 10 14 \" << n - 30 << \"\\n\";\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/660 Div 2/Explanations/Captain Flint and a Long Voyage Explanation.txt",
    "content": "First of all, we want the length of the binary number to be maximum possible.\nSo, we will use a 4 digit number.\n\nIf the digit is deleted, then we cannot distinguish between 8 and 9.\nAs they have asked for the smallest such answer if there are multiple, we will print 8\n\nAfter all the deletions are over, we will print all 9's to make the integer as large as possible\n\n-----\n\n void solve()\n{\n    int n;\n    cin >> n;\n\n    int eights = n/4 + (n%4 != 0);\n\n    int nines = n - eights;\n\n    for(int i = 1; i <= nines; i++)\n    {\n        cout << \"9\";\n    }\n\n    for(int i = 1; i <= eights; i++)\n    {\n        cout << \"8\";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/660 Div 2/Programs/Captain Flint and Crew Recruitment.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    if(n <= 30)\n    {\n        cout << \"NO\\n\";\n        \n        return;\n    }\n    \n    cout << \"YES\\n\";\n    switch(n)\n    {\n        case 36 :\n        case 40 :\n        case 44 : cout << \"6 10 15 \" << n - 31 << \"\\n\";\n            return;\n            \n        default : cout << \"6 10 14 \" << n - 30 << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/660 Div 2/Programs/Captain Flint and a Long Voyage.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int eights = n/4 + (n%4 != 0);\n\n    int nines = n - eights;\n    \n    for(int i = 1; i <= nines; i++)\n    {\n        cout << \"9\";\n    }\n    \n    for(int i = 1; i <= eights; i++)\n    {\n        cout << \"8\";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/662 Div 2/Programs/Rainbow Dash, Fluttershy and Chess Coloring.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int no_of_moves = n/2 + 1;\n    \n    cout << no_of_moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Explanations/Bandit in a City Explanation.txt",
    "content": "The answer for a given node is\n\nmaximum of the value of any leaf in it's subtree or\nceil(sum[v], leaves[v])\n\n-----\n\n- If we are at a leaf, then the answer is equal to the value of the leaf.\n- Suppose we are at a vertex, all of who’s children are leaves 🍁\n    - If the subtree sum is $S[v]$, and the number of leaves is $l[v]$,\n    at least one leaf has to have $S[v]/l[v]$ by the PigeonHole Principle.\n    - However, if some leaf already has a greater amount, then we cannot change it.\n    - When we reach $v$, if every leaf has a smaller amount than $S[V]/l[v]$,\n    then we can achieve $S[v]/l[v]$ by distributing in the required way.\n    - $M[v] = \\max(M[c], S[v]/l[v])$ is the answer.\n- We can apply this logic recursively.\nFor every vertex $v$ that we visit, we already know the values of $M, S, l$ for all it's children.\nIf every single leaf in it's subtree has weight $< S[v]/l[v]$, we can achieve it.\nOtherwise, we leave the maximum undisturbed and distribute into the other leaves.\n    - Please note that it is always possible to distribute into the other leafs and\n    ensure that the maximum does not exceed $M[v]$ if $M[v] > S[v]/L[v]$. The reason is that if $M[v]$ is greater than this, at least one leaf has to be smaller than this value.\n\n-----\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0 ? 1 : 0);\n}\n\nvoid dfs(int v)\n{\n    sum[v] = A[v];\n\n    if(tree[v].size() == 0)\n    {\n        leaves[v] = 1;\n\n        maximum[v] = sum[v];\n\n        return;\n    }\n\n    for(int child_v : tree[v])\n    {\n        dfs(child_v);\n\n        leaves[v] += leaves[child_v];\n\n        sum[v] += sum[child_v];\n\n        maximum[v] = max(maximum[v], maximum[child_v]);\n    }\n\n    maximum[v] = max(maximum[v], ceil(sum[v], leaves[v]));\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n\n    for(int i = 2; i <= no_of_vertices; i++)\n    {\n        int source;\n        cin >> source;\n\n        tree[source].push_back(i);\n    }\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> A[i];\n\n        leaves[i] = 0;\n        maximum[i] = 0;\n    }\n\n    dfs(1);\n\n    cout << maximum[1] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Explanations/Binary Search Explanation.txt",
    "content": "We will simulate binary search and count the number of indices which\nneed to have a larger and smaller element.\n\nThere are (N - X) larger elements and they can be placed in P(N - X, L) ways.\nThere are (X - 1) smaller elementss and they can be placed in P(X - 1, S) ways.\nThe remaining R elements can be placed anywhere.\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nconst int MOD = 1e9 +7;\n\nlong long power_mod(long long x, long long power)\n{\n    if(power < 0)\n    {\n        return 0;\n    }\n\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%MOD;\n\n        x = (x*x)%MOD;\n\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nlong long inverse(long long n)\n{\n    return power_mod(n, MOD - 2);\n}\n\nlong long factorial(long long n)\n{\n    long long answer = 1;\n    for(int i = 2; i <= n; i++)\n    {\n        answer = (answer*i)%MOD;\n    }\n\n    return answer;\n}\n\nlong long choose(long long n, long long r)\n{\n    if(r > n)\n    {\n        return 0;\n    }\n\n    long long denominator = factorial(n - r);\n\n    return (factorial(n)*inverse(denominator))%MOD;\n}\n\nint main()\n{\n    int no_of_elements, x, position;\n    cin >> no_of_elements >> x >> position;\n\n    int larger = 0, smaller = 0;\n\n    int left = 0, right = no_of_elements;\n    while(left < right)\n    {\n        int mid = (left + right)/2;\n\n        if(mid <= position)\n        {\n            left = mid + 1;\n            smaller++;\n        }\n        else\n        {\n            right = mid;\n            larger++;\n        }\n    }\n\n    long long result = (choose(no_of_elements - x, larger)*choose(x - 1, smaller - 1))%MOD;\n\n    int remaining = no_of_elements - (larger + smaller);\n    result = (result*factorial(remaining))%MOD;\n\n    cout << result << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Explanations/Complicated Computations Explanation.txt",
    "content": "We are looking for the smallest integer which is not a MEX in any subarray\n\nGiven an integer X, how do we check which subarrays it is a MEX in ?\n\nIt turns out that if there is any subarray in which x is a MEX,\na subarray between consecutive occurrences of x will also satisfy this property.\n\nSuppose MEX[L, R] = X\nThen, MEX[L - 1, R] or MEX[L, R + 1] will also be X\nas long as A[L - 1] =/= X and A[R + 1] =/= X\n\nX can only be a MEX in some subarray that does not contain it.\n\n-----\n\nFor each X, we will check the following segments -\n\n1. The subarray between consecutive occurrences of X\n2. The prefix subarray before the first occurrence of X\n3. The suffix subarray after the last occurrence of X\n\nWe don't need to handle the last case seperately since last[x] = 0,\nfor all x in the beginning.\n\nWe will also need to find out the MEX of the entire array.\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    map <int, int> last;\n    vector <int> is_mex(no_of_elements + 10, false);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(last[A[i]] + 1 != i)\n        {\n            int mex_here = get_first_smaller(1, 1, MAX_N, last[A[i]] + 1);\n\n            //cout << \"Mex[\" << last[A[i]] + 1 << \",\" << i - 1 << \"] = \" << mex_here << \"\\n\";\n\n            is_mex[mex_here] = true;\n        }\n\n        last[A[i]] = i;\n\n        update(1, 1, MAX_N, A[i], i);\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(last[A[i]] != no_of_elements)\n        {\n            int suffix_mex = get_first_smaller(1, 1, MAX_N, last[A[i]] + 1);\n\n            //cout << \"Suffix Mex[\" << last[A[i]] + 1 << \",\" << no_of_elements << \"] = \" << suffix_mex << \"\\n\";\n            is_mex[suffix_mex] = true;\n        }\n    }\n\n    int array_mex = get_first_smaller(1, 1, MAX_N, 1);\n    is_mex[array_mex] = true;\n\n    //cout << \"Array Mex = \" << array_mex << \"\\n\";\n\n    int final_mex = 0;\n    for(int i = 1; i < is_mex.size(); i++)\n    {\n        if(!is_mex[i])\n        {\n            final_mex = i;\n            break;\n        }\n    }\n\n    cout << final_mex << \"\\n\";\n    return 0;\n}\n\n-----\n\nHow do we find out the MEX of a segment [L, R] ?\n\n1. Let us maintain an array last, which contains the last occurrence of x\n2. Let us suppose we have processed all elements from [1, R] and know their\nlast occurrence\n3. We are looking for the first index i, such that last[i] < L\n\nThis means that i does not occur in the segment [L, R]\nand is the smallest integer which satisfies this property and is therefore the MEX.\n\nWe can get the first element in last which is < L in O(log n) time using a\nminimum segment tree like this\n\n-----\n\nint get_first_smaller(int n, int left, int right, int x)\n{\n    if(min_tree[n] > x)\n    {\n        return -1;\n    }\n\n    if(left == right)\n    {\n        return left;\n    }\n\n    int mid = (left + right)/2;\n\n    if(min_tree[LEFT(n)] < x)\n    {\n        return get_first_smaller(LEFT(n), left, mid, x);\n    }\n\n    return get_first_smaller(RIGHT(n), mid + 1, right, x);\n}\n\n-----\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Explanations/Prime Square Explanation.txt",
    "content": "1 + 4 = 5 is a prime number.\n\nSo, I put exactly one 1 and one 4 in every row and column and padded the remaining with 0s\n\nThe editorial solution was even more slick. It used 1 + 1 = 2 and just padded with 1s\n\n-----\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if(i == j)\n            {\n                cout << \"1 \";\n            }\n            else if(j == (i + 1) || (i == n && j == 1))\n            {\n                cout << \"4 \";\n            }\n            else\n            {\n                cout << \"0 \";\n            }\n        }\n\n        cout << \"\\n\";\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Explanations/Reorder Explanation.txt",
    "content": "A[i]/i is counted i times, so we are actually counting\n\ni(A[i]/i) = A[i]\n\nThe question is asking if the sum of the array is equal to m !\n\nIt's quite beautiful\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, target_sum;\n    cin >> no_of_elements >> target_sum;\n\n    int sum = 0;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        sum += A[i];\n    }\n\n    cout << (sum == target_sum ? \"YES\" : \"NO\") << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Explanations/Sum Over Subsets Explanation.txt",
    "content": "Thank you for the success, safety, peace and love.\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Programs/Bandit in a City.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\n\nlong long leaves[MAX_N], maximum[MAX_N], sum[MAX_N], A[MAX_N];\nvector <int> tree[MAX_N];\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0 ? 1 : 0);\n}\n\nvoid dfs(int v)\n{\n    sum[v] = A[v];\n    \n    if(tree[v].size() == 0)\n    {\n        leaves[v] = 1;\n        \n        maximum[v] = sum[v];\n        \n        return;\n    }\n    \n    for(int child_v : tree[v])\n    {\n        dfs(child_v);\n        \n        leaves[v] += leaves[child_v];\n        \n        sum[v] += sum[child_v];\n        \n        maximum[v] = max(maximum[v], maximum[child_v]);\n    }\n    \n    maximum[v] = max(maximum[v], ceil(sum[v], leaves[v]));\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    for(int i = 2; i <= no_of_vertices; i++)\n    {\n        int source;\n        cin >> source;\n        \n        tree[source].push_back(i);\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> A[i];\n        \n        leaves[i] = 0;\n        maximum[i] = 0;\n    }\n    \n    dfs(1);\n    \n    cout << maximum[1] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Programs/Binary Search.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nconst int MOD = 1e9 +7;\n\nlong long power_mod(long long x, long long power)\n{\n    if(power < 0)\n    {\n        return 0;\n    }\n    \n    long long result = 1;\n    \n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        \n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nlong long inverse(long long n)\n{\n    return power_mod(n, MOD - 2);\n}\n\nlong long factorial(long long n)\n{\n    long long answer = 1;\n    for(int i = 2; i <= n; i++)\n    {\n        answer = (answer*i)%MOD;\n    }\n    \n    return answer;\n}\n\nlong long choose(long long n, long long r)\n{\n    if(r > n)\n    {\n        return 0;\n    }\n    \n    long long denominator = factorial(n - r);\n    \n    return (factorial(n)*inverse(denominator))%MOD;\n}\n\nint main()\n{\n    int no_of_elements, x, position;\n    cin >> no_of_elements >> x >> position;\n    \n    int larger = 0, smaller = 0;\n    \n    int left = 0, right = no_of_elements;\n    while(left < right)\n    {\n        int mid = (left + right)/2;\n        \n        if(mid <= position)\n        {\n            left = mid + 1;\n            smaller++;\n        }\n        else\n        {\n            right = mid;\n            larger++;\n        }\n    }\n    \n    long long result = (choose(no_of_elements - x, larger)*choose(x - 1, smaller - 1))%MOD;\n    \n    int remaining = no_of_elements - (larger + smaller);\n    result = (result*factorial(remaining))%MOD;\n    \n    cout << result << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Programs/Complicated Computations.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5;\nvector <int> min_tree(3*MAX_N + 5, 0);\n\nvoid update(int n, int left, int right, int position, int value)\n{\n    if(right < position || position < left)\n    {\n        return;\n    }\n    \n    if(left == right)\n    {\n        min_tree[n] = value;\n        return;\n    }\n    \n    int mid = (left + right)/2;\n    update(LEFT(n), left, mid, position, value);\n    update(RIGHT(n), mid + 1, right, position, value);\n    \n    min_tree[n] = min(min_tree[LEFT(n)], min_tree[RIGHT(n)]);\n}\n\nint get_first_smaller(int n, int left, int right, int x)\n{\n    if(min_tree[n] > x)\n    {\n        return -1;\n    }\n    \n    if(left == right)\n    {\n        return left;\n    }\n    \n    int mid = (left + right)/2;\n    \n    if(min_tree[LEFT(n)] < x)\n    {\n        return get_first_smaller(LEFT(n), left, mid, x);\n    }\n    \n    return get_first_smaller(RIGHT(n), mid + 1, right, x);\n}\n\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    map <int, int> last;\n    vector <int> is_mex(no_of_elements + 10, false);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(last[A[i]] + 1 != i)\n        {\n            int mex_here = get_first_smaller(1, 1, MAX_N, last[A[i]] + 1);\n            \n            //cout << \"Mex[\" << last[A[i]] + 1 << \",\" << i - 1 << \"] = \" << mex_here << \"\\n\";\n            \n            is_mex[mex_here] = true;\n        }\n        \n        last[A[i]] = i;\n        \n        update(1, 1, MAX_N, A[i], i);\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(last[A[i]] != no_of_elements)\n        {\n            int suffix_mex = get_first_smaller(1, 1, MAX_N, last[A[i]] + 1);\n            \n            //cout << \"Suffix Mex[\" << last[A[i]] + 1 << \",\" << no_of_elements << \"] = \" << suffix_mex << \"\\n\";\n            is_mex[suffix_mex] = true;\n        }\n    }\n    \n    int array_mex = get_first_smaller(1, 1, MAX_N, 1);\n    is_mex[array_mex] = true;\n    \n    //cout << \"Array Mex = \" << array_mex << \"\\n\";\n    \n    int final_mex = 0;\n    for(int i = 1; i < is_mex.size(); i++)\n    {\n        if(!is_mex[i])\n        {\n            final_mex = i;\n            break;\n        }\n    }\n    \n    cout << final_mex << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Programs/Prime Square.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if(i == j)\n            {\n                cout << \"1 \";\n            }\n            else if(j == (i + 1) || (i == n && j == 1))\n            {\n                cout << \"4 \";\n            }\n            else\n            {\n                cout << \"0 \";\n            }\n        }\n        \n        cout << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Programs/Reorder.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, target_sum;\n    cin >> no_of_elements >> target_sum;\n    \n    int sum = 0;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        sum += A[i];\n    }\n    \n    cout << (sum == target_sum ? \"YES\" : \"NO\") << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/678 Div 2/Programs/Sum Over Subsets.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MOD = 998244353;\nvector <int> mu(MAX_N, 1);\nvector <int> A(MAX_N);\nmap <int, long long> frequency;\n\nlong long square(long long n)\n{\n    return (n*n)%MOD;\n}\n\nlong long power_mod(long long x, long long power)\n{\n    long long result = 1;\n    \n    while(power > 0)\n    {\n        if(power%2)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nvoid precompute()\n{\n    vector <int> is_prime(MAX_N + 1, true);\n    is_prime[1] = is_prime[0] =  false;\n    mu[1] = 1;\n    \n    for(int i = 2; i < MAX_N; i++)\n    {\n        if(!is_prime[i])\n        {\n            continue;\n        }\n        \n        for(int multiple = i; multiple < MAX_N; multiple += i)\n        {\n            mu[multiple] *= -1;\n            \n            is_prime[multiple] = false;\n        }\n        \n        for(long long square = i*1LL*i; square < MAX_N; square += i*1LL*i)\n        {\n            mu[square] = 0;\n        }\n    }\n}\n\nlong long count_with_gcd(int x)\n{\n    long long square_sum = 0, pairwise_sum = 0, sum = 0, total = 0;\n    \n    for(int i = x; i < MAX_N; i += x)\n    {\n        square_sum += ( square(i)*frequency[i] )%MOD;\n        square_sum %= MOD;\n        \n        sum += (i*frequency[i])%MOD;\n        sum %= MOD;\n        \n        total += frequency[i];\n    }\n    \n    pairwise_sum = (sum*sum - square_sum + MOD)%MOD;\n    \n    \n    long long answer = 0;\n    \n    if(total >= 2)\n    {\n        //cout << \" Squares = \" << square_sum << \" Pairs = \" << pairwise_sum << \"\\n\";\n        \n        long long t_minus_1 = (total + MOD - 1)%MOD, t_minus_2 = (total + MOD - 2)%MOD;\n        \n        long long same_term = ((t_minus_1)*power_mod(2, total - 2))%MOD;\n        same_term = (same_term*square_sum)%MOD;\n        \n        long long different_term = power_mod(2, total - 2);\n        \n        if(total >= 3)\n        {\n            different_term += (power_mod(2, total - 3)*t_minus_2)%MOD;\n            \n            different_term %= MOD;\n        }\n        //cout << \"Multiplier = \" << different_term << \"\\n\";\n        different_term = (different_term*pairwise_sum)%MOD;\n        \n        //cout << \"Answer for x = \" << x << \" = \" << same_term << \" + \" << different_term;\n        answer = (same_term + different_term)%MOD; //cout << \" = \" << answer << \"\\n\";\n    }\n    \n    return answer;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    precompute();\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        cin >> frequency[A[i]];\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i < MAX_N; i++)\n    {\n        answer += mu[i]*count_with_gcd(i);\n        \n        answer = (answer + MOD)%MOD;\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Explanations/Binary Table Explanation.txt",
    "content": "If there are an odd number of rows or odd number of columns,\nwe will handle the last odd row and last odd column seperately.\n\nWe will do this greedily.\n\nIf two consecutive elements of a row or column are 1,\nwe will flip a L that involves both of them.\nOtherwise, we will flip an L that involves only one of them.\n\nI have written various helper functions to do this.\n\nNote - When both rows and columns are odd\nWhile making a flip operation on the last column,\navoid performing an operation that would flip an element of the last row.\nThe reason is we have already flipped the last row first\nand the last row should contain all 0s.\n\n-----\n\nNow, we have a NxM matrix where both N and M are even.\nDivide the matrix in 2x2 squares and solve each 2x2 square seperately.\n\nThere are basically $4$ cases - The square can have $\\{1, 2, 3, 4\\}$ ones. Each case should be handled differently\n\nI came up with an elegant implementation. Instead of writing separate code for each of the $4$ cases, I reduced each case to another case.\n\n1. If it has 4 ones, flip and make it have 1 one.\n2. If it has 1 one, flip and make it have 2 ones.\n3. If it has 2 ones, flip and make it have 3 ones.\n4. If it has 3 ones, flip and make it have 0 ones.\n\nEvery 2x2 square takes at most 4 operations.\n\n-----\n\nvoid get(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    int one_count = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        one_count += (M[S[i].first][S[i].second] == 1);\n    }\n\n    switch(one_count)\n    {\n        case 4 : solve_4(M, op, S);\n        case 1 : solve_1(M, op, S);\n        case 2 : solve_2(M, op, S);\n        case 3 : solve_3(M, op, S);\n    }\n}\n\n-----\n\nHow do we convert a matrix with 4 ones to 1 one ?\n\nFlip any arbitrary L\n\nvoid solve_4(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    for(int i = 0; i < 3; i++)\n    {\n        perform(M, op, S[i]);\n    }\n}\n\n\n------\n\nHow do we convert a matrix with 1 one to 2 ones ?\n\nFlip any L containing the 1\n\nvoid solve_1(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    int r_1, c_1;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(M[S[i].first][S[i].second] == 1)\n        {\n            r_1 = S[i].first; c_1 = S[i].second;\n        }\n    }\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i].first == r_1 || S[i].second == c_1)\n        {\n            perform(M, op, S[i]);\n        }\n    }\n}\n\n-----\n\nHow do we convert a matrix with 2 ones to 3 ones ?\n\nFlip a L that contains one of the 1's\n\nvoid solve_2(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    int frequency_1 = 0;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(M[S[i].first][S[i].second] == 1)\n        {\n            if(frequency_1 == 0)\n            {\n                perform(M, op, S[i]);\n            }\n\n            frequency_1++;\n        }\n        else\n        {\n            perform(M, op, S[i]);\n        }\n    }\n}\n\n------\n\nHow do we convert a matrix with 3 1's to a matrix with 0 1's ?\n\nFlip the 3 1's\n\nvoid solve_3(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(M[S[i].first][S[i].second] == 1)\n        {\n            perform(M, op, S[i]);\n        }\n    }\n}\n\n------\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Explanations/Buy the String Explanation.txt",
    "content": "If (h + cost[0] < cost[1]), we will convert all the 1's to 0's\n\nIf (h + cost[1] < cost[0]), we will convert all the 0's to 1's\n\nOtherwise, we will not do a single change.\n\nPlease note that it is not possible for both of these conditions to be true at the same time\n\nIt would imply 2h < 0\n\n-----\n\nvoid solve()\n{\n    int length, cost[2], change;\n    string S;\n    cin >> length >> cost[0] >> cost[1] >> change >> S;\n\n    int answer = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(change + cost[0] < cost[1])\n        {\n            if(S[i] == '1')\n            {\n                answer += change;\n            }\n\n            answer += cost[0];\n        }\n        else if(change + cost[1] < cost[0])\n        {\n            if(S[i] == '0')\n            {\n                answer += change;\n            }\n\n            answer += cost[1];\n        }\n        else if(change >= max(cost[0] - cost[1], cost[1] - cost[0]))\n        {\n            answer += cost[S[i] - '0'];\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Explanations/Graph Subset Problem Explanation.txt",
    "content": "Let us process the vertices in ascending order of their degree.\n\nLet d(v) be the degree of the smallest vertex.\n\nIf d(v) < k - 1, then v is not part of any clique or good subset.\nSo, we can delete v from the graph along with all it's edges.\n\nIf d(v) = k - 1, then it is possible that v and all it's edges are part of a clique.\nWe will check this set of k vertices to check if every pair of vertices is connected.\nThis takes O(k^2) time.\n\nIf d(v) >= k, then all the remaining vertices have at least k neighbours.\nThis means that the remaining vertices form a good subset so we can just print the subset.\n\n-----\n\nIn order to support deletion of vertices quickly, we will store the graph in an Adjacency set.\n\nvector <set <int> > did not clear the time limit.\nSo, use vector < unordered_set <int> >\n\n-----\n\nLet us notice that a clique has k(k - 1)/2 edges.\nAnd a good subset has at least k^2 edges.\n\nThis means that 2m >= root(k) approximately.\nSo, if m = 2 x 10^5, k can be around 600.\n\nSince the value of k in which the answer exists is small, we can afford to do brute force.\n\nEvery time we check a clique candidate, we eliminate (k - 1) edges.\nSo, we can check at most (M/K - 1) candidates.\nSo, the time complexity of this is O(M/K)O(K^2) = O(M K)\n\n-----\n\nvoid solve()\n{\n    int no_of_vertices, no_of_edges, k;\n    cin >> no_of_vertices >> no_of_edges >> k;\n\n    vector <unordered_set <int> > graph(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].insert(v);\n        graph[v].insert(u);\n    }\n\n    vector <int> is_active(no_of_vertices + 1, true);\n    set <pair <int, int> > degree;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        degree.insert(make_pair(graph[i].size(), i));\n    }\n\n    int subset_found = false, clique = false;\n    for(set <pair <int, int> > :: iterator it = degree.begin(); degree.size() > 0; )\n    {\n        it = degree.begin();\n\n        if( (*it).first >= k )\n        {\n            subset_found = true;\n            break;\n        }\n\n        if( (*it).first == k - 1 && 2LL*no_of_edges >= k*1LL*(k - 1))\n        {\n            clique = (*it).second;\n            vector <int> current_candidates;\n\n            current_candidates.push_back(clique);\n            for(unordered_set <int> :: iterator it_1 = graph[clique].begin(); clique && it_1 != graph[clique].end(); it_1++)\n            {\n                current_candidates.push_back(*it_1);\n            }\n\n            for(int i = 0; i < current_candidates.size() && clique != false; i++)\n            {\n                for(int j = i + 1; j < current_candidates.size(); j++)\n                {\n                    if(graph[current_candidates[i]].count(current_candidates[j]) == 0)\n                    {\n                        clique = false;\n                        break;\n                    }\n                }\n            }\n\n            if(clique)\n            {\n                break;\n            }\n        }\n\n        int v = (*it).second;\n\n        for(unordered_set <int> :: iterator it = graph[v].begin(); it != graph[v].end(); it++)\n        {\n            int u = *it;\n\n            degree.erase(make_pair(graph[u].size(), u));\n            graph[u].erase(v);\n            degree.insert(make_pair(graph[u].size(), u));\n        }\n\n        no_of_edges -= (*it).first;\n        degree.erase(it);\n    }\n\n    if(subset_found)\n    {\n        cout << \"1 \" << degree.size() << \"\\n\";\n\n        for(set <pair <int, int> > :: iterator it = degree.begin(); it != degree.end(); it++)\n        {\n            cout << (*it).second << \" \";\n        }\n\n        cout << \"\\n\";\n\n        return;\n    }\n\n    if(clique)\n    {\n        cout << \"2\\n\";\n        cout << clique << \" \";\n\n        for(unordered_set <int> :: iterator it = graph[clique].begin(); it != graph[clique].end(); it++)\n        {\n            cout << (*it) << \" \";\n        }\n\n        cout << \"\\n\";\n\n        return;\n    }\n\n    cout << \"-1\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Explanations/Greedy Shopping Explanation.txt",
    "content": "The array is sorted in non-increasing order.\nThis is important because it allows us to use a Minimum Segment Tree built over A.\n\nLet us see how we can simulate the process.\n\nWe will start at 1 and then traverse the tree.\n\nIf the current node's range is completely outside the range we are looking at, discard it.\nIf the current node's minimum is > M, then we cannot buy a single element here, so discard it.\n\nIf these two conditions are not satisfied,\nthen it means there is at least 1 element here which we can buy.\n\nIf the current node is completely within the range and the sum < M, buy everything in the range.\n\nOtherwise, go to the left child and then the right child.\n\nThis ensures we are visiting the array elements in left-to-right order.\nThe sorting helps us use the Minimum Segment Tree\n\n-----\n\n{\n    propagate(n, left, right);\n\n    if(right < query_left || query_right < left)\n    {   //cout << \"Outside range\\n\";\n        return;\n    }\n\n    //cout << \"In \"<< n << \" [\" << left << \",\" << right << \"]\\n\";\n    if(tree[n].minimum > M)\n    {   //cout << \"Minimum = \" << tree[n].minimum << \" > \" << M << \"\\n\";\n        return;\n    }\n\n    if(query_left <= left && right <= query_right && tree[n].sum <= M)\n    {\n        M -= tree[n].sum; //cout << \"Sum = \" << tree[n].sum << \"\\n\";\n        C += (right - left + 1);\n        //cout << \"Completely within Range and now \" << M << \"\\n\";\n        return;\n    }\n\n    int mid = (left + right)/2;\n    //cout << \"Breaking into Left with \" << M << \"\\n\";\n    go_right(LEFT(n), left, mid, query_left, query_right, M, C); //cout << \"Breaking into right with \" << M << \"\\n\";\n    go_right(RIGHT(n), mid + 1, right, query_left, query_right, M, C);\n}\n\n-----\n\nBe careful while doing lazy propagation. I had 2 mistakes -\n\n1. I was propagating even when lazy[n] = 0\n2. I was adding lazy[n] to it's children, when I should be assigning.\nAdding affects the sum and the minimum.\n\nDo not propagate if you are at a leaf node. I avoided this mistake, but it is a common one.\n\n-----\n\nstruct node\n{\n    long long sum, minimum, maximum, lazy;\n\n    node()\n    {\n        sum = 0; lazy = 0;\n    }\n\n    node(long long S, long long Min, long long Max)\n    {\n        sum = S; minimum = Min; maximum = Max;\n        lazy = 0;\n    }\n};\n\nnode merge(node &L, node &R)\n{\n    return node(L.sum + R.sum, min(L.minimum, R.minimum), max(L.maximum, R.maximum));\n}\n\nconst int MAX_N = 2e5 + 5, oo = 1e9;\nnode tree[3*MAX_N];\n\nvoid propagate(int n, int left, int right)\n{\n    if(tree[n].lazy == 0)\n    {\n        return;\n    }\n\n    tree[n].maximum = tree[n].lazy;\n    tree[n].minimum = tree[n].lazy;\n    tree[n].sum = (right - left + 1)*tree[n].lazy;\n\n    if(left != right)\n    {\n        tree[LEFT(n)].lazy = tree[n].lazy;\n        tree[RIGHT(n)].lazy = tree[n].lazy;\n    }\n\n    tree[n].lazy = 0;\n}\n\n\n-----\n\nFor the update operation, we have to update some suffix of the prefix since A is sorted.\nSo, we will look for the first integer < y and then update everything in [i, x]\n\nint find_first(int n, int left, int right, int x)\n{\n    propagate(n, left, right);\n\n    if(tree[n].minimum >= x)\n    {\n        return oo;\n    }\n\n    if(left == right)\n    {\n        return right;\n    }\n\n    int mid = (left + right)/2;\n\n    if(tree[LEFT(n)].minimum < x)\n    {\n        return find_first(LEFT(n), left, mid, x);\n    }\n\n    return find_first(RIGHT(n), mid + 1, right, x);\n}\n\n-----\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Explanations/Sum of Medians Explanation.txt",
    "content": "We will be greedy and try to put the largest possible elements in the medians.\n\nLet us sort the array in descending order.\n\nSuppose the array length is n. Then the suffix length is (n/2).\n\nThe first (n/2) elements cannot be a median of any array.\nThe largest median possible is A[n/2 + 1].\n\nSimilarly, the largest value of the second median is A[n/2 + 1 + n/2 + 1].\n\nAnd so on.\n\nWe will choose all elements that are a multiple of (n/2 + 1).\n\nWe can prove this by an exchange argument.\nLet us suppose we have k medians.\n\nWe can take the largest median and replace it with A[n/2 + 1].\nWe cannot replace it with any larger integer since it requires (n/2) greater elements.\nThe sum either remains the same or increases.\n\nAfter this, we can do the same with the second largest median after deleting the largest median\nand the first (n/2) and last (n/2) elements.\n\nUltimately, we will be left with the medians that we have constructed.\n------\n\nvoid solve()\n{\n    int no_of_elements, no_of_arrays;\n    cin >> no_of_elements >> no_of_arrays;\n\n    vector <int> A(no_of_elements*no_of_arrays + 1);\n    for(int i = 1; i <= no_of_elements*no_of_arrays; i++)\n    {\n        cin >> A[i];\n    }\n\n    int median_position = (no_of_elements/2) + (no_of_elements%2);\n    int suffix = no_of_elements - median_position;\n\n    sort(all(A));\n    reverse(all(A));\n\n    long long answer = 0;\n    for(int i = suffix + 1, medians = 0; medians < no_of_arrays; i += (suffix + 1))\n    {\n\n            answer += A[i];\n\n            medians++;\n\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Programs/Binary Table.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstdio>\n\nusing namespace std;\n\nint flip(int x)\n{\n    return (1 - x);\n}\n\nvoid perform(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    op.push_back(make_pair(i, j));\n    \n    M[i][j] = flip(M[i][j]);\n}\n\nvoid perform(vector <vector <int> > &M, vector <pair <int, int> > &op, pair <int, int> P)\n{\n    perform(M, op, P.first, P.second);\n}\n\n/*x x\n    x*/\nvoid flip_corner_L(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    perform(M, op, i, j);\n    \n    perform(M, op, i - 1, j);\n    \n    perform(M, op, i - 1, j - 1);\n}\n\n/*x x\n    x*/\nvoid flip_down_corner_L(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    perform(M, op, i, j);\n    \n    perform(M, op, i + 1, j);\n    \n    perform(M, op, i, j - 1);\n}\n\n/* x\n   x x */\nvoid flip_down_L(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    perform(M, op, i, j);\n    \n    perform(M, op, i, j + 1);\n    \n    perform(M, op, i - 1, j);\n}\n\n/* x\n   x x */\nvoid flip_down_back_L(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    perform(M, op, i, j);\n    \n    perform(M, op, i, j - 1);\n    \n    perform(M, op, i - 1, j - 1);\n}\n\n/*x x\n  x */\nvoid flip_up_L(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    perform(M, op, i, j);\n    \n    perform(M, op, i - 1, j);\n    \n    perform(M, op, i - 1, j + 1);\n}\n\n/*x x\n  x */\nvoid flip_down_up_L(vector <vector <int> > &M, vector <pair <int, int> > &op, int i, int j)\n{\n    perform(M, op, i, j);\n    \n    perform(M, op, i, j - 1);\n    \n    if(i == 1)\n    {\n        perform(M, op, i + 1, j - 1);\n    }\n    else\n    {\n        perform(M, op, i - 1, j - 1);\n    }\n}\n\n\nvoid solve_3(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(M[S[i].first][S[i].second] == 1)\n        {\n            perform(M, op, S[i]);\n        }\n    }\n}\n\nvoid solve_2(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    int frequency_1 = 0;\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        if(M[S[i].first][S[i].second] == 1)\n        {\n            if(frequency_1 == 0)\n            {\n                perform(M, op, S[i]);\n            }\n            \n            frequency_1++;\n        }\n        else\n        {\n            perform(M, op, S[i]);\n        }\n    }\n}\n\nvoid solve_1(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    int r_1, c_1;\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        if(M[S[i].first][S[i].second] == 1)\n        {\n            r_1 = S[i].first; c_1 = S[i].second;\n        }\n    }\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i].first == r_1 || S[i].second == c_1)\n        {\n            perform(M, op, S[i]);\n        }\n    }\n}\n\nvoid solve_4(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    for(int i = 0; i < 3; i++)\n    {\n        perform(M, op, S[i]);\n    }\n}\n\nvoid get(vector <vector <int> > &M, vector <pair <int, int> > &op, vector <pair <int, int> > &S)\n{\n    int one_count = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        one_count += (M[S[i].first][S[i].second] == 1);\n    }\n    \n    switch(one_count)\n    {\n        case 4 : solve_4(M, op, S);\n        case 1 : solve_1(M, op, S);\n        case 2 : solve_2(M, op, S);\n        case 3 : solve_3(M, op, S);\n    }\n}\n\nvoid solve()\n{\n    int rows, columns;\n    scanf(\"%d %d\", &rows, &columns);\n    \n    vector <vector <int> > M(rows + 1, vector <int> (columns + 1));\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            scanf(\"%1d\", &M[i][j]);\n            //printf(\"%d\\n\", M[i][j]);\n        }\n    }\n    \n    vector <pair <int, int> > operations;\n    \n    if(rows%2 == 1)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(M[rows][j] == 1)\n            {\n                if(j == columns)\n                {\n                    flip_corner_L(M, operations, rows, j);\n                }\n                else if(M[rows][j + 1] == 1)\n                {\n                    flip_down_L(M, operations, rows, j);\n                }\n                else\n                {\n                    flip_up_L(M, operations, rows, j);\n                }\n            }\n        }\n    }\n    \n    if(columns%2 == 1)\n    {\n        for(int i = 1; i <= rows; i++)\n        {\n            if(M[i][columns] == 1)\n            {\n                if(i == rows)\n                {\n                    flip_down_back_L(M, operations, i, columns);\n                }\n                else if(M[i + 1][columns] == 1)\n                {\n                    flip_down_corner_L(M, operations, i, columns);\n                }\n                else\n                {\n                    flip_down_up_L(M, operations, i, columns);\n                }\n            }\n        }\n    }\n    \n    for(int i = 1; i + 1 <= rows; i += 2)\n    {\n        for(int j = 1; j + 1 <= columns; j += 2)\n        {\n            vector <pair <int, int> > squares;\n            \n            int next_r = i + 1, next_c = j + 1;\n            \n            squares.push_back(make_pair(i, j));\n            squares.push_back(make_pair(i + 1, j));\n            squares.push_back(make_pair(i, j + 1));\n            squares.push_back(make_pair(i + 1, j + 1));\n            \n            get(M, operations, squares);\n        }\n    }\n    \n    printf(\"%d\\n\", operations.size()/3);\n    \n    for(int i = 0; i < operations.size(); i++)\n    {\n        printf(\"%d %d \", operations[i].first, operations[i].second);\n        \n        if((i + 1)%3 == 0)\n        {\n            printf(\"\\n\");\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    scanf(\"%d\", &no_of_test_cases);\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Programs/Buy the String.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, cost[2], change;\n    string S;\n    cin >> length >> cost[0] >> cost[1] >> change >> S;\n    \n    int answer = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(change + cost[0] < cost[1])\n        {\n            if(S[i] == '1')\n            {\n                answer += change;\n            }\n            \n            answer += cost[0];\n        }\n        else if(change + cost[1] < cost[0])\n        {\n            if(S[i] == '0')\n            {\n                answer += change;\n            }\n            \n            answer += cost[1];\n        }\n        else if(change >= max(cost[0] - cost[1], cost[1] - cost[0]))\n        {\n            answer += cost[S[i] - '0'];\n        }\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Programs/Graph Subset Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <unordered_set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_vertices, no_of_edges, k;\n    cin >> no_of_vertices >> no_of_edges >> k;\n    \n    vector <unordered_set <int> > graph(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].insert(v);\n        graph[v].insert(u);\n    }\n    \n    vector <int> is_active(no_of_vertices + 1, true);\n    set <pair <int, int> > degree;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        degree.insert(make_pair(graph[i].size(), i));\n    }\n    \n    int subset_found = false, clique = false;\n    for(set <pair <int, int> > :: iterator it = degree.begin(); degree.size() > 0; )\n    {\n        it = degree.begin();\n        \n        if( (*it).first >= k )\n        {\n            subset_found = true;\n            break;\n        }\n        \n        if( (*it).first == k - 1 && 2LL*no_of_edges >= k*1LL*(k - 1))\n        {\n            clique = (*it).second;\n            vector <int> current_candidates;\n            \n            current_candidates.push_back(clique);\n            for(unordered_set <int> :: iterator it_1 = graph[clique].begin(); clique && it_1 != graph[clique].end(); it_1++)\n            {\n                current_candidates.push_back(*it_1);\n            }\n            \n            for(int i = 0; i < current_candidates.size() && clique != false; i++)\n            {\n                for(int j = i + 1; j < current_candidates.size(); j++)\n                {\n                    if(graph[current_candidates[i]].count(current_candidates[j]) == 0)\n                    {\n                        clique = false;\n                        break;\n                    }\n                }\n            }\n                       \n            if(clique)\n            {\n                break;\n            }\n        }\n        \n        int v = (*it).second;\n        \n        for(unordered_set <int> :: iterator it = graph[v].begin(); it != graph[v].end(); it++)\n        {\n            int u = *it;\n            \n            degree.erase(make_pair(graph[u].size(), u));\n            graph[u].erase(v);\n            degree.insert(make_pair(graph[u].size(), u));\n        }\n        \n        no_of_edges -= (*it).first;\n        degree.erase(it);\n    }\n    \n    if(subset_found)\n    {\n        cout << \"1 \" << degree.size() << \"\\n\";\n        \n        for(set <pair <int, int> > :: iterator it = degree.begin(); it != degree.end(); it++)\n        {\n            cout << (*it).second << \" \";\n        }\n        \n        cout << \"\\n\";\n        \n        return;\n    }\n    \n    if(clique)\n    {\n        cout << \"2\\n\";\n        cout << clique << \" \";\n        \n        for(unordered_set <int> :: iterator it = graph[clique].begin(); it != graph[clique].end(); it++)\n        {\n            cout << (*it) << \" \";\n        }\n        \n        cout << \"\\n\";\n        \n        return;\n    }\n    \n    cout << \"-1\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Programs/Greedy Shopping.cpp",
    "content": "#include <iostream>\n#include <vector>\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nstruct node\n{\n    long long sum, minimum, maximum, lazy;\n    \n    node()\n    {\n        sum = 0; lazy = 0;\n    }\n    \n    node(long long S, long long Min, long long Max)\n    {\n        sum = S; minimum = Min; maximum = Max;\n        lazy = 0;\n    }\n};\n\nnode merge(node &L, node &R)\n{\n    return node(L.sum + R.sum, min(L.minimum, R.minimum), max(L.maximum, R.maximum));\n}\n\nconst int MAX_N = 2e5 + 5, oo = 1e9;\nnode tree[3*MAX_N];\n\nvoid propagate(int n, int left, int right)\n{\n    if(tree[n].lazy == 0)\n    {\n        return;\n    }\n    \n    tree[n].maximum = tree[n].lazy;\n    tree[n].minimum = tree[n].lazy;\n    tree[n].sum = (right - left + 1)*tree[n].lazy;\n    \n    if(left != right)\n    {\n        tree[LEFT(n)].lazy = tree[n].lazy;\n        tree[RIGHT(n)].lazy = tree[n].lazy;\n    }\n    \n    tree[n].lazy = 0;\n}\n\nvoid update(int n, int left, int right, int query_left, int query_right, long long x)\n{\n    propagate(n, left, right);\n    \n    if(right < left || query_right < query_left || query_right < left || right < query_left)\n    {\n        return;\n    }\n    \n    if(query_left <= left && right <= query_right)\n    { //cout << \" Updating [\" << left << \",\" << right << \"] = \" << x;\n        tree[n].lazy = x;\n        propagate(n, left, right); //cout << \" Sum = \" << tree[n].sum << \"\\n\";\n        return;\n    }\n    \n    int mid = (left + right)/2;\n    \n    update(LEFT(n), left, mid, query_left, query_right, x);\n    update(RIGHT(n), mid + 1, right, query_left, query_right, x);\n    \n    tree[n] = merge(tree[LEFT(n)], tree[RIGHT(n)]);\n}\n\nint find_first(int n, int left, int right, int x)\n{\n    propagate(n, left, right);\n    \n    if(tree[n].minimum >= x)\n    {\n        return oo;\n    }\n    \n    if(left == right)\n    {\n        return right;\n    }\n    \n    int mid = (left + right)/2;\n    \n    if(tree[LEFT(n)].minimum < x)\n    {\n        return find_first(LEFT(n), left, mid, x);\n    }\n    \n    return find_first(RIGHT(n), mid + 1, right, x);\n}\n\nvoid go_right(int n, int left, int right, int query_left, int query_right, int &M, int &C)\n{\n    propagate(n, left, right);\n    \n    if(right < query_left || query_right < left)\n    {   //cout << \"Outside range\\n\";\n        return;\n    }\n    \n    //cout << \"In \"<< n << \" [\" << left << \",\" << right << \"]\\n\";\n    if(tree[n].minimum > M)\n    {   //cout << \"Minimum = \" << tree[n].minimum << \" > \" << M << \"\\n\";\n        return;\n    }\n    \n    if(query_left <= left && right <= query_right && tree[n].sum <= M)\n    {\n        M -= tree[n].sum; //cout << \"Sum = \" << tree[n].sum << \"\\n\";\n        C += (right - left + 1);\n        //cout << \"Completely within Range and now \" << M << \"\\n\";\n        return;\n    }\n    \n    int mid = (left + right)/2;\n    //cout << \"Breaking into Left with \" << M << \"\\n\";\n    go_right(LEFT(n), left, mid, query_left, query_right, M, C); //cout << \"Breaking into right with \" << M << \"\\n\";\n    go_right(RIGHT(n), mid + 1, right, query_left, query_right, M, C);\n}\n\nint main()\n{\n    int no_of_elements, no_of_queries;\n    cin >> no_of_elements >> no_of_queries;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n        \n        update(1, 1, no_of_elements, i, i, x);\n    }\n    \n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int type, x, y;\n        cin >> type >> x >> y;\n        \n        const int UPDATE = 1, QUERY = 2;\n        switch(type)\n        {\n            case UPDATE : {\n                              int prefix = x, value = y;\n                              int i = find_first(1, 1, no_of_elements, value);\n                \n                //cout << \"First < \" << value << \" is \" << i << \"\\n\";\n                              update(1, 1, no_of_elements, i, prefix, value);\n                                break;\n                          }\n                \n            case QUERY :  {\n                                int money = y, start = x;\n                                int visit_count = 0;\n                \n                go_right(1, 1, no_of_elements, start, no_of_elements, money, visit_count);\n                \n                cout << visit_count << \"\\n\";\n                          }\n        }\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/684 Div 2/Programs/Sum of Medians.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin() + 1, (v).end()\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, no_of_arrays;\n    cin >> no_of_elements >> no_of_arrays;\n    \n    vector <int> A(no_of_elements*no_of_arrays + 1);\n    for(int i = 1; i <= no_of_elements*no_of_arrays; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int median_position = (no_of_elements/2) + (no_of_elements%2);\n    int suffix = no_of_elements - median_position;\n    \n    sort(all(A));\n    reverse(all(A));\n    \n    long long answer = 0;\n    for(int i = suffix + 1, medians = 0; medians < no_of_arrays; i += (suffix + 1))\n    {\n        \n            answer += A[i];\n            \n            medians++;\n        \n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Explanations/Bitwise Queries Explanation.txt",
    "content": "Here is the main idea of the problem -\n\n1. We will find 1 element.\n2. We will use that element to determine the rest of the array.\n\n-----\n\nHow do we find out 1 element ? And how do we use it to find the remaining ?\n\nFirstly, we will keep XOR[i] = XOR(A[1], A[i]), for all i\n\nIf we know A[1], then A[i] = XOR(A[1], XOR[i])\n\nXOR is the best operation for recovering the original elements because OR and AND lose bits.\nIn general, the symmetry offered by XOR is always the best for such problems.\n\nWe will use the following identity - a + b = XOR(a, b) + 2AND(a, b)\n\nThe reason is -\n\n1. When both a, b have a 0 at a bit, XOR is also 0 and addition is also 0\n2. When one has a 1, XOR and addition both give 1\n3. When both have a 1, XOR contributes 0 and addition contributes 2x2^i\n\nSo, in order to complete addition, we need to add double of all the bits that are set in both a and b\nThis is AND(a, b) !\n\n------\n\nWe will find out the sums of\n\nA[1] + A[2] = S[12]\nA[2] + A[3] = S[23]\nA[3] + A[1] = S[31]\n\nThis requires 6 queries and the remaining (n - 3) can be guessed with 1 query each.\n\nBut, we can use the following idea to bring it down to 5 -\n\nXOR(A[2], A[3]) = XOR( XOR(A[1], A[2]), XOR(A[1], A[3]) )\n\nThis is enough for the Easy Version\n\n------\n\nLet us use the fact that all integer are in [0, n - 1] and\nthat n is a power of 2.\n\nThis means that either there is some integer that repeats twice or\nall integers in [0, n - 1] are present.\n\nIf some integer is present twice, then XOR[i] = XOR[j].\nWe can use AND(i, j) to find out A[i] and use A[i] to find out A[1]\nA[1] can be used to find out the remaining array. This requires\n1 + (n - 1) = n operations\n\nIf every integer is present, it means every integer's binary complement occurs.\nThis means that for every integer, there will be an integer such that their sum is (n - 1).\nThis means that the XOR is (N - 1) and AND is 0.\nThis save us a query.\n\nIf XOR[i] = N - 1, then we will find out (A[1], A[i], A[j]) using the system of equations method we used.\nBut we only need 4 queries instead of 5 since AND(A[1], A[i]) is known.\n\n------\n\nvoid ask(int i, int j, string operation, int &result)\n{\n    cout << operation << \" \" << i << \" \" << j << \"\\n\";\n    cout.flush();\n\n    cin >> result;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1, -1);\n    vector <int> xor_1(no_of_elements + 1, 0);\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        ask(1, i, \"XOR\", xor_1[i]);\n    }\n\n    int and_12 = -1, and_23 = -1, and_13 = -1;\n    int xor_12 = -1 , xor_13 = -1, xor_23 = -1;\n    int second = 0, third = 0;\n\n    map <int, int> last_xor_occurence;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        //All Elements Different, At least one pair XOR = n - 1, n = 2^p\n        if(xor_1[i] == no_of_elements - 1)\n        {\n            second = i;\n            third = (i == 2 ? 3 : 2);\n\n            xor_12 = xor_1[second];\n            xor_13 = xor_1[third];\n            xor_23 =  xor_1[second]^xor_1[third];\n\n            and_12 = 0;\n            ask(second, third, \"AND\", and_23);\n            ask(1, third, \"AND\", and_13);\n            break;\n        }\n\n        //Two Equal Elements\n        if(last_xor_occurence[xor_1[i]] != 0)\n        {\n            ask(last_xor_occurence[xor_1[i]], i, \"AND\", A[i]);\n            A[1] = A[i]^xor_1[i];\n\n            break;\n        }\n\n        last_xor_occurence[xor_1[i]] = i;\n    }\n\n    if(second != 0 && third != 0)\n    {\n        int sum_12 = xor_12 + 2*and_12;\n        int sum_23 = xor_23 + 2*and_23;\n        int sum_13 = xor_13 + 2*and_13;\n\n        A[1] = (sum_12 - sum_23 + sum_13)/2;\n    }\n\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        A[i] = A[1]^xor_1[i];\n    }\n\n    cout << \"! \";\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    cout << \"\\n\";\n    cout.flush();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Explanations/Circle Game Explanation.txt",
    "content": "Let us look at the line x = y.\n\nSuppose the furthest points in the line x = y inside the circle is\n\n(kz, kz)\n\nLet (k(z + 1), kz) be outside the circle of radius d.\nThen, the second person will always win.\nNo matter what the first player does, the second player can always ensure that\nthe coin remains on the line (x = y).\nIt will be the first player who moves out of the circle.\n\n\n-----\n\nIf (k(z + 1), kz)) is inside the circle,\nthen after the first player makes a move, the first player is in the same position\nthe second player was in the previous situation.\n\nThe first player can always ensure the difference in the multiplier of x and y\ndiffers by 1 after each of his move so\n\n(k(z + 1, kz)) can only be reached after the first player's turn. \n\n-----\n\nWe will do binary search to find the furthest z, such that\n\n(kz, kz) is inside d-circle\n\n------\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nlong long square(long long n)\n{\n    return n*n;\n}\n\nvoid solve()\n{\n    long long d, k;\n    cin >> d >> k;\n\n    long long left = 0, right = ceil(d, k);\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n\n        if(2*square(k*mid) <= square(d))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n\n    long long z = left;\n\n    cout << (square(k*z) + square(k*(z + 1)) <= square(d) ? \"Ashish\" : \"Utkarsh\") << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Explanations/Non Substring Subsequence Explanation.txt",
    "content": "We will search for A[L] in S[1, L - 1]\nWe will search for A[R] in S[R + 1, N]\n\nIf either of these conditions are met, the subsequence is met.\nBut, we must show that it is also necessary.\n\nLet us suppose that there is such a sequence in S.\nIf the sequence begins before A[L], then the first character is before A[L].\n\n(If the first occurence of A[L] is A[L], then it is not possible.)\n\nIf the sequence begins After A[L],\nthen the last character must occur again after A[R].\n\n(If the last occurence of A[R] is R, then it is not possible.)\n\n-----\n\nvoid solve()\n{\n    int length, queries;\n    cin >> length >> queries;\n\n    string S;\n    cin >> S;\n\n    for(int i = 1; i <= queries; i++)\n    {\n        int left, right;\n        cin >> left >> right;\n\n        int answer_found = false;\n        for(int i = right + 1; i <= length; i++)\n        {\n            if(S[right - 1] == S[i - 1])\n            {\n                cout << \"YES\\n\";\n                answer_found = true;\n                break;\n            }\n        }\n\n        if(answer_found)\n        {\n            continue;\n        }\n\n        for(int i = 1; i < left; i++)\n        {\n            if(S[i - 1] == S[left - 1])\n            {\n                cout << \"YES\\n\";\n                answer_found = true;\n                break;\n            }\n        }\n\n        if(answer_found)\n        {\n            continue;\n        }\n\n        cout << \"NO\\n\";\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Explanations/Nullify the Matrix Explanation.txt",
    "content": "1. Because of the constraint (r1 <= r2) and (c1 <= c2),\nany path we choose will contain only one square on the diagonal (r1 + c1).\n\n2. Let us notice something. If any diagonal has XOR 0, we can choose a path\nthat makes the XOR of every diagonal = 0\nIf every diagonal has XOR 0, then any path we choose will make the XOR non zero\n\nSince the final matrix has the XOR of every diagonal 0,\nthis helps us in determining the winner.\n\n3. Let us choose the smallest and largest diagonals having (r + c) values\nwhich are non-zero XOR\n\nIn the first diagonal, we will choose a square which has the same bit set as X(r + c).\nThere has to be at least one such square or the XOR will not have that bit set.\nWe will perform subtraction to ensure the XOR becomes 0.\nSuppose the XOR was X and the square has S,\n\nWe will make the square = XOR(S, X)\n\nEvery other diagonal, there are additions allowed so we can make all the XOR's 0\n\n4. If the XOR is 0, then our subtraction in the first square makes it non zero.\n\n5. Each diagonal corresponds to a pile of stones.\nWe can subtract from 1 set of piles but can add on the other piles.\nWe can come up with this observation by noticing that the question\nsays only the first square has a restriction of addition and the other squares are free.\nWhat is a property of the first square that no other square in the path has ?\nThe diagonal !\nThis is the way to think of this \n\n-----\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    vector <int> diagonal (rows + columns + 1);\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int x;\n            cin >> x;\n\n            diagonal[i + j] ^= x;\n        }\n    }\n\n    int nim_sum = 0;\n    for(int i = 2; i <= rows + columns; i++)\n    {\n        nim_sum += diagonal[i];\n    }\n\n    cout << (nim_sum != 0 ? \"Ashish\\n\" : \"Jeel\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Explanations/String Equality Explanation.txt",
    "content": "Fact 1 - If A and B are anagrams, we can always make A = B\n\nLet us perform the swaps to make the last alphabet of A = last alphabet of B\n\nThen, we can delete the last character and repeat the same with strings of length (n - 1).\n\n------\n\nFact 2 - The frequency of every alphabet (mod K) never changes\n\nWe can change exactly K alphabets at a time.\n\nSo the number of removals or additions to any alphabet can only be K at a time.\n\nSo frequency[alphabet] (mod K) is invariant.\n\nIf (frequency_A[alpha] %k != frequency_B[alpha]%k), then\nA and B can never have the same frequency of that alphabet.\n\nIf they have the same remainder mod K for every alphabet, we will do a simulation.\n\n-----\n\nvoid solve()\n{\n    int length, k;\n    string A, B;\n    cin >> length >> k >> A >> B;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <int> frequency_A(NO_OF_ALPHABETS + 1, 0), frequency_B(NO_OF_ALPHABETS + 1, 0);\n    for(int i = 0; i < length; i++)\n    {\n        frequency_A[A[i] - 'a']++;\n        frequency_B[B[i] - 'a']++;\n    }\n\n    int possible = true;\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(frequency_A[alpha]%k != frequency_B[alpha]%k)\n        {\n            possible = false;\n        }\n    }\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(frequency_B[alpha] > frequency_A[alpha])\n        {\n            possible = false;\n            break;\n        }\n\n        int extra = frequency_A[alpha] - frequency_B[alpha];\n\n        frequency_A[alpha + 1] += extra;\n    }\n\n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Explanations/Subtract or Divide Explanation.txt",
    "content": "1. If n is 1, we do not need to do anything.\n2. If n is 2, we can subtract 1 and do it in each step.\n3. If n is even, we can go to 2 in 1 step and 1 in another. It is 2.\n4. If n is 3, we can go to 2 in one step. And reach 1 in 2.\n5. If n is odd, we can go an even integer in 1 step. And reach 1 in 3.\n\n------\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    int moves = 0;\n\n    if(n == 2)\n    {\n        moves++;\n    }\n    else if(n%2 == 0)\n    {\n        moves = 2;\n    }\n    else if(n > 1)\n    {\n        moves = (n == 3 ? 2 : 3);\n    }\n\n    cout << moves << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/Bitwise Queries (Hard Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid ask(int i, int j, string operation, int &result)\n{\n    cout << operation << \" \" << i << \" \" << j << \"\\n\";\n    cout.flush();\n    \n    cin >> result;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1, -1);\n    vector <int> xor_1(no_of_elements + 1, 0);\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        ask(1, i, \"XOR\", xor_1[i]);\n    }\n    \n    int and_12 = -1, and_23 = -1, and_13 = -1;\n    int xor_12 = -1 , xor_13 = -1, xor_23 = -1;\n    int second = 0, third = 0;\n    \n    map <int, int> last_xor_occurence;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        //All Elements Different, At least one pair XOR = n - 1, n = 2^p\n        if(xor_1[i] == no_of_elements - 1)\n        {\n            second = i;\n            third = (i == 2 ? 3 : 2);\n            \n            xor_12 = xor_1[second];\n            xor_13 = xor_1[third];\n            xor_23 =  xor_1[second]^xor_1[third];\n            \n            and_12 = 0;\n            ask(second, third, \"AND\", and_23);\n            ask(1, third, \"AND\", and_13);\n            break;\n        }\n        \n        //Two Equal Elements\n        if(last_xor_occurence[xor_1[i]] != 0)\n        {\n            ask(last_xor_occurence[xor_1[i]], i, \"AND\", A[i]);\n            A[1] = A[i]^xor_1[i];\n            \n            break;\n        }\n        \n        last_xor_occurence[xor_1[i]] = i;\n    }\n    \n    if(second != 0 && third != 0)\n    {\n        int sum_12 = xor_12 + 2*and_12;\n        int sum_23 = xor_23 + 2*and_23;\n        int sum_13 = xor_13 + 2*and_13;\n\n        A[1] = (sum_12 - sum_23 + sum_13)/2;\n    }\n    \n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        A[i] = A[1]^xor_1[i];\n    }\n    \n    cout << \"! \";\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/Bitwise Queries.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid ask(int i, int j, string operation, int &result)\n{\n    cout << operation << \" \" << i << \" \" << j << \"\\n\";\n    cout.flush();\n    \n    cin >> result;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    vector <int> xor_1(no_of_elements + 1);\n    int and_12, and_23, and_13;\n    \n    ask(1, 2, \"XOR\", xor_1[2]);\n    ask(1, 2, \"AND\", and_12);\n    \n    ask(1, 3, \"XOR\", xor_1[3]);\n    ask(1, 3, \"AND\", and_13);\n    \n    ask(2, 3, \"AND\", and_23);\n    int xor_23 = xor_1[2]^xor_1[3]; //(1^2)^(1^3) = 2^3\n    \n    int sum_12 = xor_1[2] + 2*and_12;\n    int sum_23 = xor_23 + 2*and_23;\n    int sum_13 = xor_1[3] + 2*and_13;\n    \n    A[1] = (sum_12 - sum_23 + sum_13)/2;\n    A[2] = A[1]^xor_1[2];\n    A[3] = A[1]^xor_1[3];\n    \n    for(int i = 4; i <= no_of_elements; i++)\n    {\n        ask(1, i, \"XOR\", xor_1[i]);\n        \n        A[i] = A[1]^xor_1[i];\n    }\n    \n    cout << \"! \";\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    cout << \"\\n\";\n    cout.flush();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/Circle Game.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nlong long square(long long n)\n{\n    return n*n;\n}\n\nvoid solve()\n{\n    long long d, k;\n    cin >> d >> k;\n    \n    long long left = 0, right = ceil(d, k);\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n        \n        if(2*square(k*mid) <= square(d))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n    \n    long long z = left;\n    \n    cout << (square(k*z) + square(k*(z + 1)) <= square(d) ? \"Ashish\" : \"Utkarsh\") << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/Non-Substring Subsequence .cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, queries;\n    cin >> length >> queries;\n    \n    string S;\n    cin >> S;\n    \n    for(int i = 1; i <= queries; i++)\n    {\n        int left, right;\n        cin >> left >> right;\n        \n        int answer_found = false;\n        for(int i = right + 1; i <= length; i++)\n        {\n            if(S[right - 1] == S[i - 1])\n            {\n                cout << \"YES\\n\";\n                answer_found = true;\n                break;\n            }\n        }\n        \n        if(answer_found)\n        {\n            continue;\n        }\n        \n        for(int i = 1; i < left; i++)\n        {\n            if(S[i - 1] == S[left - 1])\n            {\n                cout << \"YES\\n\";\n                answer_found = true;\n                break;\n            }\n        }\n        \n        if(answer_found)\n        {\n            continue;\n        }\n        \n        cout << \"NO\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/Nullify the Matrix.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    vector <int> diagonal (rows + columns + 1);\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int x;\n            cin >> x;\n            \n            diagonal[i + j] ^= x;\n        }\n    }\n    \n    int nim_sum = 0;\n    for(int i = 2; i <= rows + columns; i++)\n    {\n        nim_sum += diagonal[i];\n    }\n    \n    cout << (nim_sum != 0 ? \"Ashish\\n\" : \"Jeel\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/String Equality.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, k;\n    string A, B;\n    cin >> length >> k >> A >> B;\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <int> frequency_A(NO_OF_ALPHABETS + 1, 0), frequency_B(NO_OF_ALPHABETS + 1, 0);\n    for(int i = 0; i < length; i++)\n    {\n        frequency_A[A[i] - 'a']++;\n        frequency_B[B[i] - 'a']++;\n    }\n    \n    int possible = true;\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(frequency_A[alpha]%k != frequency_B[alpha]%k)\n        {\n            possible = false;\n        }\n    }\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(frequency_B[alpha] > frequency_A[alpha])\n        {\n            possible = false;\n            break;\n        }\n        \n        int extra = frequency_A[alpha] - frequency_B[alpha];\n        \n        frequency_A[alpha + 1] += extra;\n    }\n    \n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/685 Div 2/Programs/Subtract or Divide .cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    int moves = 0;\n    \n    if(n == 2)\n    {\n        moves++;\n    }\n    else if(n%2 == 0)\n    {\n        moves = 2;\n    }\n    else if(n > 1)\n    {\n        moves = (n == 3 ? 2 : 3);\n    }\n    \n    cout << moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Explanations/Bouncing Ball Explanation.txt",
    "content": "Let us start at the i-th position.\n\nThen the cost is (A[i] + A[i + k] + A[i + 2k] + ... )\n\nWe will iterate through all possible candidates for the starting,\n\ni >= p and calculate the total cost\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, p, k;\n    cin >> no_of_elements >> p >> k;\n\n    string S;\n    cin >> S;\n\n    int add_cost, removal_cost;\n    cin >> add_cost >> removal_cost;\n\n    vector <long long> sum(S.size() + k + 1, 0);\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        sum[i] = add_cost*(S[i] == '0') + sum[i + k];\n\n        //cout << \"Sum \" << i << \" = \" << sum[i] << \"\\n\";\n    }\n\n    const long long oo = 1e18;\n    long long answer = oo;\n\n    for(int i = p - 1, j = S.size(), r = 0; j >= p && i < S.size(); i++, j--, r++)\n    {\n        answer = min(answer, (r)*removal_cost + sum[i]);\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Explanations/New Game Plus Explanation.txt",
    "content": "Suppose we use (A[1], A[2], ... , A[x]) before using a reset.\nWhat is the total cost ?\n\nRemember that we can only add the boss point to our total before killing the boss.\nTotal = (x - 1)A[1] + (x - 2)A[2] + ... + 0A[x]\n\nSeeing this, it is clearly optimal to visit elements in non-increasing order\nin 1 play through.\n\n-----\n\nHowever, we also have negative increments. In this situation, it is better to use our play throughs.\n\nWe need to imagine we have (k + 1) piles or stacks.\n\nIt is always better for the larger element to be at a higher level in a stack.\n\nSuppose we have to elements a and b with a >= b\nat levels i and j respectively with i < j\n\nThe current contribution to the total from both of these is\n\nai + bj\n\nBut, if we swap a and b, we will make the contribution (aj + bi),\nwhich is greater.\n\n-----\n\nSo, we will keep the lowest elements in the lowest level of all stacks.\nThen, the next lowest in the second,\nand so on.\n\nThis is what we will start with - Distribute the integers as evenly as possible.\nAfter that, we will see if the answer can be improved by moving some of the greatest integers\ninto one stack.\n\n-----\n\nWhen i = 0 (mod k), we cannot put any more piles on the same stack since we have reached the limit.\n\nSuppose there are the 4 stacks and we are trying to build a tower of maximum length.\nWe can put the box on the second stack on the first tower,\nbox of the third stack on the first tower,\nbox of the fourth stack on the first tower\nBut we increase the height further as the\nbox of the first pile is already in the first pile.\n\n-----\n\nint main()\n{\n    int no_of_elements, no_of_resets;\n    cin >> no_of_elements >> no_of_resets;\n\n    int no_of_stacks = no_of_resets + 1;\n\n    vector <long long> A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    vector <long long> suffix_sum(no_of_elements + 5, 0);\n    for(int i = no_of_elements - 1; i >= 0; i--)\n    {\n        suffix_sum[i] = suffix_sum[i + 1] + A[i];\n    }\n\n    long long total = 0;\n\n    //Distribute Negative Integers Evenly\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        total += A[i]*(i/no_of_stacks);\n    }\n\n    for(int i = no_of_elements - 1; i >= 0; i--)\n    {\n        if(i%no_of_stacks == 0) //This element stays on same level\n        {\n            continue;\n        }\n        //cout << \"i = \" << i << \" Total = \" << total  << \" and suffix = \" << suffix_sum[i] << \"\\n\";\n        total = max(total, total + suffix_sum[i]); //cout << \"total = \" << total << \"\\n\";\n    }\n\n    cout << total << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Explanations/Prison Break Explanation.txt",
    "content": "The X and Y axes are independent.\n\nThe X answer is max(i - 1, n - i)\nThe Y answer is max(j - 1, m - j)\n\nAdd the answers\n\n-----\n\nvoid solve()\n{\n    int rows, columns, i, j;\n    cin >> rows >> columns >> i >> j;\n\n    int row_answer = max(rows - i, i - 1);\n    int column_answer = max(columns - j, j - 1);\n\n    int answer = row_answer + column_answer;\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Explanations/Repainting Street Explanation.txt",
    "content": "There are only 100 colours so check the cost to make the array equal to each colour.\n\nThe check can be done greedily.\n\n-----\n\nint calculate(vector <int> &A, int k, int chosen)\n{\n    int n = A.size() - 1, no_of_days = 0;\n\n    for(int i = 1; i <= n; i++)\n    {\n        if(A[i] != chosen)\n        {\n            no_of_days++;\n\n            i += (k - 1);\n        }\n    }\n\n    return no_of_days;\n}\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int MAX_COLOURS = 100;\n    int answer = ceil(no_of_elements, k);\n    for(int c = 1; c <= MAX_COLOURS; c++)\n    {\n        answer = min(answer, calculate(A, k, c));\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Explanations/XOR Gun Explanation.txt",
    "content": "Suppose there are 3 integers which have the same MSB.\n\nA[i], A[i + 1], A[i + 2]\n\nXOR(A[i + 1], A[i + 2]) will have a 0 in that bit position and be < A[i]\n\nSo, it is always possible with 1 step.\n\nIf every MSB occurs at most twice, we will have around 60 elements.\n\nThen, we will check it with brute force.\n\nFor every pair (i, i + 1),\n\nXOR A[i] with some prefix and A[i + 1] with some suffix and check\n\nif it is possible to make A[i] > A[i + 1]\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0 );\n}\n\nint msb(int n)\n{\n    const int NO_OF_BITS = 31;\n\n    for(int i = NO_OF_BITS; i >= 0; i--)\n    {\n        if(is_bit_set(n, i))\n        {\n            return i;\n        }\n    }\n\n    return 0;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    int possible = false;\n\n    const int NO_OF_BITS = 31;\n    vector <int> msb_frequency(NO_OF_BITS + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        msb_frequency[msb(A[i])]++;\n    }\n\n    int answer = no_of_elements + 1;\n    for(int bit = 0; bit < NO_OF_BITS; bit++)\n    {\n        if(msb_frequency[bit] >= 3)\n        {\n            possible = true;\n            answer = 1;\n\n            break;\n        }\n    }\n\n    vector <int> prefix_xor(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_xor[i] = prefix_xor[i - 1]^A[i];\n    }\n\n    for(int i = 1; i < no_of_elements && answer > 1; i++)\n    {\n        for(int j = i - 1; j >= 0; j--)\n        {\n            int prefix = prefix_xor[i]^prefix_xor[j];\n            int prefix_operations = (i - 1) - j;\n\n            for(int k = i + 1; k <= no_of_elements; k++)\n            {\n                int suffix = prefix_xor[k]^prefix_xor[i];\n                int suffix_operations = k - (i + 1);\n\n                if(prefix > suffix)\n                {\n                    possible = true;\n                    answer = min(answer, prefix_operations + suffix_operations);\n                }\n            }\n        }\n    }\n\n    cout << (possible ? answer : -1) << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Programs/Bouncing Ball.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, p, k;\n    cin >> no_of_elements >> p >> k;\n    \n    string S;\n    cin >> S;\n    \n    int add_cost, removal_cost;\n    cin >> add_cost >> removal_cost;\n    \n    vector <long long> sum(S.size() + k + 1, 0);\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        sum[i] = add_cost*(S[i] == '0') + sum[i + k];\n        \n        //cout << \"Sum \" << i << \" = \" << sum[i] << \"\\n\";\n    }\n    \n    const long long oo = 1e18;\n    long long answer = oo;\n    \n    for(int i = p - 1, j = S.size(), r = 0; j >= p && i < S.size(); i++, j--, r++)\n    {\n        answer = min(answer, (r)*removal_cost + sum[i]);\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Programs/New Game Plus.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, no_of_resets;\n    cin >> no_of_elements >> no_of_resets;\n    \n    int no_of_stacks = no_of_resets + 1;\n    \n    vector <long long> A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    \n    vector <long long> suffix_sum(no_of_elements + 5, 0);\n    for(int i = no_of_elements - 1; i >= 0; i--)\n    {\n        suffix_sum[i] = suffix_sum[i + 1] + A[i];\n    }\n    \n    long long total = 0;\n    \n    //Distribute Negative Integers Evenly\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        total += A[i]*(i/no_of_stacks);\n    }\n    \n    for(int i = no_of_elements - 1; i >= 0; i--)\n    {\n        if(i%no_of_stacks == 0) //This element stays on same level\n        {\n            continue;\n        }\n        //cout << \"i = \" << i << \" Total = \" << total  << \" and suffix = \" << suffix_sum[i] << \"\\n\";\n        total = max(total, total + suffix_sum[i]); //cout << \"total = \" << total << \"\\n\";\n    }\n    \n    cout << total << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Programs/Prison Break.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int rows, columns, i, j;\n    cin >> rows >> columns >> i >> j;\n    \n    int row_answer = max(rows - i, i - 1);\n    int column_answer = max(columns - j, j - 1);\n    \n    int answer = row_answer + column_answer;\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Programs/Repainting Street.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint ceil(int n, int d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nint calculate(vector <int> &A, int k, int chosen)\n{\n    int n = A.size() - 1, no_of_days = 0;\n    \n    for(int i = 1; i <= n; i++)\n    {\n        if(A[i] != chosen)\n        {\n            no_of_days++;\n            \n            i += (k - 1);\n        }\n    }\n    \n    return no_of_days;\n}\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n   \n    const int MAX_COLOURS = 100;\n    int answer = ceil(no_of_elements, k);\n    for(int c = 1; c <= MAX_COLOURS; c++)\n    {\n        answer = min(answer, calculate(A, k, c));\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/687 Div 2 Technocup 2021 Elimination Round 2/Programs/XOR Gun.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0 );\n}\n\nint msb(int n)\n{\n    const int NO_OF_BITS = 31;\n    \n    for(int i = NO_OF_BITS; i >= 0; i--)\n    {\n        if(is_bit_set(n, i))\n        {\n            return i;\n        }\n    }\n    \n    return 0;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int possible = false;\n    \n    const int NO_OF_BITS = 31;\n    vector <int> msb_frequency(NO_OF_BITS + 1, 0);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        msb_frequency[msb(A[i])]++;\n    }\n    \n    int answer = no_of_elements + 1;\n    for(int bit = 0; bit < NO_OF_BITS; bit++)\n    {\n        if(msb_frequency[bit] >= 3)\n        {\n            possible = true;\n            answer = 1;\n            \n            break;\n        }\n    }\n    \n    vector <int> prefix_xor(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_xor[i] = prefix_xor[i - 1]^A[i];\n    }\n    \n    for(int i = 1; i < no_of_elements && answer > 1; i++)\n    {\n        for(int j = i - 1; j >= 0; j--)\n        {\n            int prefix = prefix_xor[i]^prefix_xor[j];\n            int prefix_operations = (i - 1) - j;\n            \n            for(int k = i + 1; k <= no_of_elements; k++)\n            {\n                int suffix = prefix_xor[k]^prefix_xor[i];\n                int suffix_operations = k - (i + 1);\n                \n                if(prefix > suffix)\n                {\n                    possible = true;\n                    answer = min(answer, prefix_operations + suffix_operations);\n                }\n            }\n        }\n    }\n    \n    cout << (possible ? answer : -1) << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/688 Div 2/Explanation/Suffix Operations Explanation.txt",
    "content": "Let us observe that if we apply the operations on [i, n],\n\nA[i + 1] - A[i],\nA[i + 2] - A[i - 1],\n...\nA[n] - A[n - 1]\n\ndo not change.\nThe differences of adjacent elements in the suffix remain the same.\n\n-----\n\nIn order to make it equal, the only way is to apply the operation to\n[i, N]\nWe have to apply it |A[i] - A[i - 1]| times.\n\nWhich element can we change ?\nIf we change A[i], it is optimal to set it to either A[i - 1] or A[i + 1].\n\n|A[i - 1] - x| + |A[i + 1] - x| is minimum when x = A[i - 1] or A[i + 1].\nWe will examine the maximum change we can do at every level and choose the best.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    long long change = max(abs(A[no_of_elements] - A[no_of_elements - 1]),\n                           abs(A[1] - A[2]));\n    for(int i = 2; i < no_of_elements; i++)\n    {\n        long long new_operations = abs(A[i + 1] - A[i - 1]);\n        long long old_operations = abs(A[i] - A[i - 1]) + abs(A[i + 1] - A[i]);\n\n        change = max(change, old_operations - new_operations);\n    }\n\n    long long answer = 0;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        answer += abs(A[i] - A[i - 1]);\n    }\n\n    answer -= change;\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/688 Div 2/Programs/Suffix Operations.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long change = max(abs(A[no_of_elements] - A[no_of_elements - 1]),\n                           abs(A[1] - A[2]));\n    for(int i = 2; i < no_of_elements; i++)\n    {\n        long long new_operations = abs(A[i + 1] - A[i - 1]);\n        long long old_operations = abs(A[i] - A[i - 1]) + abs(A[i + 1] - A[i]);\n        \n        change = max(change, old_operations - new_operations);\n    }\n    \n    long long answer = 0;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        answer += abs(A[i] - A[i - 1]);\n    }\n    \n    answer -= change;\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Explanations/Divide and Summarize Explanation.txt",
    "content": "Let us precompute all possible sums we can get and store it in a set.\nThis allows us to answer each query in O(log N) time.\n\nWhile we are precomputing the sums, we keep dividing the array into 2\nand the height of this tree is at most Log N.\n\nSo, the total time taken to precompute is O(N Log N)\n\nThe number of sums stored is N + N/2 + N/4 + N/8 + N/16 + ... = O(N log N)\n-----\n\nvoid check(map <long long, int> &S, int left, int right)\n{\n    S[get_sum(left, right)] = true;\n\n    if(A[left] == A[right])\n    {\n        return;\n    }\n\n    int middle_element = (A[left] + A[right])/2;\n\n    //Points to last occurrence of middle_element\n    int mid = upper_bound(A.begin() + left, A.begin() + right, middle_element) - A.begin() - 1;\n\n    check(S, left, mid);\n    check(S, mid + 1, right);\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Explanations/Find a Spruce Explanation.txt",
    "content": "Let L[i][j] denote the maximum size of the left spruce\nstarting at (i, j) and only going left.\n\nL[i][j] has a left spruce of size x, if\n\nL[i][j] >= x and L[i][j - 1] >= x - 1\n\nSo,\n\nL[i][j] = min(Height[i][j], L[i][j - 1] + 1)\n\nLet R[i][j] denote the maximum size of the right spruce\nstarting at (i, j)\n\nR[i][j] = min(Height[i][j], R[i][j + 1] + 1)\n\n The length of the spruce at (i, j) is min(L[i][j], R[i][j])\n\n -----\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    vector <string> grid(rows);\n    for(int i = 0; i < rows; i++)\n    {\n        cin >> grid[i];\n    }\n\n    vector <vector <int> > height(rows, vector <int> (columns, 0));\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(grid[i][j] == '*')\n            {\n                height[i][j] = (i == 0 ? 1 : height[i - 1][j] + 1);\n            }\n\n        }\n    }\n\n    vector <vector <int> > left_spruce(rows, vector <int> (columns, 0));\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            left_spruce[i][j] = height[i][j];\n\n            if(j == 0)\n            {\n                left_spruce[i][j] = min(left_spruce[i][j], 1);\n            }\n\n            if(j > 0)\n            {\n                left_spruce[i][j] = min(left_spruce[i][j], left_spruce[i][j - 1] + 1);\n            }\n        }\n    }\n\n    vector <vector <int> > right_spruce(rows, vector <int> (columns, 0));\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = columns - 1; j >= 0; j--)\n        {\n            right_spruce[i][j] = height[i][j];\n\n            if(j == columns - 1)\n            {\n                right_spruce[i][j] = min(right_spruce[i][j], 1);\n            }\n\n            if(j < columns - 1)\n            {\n                right_spruce[i][j] = min(right_spruce[i][j], right_spruce[i][j + 1] + 1);\n            }\n        }\n    }\n\n    long long total_spruce = 0;\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            int spruce_here = min(right_spruce[i][j], left_spruce[i][j]);\n\n            total_spruce += spruce_here;\n        }\n    }\n\n    cout << total_spruce << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Explanations/Mathematical Expression Explanation.txt",
    "content": "Let us go case by case and eliminiate the simple cases.\n\nIf there is only 1 sign, then we have to use that sign everywhere.\n\nSuppose there is (+-), we will use addition everywhere.\nSuppose there is (-*), we will use multiplication everywhere\nexcept near a 0.\n\n-----\n\nThe case (+*) is the same as (+*-).\nWe can eliminate the minus sign and just solve it with the other two.\n\nNow, multiplication is normally better than addition\n\nEven, 2 x 2 = 2 + 2, and for all other integers > 2, multiplication is clearly better.\n\nThe problem is when there are ones.\n\nWe might be better off adding some ones and then using a multiplication.\n\n-----\n\nNow, how do we handle the case where there is both + and *\n\nWe will solve each segment of non-zero digits separately.\n\n-----\n\nLet f(i) be the maximum for the first i digits.\nLet us iterate over the position of the last plus sign.\n\nf(i) = max{f(j) + A[j... i]}, for all j\n\nNow, this is a O(n^2) DP, but we can make some observations that ensure we do\nat most 20 linear scans.\n\n-----\n\nWhen we begin processing a segment, we will put + signs on all the prefix and suffix ones.\nThis is the best because multiplication here would just make the answer 1.\n\nNow, we have a segment A[L, R], where A[L] > 1 and A[R] > 1\n\n1. We will find the best value of f(i) only at the non-1 elements.\n2. If there are more than 20 non-one elements, we will do multiplication everywhere.\n\n-----\n\nSuppose there are 20 elements > 1. 2^{20} is the smallest such product.\nSuppose we replace any multiplication sign on this segment with an addition sign.\n\nThe product is reducing at least by 2^{19}\nand the maximum value we can get by addition is 10^5, which is smaller.\n\nSo, we are better off doing multiplication everywhere.\n\n-----\n\nIf A[i] = 1, then f(i) = f(i - 1) + 1\n\nIf the last element of the segment is 1, it is better to add 1 then multiply.\n\nSo, we only need to loop backwards when A[i] > 1, which only happens 20 times.\n\n-----\n\nvoid solve(int left, int right, vector <char> &S, vector <int> &A)\n{\n    while(left <= right && A[left] == 1)\n    {\n        S[left] = '+';\n        left++;\n    }\n\n    if(right <= left)\n    {\n        return;\n    }\n\n    while(right >= left && A[right] == 1)\n    {\n        S[right - 1] = '+';\n        right--;\n    }\n\n    const int MAX_NON_1 = 20;\n    int non_1 = 0;\n    for(int i = left; i <= right; i++)\n    {\n        non_1 += (A[i] != 1);\n    }\n\n    if(non_1 >= MAX_NON_1)\n    {\n        for(int i = left; i < right; i++)\n        {\n            S[i] = '*';\n        }\n\n        return;\n    }\n\n    for(int i = left; i <= right; i++)\n    {\n        last_plus[i] = 0;\n        max_answer[i] = 0;\n    }\n\n    for(int i = left; i <= right; i++)\n    {\n        if(A[i] == 1)\n        {\n            max_answer[i] = max_answer[i - 1] + 1;\n            last_plus[i] = i - 1;\n            continue;\n        }\n\n        long long product_here = 1;\n        for(int j = i; j >= left; j--)\n        {\n            product_here *= A[j];\n\n            if(product_here + max_answer[j - 1] > max_answer[i])\n            {\n                max_answer[i] = max_answer[j - 1] + product_here;\n                last_plus[i] = j - 1;\n\n                //cout << \"Max \" << j << \" = \" << max_answer[j] << \" and last plus = \" << last_plus[i] << \"\\n\";\n            }\n        }\n    }\n\n    for(int i = right; i >= left; i = last_plus[i])\n    {\n        for(int j = i - 1; j > last_plus[i]; j--)\n        {\n            S[j] = '*';\n        }\n\n        S[last_plus[i]] = '+';\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Explanations/Random Events Explanation.txt",
    "content": "Let us look at the rightmost unsorted element.\n\nIf this element is not in it's correct place, the array will not be sorted.\n\nSo, we will only look at segments which impact this element.\n\nThis element will be in it's correct place if at least 1 or more of these segments work.\n\nIn order to make it easier, we will calculate the probability of failure and subtract 1 from it.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, no_of_operations;\n    cin >> no_of_elements >> no_of_operations;\n\n    int maximum_unsorted = 0;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        if(A[i] != i)\n        {\n            maximum_unsorted = max(maximum_unsorted, i);\n        }\n    }\n\n    double failure_probability = (maximum_unsorted == 0 ? 0 : 1);\n    for(int i = 1; i <= no_of_operations; i++)\n    {\n        int right;\n        double p;\n        cin >> right >> p;\n\n        if(right >= maximum_unsorted)\n        {\n            failure_probability *= (1 - p);\n        }\n    }\n\n    double success_probability = 1 - failure_probability;\n    cout << fixed << setprecision(6) << success_probability << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Explanations/String Generation Explanation.txt",
    "content": "We will print a string of K a's followed by (cba) concatenated till the end.\n\ncbacba... can never form a palindrome of length > 1\n\n-----\n\nvoid solve()\n{\n    int length, palindrome_length;\n    cin >> length >> palindrome_length;\n\n    vector <char> S(length + 3);\n    for(int i = 0; i < palindrome_length; i++)\n    {\n        S[i] = 'a';\n    }\n\n    for(int i = palindrome_length; i < length; i += 3)\n    {\n        S[i] = 'c';\n        S[i + 1] = 'b';\n        S[i + 2] = 'a';\n    }\n\n    for(int i = 0; i < length; i++)\n    {\n        cout << S[i];\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Explanations/Water Level Explanation.txt",
    "content": "We need to deal with 3 different cases.\n\n1. Refill < usage\n2. Refill = usage\n3. Refill > usage\n\n------\n\nWhen refill < usage, we will refill it everyday to ensure it stays in the limit.\nWe only need to see if we can refill it on the very first day as a special case.\n\n-----\n\nWhen refill = usage, just check if refilling or using it makes it go out of bounds.\n\n-----\n\nWhen refill > usage, we do not want to overflow.\nSo, we will only refill it greedily just when another usage would make the\nwater level drop below L.\n\nIn fact, we will look at the water level (mod u).\nAs long as we are using without refilling, the remainder is invariant.\nWhen we refill it, it becomes (x + R) (mod u).\nWe will check if we every visit a remainder that is already visited.\nIf so, we have reached a cycle and will be within [L, R] indefinitely.\n\n\n-----\n\nint main()\n{\n    long long left, right, initial, no_of_days, usage, refill;\n    cin >> initial >> left >> right >> no_of_days >> usage >> refill;\n\n    int possible = true;\n    if(refill < usage)\n    {\n        long long reduction = usage - refill;\n\n        if(initial + refill > right)\n        {\n            initial -= usage;\n            no_of_days--;\n        }\n\n        if(left > initial)\n        {\n            possible = false;\n        }\n\n        long long days_used = (initial - left)/reduction;\n\n        if(days_used < no_of_days)\n        {\n            possible = false;\n        }\n    }\n    else if(refill == usage)\n    {\n        if(initial + refill > right && initial - refill < left)\n        {\n            possible = false;\n        }\n    }\n    else\n    {\n        vector <int> reached(usage + 1, false);\n        reached[initial%usage] = true;\n\n        possible = in_between(initial, left, right);\n        while(no_of_days > 0 && possible)\n        {\n            long long days_used = (initial - left)/usage;\n\n            no_of_days -= days_used;\n            initial -= (days_used*usage);\n\n            if(no_of_days <= 0)\n            {   //cout << \"Not enought days\\n\";\n                possible = true;\n                break;\n            }\n\n            initial += refill; //cout << \"After refill = \" << initial << \"\\n\";\n\n            if(initial > right)\n            {   //cout << \"Overflow\\n\";\n                possible = false;\n                break;\n            }\n\n            if(reached[initial%usage])\n            {   //cout << \"Already reached\\n\";\n                possible = true;\n                break;\n            }\n\n\n            reached[initial%usage] = true;\n        }\n    }\n\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Programs/Divide and Summarize.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5;\nvector <long long> A(MAX_N, 0), sum(MAX_N, 0);\n\nlong long get_sum(int left, int right)\n{\n    return (sum[right] - sum[left - 1]);\n}\n\nvoid check(map <long long, int> &S, int left, int right)\n{\n    S[get_sum(left, right)] = true;\n    \n    if(A[left] == A[right])\n    {\n        return;\n    }\n    \n    int middle_element = (A[left] + A[right])/2;\n    \n    //Points to last occurrence of middle_element\n    int mid = upper_bound(A.begin() + left, A.begin() + right, middle_element) - A.begin() - 1;\n    \n    check(S, left, mid);\n    check(S, mid + 1, right);\n}\n\nvoid solve()\n{\n    int no_of_elements, no_of_queries;\n    cin >> no_of_elements >> no_of_queries;\n    \n    A[0] = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(A.begin() + 1, A.begin() + no_of_elements + 1);\n    \n    sum[0] = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum[i] = sum[i - 1] + A[i];\n    }\n    \n    map <long long, int> possible_sums;\n    check(possible_sums, 1, no_of_elements);\n    \n    while(no_of_queries--)\n    {\n        long long target_sum;\n        cin >> target_sum;\n        \n        cout << (possible_sums.count(target_sum) > 0 ? \"Yes\" : \"No\") << \"\\n\";\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Programs/Find the Spruce.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    vector <string> grid(rows);\n    for(int i = 0; i < rows; i++)\n    {\n        cin >> grid[i];\n    }\n    \n    vector <vector <int> > height(rows, vector <int> (columns, 0));\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(grid[i][j] == '*')\n            {\n                height[i][j] = (i == 0 ? 1 : height[i - 1][j] + 1);\n            }\n            \n        }\n    }\n    \n    vector <vector <int> > left_spruce(rows, vector <int> (columns, 0));\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            left_spruce[i][j] = height[i][j];\n            \n            if(j == 0)\n            {\n                left_spruce[i][j] = min(left_spruce[i][j], 1);\n            }\n            \n            if(j > 0)\n            {\n                left_spruce[i][j] = min(left_spruce[i][j], left_spruce[i][j - 1] + 1);\n            }\n        }\n    }\n    \n    vector <vector <int> > right_spruce(rows, vector <int> (columns, 0));\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = columns - 1; j >= 0; j--)\n        {\n            right_spruce[i][j] = height[i][j];\n            \n            if(j == columns - 1)\n            {\n                right_spruce[i][j] = min(right_spruce[i][j], 1);\n            }\n            \n            if(j < columns - 1)\n            {\n                right_spruce[i][j] = min(right_spruce[i][j], right_spruce[i][j + 1] + 1);\n            }\n        }\n    }\n    \n    long long total_spruce = 0;\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            int spruce_here = min(right_spruce[i][j], left_spruce[i][j]);\n            \n            total_spruce += spruce_here;\n        }\n    }\n    \n    cout << total_spruce << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Programs/Mathematical Expression.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5;\nint last_plus[MAX_N], max_answer[MAX_N];\n\nvoid solve(int left, int right, vector <char> &S, vector <int> &A)\n{\n    while(left <= right && A[left] == 1)\n    {\n        S[left] = '+';\n        left++;\n    }\n    \n    if(right <= left)\n    {\n        return;\n    }\n    \n    while(right >= left && A[right] == 1)\n    {\n        S[right - 1] = '+';\n        right--;\n    }\n    \n    const int MAX_NON_1 = 20;\n    int non_1 = 0;\n    for(int i = left; i <= right; i++)\n    {\n        non_1 += (A[i] != 1);\n    }\n    \n    if(non_1 >= MAX_NON_1)\n    {\n        for(int i = left; i < right; i++)\n        {\n            S[i] = '*';\n        }\n        \n        return;\n    }\n    \n    for(int i = left; i <= right; i++)\n    {\n        last_plus[i] = 0;\n        max_answer[i] = 0;\n    }\n    \n    for(int i = left; i <= right; i++)\n    {\n        if(A[i] == 1)\n        {\n            max_answer[i] = max_answer[i - 1] + 1;\n            last_plus[i] = i - 1;\n            continue;\n        }\n        \n        long long product_here = 1;\n        for(int j = i; j >= left; j--)\n        {\n            product_here *= A[j];\n            \n            if(product_here + max_answer[j - 1] > max_answer[i])\n            {\n                max_answer[i] = max_answer[j - 1] + product_here;\n                last_plus[i] = j - 1;\n                \n                //cout << \"Max \" << j << \" = \" << max_answer[j] << \" and last plus = \" << last_plus[i] << \"\\n\";\n            }\n        }\n    }\n    \n    for(int i = right; i >= left; i = last_plus[i])\n    {\n        for(int j = i - 1; j > last_plus[i]; j--)\n        {\n            S[j] = '*';\n        }\n        \n        S[last_plus[i]] = '+';\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    string S;\n    cin >> S;\n    \n    sort(S.begin(), S.end());\n    \n    if(S.size() == 1)\n    {\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            cout << A[i] << (i < no_of_elements ? S : \"\\n\");\n        }\n        \n        return 0;\n    }\n    \n    if(S == \"+-\")\n    {\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            cout << A[i] << (i < no_of_elements ? \"+\" : \"\\n\");\n        }\n        \n        return 0;\n    }\n    \n    if(S == \"*-\")\n    {\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            cout << A[i];\n            if(i < no_of_elements)\n            {\n                cout << (A[i + 1] == 0 ? \"-\" : \"*\");\n            }\n        }\n        \n        cout << \"\\n\";\n        \n        return 0;\n    }\n    \n    vector <char> signs(no_of_elements + 5, '?');\n    \n    //Invariant that A[i] = 0 always\n    for(int i = 0, j = 1; i < no_of_elements; i = j)\n    {\n        for(j = i + 1; j <= no_of_elements && A[j] != 0; )\n        {\n            j++;\n        }\n        \n        \n        //cout << \"Solve [\" << i + 1 << \",\" << j - 1 << \"]\\n\";\n        solve(i + 1, j - 1, signs, A);\n        signs[i - 1] = signs[i] = signs[j - 1] = signs[j] = '+';\n        \n        /*for(int i = 1; i <= no_of_elements; i++)\n        {\n            cout << A[i] << (i < no_of_elements ? signs[i] : '\\n');\n        }*/\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << (i < no_of_elements ? signs[i] : '\\n');\n    }\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Programs/Random Events.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <iomanip>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, no_of_operations;\n    cin >> no_of_elements >> no_of_operations;\n    \n    int maximum_unsorted = 0;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        if(A[i] != i)\n        {\n            maximum_unsorted = max(maximum_unsorted, i);\n        }\n    }\n    \n    double failure_probability = (maximum_unsorted == 0 ? 0 : 1);\n    for(int i = 1; i <= no_of_operations; i++)\n    {\n        int right;\n        double p;\n        cin >> right >> p;\n        \n        if(right >= maximum_unsorted)\n        {\n            failure_probability *= (1 - p);\n        }\n    }\n    \n    double success_probability = 1 - failure_probability;\n    cout << fixed << setprecision(6) << success_probability << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Programs/String Generation.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, palindrome_length;\n    cin >> length >> palindrome_length;\n    \n    vector <char> S(length + 3);\n    for(int i = 0; i < palindrome_length; i++)\n    {\n        S[i] = 'a';\n    }\n    \n    for(int i = palindrome_length; i < length; i += 3)\n    {\n        S[i] = 'c';\n        S[i + 1] = 'b';\n        S[i + 2] = 'a';\n    }\n    \n    for(int i = 0; i < length; i++)\n    {\n        cout << S[i];\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/689 Div 2/Programs/Water Level.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint in_between(long long x, long long left, long long right)\n{\n    return (left <= x && x <= right);\n}\n\nint main()\n{\n    long long left, right, initial, no_of_days, usage, refill;\n    cin >> initial >> left >> right >> no_of_days >> usage >> refill;\n    \n    int possible = true;\n    if(refill < usage)\n    {\n        long long reduction = usage - refill;\n        \n        if(initial + refill > right)\n        {\n            initial -= usage;\n            no_of_days--;\n        }\n        \n        if(left > initial)\n        {\n            possible = false;\n        }\n        \n        long long days_used = (initial - left)/reduction;\n        \n        if(days_used < no_of_days)\n        {\n            possible = false;\n        }\n    }\n    else if(refill == usage)\n    {\n        if(initial + refill > right && initial - refill < left)\n        {\n            possible = false;\n        }\n    }\n    else\n    {\n        vector <int> reached(usage + 1, false);\n        reached[initial%usage] = true;\n        \n        possible = in_between(initial, left, right);\n        while(no_of_days > 0 && possible)\n        {\n            //cout << \"Water = \" << initial << \" \";\n            long long days_used = (initial - left)/usage;\n            \n            no_of_days -= days_used; //cout << \"No of days = \" << days_used << \"\\n\";\n            initial -= (days_used*usage); //cout << \"After usage = \" << initial << \"\\n\";\n            \n            if(no_of_days <= 0)\n            {   //cout << \"Not enought days\\n\";\n                possible = true;\n                break;\n            }\n            \n            initial += refill; //cout << \"After refill = \" << initial << \"\\n\";\n            \n            if(initial > right)\n            {   //cout << \"Overflow\\n\";\n                possible = false;\n                break;\n            }\n            \n            if(reached[initial%usage])\n            {   //cout << \"Already reached\\n\";\n                possible = true;\n                break;\n            }\n            \n            \n            reached[initial%usage] = true;\n        }\n    }\n    \n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/691 Div 2/Explanation/Move and Turn Explanation.txt",
    "content": "We will be making independent horizontal steps and vertical steps of n/2.\n\nLet us see the number of possibilities of horizontal steps.\n\nK right 0 left = K\n(K - 1) right 1 left = K - 2\n(K - 2) right 2 left = K - 4\n.\n.\n0 right K left = -K\n\nEach of these (K + 1) steps lead to a different result.\n\n-----\n\nIf n is odd, then we will make one more horizontal step than vertical step\nor other way around.\n\n-----\n\nint main()\n{\n    int length;\n    cin >> length;\n\n    int horizontal_steps = length/2, vertical_steps = length/2;\n    long long horizontal_results = (horizontal_steps + 1);\n    long long vertical_results = (vertical_steps + 1);\n\n    long long answer;\n\n    if(length%2 == 1)\n    {\n        answer = (horizontal_results + 1)*(vertical_results) + (horizontal_results)*(vertical_results + 1);\n    }\n    else\n    {\n        answer = horizontal_results*vertical_results;\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/691 Div 2/Explanation/Red Blue Shuffle Explanation.txt",
    "content": "The red card is greater than the blue card if they have some prefix\nwhere R[i] = B[i] and then R[i] > B[i]\n\nLet us iterate over the possibility of the first unequal card.\n\nIf there are more cards where R[i] > B[i], red is the winner\nIf B[i] > R[i], blue is the winner.\n\n-----\n\nvoid solve()\n{\n    int length;\n    string R, B;\n    cin >> length >> R >> B;\n\n    int red_cards = 0, blue_cards = 0;\n    for(int i = 0; i < length; i++)\n    {\n        if(R[i] > B[i])\n        {\n            red_cards++;\n        }\n        else if(B[i] > R[i])\n        {\n            blue_cards++;\n        }\n    }\n\n    if(red_cards == blue_cards)\n    {\n        cout << \"EQUAL\\n\";\n    }\n    else\n    {\n        cout << (red_cards > blue_cards ? \"RED\\n\" : \"BLUE\\n\");\n    }\n}\n"
  },
  {
    "path": "2020/Div 2/691 Div 2/Explanation/Row GCD Explanation.txt",
    "content": "- $g = \\gcd(a_1 + b_i, a_2 + b_i, a_3 + b_i, \\dots , a_n + b_i) = \\gcd(a_1 + b_i, a_2 - a_1, a_3 - a_2, \\dots , a_n - a_{n - 1})$\n- We will precalculate the GCD of the differences before hand so we can find the GCD in one step.\n\n-----\n\nint main()\n{\n    int no_of_elements_a, no_of_elements_b;\n    cin >> no_of_elements_a >> no_of_elements_b;\n\n    vector <long long> A(no_of_elements_a + 1), B(no_of_elements_b + 1);\n    for(int i = 1; i <= no_of_elements_a; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = 1; i <= no_of_elements_b; i++)\n    {\n        cin >> B[i];\n    }\n\n    sort(all(A));\n\n    vector <long long> difference(no_of_elements_a);\n    for(int i = 1; i < no_of_elements_a; i++)\n    {\n        difference[i] = A[i + 1] - A[i];\n    }\n\n    long long array_gcd = 0;\n    for(int i = 2; i < no_of_elements_a; i++)\n    {\n        array_gcd = gcd(array_gcd, difference[i]);\n    }\n\n    vector <long long> answer(no_of_elements_b + 1);\n    for(int i = 1; i <= no_of_elements_b; i++)\n    {\n        answer[i] = gcd(A[1] + B[i], array_gcd);\n    }\n\n    for(int i = 1; i <= no_of_elements_b; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/691 Div 2/Programs/Move and Turn.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    cin >> length;\n    \n    int horizontal_steps = length/2, vertical_steps = length/2;\n    long long horizontal_results = (horizontal_steps + 1);\n    long long vertical_results = (vertical_steps + 1);\n    \n    long long answer;\n    \n    if(length%2 == 1)\n    {\n        answer = (horizontal_results + 1)*(vertical_results) + (horizontal_results)*(vertical_results + 1);\n    }\n    else\n    {\n        answer = horizontal_results*vertical_results;\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/691 Div 2/Programs/Red Blue Shuffle.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string R, B;\n    cin >> length >> R >> B;\n    \n    int red_cards = 0, blue_cards = 0;\n    for(int i = 0; i < length; i++)\n    {\n        if(R[i] > B[i])\n        {\n            red_cards++;\n        }\n        else if(B[i] > R[i])\n        {\n            blue_cards++;\n        }\n    }\n    \n    if(red_cards == blue_cards)\n    {\n        cout << \"EQUAL\\n\";\n    }\n    else\n    {\n        cout << (red_cards > blue_cards ? \"RED\\n\" : \"BLUE\\n\");\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/691 Div 2/Programs/Row GCD.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nusing namespace std;\n\n#define all(v) (v).begin(), (v).end()\n\nlong long gcd(long long a, long long b)\n{\n    if(min(a, b) == 0)\n        return max(a, b);\n    \n    return gcd(min(a, b), max(a, b)%min(a, b));\n}\n\nint main()\n{\n    int no_of_elements_a, no_of_elements_b;\n    cin >> no_of_elements_a >> no_of_elements_b;\n    \n    vector <long long> A(no_of_elements_a + 1), B(no_of_elements_b + 1);\n    for(int i = 1; i <= no_of_elements_a; i++)\n    {\n        cin >> A[i];\n    }\n    \n    for(int i = 1; i <= no_of_elements_b; i++)\n    {\n        cin >> B[i];\n    }\n    \n    sort(all(A));\n    \n    vector <long long> difference(no_of_elements_a);\n    for(int i = 1; i < no_of_elements_a; i++)\n    {\n        difference[i] = A[i + 1] - A[i];\n    }\n    \n    long long array_gcd = 0;\n    for(int i = 2; i < no_of_elements_a; i++)\n    {\n        array_gcd = gcd(array_gcd, difference[i]);\n    }\n    \n    vector <long long> answer(no_of_elements_b + 1);\n    for(int i = 1; i <= no_of_elements_b; i++)\n    {\n        answer[i] = gcd(A[1] + B[i], array_gcd);\n    }\n    \n    for(int i = 1; i <= no_of_elements_b; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/692 Div 2/Explanations/Fair Numbers Explanation.txt",
    "content": "In Any interval [L, L + X], there will be at least one multiple of x. \n\nThe LCM of (1, 2, ... , 9) is 2520. \n\nIn any interval of 2520 integers, there is at least one number that is divisible \nby all 9 digits. \n\nSo the gap in between two fair integers cannot exceed 2520. \n\nThis allows us to compute it using brute force. \n\n-----\n\nint fair(long long n)\n{\n    long long value = n;\n    \n    while(n)\n    {\n        int digit = n%10;\n        \n        if(digit != 0 && value%digit != 0)\n        {//cout << value << \" not divisible \"\n            return false;\n        }\n        \n        n /= 10;\n    }\n    \n    return true;\n}\n \nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    long long answer;\n    \n    for(answer = n; !fair(answer); answer++);\n    \n    cout << answer << \"\\n\";\n}\n \n"
  },
  {
    "path": "2020/Div 2/692 Div 2/Explanations/In Game Chat Explanation.txt",
    "content": "Count the suffix of ) and compare with the rest of the string \n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    \n    cin >> length >> S;\n    \n    int suffix = 0;\n    for(int i = length - 1; i >= 0; i--)\n    {\n        if(S[i] != ')')\n        {\n            break;\n        }\n        \n        suffix++;\n    }\n    \n    //cout << \"String Read : \" << S << \" Suffix = \" << suffix << \"\\n\";\n    \n    int prefix = length - suffix;\n    cout << (prefix < suffix ? \"Yes\" : \"No\") << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/692 Div 2/Programs/Fair Numbers.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint fair(long long n)\n{\n    long long value = n;\n    \n    while(n)\n    {\n        int digit = n%10;\n        \n        if(digit != 0 && value%digit != 0)\n        {//cout << value << \" not divisible \"\n            return false;\n        }\n        \n        n /= 10;\n    }\n    \n    return true;\n}\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    long long answer;\n    \n    for(answer = n; !fair(answer); answer++);\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/692 Div 2/Programs/In Game Chat.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    \n    cin >> length >> S;\n    \n    int suffix = 0;\n    for(int i = length - 1; i >= 0; i--)\n    {\n        if(S[i] != ')')\n        {\n            break;\n        }\n        \n        suffix++;\n    }\n    \n    //cout << \"String Read : \" << S << \" Suffix = \" << suffix << \"\\n\";\n    \n    int prefix = length - suffix;\n    cout << (prefix < suffix ? \"Yes\" : \"No\") << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Explanations/Grade Allocation Explanation.txt",
    "content": "We will make score[1] = total_sum or highest_score, whichever is lower\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_students, highest_score;\n    cin >> no_of_students >> highest_score;\n\n    vector <int> score(no_of_students + 1);\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cin >> score[i];\n    }\n\n    int remaining_sum = 0;\n    for(int i = 2; i <= no_of_students; i++)\n    {\n        remaining_sum += score[i];\n    }\n\n    score[1] = min(highest_score, score[1] + remaining_sum);\n\n    cout << score[1] << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Explanations/Nash Matrix Explanation.txt",
    "content": "There are two types of components in this graph\n\nThose that are in a cycle and those that have a 'sink'.\n\nFor all those vertices that end up in a sink, we will start from the sink and do a DFS to cover all cells reachable from it\n\nFor the cycle, we will do this\n\nIf X[i][j] = -1 and Y[i][j] = -1, we will look at any of it's neighbours which are -1\n\nWhichever neighbour is -1, we will create a loop between them like LR or RL or UD or DU\n\nThis will lead to a cycle of length 2. Any -1 cell cluster that is connected to this 2-cycle will eventually fall into a cycle too\n\n-----\n\nA finer point needs to be said here\n\nAbout the components that end up in a sink, we must always start from the sink and then go 'outwards'.\n\nWe cannot start from any random point of the component and then go 'inwards'\n\nSuppose we have\n\n(2, 2) (2, 2)\n(2, 2) (2, 2)\n\nMy algorithm was labelling it as\n\nRL\nUX\n\nWhich is wrong because RL ends up in a loop\n\nIt should be\n\nRD\nLX\n\nThe main reason for this is that I was starting the DFS from any point in the component. I should only be starting the DFS from the 'sink' or the starting point of the component\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 1e3 + 5, NO_OF_DIRECTIONS = 4;\nchar grid[MAX_N][MAX_N];\nint X[MAX_N][MAX_N], Y[MAX_N][MAX_N];\nchar direction[NO_OF_DIRECTIONS] = {'U', 'R', 'L', 'D'};\nchar reverse_direction[NO_OF_DIRECTIONS] = {'D', 'L', 'R', 'U'};\nint next_x[NO_OF_DIRECTIONS] = {-1, 0, 0, 1};\nint next_y[NO_OF_DIRECTIONS] = {0, 1, -1, 0};\n\nvoid find_looping_partner(int i, int j)\n{\n    for(int d = 0; d < NO_OF_DIRECTIONS; d++)\n    {\n        int next_i = i + next_x[d];\n        int next_j = j + next_y[d];\n\n        if(X[next_i][next_j] == -1 && Y[next_i][next_j] == -1)\n        {\n            grid[i][j] = direction[d];\n            grid[next_i][next_j] = reverse_direction[d];\n\n            return;\n        }\n    }\n}\n\nvoid dfs(int i, int j, int final_x, int final_y, char D)\n{\n    grid[i][j] = D;\n\n    for(int d = 0; d < NO_OF_DIRECTIONS; d++)\n    {\n        int next_i = i + next_x[d];\n        int next_j = j + next_y[d];\n\n        if(grid[next_i][next_j] != 0)\n        {\n            continue;\n        }\n\n        if(X[next_i][next_j] == final_x && Y[next_i][next_j] == final_y)\n        {\n            dfs(next_i, next_j, final_x, final_y, reverse_direction[d]);\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n;\n    cin >> n;\n\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            cin >> X[i][j] >> Y[i][j];\n        }\n    }\n\n    memset(grid, 0, sizeof(grid));\n\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if(grid[i][j] != 0)\n            {\n                continue;\n            }\n\n            if(X[i][j] == i && Y[i][j] == j)\n            {\n                dfs(i, j, X[i][j], Y[i][j], 'X');\n            }\n\n            if(X[i][j] == -1 && Y[i][j] == -1)\n            {\n                find_looping_partner(i, j);\n            }\n        }\n    }\n\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if(grid[i][j] == 0)\n            {\n                cout << \"INVALID\\n\";\n\n                return 0;\n            }\n        }\n    }\n\n    cout << \"VALID\\n\";\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            cout << grid[i][j];\n        }\n\n        cout << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Explanations/Primitive Primes Explanation.txt",
    "content": "Let A[i] be the first coefficient of A that is not a multiple of p\n\nLet B[j] be the first coefficient of B that is not a multiple of p\n\nThen, our claim is that the coefficient of degree (i + j) of A.B \nis not a multiple of p\n\n-----\n\nHow do we calculate the coefficient of degree k of polynomial A.B\n\nCoefficient [k] = Sum(A[i] B[i - k])\n\n-----\n\nNow, let us look at coefficient of (i + j)\n\nA[0]B[i + j] + A[1]B[i + j - 1] + .... + A[i - 1]B[i + j - (i - 1)] +\nA[i]B[j] + \nA[i + 1]B[j - 1] + A[i + 2]B[j - 2] + ... + A[i + j]B[0]\n\nSince A[i] is the first coefficient of A that is not a multiple of p, \nAll of A[0, ... , i - 1] is a multiple of p \n\nSimilarly all of B[0, .... , j - 1] is a multiple of p\n\nSo, this means that all the terms in the first and third line are a multiple of p \nbecause at least one of the terms of each product is a multiple of p\n\nThis means coefficient (i + j) = A[i]B[j] (mod p) \n\nThis cannot be = 0 (mod p)\n\nHence, (i + j) is the answer\n\n------\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_terms_A, no_of_terms_B, p;\n    cin >> no_of_terms_A >> no_of_terms_B >> p;\n    \n    vector <int> A(no_of_terms_A + 1);\n    for(int i = 0; i < no_of_terms_A; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_terms_B + 1);\n    for(int i = 0; i < no_of_terms_B; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int first_A = 0;\n    while(A[first_A]%p == 0)\n    {\n        first_A++;\n    }\n    \n    int first_B = 0;\n    while(B[first_B]%p == 0)\n    {\n        first_B++;\n    }\n    \n    int answer = first_A + first_B;\n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Explanations/String Modification Explanation.txt",
    "content": "Let us simulate the process for each k\n\nS[k] goes to S[1]\nS[k + 1] goes to S[2]\nand so on\n\nThe ending of the string is either S[1], S[2], ... , S[k - 1]\nor S[k - 1], S[k - 2], .... , S[1]\n\ndepending on whether k is even or odd respectively\n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    string smallest = S, smallest_here = S;\n    int best_k = 1;\n\n    for(int k = 2; k <= length; k++)\n    {\n        for(int i = 0, j = k - 1 + i; j < length; i++, j++)\n        {\n            smallest_here[i] = S[j]; //cout << smallest_here[i];\n        }\n        //cout << \"\\n\";\n        for(int j = 0, i = length - k + 1; i < length; i++, j++)\n        {\n            smallest_here[i] = S[j];\n        }\n\n        if( (length - k + 1)%2 == 1)\n        {\n            reverse(smallest_here.begin() + length - k + 1, smallest_here.end());\n        }\n\n        //cout << \"k = \" << k << \" S = \" << smallest_here << \"\\n\";\n\n        if(smallest_here < smallest)\n        {\n            smallest = smallest_here;\n            best_k = k;\n        }\n    }\n\n    cout << smallest << \"\\n\" << best_k << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Explanations/Team Building Explanation.txt",
    "content": "Let us suppose the option to play in the audience does not exist.\nThen, we can do a straightforward DP, f(i, m)\nLet f(i, m) represent the highest strength we can have for the first i people with mask = m\n\nIf m = 1001001, it means that we have taken the first, fourth and seventh player\n\nThe transition is, f(i, m) = max(f(i - 1, m xor 2^p) + A[i][p], f(i - 1, m))\n\n-----\n\nNow, since we have the additional requirement of audience\nIf two people are not playing, it is always better to choose the higher audience person for the audience position\n\nLet us sort all the players in descending order of their audience strength\n\n-----\n\nNow, if we are at player i and have taken mask m = 10001001\nIt means we have taken 3 players in the team\nAnd the remaining (i - 1) - 3 players are in the audience\n\nNow, we have an additional transition apart from the normal transition.\nWe have to check if the i-th person can be in the audience\n\nf(i, m) = A[i] + f(i - 1, m)\n\n-----\n\nf(0, 0) = 0\n\nAnd another thing we have to be careful about is to not visit any unvisited state.\nBefore transitioning, we have to ensuring f(i - 1, m) is not -1\nOtherwise, it is not possible\n\n-----\n\nf(1, 100011011) is not attainable because we have not yet seen 5 people\nSo, before transitioning to f(i - 1, m) we have to check if it is not -1 and is attainable\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstring>\n\n#define all(v) (v).begin() + 1, (v).end()\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MAX_M = (1 << 7) + 1;\nlong long max_till[MAX_N][MAX_M], value[MAX_N][9];\n\nint no_of_bits(int n)\n{\n    int count = 0;\n\n    while(n)\n    {\n        count += (n%2);\n\n        n /= 2;\n    }\n\n    return count;\n}\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n & (1 << bit)) != 0);\n}\n\nint main()\n{\n    int no_of_elements, no_of_players, audience;\n    cin >> no_of_elements >> no_of_players >> audience;\n\n    vector < pair<int, int> > A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i].first;\n\n        A[i].second = i;\n    }\n\n    sort(all(A));\n    reverse(all(A));\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = 0; j < no_of_players; j++)\n        {\n            cin >> value[i][j];\n        }\n    }\n\n    memset(max_till, -1, sizeof(max_till));\n    max_till[0][0] = 0;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int index = A[i].second; //cout << \"(\" << A[i].first << \",\" << A[i].second << \")\\n\";\n\n        for(int m = 0; m < (1 << no_of_players); m++)\n        {\n            int players = no_of_bits(m);\n            int audience_so_far = (i - 1) - players;\n\n            if(players > i)\n            {\n                continue;\n            }\n\n            if(audience_so_far < audience)\n            {\n                if(max_till[i - 1][m] != -1)\n                {   //cout << \"Audience = \" << A[i].first << \"\\n\";\n                    max_till[i][m] = max_till[i - 1][m] + A[i].first;\n                }\n            }\n            else\n            {\n                if(max_till[i - 1][m] != -1)\n                {\n                    max_till[i][m] = max_till[i - 1][m];\n                }\n            }\n\n            for(int bit = 0; bit < no_of_players; bit++)\n            {\n                if(is_bit_set(m, bit) && max_till[i - 1][m^(1 << bit)] != -1)\n                {\n                    //cout << \"Choice is \" << max_till[i][m] << \" and \" << value[index][bit] << \" + \" << max_till[i - 1][m^(1 << bit)] << \"\\n\";\n\n                    max_till[i][m] = max(max_till[i][m],\n                                         value[index][bit] + max_till[i - 1][m^(1 << bit)]);\n                }\n            }\n\n            //cout << \"f(\" << i << \",\" << m << \") = \" << max_till[i][m] << \"\\n\";\n        }\n    }\n\n    int total = (1 << no_of_players) - 1;\n    cout << max_till[no_of_elements][total] << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Programs/Grade Allocation.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_students, highest_score;\n    cin >> no_of_students >> highest_score;\n    \n    vector <int> score(no_of_students + 1);\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cin >> score[i];\n    }\n    \n    int remaining_sum = 0;\n    for(int i = 2; i <= no_of_students; i++)\n    {\n        remaining_sum += score[i];\n    }\n    \n    score[1] = min(highest_score, score[1] + remaining_sum);\n    \n    cout << score[1] << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Programs/Nash Matrix.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 1e3 + 5, NO_OF_DIRECTIONS = 4;\nchar grid[MAX_N][MAX_N];\nint X[MAX_N][MAX_N], Y[MAX_N][MAX_N];\nchar direction[NO_OF_DIRECTIONS] = {'U', 'R', 'L', 'D'};\nchar reverse_direction[NO_OF_DIRECTIONS] = {'D', 'L', 'R', 'U'};\nint next_x[NO_OF_DIRECTIONS] = {-1, 0, 0, 1};\nint next_y[NO_OF_DIRECTIONS] = {0, 1, -1, 0};\n\nvoid find_looping_partner(int i, int j)\n{\n    for(int d = 0; d < NO_OF_DIRECTIONS; d++)\n    {\n        int next_i = i + next_x[d];\n        int next_j = j + next_y[d];\n        \n        if(X[next_i][next_j] == -1 && Y[next_i][next_j] == -1)\n        {\n            grid[i][j] = direction[d];\n            grid[next_i][next_j] = reverse_direction[d];\n            \n            return;\n        }\n    }\n}\n\nvoid dfs(int i, int j, int final_x, int final_y, char D)\n{\n    grid[i][j] = D;\n    \n    for(int d = 0; d < NO_OF_DIRECTIONS; d++)\n    {\n        int next_i = i + next_x[d];\n        int next_j = j + next_y[d];\n        \n        if(grid[next_i][next_j] != 0)\n        {\n            continue;\n        }\n       \n        if(X[next_i][next_j] == final_x && Y[next_i][next_j] == final_y)\n        {\n            dfs(next_i, next_j, final_x, final_y, reverse_direction[d]);\n        }\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int n;\n    cin >> n;\n    \n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            cin >> X[i][j] >> Y[i][j];\n        }\n    }\n    \n    memset(grid, 0, sizeof(grid));\n    \n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if(grid[i][j] != 0)\n            {\n                continue;\n            }\n            \n            if(X[i][j] == i && Y[i][j] == j)\n            {\n                dfs(i, j, X[i][j], Y[i][j], 'X');\n            }\n            \n            if(X[i][j] == -1 && Y[i][j] == -1)\n            {\n                find_looping_partner(i, j);\n            }\n        }\n    }\n    \n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if(grid[i][j] == 0)\n            {\n                cout << \"INVALID\\n\";\n                \n                return 0;\n            }\n        }\n    }\n    \n    cout << \"VALID\\n\";\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            cout << grid[i][j];\n        }\n        \n        cout << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Programs/Primitive Primes.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_terms_A, no_of_terms_B, p;\n    cin >> no_of_terms_A >> no_of_terms_B >> p;\n    \n    vector <int> A(no_of_terms_A + 1);\n    for(int i = 0; i < no_of_terms_A; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_terms_B + 1);\n    for(int i = 0; i < no_of_terms_B; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int first_A = 0;\n    while(A[first_A]%p == 0)\n    {\n        first_A++;\n    }\n    \n    int first_B = 0;\n    while(B[first_B]%p == 0)\n    {\n        first_B++;\n    }\n    \n    int answer = first_A + first_B;\n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Programs/String Modification.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    string smallest = S, smallest_here = S;\n    int best_k = 1;\n    \n    for(int k = 2; k <= length; k++)\n    {\n        for(int i = 0, j = k - 1 + i; j < length; i++, j++)\n        {\n            smallest_here[i] = S[j]; //cout << smallest_here[i];\n        }\n        //cout << \"\\n\";\n        for(int j = 0, i = length - k + 1; i < length; i++, j++)\n        {\n            smallest_here[i] = S[j];\n        }\n        \n        if( (length - k + 1)%2 == 1)\n        {\n            reverse(smallest_here.begin() + length - k + 1, smallest_here.end());\n        }\n        \n        //cout << \"k = \" << k << \" S = \" << smallest_here << \"\\n\";\n        \n        if(smallest_here < smallest)\n        {\n            smallest = smallest_here;\n            best_k = k;\n        }\n    }\n    \n    cout << smallest << \"\\n\" << best_k << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 2/CodeCraft 2020/Programs/Team Building.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <cstring>\n\n#define all(v) (v).begin() + 1, (v).end()\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MAX_M = (1 << 7) + 1;\nlong long max_till[MAX_N][MAX_M], value[MAX_N][9];\n\nint no_of_bits(int n)\n{\n    int count = 0;\n    \n    while(n)\n    {\n        count += (n%2);\n        \n        n /= 2;\n    }\n    \n    return count;\n}\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n & (1 << bit)) != 0);\n}\n\nint main()\n{\n    int no_of_elements, no_of_players, audience;\n    cin >> no_of_elements >> no_of_players >> audience;\n    \n    vector < pair<int, int> > A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i].first;\n        \n        A[i].second = i;\n    }\n    \n    sort(all(A));\n    reverse(all(A));\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = 0; j < no_of_players; j++)\n        {\n            cin >> value[i][j];\n        }\n    }\n    \n    memset(max_till, -1, sizeof(max_till));\n    max_till[0][0] = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int index = A[i].second; //cout << \"(\" << A[i].first << \",\" << A[i].second << \")\\n\";\n        \n        for(int m = 0; m < (1 << no_of_players); m++)\n        {\n            int players = no_of_bits(m);\n            int audience_so_far = (i - 1) - players;\n            \n            if(players > i)\n            {\n                continue;\n            }\n            \n            if(audience_so_far < audience)\n            {\n                if(max_till[i - 1][m] != -1)\n                {   //cout << \"Audience = \" << A[i].first << \"\\n\";\n                    max_till[i][m] = max_till[i - 1][m] + A[i].first;\n                }\n            }\n            else\n            {\n                if(max_till[i - 1][m] != -1)\n                {\n                    max_till[i][m] = max_till[i - 1][m];\n                }\n            }\n            \n            for(int bit = 0; bit < no_of_players; bit++)\n            {\n                if(is_bit_set(m, bit) && max_till[i - 1][m^(1 << bit)] != -1)\n                {\n                    //cout << \"Choice is \" << max_till[i][m] << \" and \" << value[index][bit] << \" + \" << max_till[i - 1][m^(1 << bit)] << \"\\n\";\n                    \n                    max_till[i][m] = max(max_till[i][m],\n                                         value[index][bit] + max_till[i - 1][m^(1 << bit)]);\n                }\n            }\n            \n            //cout << \"f(\" << i << \",\" << m << \") = \" << max_till[i][m] << \"\\n\";\n        }\n    }\n    \n    int total = (1 << no_of_players) - 1;\n    cout << max_till[no_of_elements][total] << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/605 Div 3/Explanations/Nearly Opposite Parity.cpp",
    "content": "Let us divide these problems into two subproblems\n\n1. Find the closest even integer to every odd integer\n2. Find the closest odd integer to every even integer\n\n-----\n\nLet us draw a 'reverse' graph.\n\nIf it is possible to go from A[i] to A[j], we will draw a directed edge from A[i] to A[j]\n\nWe will do Multi Source BFS with all the even integers as the sources and calculate the minimum distance to each A[i]\n\n-----\n\nThen, we will do the same for all even integers\n\n\nvoid bfs(vector <int> &A, vector <int> &answer, int parity)\n{\n    vector <int> distance(A.size() + 1, oo);\n    queue <int> Q;\n\n    for(int i = 1; i < A.size(); i++)\n    {\n        if(A[i]%2 != parity)\n        {\n            distance[i] = 0;\n\n            Q.push(i);\n        }\n    }\n\n    while(!Q.empty())\n    {\n        int index = Q.front();\n        Q.pop();\n\n        for(int v = 0; v < graph[index].size(); v++)\n        {\n            int next = graph[index][v];\n\n            if(1 + distance[index] < distance[next])\n            {\n                distance[next] = 1 + distance[index];\n\n                Q.push(next);\n            }\n        }\n    }\n\n     for(int i = 1; i < A.size(); i++)\n     {\n         if(A[i]%2 == parity)\n         {\n            answer[i] = (distance[i] == oo ? -1 : distance[i]);\n         }\n     }\n}\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        if(1 <= i - A[i])\n        {\n            graph[i - A[i]].push_back(i);\n        }\n\n        if(i + A[i] <= no_of_elements)\n        {\n            graph[i + A[i]].push_back(i);\n        }\n    }\n\n    vector <int> answer(no_of_elements + 1, oo);\n    bfs(A, answer, EVEN);\n    bfs(A, answer, ODD);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/605 Div 3/Explanations/Remove One Element Explanation.txt",
    "content": "We can solve this problem with DP\n\n//\n//  main.cpp\n//  Remove One Element\n//\n//  Created by Saikat Ghosh on 13/12/19.\n//  Copyright © 2019 Saikat Ghosh. All rights reserved.\n//\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int WITHOUT_DELETE = 0, WITH_DELETE = 1;\n    vector <vector <int> > max_length_till(no_of_elements + 1, vector <int> (2, 0));\n    \n    max_length_till[1][WITHOUT_DELETE] = 1;\n    max_length_till[1][WITH_DELETE] = 1;\n    \n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        max_length_till[i][WITH_DELETE] = 1;\n        max_length_till[i][WITHOUT_DELETE] = 1;\n        \n        if(i >= 1 && A[i] > A[i - 1])\n        {\n            max_length_till[i][WITHOUT_DELETE] =                               max_length_till[i - 1][WITHOUT_DELETE] + 1;\n            \n            max_length_till[i][WITH_DELETE] = 1 + max_length_till[i - 1][WITH_DELETE];\n        }\n        \n        if(i >= 2 && A[i] > A[i - 2])\n        {\n            max_length_till[i][WITH_DELETE] = max(max_length_till[i][WITH_DELETE],\n             1 + max_length_till[i - 2][WITHOUT_DELETE]);\n        }\n    }\n    \n    int answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int answer_here = max(max_length_till[i][WITHOUT_DELETE], max_length_till[i][WITH_DELETE]);\n        answer = max(answer, answer_here);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/605 Div 3/Programs/Nearly Opposite Parity.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nconst int ODD = 1, EVEN = 0, oo = 1e9, MAX_N = 2e5 + 5;\n\nvector <int> graph[MAX_N];\n\nvoid bfs(vector <int> &A, vector <int> &answer, int parity)\n{\n    vector <int> distance(A.size() + 1, oo);\n    queue <int> Q;\n    \n    for(int i = 1; i < A.size(); i++)\n    {\n        if(A[i]%2 != parity)\n        {\n            distance[i] = 0;\n            \n            Q.push(i);\n        }\n    }\n    \n    while(!Q.empty())\n    {\n        int index = Q.front();\n        Q.pop();\n        \n        for(int v = 0; v < graph[index].size(); v++)\n        {\n            int next = graph[index][v];\n            \n            if(1 + distance[index] < distance[next])\n            {\n                distance[next] = 1 + distance[index];\n                \n                Q.push(next);\n            }\n        }\n    }\n                                                 \n     for(int i = 1; i < A.size(); i++)\n     {\n         if(A[i]%2 == parity)\n         {\n            answer[i] = (distance[i] == oo ? -1 : distance[i]);\n         }\n     }\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        if(1 <= i - A[i])\n        {\n            graph[i - A[i]].push_back(i);\n        }\n        \n        if(i + A[i] <= no_of_elements)\n        {\n            graph[i + A[i]].push_back(i);\n        }\n    }\n    \n    vector <int> answer(no_of_elements + 1, oo);\n    bfs(A, answer, EVEN);\n    bfs(A, answer, ODD);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/605 Div 3/Programs/Remove One Element.cpp",
    "content": "//\n//  main.cpp\n//  Remove One Element\n//\n//  Created by Saikat Ghosh on 13/12/19.\n//  Copyright © 2019 Saikat Ghosh. All rights reserved.\n//\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int WITHOUT_DELETE = 0, WITH_DELETE = 1;\n    vector <vector <int> > max_length_till(no_of_elements + 1, vector <int> (2, 0));\n    \n    max_length_till[1][WITHOUT_DELETE] = 1;\n    max_length_till[1][WITH_DELETE] = 1;\n    \n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        max_length_till[i][WITH_DELETE] = 1;\n        max_length_till[i][WITHOUT_DELETE] = 1;\n        \n        if(i >= 1 && A[i] > A[i - 1])\n        {\n            max_length_till[i][WITHOUT_DELETE] =                               max_length_till[i - 1][WITHOUT_DELETE] + 1;\n            \n            max_length_till[i][WITH_DELETE] = 1 + max_length_till[i - 1][WITH_DELETE];\n        }\n        \n        if(i >= 2 && A[i] > A[i - 2])\n        {\n            max_length_till[i][WITH_DELETE] = max(max_length_till[i][WITH_DELETE],\n             1 + max_length_till[i - 2][WITHOUT_DELETE]);\n        }\n    }\n    \n    int answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int answer_here = max(max_length_till[i][WITHOUT_DELETE], max_length_till[i][WITH_DELETE]);\n        answer = max(answer, answer_here);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Explanations/Candies Division Explanation.txt",
    "content": "After giving everyone C/N number of candies,\nwe will look at the remainder.\n\nWe can only give (C/2) or (C mod N) candies - whichever is lesser.\n\nvoid solve()\n{\n    int no_of_candies, no_of_kids;\n    cin >> no_of_candies >> no_of_kids;\n\n    int candies_given_to_one_kid = no_of_candies/no_of_kids;\n\n    int candies_given = no_of_kids*candies_given_to_one_kid;\n    no_of_candies %= no_of_kids;\n\n    candies_given += min(no_of_candies, no_of_kids/2);\n\n    cout << candies_given << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Explanations/Christmas Trees Explanation.txt",
    "content": "We will first look at all points which are at a distance 1 from a tree.\nThen, we will look at all points which are at a distance 2 from a tree.\nThen, we will look at all points which are at a distance 3 from a tree.\n\nThis suggests BFS. We will insert all the Christmas trees as sources.\nAfter visiting a point, we will insert (x + 1) and (x - 1) into the queue if we have not already visited it.\n\nIf we insert (x + 1) or (x - 1) after x, then\n\nd(x + 1) = d(x - 1) = d(x) + 1\n\nThis is the minimum distance to either (x + 1) or (x - 1).\nThe reason is that we are performing BFS.\n\nIf we had another path to (x + 1) or (x - 1) from y, and d(y) < d(x),\nthen we would have visited y before we had visited x.\n\n------\n\nint main()\n{\n    int no_of_trees, no_of_people;\n    cin >> no_of_trees >> no_of_people;\n\n    vector <int> X(no_of_trees);\n    for(int i = 0; i < no_of_trees; i++)\n    {\n        cin >> X[i];\n    }\n\n    map <int, int> distance;\n    queue <int> Q;\n    for(int i = 0; i < no_of_trees; i++)\n    {\n        Q.push(X[i]);\n\n        distance[X[i]] = 0;\n    }\n\n    long long total_distance = 0;\n    vector <int> people;\n    while(!Q.empty() && people.size() < no_of_people)\n    {\n        int current = Q.front();\n        Q.pop();\n\n        if(distance[current] != 0)\n        {\n            total_distance += distance[current];\n\n            people.push_back(current);\n        }\n\n        if(distance.count(current + 1) == 0)\n        {\n            distance[current + 1] = distance[current] + 1;\n\n            Q.push(current + 1);\n        }\n\n        if(distance.count(current - 1) == 0)\n        {\n            distance[current - 1] = distance[current] + 1;\n\n            Q.push(current - 1);\n        }\n    }\n\n    cout << total_distance << \"\\n\";\n    for(int i = 0; i < no_of_people; i++)\n    {\n        cout << people[i] << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Explanations/DIY Garland Explanation.txt",
    "content": "Let us make a few simple observations - \n\n1. The first vertex is the root. \n2. Leaves are the vertices which are never mentioned in the list. \n3. If we have multiple leaves, then the leaf which has the greater number has their parent coming first. \n4. If there is a situation where we must match a vertex to a leaf, we must choose the largest available leaf.\n5. The i-th edge will start from the i-th vertex on the list. \n\n------\n\nWhen we are at vertex A[i], we know that cutting a wire from A[i] is more important than the wire from A[i + 1].\nHaving said that all the vertices affected by cutting the wire from A[i + 1] will also be effected by cutting the wire from A[i] if we draw an edge between A[i] and A[i + 1]. \nSo, we will simply draw an edge between A[i] and A[i + 1] if we have not drawn an edge to A[i + 1] before. \n\nIf we have, then we will simply connect A[i] to the largest leaf available at the time. \n\n-----\n\n\nint main()\n{\n    int no_of_lamps;\n    cin >> no_of_lamps;\n    \n    vector <int> index(no_of_lamps);\n    for(int i = 1; i < no_of_lamps; i++)\n    {\n        cin >> index[i];\n    }\n    \n    vector <int> used(no_of_lamps + 1, false);\n    int root = index[1];\n    int current = no_of_lamps;\n    \n    cout << root << \"\\n\";\n    for(int i = 1; i < no_of_lamps; i++)\n    {\n        used[index[i]] = true;\n        \n        while(used[current])\n        {\n            current--;\n        }\n        \n        if(i == no_of_lamps - 1 || used[index[i + 1]])\n        {\n            cout << index[i] << \" \" << current << \"\\n\";\n            \n            used[current] = true;\n        }\n        else\n        {\n            cout << index[i] << \" \" << index[i + 1] << \"\\n\";\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Explanations/Friends and Gifts Explanation.txt",
    "content": "Let us draw a graph to represent the permutation.\nEach vertex should have exactly 1 edge coming in and exactly 1 edge coming out.\n\nAfter we draw the graph, there will be some vertices which are isolated.\n\nIf there are no isolated vertices, then we are good.\nIf there is one isolated vertex, we will draw an edge from here to so me other vertex which does not have an incoming edge.\n(There have to be n incoming and n outgoing edges.\nIf 1 vertex does not have an outgoing edge,\nit means some other vertex does not have an incoming edge.)\n\nIf there are more than one isolated vertices, then we will create a cycle with them.\n\nAfter we are done, there will be some vertices which don't have an incoming edge and some vertices which don't have an outgoing edge, but not both.\n(As we already took care of the isolated vertices.)\n\n-----\n\nBy our previous proof, they will be equal in number and we will just match them.\n\n-----\n\nint main()\n{\n    int no_of_friends;\n    cin >> no_of_friends;\n\n    vector <int> A(no_of_friends + 1);\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> indegree(no_of_friends + 1);\n    vector <int> outdegree(no_of_friends + 1);\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        if(A[i] != 0)\n        {\n            indegree[A[i]]++;\n            outdegree[i]++;\n        }\n    }\n\n    vector <int> isolated_vertices;\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        if(indegree[i] == 0 && outdegree[i] == 0)\n        {\n            isolated_vertices.push_back(i);\n        }\n    }\n\n    if(isolated_vertices.size() == 1)\n    {\n        int v = isolated_vertices[0];\n\n        for(int i = 1; i <= no_of_friends; i++)\n        {\n            if(indegree[i] == 0 && i != v)\n            {\n                A[v] = i;\n\n                indegree[i]++;\n                outdegree[v]++;\n\n                break;\n            }\n        }\n    }\n    else if(isolated_vertices.size() > 1)\n    {\n        for(int i = 0; i < isolated_vertices.size(); i++)\n        {\n            int u = isolated_vertices[i], v = isolated_vertices[(i + 1)%isolated_vertices.size()];\n\n            A[u] = v;\n            indegree[v]++;\n            outdegree[u]++;\n        }\n    }\n\n    vector <int> empty_in;\n    vector <int> empty_out;\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        if(indegree[i] == 0)\n        {\n            empty_in.push_back(i);\n        }\n        if(outdegree[i] == 0)\n        {\n            empty_out.push_back(i);\n        }\n    }\n\n    for(int i = 0; i < empty_out.size(); i++)\n    {\n        int u = empty_out[i], v = empty_in[i];\n\n        A[u] = v;\n    }\n\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Explanations/Minutes Before the New Year Explanation.txt",
    "content": "We will calculate the number of minutes left.\n\nvoid solve()\n{\n    int hours, minutes;\n    cin >> hours >> minutes;\n\n    const int MAX_HOUR = 23, MAX_MINUTE = 60;\n    int remaining_minutes = 60*(MAX_HOUR - hours) + (MAX_MINUTE - minutes);\n\n    cout << remaining_minutes << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Explanations/New Year Parties Explanation.txt",
    "content": "Let us divide the problem into two subproblems - Maximizing and Minimizing\n\n-----\n\nI solved the Maximising problem using Greedy.\nThe idea is that we will make each element as small as possible.\n\nint maximise_houses(int n, vector <int> X)\n{\n    set <int> S;\n    for(int i = 1; i <= n; i++)\n    {\n        if(S.find(X[i] - 1) == S.end())\n        {\n            S.insert(X[i] - 1);\n        }\n        else if(S.find(X[i]) == S.end())\n        {\n            S.insert(X[i]);\n        }\n        else if(S.find(X[i] + 1) == S.end())\n        {\n            S.insert(X[i] + 1);\n        }\n    }\n\n    return S.size();\n}\n\n-----\n\nI solved the minimizing problems using a DP.\nThere is also a Greedy solution\n\nint minimise_houses(int n, vector <int> X)\n{\n    vector <vector <int> > minimum_houses(n + 1, vector <int> (4, 0));\n\n    const int BACKWARD = 0, SAME = 1, FORWARD = 2;\n    for(int i = 1; i <= n; i++)\n    {\n        if(i == 1)\n        {\n            minimum_houses[i][BACKWARD] = minimum_houses[i][SAME] = minimum_houses[i][FORWARD] = 1;\n\n            //continue;\n        }\n        else if(X[i - 1] < X[i] - 2)\n        {\n            minimum_houses[i][BACKWARD] =\n            minimum_houses[i][SAME] =\n            minimum_houses[i][FORWARD] = 1 + min_3(minimum_houses[i - 1][BACKWARD], minimum_houses[i - 1][SAME], minimum_houses[i - 1][FORWARD]);\n\n            //continue;\n        }\n        else if(X[i - 1] + 1 == X[i] - 1)\n        {\n            minimum_houses[i][BACKWARD] = min_3(minimum_houses[i - 1][FORWARD], 1 + minimum_houses[i - 1][SAME], 1 + minimum_houses[i - 1][BACKWARD]);\n\n            minimum_houses[i][SAME] =\n            minimum_houses[i][FORWARD] = 1 + min_3(minimum_houses[i - 1][BACKWARD], minimum_houses[i - 1][SAME], minimum_houses[i - 1][FORWARD]);\n\n            //continue;\n        }\n        else if(X[i - 1] + 1 == X[i])\n        {\n            minimum_houses[i][BACKWARD] = min_3(1 + minimum_houses[i - 1][BACKWARD], minimum_houses[i - 1][SAME], 1 + minimum_houses[i - 1][FORWARD]);\n\n            minimum_houses[i][SAME] = min_3(1 + minimum_houses[i - 1][BACKWARD], 1 + minimum_houses[i - 1][SAME], minimum_houses[i - 1][FORWARD]);\n\n            minimum_houses[i][FORWARD] = 1 + min_3(minimum_houses[i - 1][BACKWARD],\n                                                   minimum_houses[i - 1][SAME],\n                                                   minimum_houses[i - 1][FORWARD]);\n\n            //continue;\n        }\n        else if(X[i - 1] == X[i])\n        {\n            minimum_houses[i][BACKWARD] = minimum_houses[i - 1][BACKWARD];\n            minimum_houses[i][SAME] = minimum_houses[i - 1][SAME];\n            minimum_houses[i][FORWARD] = minimum_houses[i - 1][FORWARD];\n\n            //continue;\n        }\n    }\n\n    return min_3(minimum_houses[n][BACKWARD], minimum_houses[n][SAME], minimum_houses[n][FORWARD]);\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Programs/Candies Division.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_candies, no_of_kids;\n    cin >> no_of_candies >> no_of_kids;\n    \n    int candies_given_to_one_kid = no_of_candies/no_of_kids;\n    \n    int candies_given = no_of_kids*candies_given_to_one_kid;\n    no_of_candies %= no_of_kids;\n    \n    candies_given += min(no_of_candies, no_of_kids/2);\n    \n    cout << candies_given << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Programs/Christmas Trees.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_trees, no_of_people;\n    cin >> no_of_trees >> no_of_people;\n    \n    vector <int> X(no_of_trees);\n    for(int i = 0; i < no_of_trees; i++)\n    {\n        cin >> X[i];\n    }\n    \n    map <int, int> distance;\n    queue <int> Q;\n    for(int i = 0; i < no_of_trees; i++)\n    {\n        Q.push(X[i]);\n        \n        distance[X[i]] = 0;\n    }\n    \n    long long total_distance = 0;\n    vector <int> people;\n    while(!Q.empty() && people.size() < no_of_people)\n    {\n        int current = Q.front();\n        Q.pop();\n        \n        if(distance[current] != 0)\n        {\n            total_distance += distance[current];\n            \n            people.push_back(current);\n        }\n        \n        if(distance.count(current + 1) == 0)\n        {\n            distance[current + 1] = distance[current] + 1;\n            \n            Q.push(current + 1);\n        }\n        \n        if(distance.count(current - 1) == 0)\n        {\n            distance[current - 1] = distance[current] + 1;\n            \n            Q.push(current - 1);\n        }\n    }\n    \n    cout << total_distance << \"\\n\";\n    for(int i = 0; i < no_of_people; i++)\n    {\n        cout << people[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Programs/DIY Garland.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_lamps;\n    cin >> no_of_lamps;\n    \n    vector <int> index(no_of_lamps);\n    for(int i = 1; i < no_of_lamps; i++)\n    {\n        cin >> index[i];\n    }\n    \n    vector <int> used(no_of_lamps + 1, false);\n    int root = index[1];\n    int current = no_of_lamps;\n    \n    cout << root << \"\\n\";\n    for(int i = 1; i < no_of_lamps; i++)\n    {\n        used[index[i]] = true;\n        \n        while(used[current])\n        {\n            current--;\n        }\n        \n        if(i == no_of_lamps - 1 || used[index[i + 1]])\n        {\n            cout << index[i] << \" \" << current << \"\\n\";\n            \n            used[current] = true;\n        }\n        else\n        {\n            cout << index[i] << \" \" << index[i + 1] << \"\\n\";\n        }\n    }\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Programs/Friends and Gifts.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_friends;\n    cin >> no_of_friends;\n    \n    vector <int> A(no_of_friends + 1);\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> indegree(no_of_friends + 1);\n    vector <int> outdegree(no_of_friends + 1);\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        if(A[i] != 0)\n        {\n            indegree[A[i]]++;\n            outdegree[i]++;\n        }\n    }\n    \n    vector <int> isolated_vertices;\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        if(indegree[i] == 0 && outdegree[i] == 0)\n        {\n            isolated_vertices.push_back(i);\n        }\n    }\n    \n    if(isolated_vertices.size() == 1)\n    {\n        int v = isolated_vertices[0];\n        \n        for(int i = 1; i <= no_of_friends; i++)\n        {\n            if(indegree[i] == 0 && i != v)\n            {\n                A[v] = i;\n                \n                indegree[i]++;\n                outdegree[v]++;\n                \n                break;\n            }\n        }\n    }\n    else if(isolated_vertices.size() > 1)\n    {\n        for(int i = 0; i < isolated_vertices.size(); i++)\n        {\n            int u = isolated_vertices[i], v = isolated_vertices[(i + 1)%isolated_vertices.size()];\n            \n            A[u] = v;\n            indegree[v]++;\n            outdegree[u]++;\n        }\n    }\n    \n    vector <int> empty_in;\n    vector <int> empty_out;\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        if(indegree[i] == 0)\n        {\n            empty_in.push_back(i);\n        }\n        if(outdegree[i] == 0)\n        {\n            empty_out.push_back(i);\n        }\n    }\n    \n    for(int i = 0; i < empty_out.size(); i++)\n    {\n        int u = empty_out[i], v = empty_in[i];\n        \n        A[u] = v;\n    }\n    \n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Programs/Minutes Before the New Year.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int hours, minutes;\n    cin >> hours >> minutes;\n    \n    const int MAX_HOUR = 23, MAX_MINUTE = 60;\n    int remaining_minutes = 60*(MAX_HOUR - hours) + (MAX_MINUTE - minutes);\n    \n    cout << remaining_minutes << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/611 Div 3/Programs/New Year Parties.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint min_3(int a, int b, int c)\n{\n    return min(a, min(b, c));\n}\n\nint maximise_houses(int n, vector <int> X)\n{\n    set <int> S;\n    for(int i = 1; i <= n; i++)\n    {\n        if(S.find(X[i] - 1) == S.end())\n        {\n            S.insert(X[i] - 1);\n        }\n        else if(S.find(X[i]) == S.end())\n        {\n            S.insert(X[i]);\n        }\n        else if(S.find(X[i] + 1) == S.end())\n        {\n            S.insert(X[i] + 1);\n        }\n    }\n    \n    return S.size();\n}\n\nint minimise_houses(int n, vector <int> X)\n{\n    vector <vector <int> > minimum_houses(n + 1, vector <int> (4, 0));\n    \n    const int BACKWARD = 0, SAME = 1, FORWARD = 2;\n    for(int i = 1; i <= n; i++)\n    {\n        if(i == 1)\n        {\n            minimum_houses[i][BACKWARD] = minimum_houses[i][SAME] = minimum_houses[i][FORWARD] = 1;\n            \n            //continue;\n        }\n        else if(X[i - 1] < X[i] - 2)\n        {\n            minimum_houses[i][BACKWARD] =\n            minimum_houses[i][SAME] =\n            minimum_houses[i][FORWARD] = 1 + min_3(minimum_houses[i - 1][BACKWARD], minimum_houses[i - 1][SAME], minimum_houses[i - 1][FORWARD]);\n            \n            //continue;\n        }\n        else if(X[i - 1] + 1 == X[i] - 1)\n        {\n            minimum_houses[i][BACKWARD] = min_3(minimum_houses[i - 1][FORWARD], 1 + minimum_houses[i - 1][SAME], 1 + minimum_houses[i - 1][BACKWARD]);\n            \n            minimum_houses[i][SAME] =\n            minimum_houses[i][FORWARD] = 1 + min_3(minimum_houses[i - 1][BACKWARD], minimum_houses[i - 1][SAME], minimum_houses[i - 1][FORWARD]);\n            \n            //continue;\n        }\n        else if(X[i - 1] + 1 == X[i])\n        {\n            minimum_houses[i][BACKWARD] = min_3(1 + minimum_houses[i - 1][BACKWARD], minimum_houses[i - 1][SAME], 1 + minimum_houses[i - 1][FORWARD]);\n            \n            minimum_houses[i][SAME] = min_3(1 + minimum_houses[i - 1][BACKWARD], 1 + minimum_houses[i - 1][SAME], minimum_houses[i - 1][FORWARD]);\n            \n            minimum_houses[i][FORWARD] = 1 + min_3(minimum_houses[i - 1][BACKWARD],\n                                                   minimum_houses[i - 1][SAME],\n                                                   minimum_houses[i - 1][FORWARD]);\n            \n            //continue;\n        }\n        else if(X[i - 1] == X[i])\n        {\n            minimum_houses[i][BACKWARD] = minimum_houses[i - 1][BACKWARD];\n            minimum_houses[i][SAME] = minimum_houses[i - 1][SAME];\n            minimum_houses[i][FORWARD] = minimum_houses[i - 1][FORWARD];\n            \n            //continue;\n        }\n    }\n    \n    return min_3(minimum_houses[n][BACKWARD], minimum_houses[n][SAME], minimum_houses[n][FORWARD]);\n}\n\nint main()\n{\n    int no_of_friends;\n    cin >> no_of_friends;\n    \n    vector <int> X(no_of_friends + 1);\n    for(int i = 1; i <= no_of_friends; i++)\n    {\n        cin >> X[i];\n    }\n    \n    sort(all(X));\n    \n    int minimum_houses = minimise_houses(no_of_friends, X);\n    int maximum_houses = maximise_houses(no_of_friends, X);\n    \n    cout << minimum_houses << \" \" << maximum_houses << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Explanations/Collecting Coins Explanation.txt",
    "content": "The total number of coins is (a + b + c + n).\n\nAt the end, every group must have T/3 coins.\n\nWe must ensure that T is divisible by 3 and then that each group has less than T/3 coins.\n\nvoid solve()\n{\n    int a, b, c, n;\n    cin >> a >> b >> c >> n;\n\n    int total = (a + b + c) + n;\n    cout << (total%3 == 0 && a <= total/3 && b <= total/3 && c <= total/3 ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Explanations/Collecting Packages Explanation.txt",
    "content": "We will visit the points in order of their x's.\n\nFor a given x, we must visit the points in ascending order of y's.\n\nAs we are only allowed to go up, we have to ensure that the y's also only go up as we go from 1 x to another.\n\n1. Sort the points by their X\n2. For each X, sort the points by their Y\n3. Check if the Y's are in non-decreasing order as we go from one Y to another.\n\n-----\n\nint sort_by_x(point &P, point &Q)\n{\n    if(P.x == Q.x)\n    {\n        return (P.y < Q.y);\n    }\n\n    return (P.x < Q.x);\n}\n\nvoid solve()\n{\n    int no_of_points;\n    cin >> no_of_points;\n\n    vector <point> P(no_of_points);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> P[i].x >> P[i].y;\n    }\n\n    sort(all(P), sort_by_x);\n\n    int y_is_sorted = true;\n    for(int i = 1; i < no_of_points; i++)\n    {\n        if(P[i - 1].y > P[i].y)\n        {\n            y_is_sorted = false;\n            break;\n        }\n    }\n\n    if(!y_is_sorted)\n    {\n        cout << \"NO\\n\";\n        return;\n    }\n\n    string answer;\n    for(int x = 0, y = 0, i = 0; i < no_of_points; i++)\n    {\n        while(x != P[i].x)\n        {//cout << \"Right\\n\" << answer << \"\\n\";\n            answer += \"R\";\n            x++;\n        }\n\n        while(y != P[i].y)\n        {   //cout << \"Up\\n\" << answer << \"\\n\";\n            answer += \"U\";\n            y++;\n        }\n    }\n\n    cout << \"YES\\n\";\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Explanations/MEX Maximising Explanation.txt",
    "content": "1. We can only add or subtract x from A[i]. So A[i] (mod x) is invariant.\n\n2. We will 'spread' out the A[i]'s across each mod.\nSuppose A[i] = 1 (mod x). Suppose, we have already have (1, x + 1, 2x + 1).\nWe will give A[i] the value = 3x + 1.\n\n\nWe will greedily give A[i] the smallest untaken value.\n\n-----\n\nThis ensures that we are maximising the Mex at each step because we are taking\nthe smallest untaken number we can at each step.\n\n----\n\nTo calculate the Mex, we can have another loop.\nAlthough it looks like it is O(N^2), it is not because the loops are independent.\n\n-----\n\nint main()\n{\n    long long no_of_operations, x;\n    cin >> no_of_operations >> x;\n\n    map <long long, int> is_present;\n    map <long long, int> last;\n\n    int mex = 0;\n    for(int i = 1; i <= no_of_operations; i++)\n    {\n        long long current;\n        cin >> current;\n\n        current %= x;\n\n        is_present[x*last[current] + current] = true;\n        last[current]++;\n\n        while(is_present[mex])\n        {\n            mex++;\n        }\n\n        cout << mex << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Explanations/Obtain a Permutation Explanation.txt",
    "content": "The column of any element is invariant across all operations.\nEvery element will stay in it's column.\n\n-----\n\nLet us find the number of moves for each column seperately.\n\nNow, how do we find out the minimum number of moves for a given column ?\n\nLet us calculate the number of moves for each rotation from 1 to N.\n\nWe will then select the rotation that minimises the number of moves.\n\nA given column i, will have all elements = i (mod M)\n\n-----\n\nNow we will see how to count the number of moves for i rotations.\n\nWe will do i moves - Rotations\n\nWe just have to count the number of Changing moves.\n\nWe can do it like this -\n\nfor(int r = 0; r < rows; r++)\n{\n    operations[r] = r;\n\n    for(int i = 1; i <= rows; i++)\n    {\n        int expected = (i - 1)*columns + columns;\n\n        int actual = A[ (i + r)mod rows + 1][j];\n\n        if(expected != actual)\n            operations[r]++\n    }\n}\n\nBasically, what we are doing is counting the number of operations for each rotation.\n\nBut, this is O(MN) for each column.\n\nWe can make a beautiful observation to make it O(M) for each iteration !\n\n-----\n\nNow, here is what we will observe.\nA[i][j] will be correct only for at most ONE rotation.\n\nThis is because the element at spot (i, j) is fixed.\nA[i][j] will fall into the correct spot in only one spot !\n\nSo, we will initially assume, rotation r will cost (r + N).\n\nThen, we will go through all N elements and\ndecrement the cost only on it's best rotation.\n\nThe code is given below\n\n-----\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d + (n%d != 0));\n}\n\nlong long calculate_best_cost(int column_no)\n{\n    vector <long long> rotation_cost(rows + 1, 0);\n    for(int rotations = 0; rotations < rows; rotations++)\n    {\n        rotation_cost[rotations] = rotations + rows;\n        //cout << \"Cost \" << rotations << \" = \" << rotation_cost[rotations] << \"\\n\";\n    }\n\n    for(int i = 1; i <= rows; i++)\n    {\n        if(A[i][column_no]%columns != column_no%columns)\n        {\n            continue;\n        }\n\n        int best_place = ceil(A[i][column_no], columns);\n\n        if(best_place > rows)\n        {\n            continue;\n        }\n\n        int best_rotation;\n\n        if(best_place <= i)\n        {\n            best_rotation = (i - best_place);\n        }\n        else\n        {\n            best_rotation = (i - 1) + (rows - best_place + 1);\n        }\n        //cout << i << \" \" << column_no << \" Best place = \" << best_place << \" \" << best_rotation << \"\\n\";\n        rotation_cost[best_rotation]--;\n        //cout << \"Cost of \" << best_rotation << \" = \" << rotation_cost[best_rotation] << \"\\n\";\n    }\n\n    long long best_cost = rotation_cost[0];\n    for(int rotations = 1; rotations < rows; rotations++)\n    {\n        best_cost = min(best_cost, rotation_cost[rotations]);\n    }\n    //cout << \"Column \" << column_no  << \" = \" << best_cost << \"\\n\";\n    return best_cost;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Explanations/Product of Three Numbers Explanation.txt",
    "content": "Let us look at the prime factorisation of N.\n\nCase 1 - N has >= 3 prime factors\n\nThen, a = p1, b = p2, c = N/(p1p2)\n\nc will have a term of p3 in it which is not there in a or b so it cannot be equal\n\n------\n\nCase 2 - N has 2 prime factors\n\nCase 2a - One of p1, p2 has exponent > 2\n\nLet it be p2\n\na = p1, b = p2, c = N/(p1p2)\n\nAs Exp(p2) > 2, the Exponent of p2 in c will be more than 1.\nThis ensures that c will not be equal to b\n\nCase 2b - p1 = p2 = 2\n\nThen, a = p1, b = p2, c = N/(p1p2)\n\nCase 2c - One of p1, p2 = 1 and the other is 2\n\nIf only one of them has exponent 2, it is not possible as\n\na = p1, b = p2, c = N/(p1p2) and c will be equal to one of (a, b)\n\nCase 2d - Both p1, p2 have exponent 1\n\nIf they both have exponent = 1, it is not possible.\n\nIt is possible everywhere other than when min(p1, p2) = 1 and max(p1, p2) <= 2\n------\n\nCase 3 - N has 1 prime factor\n\na = p1, b = p1^2, c = p1^3 (at least)\n\nIt is not possible if the exponent is less than 6\n\n------\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid factorise(int n, vector <int> &P, vector <int> &E)\n{\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            int exponent = 0;\n\n            while(n%i == 0)\n            {\n                n /= i;\n                exponent++;\n            }\n\n            P.push_back(i);\n            E.push_back(exponent);\n        }\n    }\n\n    if(n > 1)\n    {\n        P.push_back(n);\n        E.push_back(1);\n    }\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n\n    vector <int> primes;\n    vector <int> exponents;\n    factorise(n, primes, exponents);\n\n    if(primes.size() >= 3)\n    {\n        cout << \"YES\\n\";\n        cout << primes[0] << \" \" << primes[1] << \" \" << n/(primes[0]*primes[1]) << \"\\n\";\n\n        return;\n    }\n\n    if(primes.size() == 1)\n    {\n        if(exponents[0] < 6)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n\n        long long f1 = primes[0], f2 = primes[0]*primes[0];\n\n        cout << \"YES\\n\";\n        cout << f1 << \" \" << f2 << \" \" << n/(f1*f2) << \"\\n\";\n\n        return;\n    }\n\n    if(primes.size() == 2)\n    {\n        if(min(exponents[0], exponents[1]) == 1 && max(exponents[0], exponents[1]) <= 2)\n        {\n            cout << \"NO\\n\";\n\n            return;\n        }\n\n        cout << \"YES\\n\";\n        cout << primes[0] << \" \" << primes[1] << \" \" << n/(primes[0]*primes[1]) << \"\\n\";\n        return;\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Explanations/Three Paths on a Tree Explanation.txt",
    "content": "The problem is to find the triameter of a tree. \n\nHere is what we will do. We will first find the diamter of the tree. \n\nWe can do this by the following way - \n\n1. Start from the root and go as far as possible using DFS. Let the point with the furthest depth be a.\n2. Start from a and do another DFS and go as far as possible. Let the point with the furthest depth be b.\n\na-b is the diamater of the tree. \n\n-----\n\nNow, how to find the third point ? \n\nFor every vertex in the graph, we have to calculate the distance to the diameter. \n\nTo do this, we will first store all the vertices of the diameter in a Queue. \n\nThen, we will perform multi source BFS. \n\nThis will help us in calculating the distance from the diameter to every vertex in the tree.\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nconst int MAX_L = 23, MAX_N = 2e5 + 5, oo = 1e9;\nvector <int> tree[MAX_N];\nint parent[MAX_N][MAX_L], depth[MAX_N];\nvector <int> lies_on_diameter(MAX_N, false);\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0) ;\n}\n\nvoid dfs(int v, int parent_v)\n{\n    depth[v] = depth[parent_v] + 1;\n    \n    parent[v][0] = parent_v;\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n    }\n}\n\nint dfs_diameter(int v, int parent_v, int destination)\n{\n    if(v == destination)\n    {\n        lies_on_diameter[v] = true;\n        return true;\n    }\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child = tree[v][i];\n        \n        if(child == parent_v)\n        {\n            continue;\n        }\n        \n        if(dfs_diameter(child, v, destination))\n        {\n            lies_on_diameter[v] = true;\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nvoid precompute_parents(int no_of_vertices)\n{\n    for(int l = 1; l < MAX_L; l++)\n    {\n        for(int i = 1; i <= no_of_vertices; i++)\n        {\n            int ancestor = parent[i][l - 1];\n            \n            parent[i][l] = parent[ancestor][l - 1];\n        }\n    }\n}\n\nint LCA(int u, int v)\n{\n    if(depth[v] < depth[u])\n    {\n        swap(u, v);\n    }\n    \n    int difference = depth[v] - depth[u];\n    \n    for(int i = MAX_L - 1; i >= 0; i--)\n    {\n        if(is_bit_set(difference, i))\n        {\n            v = parent[v][i];\n        }\n    }\n    \n    if(u == v)\n    {\n        return u;\n    }\n    \n    for(int i = MAX_L - 1; i >= 0; i--)\n    {\n        if(parent[u][i] != parent[v][i])\n        {\n            u = parent[u][i];\n            v = parent[v][i];\n        }\n    }\n    \n    return parent[u][0];\n}\n\nint tree_distance(int u, int v)\n{\n    return (depth[u] + depth[v] - 2*depth[LCA(u, v)]);\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    depth[0] = 0;\n    dfs(1, 0);\n    \n    precompute_parents(no_of_vertices);\n    \n    int max_depth = 0;\n    int a = 1, b = 1, c = 1;\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        if(depth[v] > max_depth)\n        {\n            max_depth = depth[v];\n            b = v;\n        }\n    }\n    \n    int edges_covered = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(tree_distance(i, b) > edges_covered)\n        {\n            edges_covered = tree_distance(i, b);\n            a = i;\n            //cout << \"a = \" << a << \" and distance = \" << edges_covered << \"\\n\";\n        }\n    }\n    \n    dfs_diameter(a, 0, b);\n    \n    queue <int> Q;\n    vector <int> distance(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(lies_on_diameter[i])\n        {\n            Q.push(i);\n            distance[i] = 0;\n        }\n        else\n        {\n            distance[i] = oo;\n        }\n    }\n    \n    int new_edges = -1;\n    while(!Q.empty())\n    {\n        int v = Q.front();\n        Q.pop();\n        \n        if(distance[v] > new_edges && v != a && v != b)\n        {\n            new_edges = distance[v];\n            c = v;\n        }\n        \n        for(int i = 0; i < tree[v].size(); i++)\n        {\n            int child = tree[v][i];\n            \n            if(distance[child] > distance[v] + 1)\n            {\n                distance[child] = distance[v] + 1;\n                \n                Q.push(child);\n            }\n        }\n    }\n    \n    edges_covered += new_edges;\n    \n    cout << edges_covered << \"\\n\";\n    cout << a << \" \" << b << \" \" << c << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Programs/Collecting Coins.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int a, b, c, n;\n    cin >> a >> b >> c >> n;\n    \n    int total = (a + b + c) + n;\n    cout << (total%3 == 0 && a <= total/3 && b <= total/3 && c <= total/3 ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Programs/Collecting Packages.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nstruct point\n{\n    int x, y;\n    \n    point(){};\n};\n\nint sort_by_x(point &P, point &Q)\n{\n    if(P.x == Q.x)\n    {\n        return (P.y < Q.y);\n    }\n    \n    return (P.x < Q.x);\n}\n\nvoid solve()\n{\n    int no_of_points;\n    cin >> no_of_points;\n    \n    vector <point> P(no_of_points);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> P[i].x >> P[i].y;\n    }\n    \n    sort(all(P), sort_by_x);\n    \n    int y_is_sorted = true;\n    for(int i = 1; i < no_of_points; i++)\n    {\n        if(P[i - 1].y > P[i].y)\n        {\n            y_is_sorted = false;\n            break;\n        }\n    }\n    \n    if(!y_is_sorted)\n    {\n        cout << \"NO\\n\";\n        return;\n    }\n    \n    string answer;\n    for(int x = 0, y = 0, i = 0; i < no_of_points; i++)\n    {\n        while(x != P[i].x)\n        {//cout << \"Right\\n\" << answer << \"\\n\";\n            answer += \"R\";\n            x++;\n        }\n        \n        while(y != P[i].y)\n        {   //cout << \"Up\\n\" << answer << \"\\n\";\n            answer += \"U\";\n            y++;\n        }\n    }\n    \n    cout << \"YES\\n\";\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Programs/MEX Maximising.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    long long no_of_operations, x;\n    cin >> no_of_operations >> x;\n    \n    map <long long, int> is_present;\n    map <long long, int> last;\n    \n    int mex = 0;\n    for(int i = 1; i <= no_of_operations; i++)\n    {\n        long long current;\n        cin >> current;\n        \n        current %= x;\n        \n        is_present[x*last[current] + current] = true;\n        last[current]++;\n        \n        while(is_present[mex])\n        {\n            mex++;\n        }\n        \n        cout << mex << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Programs/Obtain a Permutation.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint rows, columns;\nvector <vector <int> > A;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d + (n%d != 0));\n}\n\nlong long calculate_best_cost(int column_no)\n{\n    vector <long long> rotation_cost(rows + 1, 0);\n    for(int rotations = 0; rotations < rows; rotations++)\n    {\n        rotation_cost[rotations] = rotations + rows;\n        //cout << \"Cost \" << rotations << \" = \" << rotation_cost[rotations] << \"\\n\";\n    }\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        if(A[i][column_no]%columns != column_no%columns)\n        {\n            continue;\n        }\n        \n        int best_place = ceil(A[i][column_no], columns);\n        \n        if(best_place > rows)\n        {\n            continue;\n        }\n        \n        int best_rotation;\n        \n        if(best_place <= i)\n        {\n            best_rotation = (i - best_place);\n        }\n        else\n        {\n            best_rotation = (i - 1) + (rows - best_place + 1);\n        }\n        //cout << i << \" \" << column_no << \" Best place = \" << best_place << \" \" << best_rotation << \"\\n\";\n        rotation_cost[best_rotation]--;\n        //cout << \"Cost of \" << best_rotation << \" = \" << rotation_cost[best_rotation] << \"\\n\";\n    }\n    \n    long long best_cost = rotation_cost[0];\n    for(int rotations = 1; rotations < rows; rotations++)\n    {\n        best_cost = min(best_cost, rotation_cost[rotations]);\n    }\n    //cout << \"Column \" << column_no  << \" = \" << best_cost << \"\\n\";\n    return best_cost;\n}\n\nint main()\n{\n    cin >> rows >> columns;\n    \n    A.resize(rows + 1);\n    for(int i = 0; i <= rows; i++)\n    {\n        A[i].resize(columns + 1);\n    }\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            cin >> A[i][j];\n        }\n    }\n    \n    long long moves = 0;\n    for(int i = 1; i <= columns; i++)\n    {\n        moves += calculate_best_cost(i);\n    }\n    \n    cout << moves << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Programs/Paths on a Tree.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nconst int MAX_L = 23, MAX_N = 2e5 + 5, oo = 1e9;\nvector <int> tree[MAX_N];\nint parent[MAX_N][MAX_L], depth[MAX_N];\nvector <int> lies_on_diameter(MAX_N, false);\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0) ;\n}\n\nvoid dfs(int v, int parent_v)\n{\n    depth[v] = depth[parent_v] + 1;\n    \n    parent[v][0] = parent_v;\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n    }\n}\n\nint dfs(int v, int parent_v, int destination)\n{\n    if(v == destination)\n    {\n        lies_on_diameter[v] = true;\n        return true;\n    }\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child = tree[v][i];\n        \n        if(child == parent_v)\n        {\n            continue;\n        }\n        \n        if(dfs(child, v, destination))\n        {\n            lies_on_diameter[v] = true;\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nvoid precompute_parents(int no_of_vertices)\n{\n    for(int l = 1; l < MAX_L; l++)\n    {\n        for(int i = 1; i <= no_of_vertices; i++)\n        {\n            int ancestor = parent[i][l - 1];\n            \n            parent[i][l] = parent[ancestor][l - 1];\n        }\n    }\n}\n\nint LCA(int u, int v)\n{\n    if(depth[v] < depth[u])\n    {\n        swap(u, v);\n    }\n    \n    int difference = depth[v] - depth[u];\n    \n    for(int i = MAX_L - 1; i >= 0; i--)\n    {\n        if(is_bit_set(difference, i))\n        {\n            v = parent[v][i];\n        }\n    }\n    \n    if(u == v)\n    {\n        return u;\n    }\n    \n    for(int i = MAX_L - 1; i >= 0; i--)\n    {\n        if(parent[u][i] != parent[v][i])\n        {\n            u = parent[u][i];\n            v = parent[v][i];\n        }\n    }\n    \n    return parent[u][0];\n}\n\nint tree_distance(int u, int v)\n{\n    return (depth[u] + depth[v] - 2*depth[LCA(u, v)]);\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    depth[0] = 0;\n    dfs(1, 0);\n    \n    precompute_parents(no_of_vertices);\n    \n    int max_depth = 0;\n    int a = 1, b = 1, c = 1;\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        if(depth[v] > max_depth)\n        {\n            max_depth = depth[v];\n            b = v;\n        }\n    }\n    \n    int edges_covered = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(tree_distance(i, b) > edges_covered)\n        {\n            edges_covered = tree_distance(i, b);\n            a = i;\n            //cout << \"a = \" << a << \" and distance = \" << edges_covered << \"\\n\";\n        }\n    }\n    \n    dfs(a, 0, b);\n    \n    queue <int> Q;\n    vector <int> distance(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(lies_on_diameter[i])\n        {   \n            Q.push(i);\n            distance[i] = 0;\n        }\n        else\n        {\n            distance[i] = oo;\n        }\n    }\n    \n    int new_edges = -1;\n    while(!Q.empty())\n    {\n        int v = Q.front();\n        Q.pop();\n        \n        if(distance[v] > new_edges && v != a && v != b)\n        {\n            new_edges = distance[v];\n            c = v;\n        }\n        \n        for(int i = 0; i < tree[v].size(); i++)\n        {\n            int child = tree[v][i];\n            \n            if(distance[child] > distance[v] + 1)\n            {\n                distance[child] = distance[v] + 1;\n                \n                Q.push(child);\n            }\n        }\n    }\n    \n    edges_covered += new_edges;\n    \n    cout << edges_covered << \"\\n\";\n    cout << a << \" \" << b << \" \" << c << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/615 Div 3/Programs/Product of Three Numbers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid factorise(int n, vector <int> &P, vector <int> &E)\n{\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            int exponent = 0;\n            \n            while(n%i == 0)\n            {\n                n /= i;\n                exponent++;\n            }\n            \n            P.push_back(i);\n            E.push_back(exponent);\n        }\n    }\n    \n    if(n > 1)\n    {\n        P.push_back(n);\n        E.push_back(1);\n    }\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    \n    vector <int> primes;\n    vector <int> exponents;\n    factorise(n, primes, exponents);\n    \n    if(primes.size() >= 3)\n    {\n        cout << \"YES\\n\";\n        cout << primes[0] << \" \" << primes[1] << \" \" << n/(primes[0]*primes[1]) << \"\\n\";\n                                                           \n        return;\n    }\n    \n    if(primes.size() == 1)\n    {\n        if(exponents[0] < 6)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n        \n        long long f1 = primes[0], f2 = primes[0]*primes[0];\n        \n        cout << \"YES\\n\";\n        cout << f1 << \" \" << f2 << \" \" << n/(f1*f2) << \"\\n\";\n        \n        return;\n    }\n    \n    if(primes.size() == 2)\n    {\n        if(min(exponents[0], exponents[1]) == 1 && max(exponents[0], exponents[1]) <= 2)\n        {\n            cout << \"NO\\n\";\n            \n            return;\n        }\n        \n        cout << \"YES\\n\";\n        cout << primes[0] << \" \" << primes[1] << \" \" << n/(primes[0]*primes[1]) << \"\\n\";\n        return;\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Explanations/Array with Odd Sum Explanation.txt",
    "content": "If there are an odd number of odd numbers, then the sum is odd\n\nIf there are an even number of odd numbers and there is at least one even number,\nwe can make the even number odd and get an odd sum\n\nIf there are no odd numbers, the sum will always be even\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    int odd_count = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n\n        odd_count += (x%2 == 1);\n    }\n\n    cout << ((odd_count%2 == 1) || (odd_count > 0 && odd_count%2 == 0 && odd_count != no_of_elements) ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Explanations/Fight with Monsters Explanation.txt",
    "content": "1. We will let the moves go as they are intended. \n2. Subtract H[i] by a, then subtract H[i] by b. Then again by a, then by b and so on.\n3. If the last move was done by a, then we don't need to do anything. \nIf the last move was done by b, then we can use a's in the intended\n\n------\n\nWe can deal with H[i] mod(a + b)\n\n1. We will write H[i] = H[i] mod (a + b)\n2. If H[i] = 0 mod(a + b), then we will write H[i] = (a + b)\n3. We will subtract a from H[i]\n\nIf H[i] > 0, then we will calculate the number of moves required for a to make this 0\n\nWe will calculate the number of moves required for each element. \n\n------\n\nWe know the number of steps required for each of the N elements. \n\nWe have an array S\n\nWe must maximise the number of elements chosen such that the sum is <= k\n\nWe can do this by sorting S and then taking the smallest elements.\n\n------\n\nint main()\n{\n    int no_of_elements, attack, opponent_attack, secrets;\n    cin >> no_of_elements >> attack >> opponent_attack >> secrets;\n    \n    vector <int> H(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> H[i];\n    }\n    \n    vector <int> skips_required(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        H[i] %= (attack + opponent_attack);\n        \n        if(H[i] == 0)\n        {\n            H[i] = (attack + opponent_attack);\n        }\n        \n        H[i] = max(H[i] - attack, 0);\n        \n        skips_required[i] = ceil(H[i], attack);\n    }\n    \n    sort(skips_required.begin(), skips_required.end());\n    \n    long long total_skips = 0, points = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(total_skips + skips_required[i] > secrets)\n        {\n            break;\n        }\n        \n        total_skips += skips_required[i];\n        \n        points++;\n    }\n    \n    cout << points << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Explanations/Food Buying Explanation.txt",
    "content": "We can just be greedy and simulate the problem.\n\nWe will use 10(X/10) coins. We will get (X/10) extra coins\n\nWe will repeat the same with the (X/10) coins that we have now and keep doing this until we have at least 10 coins\n\n\n-----\n\nvoid solve()\n{\n    int budget;\n    cin >> budget;\n\n    long long no_of_moves = 0;\n    while(budget >= 10)\n    {\n        long long move = budget/10;\n\n        budget = budget - 10*move + move;\n\n        no_of_moves += 10*move;\n    }\n\n    no_of_moves += budget;\n    cout << no_of_moves << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Explanations/String Colouring (Easy Version) Explanation.txt",
    "content": "Let us make an observation\n\nFor every character S[j] that comes after S[i],\nIf S[j] > S[i], S[j] will have to meet S[i] at some point.\n\nWe need to draw an edge between all pairs (i, j) such that\n(i < j) and (S[i] > S[j]) and then check for bipartite matching.\n\nWe can do this in O(n^2) time.\nWe will colour a point red if it is uncoloured and then\ncolour all it's neighbours blue.\n\nIf any of it's neighbours is forced to be red, then it is not possible.\n\n-----\n\nint main()\n{\n    int length;\n    string S;\n\n    cin >> length >> S;\n\n    vector <int> colour(length, UNCOLOURED);\n    for(int i = 0; i < length; i++)\n    {\n        if(colour[i] == UNCOLOURED)\n        {\n            colour[i] = RED;\n        }\n\n        for(int j = i + 1; j < length; j++)\n        {\n            if(S[j] < S[i] && colour[j] == UNCOLOURED)\n            {\n                colour[j] = other(colour[i]);\n\n                continue;\n            }\n\n            if(S[j] < S[i] && colour[i] == colour[j])\n            {\n                cout << \"NO\\n\";\n\n                return 0;\n            }\n        }\n    }\n\n    cout << \"YES\\n\";\n    for(int i = 0; i < length; i++)\n    {\n        cout << colour[i];\n    }\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Explanations/String Colouring (Hard Version) Explanation.txt",
    "content": "There is a theorem called Dilworth's Theorem. It can be applied here.\n\nWe have to count the minimum number of non-decreasing sequences in this array.\n\nThis is equal to the length of the longest non-increasing sequence in the array.\n\nWe will calculate the length of the longest non-increasing sequence.\n\nAs the size of the alphabet is small, we can do it in O(26N) time.\n\n-----\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <int> max_till(NO_OF_ALPHABETS);\n    vector <int> sequence_no(length, 1);\n\n    int no_of_sequences = 0;\n    for(int i = 0; i < length; i++)\n    {\n        for(int alpha = S[i] - 'a' + 1; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            sequence_no[i] = max(sequence_no[i], max_till[alpha] + 1);\n        }\n\n        max_till[S[i] - 'a'] = max(max_till[S[i] - 'a'], sequence_no[i]);\n\n        no_of_sequences = max(no_of_sequences, sequence_no[i]);\n    }\n\n    cout << no_of_sequences << \"\\n\";\n\n    for(int i = 0; i < length; i++)\n    {\n        cout << sequence_no[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Explanations/Yet Another Walking Robot Explanation.txt",
    "content": "We will keep track of (x, y) at every stage.\n\nSuppose we have done i steps and are at (x, y) and we were at (x, y) at step p too.\n\nThen, [p + 1, i] is a substring we can remove.\n\nFor every i, we will check which was the last point at which we were at (x, y)\n\nAccordingly, we will check the size of the segment [L, R] and check if it is the smallest segment we have encountered so far\n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    map <pair <int, int>, int> position;\n    int minimum_distance = length + 1, left = 0, right = length + 1;\n\n    position[make_pair(0, 0)] = -1;\n    for(int x = 0, y = 0, i = 0; i < length; i++)\n    {\n        switch(S[i])\n        {\n            case 'L' : x++; break;\n            case 'R' : x--; break;\n            case 'U' : y++; break;\n            case 'D' : y--; break;\n        }\n\n        if(position.count(make_pair(x, y)) != 0)\n        {\n            int last_i = position[make_pair(x, y)] + 1;\n\n            int distance = (i) - (last_i - 1);\n\n            if(distance < minimum_distance)\n            {\n                minimum_distance = distance;\n                left = last_i ; right = i;\n            }\n        }\n\n        position[make_pair(x, y)] = i;\n    }\n\n    if(minimum_distance > length)\n    {\n        cout << \"-1\\n\";\n        return;\n    }\n\n    cout << left + 1 << \" \" << right + 1 << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Programs/Array with Odd Sum.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    int odd_count = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int x;\n        cin >> x;\n        \n        odd_count += (x%2 == 1);\n    }\n    \n    cout << ((odd_count%2 == 1) || (odd_count > 0 && odd_count%2 == 0 && odd_count != no_of_elements) ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Programs/Fight with Monsters.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint ceil(int a, int b)\n{\n    return (a/b) + (a%b != 0);\n}\n\nint main()\n{\n    int no_of_elements, attack, opponent_attack, secrets;\n    cin >> no_of_elements >> attack >> opponent_attack >> secrets;\n    \n    vector <int> H(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> H[i];\n    }\n    \n    vector <int> skips_required(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        H[i] %= (attack + opponent_attack);\n        \n        if(H[i] == 0)\n        {\n            H[i] = (attack + opponent_attack);\n        }\n        \n        H[i] = max(H[i] - attack, 0);\n        \n        skips_required[i] = ceil(H[i], attack);\n    }\n    \n    sort(skips_required.begin(), skips_required.end());\n    \n    long long total_skips = 0, points = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(total_skips + skips_required[i] > secrets)\n        {\n            break;\n        }\n        \n        total_skips += skips_required[i];\n        \n        points++;\n    }\n    \n    cout << points << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Programs/Food Buying.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int budget;\n    cin >> budget;\n    \n    long long no_of_moves = 0;\n    while(budget >= 10)\n    {\n        long long move = budget/10;\n        \n        budget = budget - 10*move + move;\n        \n        no_of_moves += 10*move;\n    }\n    \n    no_of_moves += budget;\n    cout << no_of_moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Programs/String Coloring (Hard Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <int> max_till(NO_OF_ALPHABETS);\n    vector <int> sequence_no(length, 1);\n    \n    int no_of_sequences = 0;\n    for(int i = 0; i < length; i++)\n    {\n        for(int alpha = S[i] - 'a' + 1; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            sequence_no[i] = max(sequence_no[i], max_till[alpha] + 1);\n        }\n        \n        max_till[S[i] - 'a'] = max(max_till[S[i] - 'a'], sequence_no[i]);\n        \n        no_of_sequences = max(no_of_sequences, sequence_no[i]);\n    }\n    \n    cout << no_of_sequences << \"\\n\";\n    \n    for(int i = 0; i < length; i++)\n    {\n        cout << sequence_no[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Programs/String Colouring (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 205, UNCOLOURED = -1, RED = 0, BLUE = 1;\nvector <int> graph[MAX_N];\n\nint other(int c)\n{\n    return (c == RED ? BLUE : RED);\n}\n\nint main()\n{\n    int length;\n    string S;\n    \n    cin >> length >> S;\n    \n    vector <int> colour(length, UNCOLOURED);\n    for(int i = 0; i < length; i++)\n    {\n        if(colour[i] == UNCOLOURED)\n        {\n            colour[i] = RED;\n        }\n        \n        for(int j = i + 1; j < length; j++)\n        {\n            if(S[j] < S[i] && colour[j] == UNCOLOURED)\n            {\n                colour[j] = other(colour[i]);\n                \n                continue;\n            }\n            \n            if(S[j] < S[i] && colour[i] == colour[j])\n            {\n                cout << \"NO\\n\";\n                \n                return 0;\n            }\n        }\n    }\n    \n    cout << \"YES\\n\";\n    for(int i = 0; i < length; i++)\n    {\n        cout << colour[i];\n    }\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/617 Div 3/Programs/Yet Another Walking Robot.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    map <pair <int, int>, int> position;\n    int minimum_distance = length + 1, left = 0, right = length + 1;\n    \n    position[make_pair(0, 0)] = -1;\n    for(int x = 0, y = 0, i = 0; i < length; i++)\n    {\n        switch(S[i])\n        {\n            case 'L' : x++; break;\n            case 'R' : x--; break;\n            case 'U' : y++; break;\n            case 'D' : y--; break;\n        }\n        \n        if(position.count(make_pair(x, y)) != 0)\n        {\n            int last_i = position[make_pair(x, y)] + 1;\n            \n            int distance = (i) - (last_i - 1);\n            \n            if(distance < minimum_distance)\n            {\n                minimum_distance = distance;\n                left = last_i ; right = i;\n            }\n        }\n        \n        position[make_pair(x, y)] = i;\n    }\n    \n    if(minimum_distance > length)\n    {\n        cout << \"-1\\n\";\n        return;\n    }\n    \n    cout << left + 1 << \" \" << right + 1 << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Explanations/Add Odd or Subtract Even Explanation.txt",
    "content": "We can always make b from a in at most 2 moves. \n\nIf the difference is > 0 and odd, then we can reach in 1 move by adding the required amount.\nOtherwise, we can reach in 2 moves by adding 2 odd integers.\n\nIf the difference is < 0 and even, then we can reach in 1 move by subtracting the required amount. \nOtherwise, we can reach in 2 moves by subtracting a big even integer followed by adding an odd integer.\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long a, b;\n    cin >> a >> b;\n    \n    long long d = (b - a);\n    \n    int moves = 0;\n    \n    if(d < 0)\n    {\n        moves = (d%2 == 0 ? 1 : 2);\n    }\n    else if(d > 0)\n    {\n        moves = (d%2 == 1 ? 1 : 2);\n    }\n    \n    cout << moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Explanations/Construct the Binary Tree Explanation.txt",
    "content": "First, we will calculate the minimum and maximum sum possible.\n\nThe minimum sum is achieved when the tree is as balanced as possible.\nThis means that level 2 is completely filled before moving to level 3\nLevel 3 is completely filled before moving to level 4\nAnd so on\n\nThe maximum sum is achieved when the tree is a chain\n1 + 2 + 3 + ... + n - 1\n\nIf the desired sum is outside this range, then it is not possible.\n\nOtherwise, we will start with the tree having maximum sum and\nkeep reducing the sum by 1 till we arrive at the desired sum\n\n-----\n\nHow to reduce the sum by 1 ?\n\nWe will choose the leaf with the lowest depth d\nWe will try to move it to some vertex of depth (d - 2) which has less than 2 children\n\nIf a leaf can't be moved in this way, we will consider it 'immobile' and search for another one \nat a greater depth\n\nThis process will continue till we reach the desired sum\nOf course, we will always reach the desired sum because\nthis process only ends when the tree becomes completely balanced and\nwe have already checked that condition\n\n-----\n\nint is_power_of_2(int n)\n{\n    return ( (n&(n - 1)) == 0 );\n\n\n}\n\nvoid solve()\n{\n    int no_of_vertices, total_depth_sum;\n    cin >> no_of_vertices >> total_depth_sum;\n\n    long long maximum_sum = (no_of_vertices*(no_of_vertices - 1))/2;\n    long long minimum_sum = 0;\n    for(int i = 1, level = 0; i <= no_of_vertices; i++)\n    {\n        if(is_power_of_2(i))\n        {\n            level++;\n        }\n\n        minimum_sum += (level - 1);\n    }\n\n    if(total_depth_sum < minimum_sum || maximum_sum < total_depth_sum)\n    {\n        cout << \"NO\\n\";\n\n        return;\n    }\n\n    vector <int> depth(no_of_vertices + 1, 0);\n    vector <int> parent(no_of_vertices + 1, 0);\n    vector <int> no_of_children(no_of_vertices + 1, 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        parent[i] = i - 1;\n        depth[i] = i - 1;\n    }\n\n    no_of_children[no_of_vertices] = 0;\n\n    vector <int> immobile(no_of_vertices + 1, false);\n\n    for(long long sum = maximum_sum; sum > total_depth_sum; )\n    {\n        int first_v = 0;\n        for(int i = 1; i <= no_of_vertices; i++)\n        {\n            if(!immobile[i] && no_of_children[i] == 0 &&\n               (first_v == 0 || depth[i] < depth[first_v]))\n            {\n                first_v = i;\n            }\n        }\n\n        int best_parent = 0;\n        for(int i = 1; i <= no_of_vertices; i++)\n        {\n            if(depth[i] == depth[first_v] - 2 && no_of_children[i] < 2)\n            {\n                best_parent = i;\n            }\n        }\n\n        if(best_parent == 0)\n        {\n            immobile[first_v] = true;\n            continue;\n        }\n\n        sum--;\n\n        no_of_children[parent[first_v]]--;\n        depth[first_v]--;\n\n        parent[first_v] = best_parent;\n        no_of_children[best_parent]++;\n    }\n\n    cout << \"YES\\n\";\n    for(int i = 2; i <= no_of_vertices; i++)\n    {\n        cout << parent[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Explanations/Moving Points Explanation.txt",
    "content": "https://qr.ae/Td8Mfd\n\nLet us sort the points in order - x1, x2, ... , xn\n\nFor a given x_i, which x_j <= x_i does it not intersect with ?\n\nWith all those x_j, for which v_j <= v_i\n\nMaintain a segment tree where the indices are the velocities and the values are pairs\n(number of points, sum of points) which have this velocity.\n\nFor any given point x_j, we will take the sum in the range [1, v_i]\n\nThe answer will increase by\n\nNumber_of_points*x_i - Sum(x)\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nstruct Point\n{\n    long long distance, velocity;\n\n    Point(){};\n\n    Point(long long D, long long V)\n    {\n        distance = D;\n        velocity = V;\n    }\n};\n\nint sort_by_distance(const Point &P, const Point &Q)\n{\n    return (P.distance < Q.distance);\n}\n\nconst int MAX_N = 2e5 + 5;\npair <long long, int> sum_tree[3*MAX_N];\n\nvoid update(int n, int left, int right, int position, long long value)\n{\n    if(position < left || right < position)\n    {\n        return;\n    }\n\n    if(left == right)\n    {\n        sum_tree[n].first += value;\n        sum_tree[n].second++;\n\n        //cout << \"Sum Tree \" << n << \" = \" << sum_tree[n].first << \",\" << sum_tree[n].second << \"\\n\";\n\n        return;\n    }\n\n    int mid = (left + right)/2;\n    update(LEFT(n), left, mid, position, value);\n    update(RIGHT(n), mid + 1, right, position, value);\n\n    sum_tree[n].second = sum_tree[LEFT(n)].second + sum_tree[RIGHT(n)].second;\n    sum_tree[n].first = sum_tree[LEFT(n)].first + sum_tree[RIGHT(n)].first;\n\n    //cout << \"Sum Tree \" << n << \" = \" << sum_tree[n].first << \",\" << sum_tree[n].second << \"\\n\";\n}\n\npair <long long, int> get(int n, int left, int right, int query_left, int query_right)\n{\n    if(query_right < left || right < query_left || query_right < query_left)\n    {\n        return make_pair(0, 0);\n    }\n\n    if(query_left <= left && right <= query_right)\n    {\n        return sum_tree[n];\n    }\n\n    int mid = (left + right)/2;\n    pair <long long, int> left_answer = get(LEFT(n), left, mid, query_left, query_right);\n    pair <long long, int> right_answer = get(RIGHT(n), mid + 1, right, query_left, query_right);\n\n    pair <long long, int> answer;\n\n    answer.second = left_answer.second + right_answer.second;\n    answer.first = left_answer.first + right_answer.first;\n\n    return answer;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_points;\n    cin >> no_of_points;\n\n    vector <Point> P(no_of_points);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> P[i].distance;\n    }\n\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> P[i].velocity;\n    }\n\n    sort(all(P), sort_by_distance);\n\n    vector <int> velocities;\n    for(int i = 0; i < no_of_points; i++)\n    {\n        velocities.push_back(P[i].velocity);\n    }\n\n    sort(all(velocities));\n\n    map <long long, int> effective_index;\n    effective_index[velocities[0]] = 1;\n\n    for(int i = 1; i < no_of_points; i++)\n    {\n        if(velocities[i] == velocities[i - 1])\n        {\n            continue;\n        }\n\n        effective_index[velocities[i]] = effective_index[velocities[i - 1]] + 1;\n    }\n\n    for(int i = 0; i < 3*MAX_N; i++)\n    {\n        sum_tree[i] = make_pair(0, 0);\n    }\n\n    long long answer = 0;\n\n    for(int i = 0; i < no_of_points; i++)\n    {\n        pair <long long, int> Q = get(1, 1, no_of_points, 1, effective_index[P[i].velocity]);\n\n        long long total = Q.first;\n        int no_of_points_here = Q.second;\n\n        //cout << \"At x = \" << P[i].distance << \" V = \" << P[i].velocity << \"\\n\";\n        //cout << \"No of Points = \" << no_of_points_here << \" Total = \" << total << \"\\n\";\n        //cout << \"Range = [1, \" << effective_index[P[i].velocity] - 1 << \"]\\n\";\n\n        answer += ( (no_of_points_here)*P[i].distance - total);\n\n        //cout << \"Answer = \" << answer << \"\\n\";\n        update(1, 1, no_of_points, effective_index[P[i].velocity], P[i].distance);\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Explanations/Perform the Combo Explanation.txt",
    "content": "Whenever there is a mistake at position i, we will add the frequency[a] in [1, i] to answer[a]\n\nWe will add the frequency of every alphabet to it's answer at the end as well\n\n-----\n\n1. We will sort P\n\n2. We will keep track of the frequency of each letter\nas we go from left to right.\n\n3. If i is a position where there is a mistake,\nthen we will add the frequency[1, P] of every alphabet to the total number of times the alphabet is no_of_hit\n\n-----\n\nvoid solve()\n{\n    int length, no_of_tries;\n    cin >> length >> no_of_tries;\n\n    string S;\n    cin >> S;\n\n    vector <int> P(no_of_tries + 1);\n    for(int i = 1; i <= no_of_tries; i++)\n    {\n        cin >> P[i];\n    }\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <long long> no_of_hits(NO_OF_ALPHABETS, 0);\n    vector <long long> frequency(NO_OF_ALPHABETS, 0);\n\n    sort(all(P));\n    vector <long long> no_of_mistakes_here(length + 1, 0);\n    for(int i = 1; i <= no_of_tries; i++)\n    {\n        no_of_mistakes_here[P[i] - 1]++;\n    }\n    no_of_mistakes_here[length - 1] = 1;\n\n    for(int i = 0, j = 1; i < length; i++)\n    {\n        frequency[S[i] - 'a']++;\n\n        if( (j <= no_of_tries && i + 1 == P[j]) || i + 1 == length)\n        {\n            for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n            {\n                no_of_hits[alpha] += no_of_mistakes_here[i]*frequency[alpha];\n                //cout << \"F\" << alpha << \" = \" << no_of_hits[alpha] << \"\\n\";\n            }\n\n            while(j <= no_of_tries && i + 1 == P[j])\n            {\n                j++;\n            }\n        }\n    }\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        cout << no_of_hits[alpha] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Explanations/Three Integers Explanation.txt",
    "content": "Let us fix some value of a.\n\nWe will iterate over the multiples of a to choose b\n\nAnd then, we will iterate over the multiples of b to choose c\n\nI set the limit as 4 x 10^4\n\nIt is enough to make the limit 2 x 10^4\n\nThe reason is that we never need to fix a for any value greater than 2a.\n\nSuppose there is some triplet (a', b', c') where a' > 2a, then we can replace it by\n(1, b', c') and that satisfies the same condition with a lower number of moves.\n\n-----\n\nvoid solve()\n{\n    const int oo = 1e9, LIMIT = 4e4;\n\n    int a, b, c;\n    cin >> a >> b >> c;\n\n    int best_moves = oo;\n    int x = a, y = b, z = c;\n\n    for(int i = 1; i <= LIMIT; i++)\n    {\n        for(int j = i; j <= LIMIT; j += i)\n        {\n            for(int k = j; k <= LIMIT; k += j)\n            {\n                int moves_here = abs(i - a) + abs(j - b) + abs(k - c);\n\n                if(moves_here < best_moves)\n                {\n                    best_moves = moves_here;\n\n                    x = i;\n                    y = j;\n                    z = k;\n                }\n            }\n        }\n    }\n\n    cout << best_moves << \"\\n\";\n    cout << x << \" \" << y << \" \" << z << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Explanations/WeirdSort Explanation.txt",
    "content": "There are some segments inside which we can conduct swaps.\nElements can never go outside these segments.\n\nWe will sort each of these segments and then check if the entire array is sorted.\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, m;\n    cin >> no_of_elements >> m;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> is_allowed(no_of_elements + 1, false);\n    vector <int> P(m + 1);\n    for(int i = 1; i <= m; i++)\n    {\n        cin >> P[i];\n\n        is_allowed[P[i]] = true;\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(!is_allowed[i])\n        {\n            continue;\n        }\n\n        int j = i;\n        while(j <= no_of_elements && is_allowed[j])\n        {\n            j++;\n        }\n\n        sort(A.begin() + i, A.begin() + j + 1);\n    }\n\n    int is_possible_to_sort = true;\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(A[i] > A[i + 1])\n        {\n            is_possible_to_sort = false;\n        }\n    }\n\n    cout << (is_possible_to_sort ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Programs/Add Odd or Subtract Even.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long a, b;\n    cin >> a >> b;\n    \n    long long d = (b - a);\n    \n    int moves = 0;\n    \n    if(d < 0)\n    {\n        moves = (d%2 == 0 ? 1 : 2);\n    }\n    else if(d > 0)\n    {\n        moves = (d%2 == 1 ? 1 : 2);\n    }\n    \n    cout << moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Programs/Construct the Binary Tree.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_power_of_2(int n)\n{\n    return ( (n&(n - 1)) == 0 );\n}\n\nvoid solve()\n{\n    int no_of_vertices, total_depth_sum;\n    cin >> no_of_vertices >> total_depth_sum;\n    \n    long long maximum_sum = (no_of_vertices*(no_of_vertices - 1))/2;\n    long long minimum_sum = 0;\n    for(int i = 1, level = 0; i <= no_of_vertices; i++)\n    {\n        if(is_power_of_2(i))\n        {\n            level++;\n        }\n        \n        minimum_sum += (level - 1);\n    }\n    \n    if(total_depth_sum < minimum_sum || maximum_sum < total_depth_sum)\n    {\n        cout << \"NO\\n\";\n        \n        return;\n    }\n    \n    vector <int> depth(no_of_vertices + 1, 0);\n    vector <int> parent(no_of_vertices + 1, 0);\n    vector <int> no_of_children(no_of_vertices + 1, 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        parent[i] = i - 1;\n        depth[i] = i - 1;\n    }\n    \n    no_of_children[no_of_vertices] = 0;\n    \n    vector <int> immobile(no_of_vertices + 1, false);\n    \n    for(long long sum = maximum_sum; sum > total_depth_sum; )\n    {\n        int first_v = 0;\n        for(int i = 1; i <= no_of_vertices; i++)\n        {\n            if(!immobile[i] && no_of_children[i] == 0 &&\n               (first_v == 0 || depth[i] < depth[first_v]))\n            {\n                first_v = i;\n            }\n        }\n        \n        int best_parent = 0;\n        for(int i = 1; i <= no_of_vertices; i++)\n        {\n            if(depth[i] == depth[first_v] - 2 && no_of_children[i] < 2)\n            {\n                best_parent = i;\n            }\n        }\n        \n        if(best_parent == 0)\n        {\n            immobile[first_v] = true;\n            continue;\n        }\n        \n        sum--;\n        \n        no_of_children[parent[first_v]]--;\n        depth[first_v]--;\n        \n        parent[first_v] = best_parent;\n        no_of_children[best_parent]++;\n    }\n    \n    cout << \"YES\\n\";\n    for(int i = 2; i <= no_of_vertices; i++)\n    {\n        cout << parent[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Programs/Moving Points.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nstruct Point\n{\n    long long distance, velocity;\n    \n    Point(){};\n    \n    Point(long long D, long long V)\n    {\n        distance = D;\n        velocity = V;\n    }\n};\n\nint sort_by_distance(const Point &P, const Point &Q)\n{\n    return (P.distance < Q.distance);\n}\n\nconst int MAX_N = 2e5 + 5;\npair <long long, int> sum_tree[3*MAX_N];\n\nvoid update(int n, int left, int right, int position, long long value)\n{\n    if(position < left || right < position)\n    {\n        return;\n    }\n    \n    if(left == right)\n    {\n        sum_tree[n].first += value;\n        sum_tree[n].second++;\n        \n        //cout << \"Sum Tree \" << n << \" = \" << sum_tree[n].first << \",\" << sum_tree[n].second << \"\\n\";\n        \n        return;\n    }\n    \n    int mid = (left + right)/2;\n    update(LEFT(n), left, mid, position, value);\n    update(RIGHT(n), mid + 1, right, position, value);\n    \n    sum_tree[n].second = sum_tree[LEFT(n)].second + sum_tree[RIGHT(n)].second;\n    sum_tree[n].first = sum_tree[LEFT(n)].first + sum_tree[RIGHT(n)].first;\n    \n    //cout << \"Sum Tree \" << n << \" = \" << sum_tree[n].first << \",\" << sum_tree[n].second << \"\\n\";\n}\n\npair <long long, int> get(int n, int left, int right, int query_left, int query_right)\n{\n    if(query_right < left || right < query_left || query_right < query_left)\n    {\n        return make_pair(0, 0);\n    }\n    \n    if(query_left <= left && right <= query_right)\n    {\n        return sum_tree[n];\n    }\n    \n    int mid = (left + right)/2;\n    pair <long long, int> left_answer = get(LEFT(n), left, mid, query_left, query_right);\n    pair <long long, int> right_answer = get(RIGHT(n), mid + 1, right, query_left, query_right);\n    \n    pair <long long, int> answer;\n    \n    answer.second = left_answer.second + right_answer.second;\n    answer.first = left_answer.first + right_answer.first;\n    \n    return answer;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_points;\n    cin >> no_of_points;\n    \n    vector <Point> P(no_of_points);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> P[i].distance;\n    }\n    \n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> P[i].velocity;\n    }\n    \n    sort(all(P), sort_by_distance);\n    \n    vector <int> velocities;\n    for(int i = 0; i < no_of_points; i++)\n    {\n        velocities.push_back(P[i].velocity);\n    }\n    \n    sort(all(velocities));\n    \n    map <long long, int> effective_index;\n    effective_index[velocities[0]] = 1;\n    \n    for(int i = 1; i < no_of_points; i++)\n    {\n        if(velocities[i] == velocities[i - 1])\n        {\n            continue;\n        }\n        \n        effective_index[velocities[i]] = effective_index[velocities[i - 1]] + 1;\n    }\n    \n    for(int i = 0; i < 3*MAX_N; i++)\n    {\n        sum_tree[i] = make_pair(0, 0);\n    }\n    \n    long long answer = 0;\n    \n    for(int i = 0; i < no_of_points; i++)\n    {\n        pair <long long, int> Q = get(1, 1, no_of_points, 1, effective_index[P[i].velocity]);\n        \n        long long total = Q.first;\n        int no_of_points_here = Q.second;\n        \n        //cout << \"At x = \" << P[i].distance << \" V = \" << P[i].velocity << \"\\n\";\n        //cout << \"No of Points = \" << no_of_points_here << \" Total = \" << total << \"\\n\";\n        //cout << \"Range = [1, \" << effective_index[P[i].velocity] - 1 << \"]\\n\";\n        \n        answer += ( (no_of_points_here)*P[i].distance - total);\n        \n        //cout << \"Answer = \" << answer << \"\\n\";\n        update(1, 1, no_of_points, effective_index[P[i].velocity], P[i].distance);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Programs/Perform the Combo.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int length, no_of_tries;\n    cin >> length >> no_of_tries;\n    \n    string S;\n    cin >> S;\n    \n    vector <int> P(no_of_tries + 1);\n    for(int i = 1; i <= no_of_tries; i++)\n    {\n        cin >> P[i];\n    }\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <long long> no_of_hits(NO_OF_ALPHABETS, 0);\n    vector <long long> frequency(NO_OF_ALPHABETS, 0);\n    \n    sort(all(P));\n    vector <long long> no_of_mistakes_here(length + 1, 0);\n    for(int i = 1; i <= no_of_tries; i++)\n    {\n        no_of_mistakes_here[P[i] - 1]++;\n    }\n    no_of_mistakes_here[length - 1] = 1;\n    \n    for(int i = 0, j = 1; i < length; i++)\n    {\n        frequency[S[i] - 'a']++;\n        \n        if( (j <= no_of_tries && i + 1 == P[j]) || i + 1 == length)\n        {\n            for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n            {\n                no_of_hits[alpha] += no_of_mistakes_here[i]*frequency[alpha];\n                //cout << \"F\" << alpha << \" = \" << no_of_hits[alpha] << \"\\n\";\n            }\n            \n            while(j <= no_of_tries && i + 1 == P[j])\n            {\n                j++;\n            }\n        }\n    }\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        cout << no_of_hits[alpha] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Programs/Three Integers.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    const int oo = 1e9, LIMIT = 4e4;\n    \n    int a, b, c;\n    cin >> a >> b >> c;\n    \n    int best_moves = oo;\n    int x = a, y = b, z = c;\n    \n    for(int i = 1; i <= LIMIT; i++)\n    {\n        for(int j = i; j <= LIMIT; j += i)\n        {\n            for(int k = j; k <= LIMIT; k += j)\n            {\n                int moves_here = abs(i - a) + abs(j - b) + abs(k - c);\n                \n                if(moves_here < best_moves)\n                {\n                    best_moves = moves_here;\n                    \n                    x = i;\n                    y = j;\n                    z = k;\n                }\n            }\n        }\n    }\n    \n    cout << best_moves << \"\\n\";\n    cout << x << \" \" << y << \" \" << z << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/624 Div 3/Programs/Weirdsort.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, m;\n    cin >> no_of_elements >> m;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> is_allowed(no_of_elements + 1, false);\n    vector <int> P(m + 1);\n    for(int i = 1; i <= m; i++)\n    {\n        cin >> P[i];\n        \n        is_allowed[P[i]] = true;\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(!is_allowed[i])\n        {\n            continue;\n        }\n        \n        int j = i;\n        while(j <= no_of_elements && is_allowed[j])\n        {\n            j++;\n        }\n        \n        sort(A.begin() + i, A.begin() + j + 1);\n    }\n    \n    int is_possible_to_sort = true;\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(A[i] > A[i + 1])\n        {\n            is_possible_to_sort = false;\n        }\n    }\n    \n    cout << (is_possible_to_sort ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Explanations/Frog Jumps Explanation.txt",
    "content": "It is always best to only jump to the 'R'\n\nIf we jump from (i to j) to a L and then jump somewhere to k,\n\nwe could have have gone directly from (i to k) with a smaller step size.\n\nThe best path is to jump across the R's.\n\nThe answer is the largest distance between R's or the longest substring of L's\n\n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    int answer = 0, last_r = -1;\n    for(int i = 0; i <= S.size(); i++)\n    {\n        if(i == S.size() || S[i] == 'R')\n        {\n            answer = max(answer, i - last_r);\n\n            last_r = i;\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Explanations/Maximum White Subtree Explanation.txt",
    "content": "Firstly, we will write +1 in the white vertices and -1 in the black vertices. \n\nNow, the problem is reduced to finding the maximum sum of any subtree containing v for all v.\n\n-----\n\n1. We will find the maximum sum for the subtree rooted at v, for every vertex v\n\nWe will do this using a DFS function. We will add sum_from[child] to sum_from[v] only if sum_from[child] > 0\n\nvoid dfs(int v, int parent_v)\n{\n    sum_from[v] = (colour[v] == WHITE ? 1 : -1);\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n        \n        sum_from[v] += max(sum_from[child_v], 0);\n    }\n}\n\n------\n\n2. Now, a subtree containing v might also contain some of it's parents.\n\nOnce again, we will start from the root and go downwards. \n\nFor every vertex v, we will find out the value of sum_from[parent] without sum_from[v]\n\n(If Sum_from[v] > 0, then subtract sum_from[v] from sum_from[parent]. \nIf Sum_from[v] < 0, then no need to subtract as it was never added to sum_from[parent].)\n\nIf sum_from[parent] without sum_from[v] is > 0, then we will add it to sum_from[v] \n\nThe important invariant here is that we are going downwards from the arbitrary root we decided. \n\nIn the first DFS, we found out the maximum sum at subtree rooted at v 'downwards'\nIn the second DFS, we check if we can add some subtree of the parent as well 'upwards'\n\nWhen we have come to v, we have already found out the maximum sum at it's parent \nso we can be assured that it is the final answer for v\n\n-----\n\nvoid dfs_adjust(int v, int parent_v)\n{\n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        int parent_sum = sum_from[v];\n        \n        if(sum_from[child_v] > 0)\n        {\n            parent_sum -= sum_from[child_v];\n        }\n        \n        if(parent_sum > 0)\n        {\n            sum_from[child_v] += parent_sum;\n        }\n        \n        dfs_adjust(child_v, v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> colour[i];\n    }\n    \n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    dfs(1, 0);\n    dfs_adjust(1, 0);\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cout << sum_from[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Explanations/Pair of Topics Explanation.txt",
    "content": "1. If (A[i] + A[j] > B[i] + B[j]), we will re-write the sum to write\neach term as a function of index\n\nA[i] - B[i] > B[j] - A[j]\n\nA[i] - B[i] > -(A[j] - B[j])\n\n-----\n\n2. We will make another array V[i] = A[i] - B[i]\n\nNow, it is just like counting inversions so we can do this with a segment tree.\n\nThe range of the elements is too big so we will assign a 'rank' to each V[i] and -V[i]\n\n-----\n\n3. We will process elements 1 by 1 from i = 1 to N\n\nWhile inserting V[i], we will count the number of elements already processed from [-V[i] + 1, N]\n\nThen, we will add 1 to the position [V[i]], indicating we have processed it\n\n-----\n\nint main()\n{\n    int no_of_topics;\n    cin >> no_of_topics;\n\n    vector <int> A(no_of_topics + 1);\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> B(no_of_topics + 1);\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        cin >> B[i];\n    }\n\n    vector <long long> value(no_of_topics + 1);\n    vector <long long> sorted_value;\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        value[i] = A[i] - B[i];\n\n        sorted_value.push_back(value[i]);\n\n        sorted_value.push_back(-value[i]);\n    }\n\n    sort(all(sorted_value));\n\n    map <long long, int> effective_index;\n    for(int i = 0; i < sorted_value.size(); i++)\n    {\n        if(i == 0)\n        {\n            effective_index[sorted_value[i]] = 1;\n        }\n        else if(sorted_value[i] != sorted_value[i - 1])\n        {\n            effective_index[sorted_value[i]] = effective_index[sorted_value[i - 1]] + 1;\n        }\n    }\n\n    long long no_of_good_pairs = 0;\n\n    memset(sum_tree, 0, sizeof(sum_tree));\n\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        no_of_good_pairs += get_sum(1, 1, 2*no_of_topics, effective_index[-value[i]] + 1, 2*no_of_topics);\n\n        update(1, 1, 2*no_of_topics, effective_index[value[i]], 1);\n    }\n\n    cout << no_of_good_pairs << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Explanations/Sleeping Schedule Explanation.txt",
    "content": "Let f(i, s) be the maximum number of good sleeps from [i, n]\nif we sleep at time s on day i\n\nWe can compute this DP in O(N.H) time\n\n-----\n\nSuppose we start at time s on day i,\nthen we have 2 options for starting on day (i + 1).\nWe can either wait time = A[i + 1] or time = A[i + 1] - 1\n\n1. (S + A[i + 1])%H\n2. (S + A[i + 1] - 1)%H\n\nWe will look at the best value of f(i + 1, next_start) and\nupdate f(i, s) accordingly\n\n-----\n\nf(i, s) = (L <= S && S <= R) +\n            max{ f(i + 1, next_start_1), f(i + 1, next_start_2)}\n\nThe final answer = max{f(1, A[1]), f(1, A[1] - 1)}\n\nas there are only 2 options in the beginning\n\n-----\n\nint main()\n{\n    int no_of_times, no_of_hours, left, right;\n    cin >> no_of_times >> no_of_hours >> left >> right;\n\n    vector <int> A(no_of_times + 1, 0);\n    for(int i = 1; i <= no_of_times; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = no_of_times; i >= 1; i--)\n    {\n        if(i == no_of_times)\n        {\n            for(int start = 0; start < no_of_hours; start++)\n            {\n                max_ways[i][start] = (left <= start && start <= right);\n            }\n\n            continue;\n        }\n\n        for(int start = 0; start < no_of_hours; start++)\n        {\n            int next_start_1 = (start + A[i + 1])%no_of_hours;\n            int next_start_2 = (start + A[i + 1] - 1 + no_of_hours)%no_of_hours;\n\n            int best_next_start;\n\n            if(max_ways[i + 1][next_start_1] < max_ways[i + 1][next_start_2])\n            {\n                best_next_start = next_start_2;\n            }\n            else\n            {\n                best_next_start = next_start_1;\n            }\n\n            max_ways[i][start] = (left <= start && start <= right) + max_ways[i + 1][best_next_start];\n        }\n    }\n\n    int answer = max(max_ways[1][A[1]], max_ways[1][A[1] - 1]);\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Explanations/Yet Another Palindrome Problem Explanation.txt",
    "content": "There are 2 types of palindromes of length 3 -\n\n(axa) and (aaa)\n\n1. If we have any alphabet who's frequency is 3, we are done\n\n2. If we have any alphabet who's frequency is 2,\nwe can append any of the alphabets in between them.\n\nWe just have to be careful if frequency[A[i]] = 2 and (A[i] = A[i - 1])\nas there is no middle character\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    int palindrome_possible = false;\n    vector <int> frequency(no_of_elements + 1, 0);\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        frequency[A[i]]++;\n\n        if(frequency[A[i]] == 3)\n        {\n            palindrome_possible = true;\n        }\n\n        if(frequency[A[i]] == 2 && (i > 1 && A[i] != A[i - 1]) )\n        {\n            palindrome_possible = true;\n        }\n    }\n\n    cout << (palindrome_possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Explanations/Yet Another Tetris Problem Explanation.txt",
    "content": "1. Firstly, adding 2 does not do anything to the parity\n\n2. When we subtract 1 from every integer.\nIf there are x odd integers and (n - x) even integers, there will be\nx even integers and (n - x) odd integers.\n\n3. Ultimately, 0 is an even integer so we need N even integers.\nThis is not possible if there are both even and odd integers in the beginning\n\n-----\n\nConversely, it is always possible when all the integers have the same parity\n\nIn every addition step, we will try to make all other integers equal to the maximum integer\n\nAs the process goes on till at least one A[i] > 0, we will always try to make the other columns = maximum column\n\n-----\n\nvoid solve()\n{\n    int no_of_columns;\n    cin >> no_of_columns;\n\n    const int MAX_HEIGHT = 105;\n    vector <int> frequency(2, 0);\n    vector <int> height(no_of_columns + 1);\n    for(int i = 1; i <= no_of_columns; i++)\n    {\n        cin >> height[i];\n\n        frequency[height[i]%2]++;\n    }\n\n    cout << (frequency[0] == 0 || frequency[1] == 0 ? \"YES\\n\" : \"NO\\n\");\n\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Programs/Frog Jumps.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    int answer = 0, last_r = -1;\n    for(int i = 0; i <= S.size(); i++)\n    {\n        if(i == S.size() || S[i] == 'R')\n        {\n            answer = max(answer, i - last_r);\n            \n            last_r = i;\n        }\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Programs/Maximum White Subtree.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5, WHITE = 1, BLACK = 0;\nvector <int> tree[MAX_N];\nint colour[MAX_N], sum_from[MAX_N];\n\nvoid dfs(int v, int parent_v)\n{\n    sum_from[v] = (colour[v] == WHITE ? 1 : -1);\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n        \n        sum_from[v] += max(sum_from[child_v], 0);\n    }\n}\n\nvoid dfs_adjust(int v, int parent_v)\n{\n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        int parent_sum = sum_from[v];\n        \n        if(sum_from[child_v] > 0)\n        {\n            parent_sum -= sum_from[child_v];\n        }\n        \n        if(parent_sum > 0)\n        {\n            sum_from[child_v] += parent_sum;\n        }\n        \n        dfs_adjust(child_v, v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> colour[i];\n    }\n    \n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    dfs(1, 0);\n    dfs_adjust(1, 0);\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cout << sum_from[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Programs/Pair of Topics.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n#include <cstring>\n\n#define all(v) (v).begin(), (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nconst int MAX_N = 1e6 + 5;\nint sum_tree[3*MAX_N];\n\nvoid update(int n, int left, int right, int position, int value)\n{\n    if(position < left || right < position)\n    {\n        return;\n    }\n    \n    if(left == right)\n    {\n        sum_tree[n] += value;\n        \n        return;\n    }\n    \n    int mid = (left + right)/2;\n    \n    update(LEFT(n), left, mid, position, value);\n    update(RIGHT(n), mid + 1, right, position, value);\n    \n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\n}\n\nint get_sum(int n, int left, int right, int query_left, int query_right)\n{\n    if(right < left || query_right < left || right < query_left)\n    {\n        return 0;\n    }\n    \n    if(query_left <= left && right <= query_right)\n    {\n        return sum_tree[n];\n    }\n    \n    int mid = (left + right)/2;\n    int left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\n    int right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\n    \n    return (left_sum + right_sum);\n}\n\nint main()\n{\n    int no_of_topics;\n    cin >> no_of_topics;\n    \n    vector <int> A(no_of_topics + 1);\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_topics + 1);\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        cin >> B[i];\n    }\n    \n    vector <long long> value(no_of_topics + 1);\n    vector <long long> sorted_value;\n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        value[i] = A[i] - B[i];\n        \n        sorted_value.push_back(value[i]);\n        \n        sorted_value.push_back(-value[i]);\n    }\n    \n    sort(all(sorted_value));\n    \n    map <long long, int> effective_index;\n    for(int i = 0; i < sorted_value.size(); i++)\n    {\n        if(i == 0)\n        {\n            effective_index[sorted_value[i]] = 1;\n        }\n        else if(sorted_value[i] != sorted_value[i - 1])\n        {\n            effective_index[sorted_value[i]] = effective_index[sorted_value[i - 1]] + 1;\n        }\n    }\n    \n    long long no_of_good_pairs = 0;\n    \n    memset(sum_tree, 0, sizeof(sum_tree));\n    \n    for(int i = 1; i <= no_of_topics; i++)\n    {\n        no_of_good_pairs += get_sum(1, 1, 2*no_of_topics, effective_index[-value[i]] + 1, 2*no_of_topics);\n    \n        update(1, 1, 2*no_of_topics, effective_index[value[i]], 1);\n    }\n    \n    cout << no_of_good_pairs << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Programs/Sleeping Schedule.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2005;\nint max_ways[MAX_N][MAX_N];\n\nint main()\n{\n    int no_of_times, no_of_hours, left, right;\n    cin >> no_of_times >> no_of_hours >> left >> right;\n    \n    vector <int> A(no_of_times + 1, 0);\n    for(int i = 1; i <= no_of_times; i++)\n    {\n        cin >> A[i];\n    }\n    \n    for(int i = no_of_times; i >= 1; i--)\n    {\n        if(i == no_of_times)\n        {\n            for(int start = 0; start < no_of_hours; start++)\n            {\n                max_ways[i][start] = (left <= start && start <= right);\n            }\n            \n            continue;\n        }\n        \n        for(int start = 0; start < no_of_hours; start++)\n        {\n            int next_start_1 = (start + A[i + 1])%no_of_hours;\n            int next_start_2 = (start + A[i + 1] - 1 + no_of_hours)%no_of_hours;\n            \n            int best_next_start;\n            \n            if(max_ways[i + 1][next_start_1] < max_ways[i + 1][next_start_2])\n            {\n                best_next_start = next_start_2;\n            }\n            else\n            {\n                best_next_start = next_start_1;\n            }\n            \n            max_ways[i][start] = (left <= start && start <= right) + max_ways[i + 1][best_next_start];\n        }\n    }\n    \n    int answer = max(max_ways[1][A[1]], max_ways[1][A[1] - 1]);\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Programs/Yet Another Palindrome Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    int palindrome_possible = false;\n    vector <int> frequency(no_of_elements + 1, 0);\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        frequency[A[i]]++;\n        \n        if(frequency[A[i]] == 3)\n        {\n            palindrome_possible = true;\n        }\n        \n        if(frequency[A[i]] == 2 && (i > 1 && A[i] != A[i - 1]) )\n        {\n            palindrome_possible = true;\n        }\n    }\n    \n    cout << (palindrome_possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/627 Div 3/Programs/Yet Another Tetris Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_columns;\n    cin >> no_of_columns;\n    \n    const int MAX_HEIGHT = 105;\n    vector <int> frequency(2, 0);\n    vector <int> height(no_of_columns + 1);\n    for(int i = 1; i <= no_of_columns; i++)\n    {\n        cin >> height[i];\n        \n        frequency[height[i]%2]++;\n    }\n    \n    cout << (frequency[0] == 0 || frequency[1] == 0 ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Explanations/Carousel Explanation.txt",
    "content": "1. If all the characters have the same value, the answer is 1\n\n2. Otherwise, there are at least 2 characters requiring at least 2 colours.\nIf the length is even, then (1 2 1 2 1 2 .... ) achieves a 2 colouring\n\nIf the length is odd, then we will look for any pair (A[i], A[i + 1]) that have the same character. We will merge them into one point and then reduce it to our even case.\n\n3. Otherwise, there are no same neighbours and we colour it\n\n(1 2 1 2 1 2 ... 1 2 3)\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    set <int> distinct;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        distinct.insert(A[i]);\n    }\n\n    int no_of_colours = 1;\n    vector <int> colour(no_of_elements + 1, 1);\n\n    if(distinct.size() == 1)\n    {\n        no_of_colours = 1;\n        for(int i = 0; i < no_of_elements; i++)\n        {\n            colour[i] = 1;\n        }\n    }\n    else if(no_of_elements%2 == 0)\n    {\n        no_of_colours = 2;\n        for(int i = 0; i < no_of_elements; i++)\n        {\n            colour[i] = (i%2 == 0 ? 2 : 1);\n        }\n    }\n    else\n    {\n        no_of_colours = 2;\n\n        int equal_point = -1;\n        for(int i = 0; i < no_of_elements; i++)\n        {\n            if(A[i] == A[(i + 1)%no_of_elements])\n            {\n                equal_point = (i + 1)%no_of_elements;\n                break;\n            }\n        }\n\n        if(equal_point != -1)\n        {\n            for(int i = 0; i < no_of_elements; i++)\n            {\n                if(i < equal_point)\n                {\n                    colour[i] = (i%2 == 0 ? 2 : 1);\n                }\n                else if(i == equal_point)\n                {\n                    colour[i] = ((i + 1)%2 == 0 ? 2 : 1); //Same as Previous\n                }\n                else if(i > equal_point)\n                {\n                    colour[i] = (i%2 == 0 ? 1 : 2);\n                }\n            }\n        }\n        else\n        {\n            no_of_colours = 3;\n            for(int i = 0; i < no_of_elements; i++)\n            {\n                colour[i] = (i%2 == 0 ? 2 : 1);\n            }\n\n            colour[no_of_elements - 1] = 3;\n        }\n    }\n\n\n    cout << no_of_colours << \"\\n\";\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cout << colour[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Explanations/Divisibility Problem Explanation.txt",
    "content": "We will always try to make a = the next multiple of b\n\nWe just have to add enough to make a = 0 (mod b)\n\nIf a = 0 (mod b) already, then we do not need to add anything\n\n-----\n\nvoid solve()\n{\n    int a, b;\n    cin >> a >> b;\n\n    a %= b;\n\n    int answer = (a == 0 ? 0 : b - a);\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Explanations/Kth Beautiful String Explanation.txt",
    "content": "There can only be 2 b's\n\nLet us iterate over the position of the first b from the left.\n\nIf b is in position i, then the second b can be placed in (i - 1) positions.\n\nWhen b is in position 2, there can be 1 string\nWhen b is in position 3, there can be 2 strings\n\nAnd so on\n\n-----\n\nWe will keep changing the position of the first b till the number of strings is more than K\n\nOnce the number of substrings is more than K, we will find the position of the second b\n\n-----\n\nInitially, the second 'b' is at the position next to the first 'b'.\nSuppose the first 'b' is fixed at position 5,\n\nthen we can have\naaab baaa\naaab abaa\naaab aaba\naaab aaab\n\nWe will move the second 'b' (no_of_strings - k) positions from position 4\n\nSo, position_2 = position_1 - (no_of_strings - k) - 1\n\n------\n\nvoid solve()\n{\n    int length, k;\n    cin >> length >> k;\n\n    int position_1 = 0, position_2 = 0;\n    int string_position = 0;\n    for(int i = 2; i <= length; i++)\n    {\n        string_position += (i - 1);\n        if(string_position >= k)\n        {\n            position_1 = i;\n            break;\n        }\n    }\n\n    position_2 = position_1 - (string_position - k) - 1;\n\n    for(int i = length; i >= 1; i--)\n    {\n        cout << (i == position_1 || i == position_2 ? 'b' : 'a');\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Explanations/Ternary XOR Explanation.txt",
    "content": "1. Let us go digit by digit \n\n2. If T[i] = 2, Then, A[i] = 1 and B[i] = 1\n\n3. If T[i] = 1, then A[i] = 1 and B[i] = 0\n\nAfter doing this, we will do the following, \n\nWe will look for the first i, where A[i] > B[i] \n\nFor every j from that point, we will make A[i] = 0 and accordingly update B[i]\n\n-----\n\nSuppose, \n\nA = 110100011\nB = 110000010\n\nHere, A[4] > B[4] and A[i] = B[i] for 1 <= i <= 3\n\nAfter this, we can maintain the same XOR by just making everything in A = 0 \n\nA = 110100000\nB = 110000021\n\n-----\n\n#include <iostream>\n#include <algorithm>\n\n#define all(v) (v).begin(),(v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string X;\n    cin >> length >> X;\n    \n    string A, B;\n    for(int i = 0; i < X.size(); i++)\n    {\n        switch(X[i])\n        {\n            case '2' : A += '1'; B += '1'; break;\n            case '1' : A += '1'; B += '0'; break;\n            case '0' : A += '0'; B += '0'; break;\n        }\n    }\n    \n    for(int i = 0, is_equal = true; i < X.size(); i++)\n    {\n        if(is_equal)\n        {\n            if(A[i] != B[i])\n            {\n                is_equal = false;\n            }\n            \n            continue;\n        }\n        \n        if(A[i] == '1' && B[i] == '0')\n        {\n            A[i] = '0';\n            B[i] = '1';\n        }\n        \n        if(A[i] == '1' && B[i] == '1')\n        {\n            A[i] = '0';\n            B[i] = '2';\n        }\n    }\n    \n    cout << A << \"\\n\" << B << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Explanations/Tree Queries Explanation.txt",
    "content": "We have to make 2 elegant observations\n\nThe first observation is that we can replace all the vertices by it's parent\n\n1. If v lies on the path from [1, x], then it's parent, p[v] must also lie on this path\n2. If v does not lie on the path, then it has to be at a distance 1 from [1, x],\nwhich means that it's parent p[v] must lie on the path [1, x].\n\n-----\n\nSo, we will replace all the vertices except the root - 1 and the deepest vertex - v\nby it's parent.\n\nNow, we are given a list of vertices and must check if they all lie on the same path.\n\n-----\n\nWe can use a very important property of DFS here.\n\nWe will maintain a 'timer' and will keep track of the time we go 'in' to every vertex v\nand the time we go 'out' on every vertex v.\n\nIf vertex v lies in the subtree of vertex u, then\n\ntime_in[v] < time_in[u] and time_out[u] < time_out[v]\n\nWe have to check this for all the vertices in our path.\n\n-----\n\nOne thing to keep in mind is that in DFS for any two vertices,\n\n[time_in[v], time_out[v]] and [time_in[u], time_out[u]] will never 'intersect'.\n\nThey will either be completely disjoint or one will be contained inside the other.\n\nSo, we have to check that every vertex in our path completely contains the 'last' vertex v\n\nIf any vertex does not satisfy this, then a path is not possible. Otherwise, it is always possible\n\n-----\n\nvoid dfs(int v, int parent_v, int &time)\n{\n    time_in[v] = time++;\n\n    parent[v] = parent_v;\n    depth[v] = depth[parent_v] + 1;\n\n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        dfs(child_v, v, time);\n    }\n\n    time_out[v] = time++;\n}\n\nvoid solve()\n{\n    int no_of_query_vertices;\n    cin >> no_of_query_vertices;\n\n    vector <int> v(no_of_query_vertices + 1);\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        cin >> v[i];\n    }\n\n    int max_depth = 0;\n    int last_v = 0;\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        if(depth[v[i]] > max_depth)\n        {\n            max_depth = depth[v[i]];\n            last_v = v[i];\n        }\n    }\n\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        if(v[i] == last_v || v[i] == 1)\n        {\n            continue;\n        }\n\n        v[i] = parent[v[i]];\n    }\n\n    int lies_on_one_path = true;\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        //cout << \"V = \" << v[i] << \" Time In = \" << time_in[v[i]] << \" Time Out = \" << time_out[v[i]] << \"\\n\";\n        if(time_in[v[i]] > time_out[last_v] || time_out[v[i]] < time_in[last_v])\n        {\n            lies_on_one_path = false;\n        }\n    }\n\n    cout << (lies_on_one_path ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_vertices, no_of_queries;\n    cin >> no_of_vertices >> no_of_queries;\n\n    tree.resize(no_of_vertices + 1);\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n\n    parent.resize(no_of_vertices + 1);\n    depth.resize(no_of_vertices + 1);\n    time_in.resize(no_of_vertices + 1);\n    time_out.resize(no_of_vertices + 1);\n\n    int time = 0;\n    dfs(1, 0, time);\n\n    /*for(int v = 1; v <= no_of_vertices; v++)\n    {\n        cout << \"V = \" << v << \" Time in = \" << time_in[v] << \" Time out = \" << time_out[v] << \"\\n\";\n    }*/\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        solve();\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Programs/Carousel.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    set <int> distinct;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        distinct.insert(A[i]);\n    }\n    \n    int no_of_colours = 1;\n    vector <int> colour(no_of_elements + 1, 1);\n    \n    if(distinct.size() == 1)\n    {\n        no_of_colours = 1;\n        for(int i = 0; i < no_of_elements; i++)\n        {\n            colour[i] = 1;\n        }\n    }\n    else if(no_of_elements%2 == 0)\n    {\n        no_of_colours = 2;\n        for(int i = 0; i < no_of_elements; i++)\n        {\n            colour[i] = (i%2 == 0 ? 2 : 1);\n        }\n    }\n    else\n    {\n        no_of_colours = 2;\n        \n        int equal_point = -1;\n        for(int i = 0; i < no_of_elements; i++)\n        {\n            if(A[i] == A[(i + 1)%no_of_elements])\n            {\n                equal_point = (i + 1)%no_of_elements;\n                break;\n            }\n        }\n        \n        if(equal_point != -1)\n        {\n            for(int i = 0; i < no_of_elements; i++)\n            {\n                if(i < equal_point)\n                {\n                    colour[i] = (i%2 == 0 ? 2 : 1);\n                }\n                else if(i == equal_point)\n                {\n                    colour[i] = ((i + 1)%2 == 0 ? 2 : 1); //Same as Previous\n                }\n                else if(i > equal_point)\n                {\n                    colour[i] = (i%2 == 0 ? 1 : 2);\n                }\n            }\n        }\n        else\n        {\n            no_of_colours = 3;\n            for(int i = 0; i < no_of_elements; i++)\n            {\n                colour[i] = (i%2 == 0 ? 2 : 1);\n            }\n            \n            colour[no_of_elements - 1] = 3;\n        }\n    }\n    \n    \n    cout << no_of_colours << \"\\n\";\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cout << colour[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Programs/Divisibility Problem.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int a, b;\n    cin >> a >> b;\n    \n    a %= b;\n    \n    int answer = (a == 0 ? 0 : b - a);\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Programs/Kth Beautiful String.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, k;\n    cin >> length >> k;\n    \n    int position_1 = 0, position_2 = 0;\n    int string_position = 0;\n    for(int i = 2; i <= length; i++)\n    {\n        string_position += (i - 1);\n        if(string_position >= k)\n        {\n            position_1 = i;\n            break;\n        }\n    }\n    \n    position_2 = position_1 - (string_position - k) - 1;\n    \n    for(int i = length; i >= 1; i--)\n    {\n        cout << (i == position_1 || i == position_2 ? 'b' : 'a');\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Programs/Ternary XOR.cpp",
    "content": "#include <iostream>\n#include <algorithm>\n\n#define all(v) (v).begin(),(v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string X;\n    cin >> length >> X;\n    \n    string A, B;\n    for(int i = 0; i < X.size(); i++)\n    {\n        switch(X[i])\n        {\n            case '2' : A += '1'; B += '1'; break;\n            case '1' : A += '1'; B += '0'; break;\n            case '0' : A += '0'; B += '0'; break;\n        }\n    }\n    \n    for(int i = 0, is_equal = true; i < X.size(); i++)\n    {\n        if(is_equal)\n        {\n            if(A[i] != B[i])\n            {\n                is_equal = false;\n            }\n            \n            continue;\n        }\n        \n        if(A[i] == '1' && B[i] == '0')\n        {\n            A[i] = '0';\n            B[i] = '1';\n        }\n        \n        if(A[i] == '1' && B[i] == '1')\n        {\n            A[i] = '0';\n            B[i] = '2';\n        }\n    }\n    \n    cout << A << \"\\n\" << B << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/629 Div 3/Programs/Tree Queries.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector <int> parent, time_in, time_out, depth;\nvector <vector <int> > tree;\n\nvoid dfs(int v, int parent_v, int &time)\n{\n    time_in[v] = time++;\n    \n    parent[v] = parent_v;\n    depth[v] = depth[parent_v] + 1;\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v, time);\n    }\n    \n    time_out[v] = time++;\n}\n\nvoid solve()\n{\n    int no_of_query_vertices;\n    cin >> no_of_query_vertices;\n    \n    vector <int> v(no_of_query_vertices + 1);\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        cin >> v[i];\n    }\n    \n    int max_depth = 0;\n    int last_v = 0;\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        if(depth[v[i]] > max_depth)\n        {\n            max_depth = depth[v[i]];\n            last_v = v[i];\n        }\n    }\n    \n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        if(v[i] == last_v || v[i] == 1)\n        {\n            continue;\n        }\n        \n        v[i] = parent[v[i]];\n    }\n    \n    int lies_on_one_path = true;\n    for(int i = 1; i <= no_of_query_vertices; i++)\n    {\n        //cout << \"V = \" << v[i] << \" Time In = \" << time_in[v[i]] << \" Time Out = \" << time_out[v[i]] << \"\\n\";\n        if(time_in[v[i]] > time_out[last_v] || time_out[v[i]] < time_in[last_v])\n        {\n            lies_on_one_path = false;\n        }\n    }\n    \n    cout << (lies_on_one_path ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_vertices, no_of_queries;\n    cin >> no_of_vertices >> no_of_queries;\n    \n    tree.resize(no_of_vertices + 1);\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    parent.resize(no_of_vertices + 1);\n    depth.resize(no_of_vertices + 1);\n    time_in.resize(no_of_vertices + 1);\n    time_out.resize(no_of_vertices + 1);\n    \n    int time = 0;\n    dfs(1, 0, time);\n    \n    /*for(int v = 1; v <= no_of_vertices; v++)\n    {\n        cout << \"V = \" << v << \" Time in = \" << time_in[v] << \" Time out = \" << time_out[v] << \"\\n\";\n    }*/\n    \n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        solve();\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Explanations/Anti Sudoku Explanation.txt",
    "content": "There is a very elegant solution.\nWe can replace all the 1's with 2's.\n\nIn fact, we can take any digit and replace it with some other digit.\nSince, each digit occurs once in every row, column and box,\nreplacing their occurences, leads to 2 of some digit in every row, column and box\n\n-----\n\nMy solution was a little different from this thought.\nWe can create a bijection between any two solved Sudoku's\n\nWe can always relabel 1 Sudoku to get another.\nFor example, if we want to create a Sudoku where the top line is\n123456789\n\nThen, we can take some solved Sudoku\nWhatever is in the first cell, we will relabel it with 1\nWhatever is in the second cell, we will relabel it with 2\nand so on\n\nSo, they have already given the solution for 1 Sudoku puzzle\n\n-----\n\n1. We will reduce the Sudoku puzzle in the question to the one we have\n2. We will use the solution of this Sudoku puzzle to create the solution of that\nSudoku puzzle\n\n-----\n\nvoid solve()\nWe\n{\n    const int MAX_N = 9;\n    vector <string> grid(MAX_N);\n    for(int i = 0; i < MAX_N; i++)\n    {\n        cin >> grid[i];\n    }\n\n    /* Make it equivalent to this\n     154873296\n     386592714\n     729641835\n     863725149\n     975314628\n     412968357\n     631457982\n     598236471\n     247189563*/\n\n    /*Make it equivalent to this -\n     154873396\n     336592714\n     729645835\n     863725145\n     979314628\n     412958357\n     631457992\n     998236471\n     247789563*/\n    grid[0][6] = grid[0][5];\n    grid[1][1] = grid[1][0];\n    grid[2][5] = grid[2][8];\n    grid[3][8] = grid[3][5];\n    grid[4][2] = grid[4][0];\n    grid[5][4] = grid[5][7];\n    grid[6][7] = grid[6][8];\n    grid[7][0] = grid[7][1];\n    grid[8][3] = grid[8][2];\n\n    for(int i = 0; i < MAX_N; i++)\n    {\n        cout << grid[i] << \"\\n\";;\n    }\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Explanations/Candies and Two Sisters Explanation.txt",
    "content": "a lies in [n/2, n - 1] and b lies in [n/2, 1]\n\nWhen n is even, then we cannot use n/2. So, answer is (n/2 - 1)\n\nOtherwise answer is (n/2)\n\n----\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n\n    long long no_of_ways = (n/2) - (n%2 == 0 ? 1 : 0);\n    cout << no_of_ways << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Explanations/Construct the String Explanation.txt",
    "content": "We will place blocks of length A\n\nThe block with have (b - 1) distinct letters followed by (a - b) occurences of b\n\nFor example here is a block with 5 distinct characters of length 9\n\nabcdeeeee\n\nWe will simply place blocks like this next to each other.\n\nWhen we slide the window, if the right pointer adds a new distinct character,\nthe left pointer removes a new distinct character.\n\nThis ensures every window of length A has B distinct characters\n\n-----\n\nvoid solve()\n{\n    int length, substring, distinct;\n    cin >> length >> substring >> distinct;\n\n    string S;\n    for(int i = 0; i < length; i++)\n    {\n        if(i < substring)\n        {\n            if(i < distinct)\n            {\n                S += (char)('a' + i);\n            }\n            else\n            {\n                S += S.back();\n            }\n        }\n        else\n        {\n            S += S[i - substring];\n        }\n    }\n\n    cout << S << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Explanations/Robots on a Grid Explanation.txt",
    "content": "Fact - If 2 Robots intersect, they will do so in the first NM moves\n\nOnce two robots meet, they will always move together.\nSo, if they meet in <= NM moves, they will be together after NM moves.\n\nLet us look at the structure of the graph.\nIt is a functional graph where each vertex has exactly one outgoing edge.\nSo, the graph consists of some cycles and some tress which go into cycles.\nAs the graph has MN vertices in total, after MN moves,\nevery robot will be inside a cycle. \n(The length of the path going into a cycle cannot be greater than MN).\n\nIf 2 robots are inside a cycle and not coincident, they will never meet\nsince they move an equal distance in the same direction each time\nand the distance between them remains constant !\n\n----\n\nNow, how do we find out where a Robot ends up in NM moves ?\nWe can use binary lifting for this.\n\n1. We will do a DFS and find out f(0, i, j), that is where the robot at\ncell (i, j) goes in 2^0 = 1 move\n\n2. Then, we will use it to recursively build this table\n\nf(L, i, j) = f(L - 1, f(L - 1, i, j))\n\nThat is we will see where we go from (i, j) in 2^{L - 1} steps\nAnd we will see where we will reach if we take 2^{L - 1} steps from there\n\n2^{L - 1} + 2^{L - 1} = 2^L\n\n-----\n\nThis table is built is O(NM log(NM)) time\n\nFor every (NM) cells, we will find out the ultimate destination it is in after\n(NM) steps\n\n-----\n\nFor every cell, we will keep track of the number of\nblack and white cells which reach here after (NM) moves.\n\nSince robots can never meet, if there are multiple robots finishing at (i, j),\nonly one of them can be in the initial grid.\nIf possible, we will choose a black square robot.\n\nOnce we are done, we will scan all NM squares\nIf black_starts(i, j) > 0, then we will update the number of black robots\nIf white_starts(i, j) > 0, then we will update the number of white robots\n\n------\n\nint get_next(int x, int y)\n{\n    switch(S[x][y])\n    {\n        case 'U' : return label(x - 1, y);\n        case 'R' : return label(x, y + 1);\n        case 'L' : return label(x, y - 1);\n        case 'D' : return label(x + 1, y);\n    }\n\n    return 0;\n}\n\nvoid dfs(int v)\n{\n    if(visited[v])\n    {\n        return;\n    }\n\n    visited[v] = true;\n\n    int x = v/columns, y = v%columns;\n\n    int next = get_next(x, y);\n    //cout << \"At \" << v << \" \" << x << \",\" << y << \" Next = \" << next << \"\\n\";\n    step[0][v] = next;\n\n    dfs(next);\n}\n\nvoid solve()\n{\n    cin >> rows >> columns;\n\n    colour.resize(rows);\n    for(int i = 0; i < rows; i++)\n    {\n        cin >> colour[i];\n    }\n\n    S.resize(rows);\n    for(int i = 0; i < rows; i++)\n    {\n        cin >> S[i];\n    }\n\n    visited.resize(rows*columns, false);\n    for(int i = 0; i < rows*columns; i++)\n    {\n        visited[i] = false;\n    }\n\n    for(int i = 0; i < MAX_L; i++)\n    {\n        step[i].resize(rows*columns);\n    }\n\n    for(int v = 0; v < rows*columns; v++)\n    {\n        if(!visited[v])\n        {\n            dfs(v);\n        }\n    }\n\n    for(int l = 1; l < MAX_L; l++)\n    {\n        for(int i = 0; i < rows*columns; i++)\n        {\n            int previous_step = step[l - 1][i];\n\n            //cout << \"L = \" << l << \"Start at \" << i/columns << \",\" << i%columns << \" previous = \" << previous_step/columns << \",\" << previous_step%columns <<\" and finish at \" << step[l - 1][previous_step]/columns << \" \" << step[l - 1][previous_step]%columns << \"\\n\";\n\n            step[l][i] = step[l - 1][previous_step];\n        }\n    }\n\n    vector <int> black_starts(rows*columns);\n    vector <int> white_starts(rows*columns);\n    int total_steps = rows*columns;\n    for(int i = 0; i < rows*columns; i++)\n    {\n        int finish = i;\n\n        for(int bit = MAX_L - 1; bit >= 0; bit--)\n        {\n            if(is_bit_set(total_steps, bit))\n            {\n                finish = step[bit][finish];\n            }\n        }\n\n        const char BLACK = '0', WHITE = '1';\n        int start_x = i/columns, start_y = i%columns;\n        if(colour[start_x][start_y] == BLACK)\n        {\n            black_starts[finish]++;\n        }\n        else\n        {\n            white_starts[finish]++;\n        }\n\n        //cout << \"Start at \" << start_x << \",\" << start_y << \" and finish at \" << finish/columns << \" \" << finish%columns << \"\\n\";\n    }\n\n    int total = 0, black = 0;\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(black_starts[label(i, j)] > 0)\n            {\n                total++;\n                black++;\n            }\n            else if(white_starts[label(i, j)] > 0)\n            {\n                total++;\n            }\n        }\n    }\n\n    cout << total << \" \" << black << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Explanations/Three Blocks Palindrome Explanation.txt",
    "content": "Let us keep track of the positions of each of the alphabets.\n\nNow, we will iterate over the possible choices for the 'outer' alphabet.\n\nIf we take p of the alphabet, we should take p/2 of it's left most and p/2 of it's right most.\n\nWe will choose the alphabet which occurs most frequently in [L, R] gap as y\n\n-----\n\nThe trick here is that the outer 2 loops visits each letter at most once.\n\nSo the over complexity is O(n) even though it looks like it's O(n^2)\n\nTotal Complexity is O(n.AL) where AL is the size of the alphabet\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    int max_n = 0;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        max_n = max(max_n, A[i]);\n    }\n\n    vector <vector <int> > position(max_n + 1);\n    vector <vector <int> > frequency(max_n + 1, vector <int> (no_of_elements + 1, 0));\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        position[A[i]].push_back(i);\n\n        for(int alpha = 1; alpha <= max_n; alpha++)\n        {\n            frequency[alpha][i] = frequency[alpha][i - 1];\n        }\n\n        frequency[A[i]][i]++;\n    }\n\n    int answer = 0;\n    for(int i = 1; i <= max_n; i++)\n    {\n        answer = max(answer, position[i].size());\n\n        for(int p = 0; 2*p < position[i].size(); p++)\n        {\n            int left = position[i][p] + 1;\n            int right = position[i][position[i].size() - p - 1] - 1;\n\n            if(left > right)\n            {\n                break;\n            }\n\n            int max_middle = 0;\n            for(int middle = 1; middle <= max_n; middle++)\n            {\n                int middle_frequency = frequency[middle][right] - frequency[middle][left - 1];\n\n                max_middle = max(max_middle, middle_frequency);\n            }\n\n\n            answer = max(answer, 2*(p + 1) + max_middle);\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Explanations/Two Teams Composing Explanation.txt",
    "content": "We will iterate over all elements and check the cost if this element\nis the one in the same set.\n\n----\n\nThere are 2 possibilities -\n\n1. We put all it's occurences in the 'Same' bucket and all the distinct in the other\n\nThis is given by min(distinct - 1, frequency[A[i]])\n\n[1, 2, 3], [4, 4, 4]\n\n2. We put one of it's occurences in the 'Distinct' bucket and all else in the 'Same' bucket\n\nThis is given by min(distinct, frequency[A[i]] - 1)\n\n[1, 2, 3, 4] [4, 4, 4, 4]\n\n-----\n\nWe will iterate over all of them and choose the best\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    set <int> distinct;\n    map <int, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        distinct.insert(A[i]);\n        frequency[A[i]]++;\n    }\n\n    int team_size = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int team_size_here_1 = min(distinct.size() - 1, frequency[A[i]]);\n\n        int team_size_here_2 = min(distinct.size(), frequency[A[i]] - 1);\n\n        int team_size_here = max(team_size_here_1, team_size_here_2);\n\n        team_size = max(team_size, team_size_here);\n    }\n\n    cout << team_size << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Programs/Anti Sudoku.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    const int MAX_N = 9;\n    vector <string> grid(MAX_N);\n    for(int i = 0; i < MAX_N; i++)\n    {\n        cin >> grid[i];\n    }\n    \n    /* Make it equivalent to this\n     154873296\n     386592714\n     729641835\n     863725149\n     975314628\n     412968357\n     631457982\n     598236471\n     247189563*/\n    \n    /*Make it equivalent to this -\n     154873396\n     336592714\n     729645835\n     863725145\n     979314628\n     412958357\n     631457992\n     998236471\n     247789563*/\n    grid[0][6] = grid[0][5];\n    grid[1][1] = grid[1][0];\n    grid[2][5] = grid[2][8];\n    grid[3][8] = grid[3][5];\n    grid[4][2] = grid[4][0];\n    grid[5][4] = grid[5][7];\n    grid[6][7] = grid[6][8];\n    grid[7][0] = grid[7][1];\n    grid[8][3] = grid[8][2];\n    \n    for(int i = 0; i < MAX_N; i++)\n    {\n        cout << grid[i] << \"\\n\";;\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Programs/Candies and Two Sisters.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    long long no_of_ways = (n/2) - (n%2 == 0 ? 1 : 0);\n    cout << no_of_ways << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Programs/Construct the String.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, substring, distinct;\n    cin >> length >> substring >> distinct;\n    \n    string S;\n    for(int i = 0; i < length; i++)\n    {\n        if(i < substring)\n        {\n            if(i < distinct)\n            {\n                S += (char)('a' + i);\n            }\n            else\n            {\n                S += S.back();\n            }\n        }\n        else\n        {\n            S += S[i - substring];\n        }\n    }\n    \n    cout << S << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Programs/Robots on a Grid.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_L = 25;\n\nint rows, columns;\nvector <string> colour;\nvector <string> S;\nvector <vector <int> > step(MAX_L);\nvector <int> visited;\n\nint label(int x, int y)\n{\n    return x*columns + y;\n}\n\nint is_bit_set(int n, int bit)\n{\n    return ((n&(1 << bit)) != 0);\n}\n\nint get_next(int x, int y)\n{\n    switch(S[x][y])\n    {\n        case 'U' : return label(x - 1, y);\n        case 'R' : return label(x, y + 1);\n        case 'L' : return label(x, y - 1);\n        case 'D' : return label(x + 1, y);\n    }\n    \n    return 0;\n}\n\nvoid dfs(int v)\n{\n    if(visited[v])\n    {\n        return;\n    }\n    \n    visited[v] = true;\n    \n    int x = v/columns, y = v%columns;\n    \n    int next = get_next(x, y);\n    //cout << \"At \" << v << \" \" << x << \",\" << y << \" Next = \" << next << \"\\n\";\n    step[0][v] = next;\n    \n    dfs(next);\n}\n\nvoid solve()\n{\n    cin >> rows >> columns;\n    \n    colour.resize(rows);\n    for(int i = 0; i < rows; i++)\n    {\n        cin >> colour[i];\n    }\n    \n    S.resize(rows);\n    for(int i = 0; i < rows; i++)\n    {\n        cin >> S[i];\n    }\n    \n    visited.resize(rows*columns, false);\n    for(int i = 0; i < rows*columns; i++)\n    {\n        visited[i] = false;\n    }\n    \n    for(int i = 0; i < MAX_L; i++)\n    {\n        step[i].resize(rows*columns);\n    }\n    \n    for(int v = 0; v < rows*columns; v++)\n    {\n        if(!visited[v])\n        {\n            dfs(v);\n        }\n    }\n    \n    for(int l = 1; l < MAX_L; l++)\n    {\n        for(int i = 0; i < rows*columns; i++)\n        {\n            int previous_step = step[l - 1][i];\n            \n            //cout << \"L = \" << l << \"Start at \" << i/columns << \",\" << i%columns << \" previous = \" << previous_step/columns << \",\" << previous_step%columns <<\" and finish at \" << step[l - 1][previous_step]/columns << \" \" << step[l - 1][previous_step]%columns << \"\\n\";\n            \n            step[l][i] = step[l - 1][previous_step];\n        }\n    }\n    \n    vector <int> black_starts(rows*columns);\n    vector <int> white_starts(rows*columns);\n    int total_steps = rows*columns;\n    for(int i = 0; i < rows*columns; i++)\n    {\n        int finish = i;\n        \n        for(int bit = MAX_L - 1; bit >= 0; bit--)\n        {\n            if(is_bit_set(total_steps, bit))\n            {\n                finish = step[bit][finish];\n            }\n        }\n        \n        const char BLACK = '0', WHITE = '1';\n        int start_x = i/columns, start_y = i%columns;\n        if(colour[start_x][start_y] == BLACK)\n        {\n            black_starts[finish]++;\n        }\n        else\n        {\n            white_starts[finish]++;\n        }\n        \n        //cout << \"Start at \" << start_x << \",\" << start_y << \" and finish at \" << finish/columns << \" \" << finish%columns << \"\\n\";\n    }\n    \n    int total = 0, black = 0;\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(black_starts[label(i, j)] > 0)\n            {\n                total++;\n                black++;\n            }\n            else if(white_starts[label(i, j)] > 0)\n            {\n                total++;\n            }\n        }\n    }\n    \n    cout << total << \" \" << black << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Programs/Three Blocks Palindrome.cpp",
    "content": "#include <iostream>\n#include <vector>\n\n#define max(a, b) (a > b ? a : b)\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    int max_n = 0;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        max_n = max(max_n, A[i]);\n    }\n    \n    vector <vector <int> > position(max_n + 1);\n    vector <vector <int> > frequency(max_n + 1, vector <int> (no_of_elements + 1, 0));\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        position[A[i]].push_back(i);\n        \n        for(int alpha = 1; alpha <= max_n; alpha++)\n        {\n            frequency[alpha][i] = frequency[alpha][i - 1];\n        }\n        \n        frequency[A[i]][i]++;\n    }\n    \n    int answer = 0;\n    for(int i = 1; i <= max_n; i++)\n    {\n        answer = max(answer, position[i].size());\n        \n        for(int p = 0; 2*p < position[i].size(); p++)\n        {\n            int left = position[i][p] + 1;\n            int right = position[i][position[i].size() - p - 1] - 1;\n            \n            if(left > right)\n            {\n                break;\n            }\n            \n            int max_middle = 0;\n            for(int middle = 1; middle <= max_n; middle++)\n            {\n                int middle_frequency = frequency[middle][right] - frequency[middle][left - 1];\n                \n                max_middle = max(max_middle, middle_frequency);\n            }\n            \n    \n            answer = max(answer, 2*(p + 1) + max_middle);\n        }\n    }\n        \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/634 Div 3/Programs/Two Teams Composing.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n\n#define max(a, b) (a > b ? a : b)\n#define min(a, b) (a < b ? a : b)\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    set <int> distinct;\n    map <int, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        distinct.insert(A[i]);\n        frequency[A[i]]++;\n    }\n    \n    int team_size = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int team_size_here_1 = min(distinct.size() - 1, frequency[A[i]]);\n        \n        int team_size_here_2 = min(distinct.size(), frequency[A[i]] - 1);\n        \n        int team_size_here = max(team_size_here_1, team_size_here_2);\n        \n        team_size = max(team_size, team_size_here);\n    }\n    \n    cout << team_size << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/636 Div 3/Explanations/Constant Palindrome Sum Explanation.txt",
    "content": "Ultimately, the sum will be in [1, 2k]\n\nWe will iterate over all x in [1, 2k] and find the best x.\n\n-----\n\nThere are 3 types of pairs -\n\n1. Pairs with 0 changes\n2. Pairs with 1 changes\n3. Pairs with 2 changes\n\n----\n\nPairs with 0 changes are those pairs who's sum = x\n\nEvery pair can be changed to have sum = k\n\nPairs with 2 changes = Total pair - 1_change - 2_changes\n\nNow, we only need to count the number of pairs with exactly 1 change\n\n-----\n\nWe have a pair (A[i], A[n - i + 1])\n\nWhat are the possible sums we can get ?\n\nSuppose, without loss of generality, that A[i] < A[n - i + 1]\n\nThen, the smallest sum we can get is (A[i], 1)\nAnd, the largest sum we can get is (k, A[n - i + 1])\n\nWe can get every sum in the range [A[i] + 1, A[n - i + 1] + k]\n\n-----\n\nNow, let us discuss a different problems,\n\nWe have a list of lines -\n\n[L1, R1]\n[L2, R2]\n[L3, R3]\n.\n.\n[Ln, Rn]\n\nHow do we calculate the number of lines that cover the point x ?\n\nLet us say that a line [L, R] starts at point L and ends at point R\n\nThen, Lines Covering x = lines Covering (x - 1) + Lines starting from(x) - Lines ending at (x)\n\n-----\n\nWe can do 1 sweep and calculate the number of lines meeting at every x from [1, 2k]\n\n----\n\nOne thing to keep in mind is that the range [A[i] + 1, A[n - i + 1] + k] covers (A[i], A[n - i + 1])\n\nBut (A[i], A[n - i + 1]) requires 0 changes\n\nSo, the number of 1-changes for x = Lines Covering x - Frequency(x)\n\nThe number of 2-changes for x = (Total Pairs - Number of 1-changes - Number of 0-changes)\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> frequency(2*k + 1, 0);\n    for(int i = 1; i <= no_of_elements/2; i++)\n    {\n        frequency[A[i] + A[no_of_elements - i + 1]]++;\n    }\n\n    vector <int> lines_starting_at(2*k + 2);\n    vector <int> lines_ending_at(2*k + 2);\n    for(int i = 1; i <= no_of_elements/2; i++)\n    {\n        lines_starting_at[min(A[i], A[no_of_elements - i + 1]) + 1]++;\n        lines_ending_at[max(A[i], A[no_of_elements - i + 1]) + k + 1]++;\n    }\n\n    vector <int> lines_passing_through(2*k + 1, 0);\n    for(int i = 1; i <= 2*k; i++)\n    {\n        lines_passing_through[i] = lines_passing_through[i - 1] + lines_starting_at[i] - lines_ending_at[i];\n     }\n\n    int answer = no_of_elements;\n    for(int x = 1; x <= 2*k; x++)\n    {\n        int changes_1 = lines_passing_through[x] - frequency[x];\n        int changes_2 = no_of_elements/2 - changes_1 - frequency[x];\n\n        answer = min(answer, changes_1 + 2*changes_2);\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/636 Div 3/Programs/Constant Palindrome Sum.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> frequency(2*k + 1, 0);\n    for(int i = 1; i <= no_of_elements/2; i++)\n    {\n        frequency[A[i] + A[no_of_elements - i + 1]]++;\n    }\n    \n    vector <int> lines_starting_at(2*k + 2);\n    vector <int> lines_ending_at(2*k + 2);\n    for(int i = 1; i <= no_of_elements/2; i++)\n    {\n        lines_starting_at[min(A[i], A[no_of_elements - i + 1]) + 1]++;\n        lines_ending_at[max(A[i], A[no_of_elements - i + 1]) + k + 1]++;\n    }\n    \n    vector <int> lines_passing_through(2*k + 1, 0);\n    for(int i = 1; i <= 2*k; i++)\n    {\n        lines_passing_through[i] = lines_passing_through[i - 1] + lines_starting_at[i] - lines_ending_at[i];\n        \n        //cout << \"L \" << i << \" = \" << lines_passing_through[i] << \"\\n\";\n    }\n    \n    int answer = no_of_elements;\n    for(int x = 1; x <= 2*k; x++)\n    {\n        int changes_1 = lines_passing_through[x] - frequency[x];\n        int changes_2 = no_of_elements/2 - changes_1 - frequency[x];\n        \n        //cout << \"Changes 1 = \" << changes_1 << \" Changes 2 = \" << changes_2 << \" for \" << x << \"\\n\";\n        answer = min(answer, changes_1 + 2*changes_2);\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Explanations/Binary String to Subsequence Explanation.txt",
    "content": "Let us keep track of the list of available sequences ending with 1 and with 0 \n\nWhen we are at S[i], we will check if there are any available sequences ending with it's complement. \n\nIf there are, then we will match S[i] with that and update it accordingly. \n\nFor example, if S[i] = 0, and we have sequence number 3 ending with 1, we will append s[i] to the third sequence \n\n-----\n\nWe will maintain a set of all avaialable sequences ending with both numbers \n\nWhen we process S[i], we will check if it's complement is empty or if there is some available sequence \n\nWe will update it accordingly \n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    vector <int> sequence_no(length + 1);\n    set <int> available_label[2];\n    \n    int no_of_sequences = 1;\n    available_label[0].insert(1);\n    available_label[1].insert(1);\n    \n    for(int i = 0; i < length; i++)\n    {\n        int current = S[i] - '0';\n        int complement = 1 - current;\n        \n        if(available_label[complement].size() == 0)\n        {\n            no_of_sequences++;\n            \n            sequence_no[i] = no_of_sequences;\n            \n            available_label[current].insert(sequence_no[i]);\n        }\n        else\n        {\n            auto it = available_label[complement].begin();\n            \n            sequence_no[i] = *it;\n            \n            available_label[current].insert(sequence_no[i]);\n            \n            available_label[complement].erase(sequence_no[i]);\n        }\n    }\n    \n    cout << no_of_sequences << \"\\n\";\n    \n    for(int i = 0; i < length; i++)\n    {\n        cout << sequence_no[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Explanations/Boats Competition Explanation.txt",
    "content": "For each possible sum between [1, 2n], we will count the number of pairs that are possible.\n\nWe will do this by maintaining the frequency of each integer and then making as many matches as possible.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> frequency(2*no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n\n    int maximum_teams = 0;\n    for(int pair_sum = 1; pair_sum < 2*no_of_elements + 1; pair_sum++)\n    {\n        int max_teams_now = 0;\n\n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            if(pair_sum - i >= i)\n            {\n                if(i != pair_sum - i)\n                {\n                    max_teams_now += min(frequency[pair_sum - i], frequency[i]);\n                }\n                else\n                {\n                    max_teams_now += frequency[i]/2;\n                }\n            }\n        }\n\n        maximum_teams = max(maximum_teams, max_teams_now);\n    }\n\n    cout << maximum_teams << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Explanations/Gifts Fixing Explanation.txt",
    "content": "We will have to make every element in each sequence equal to their minimum.\n\nWe can calculate the number of subtractions required for both (A[i], B[i]).\n\nWe will do as many operations of the pair as we can and then only do on the single.\n\nThe total number of operations like this is max(A[i] - target_A, B[i] - target_B)\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    const int oo = 1e9 + 9;\n    int target_A = oo, target_B = oo;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        target_A = min(target_A, A[i]);\n        target_B = min(target_B, B[i]);\n    }\n\n    long long no_of_moves = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long a_moves_here = A[i] - target_A, b_moves_here = B[i] - target_B;\n\n        no_of_moves += max(a_moves_here, b_moves_here);\n    }\n\n    cout << no_of_moves << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Explanations/Remove Smallest Explanation.txt",
    "content": "Let us look at the sorted list\n\nA[1] <= A[2] <= A[3] <= A[4] <= A[5] <= ...  <= A[n]\n\nIf it satisfies the condition, then each contiguous pair can only differ by 1.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    int possible = true;\n\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        if(A[i] - A[i - 1] > 1)\n        {\n            possible = false;\n            break;\n        }\n    }\n\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Programs/Binary String to Subsequences.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    vector <int> sequence_no(length + 1);\n    set <int> available_label[2];\n    \n    int no_of_sequences = 1;\n    available_label[0].insert(1);\n    available_label[1].insert(1);\n    \n    for(int i = 0; i < length; i++)\n    {\n        int current = S[i] - '0';\n        int complement = 1 - current;\n        \n        if(available_label[complement].size() == 0)\n        {\n            no_of_sequences++;\n            \n            sequence_no[i] = no_of_sequences;\n            \n            available_label[current].insert(sequence_no[i]);\n        }\n        else\n        {\n            auto it = available_label[complement].begin();\n            \n            sequence_no[i] = *it;\n            \n            available_label[current].insert(sequence_no[i]);\n            \n            available_label[complement].erase(sequence_no[i]);\n        }\n    }\n    \n    cout << no_of_sequences << \"\\n\";\n    \n    for(int i = 0; i < length; i++)\n    {\n        cout << sequence_no[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Programs/Boats Competition.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> frequency(2*no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n    \n    int maximum_teams = 0;\n    for(int pair_sum = 1; pair_sum < 2*no_of_elements + 1; pair_sum++)\n    {\n        int max_teams_now = 0;\n        \n        for(int i = 1; i <= no_of_elements; i++)\n        {\n            if(pair_sum - i >= i)\n            {\n                if(i != pair_sum - i)\n                {\n                    max_teams_now += min(frequency[pair_sum - i], frequency[i]);\n                }\n                else\n                {\n                    max_teams_now += frequency[i]/2;\n                }\n            }\n        }\n        \n        maximum_teams = max(maximum_teams, max_teams_now);\n    }\n    \n    cout << maximum_teams << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Programs/Gifts Fixing.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n    \n    const int oo = 1e9 + 9;\n    int target_A = oo, target_B = oo;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        target_A = min(target_A, A[i]);\n        target_B = min(target_B, B[i]);\n    }\n    \n    long long no_of_moves = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long a_moves_here = A[i] - target_A, b_moves_here = B[i] - target_B;\n        \n        no_of_moves += max(a_moves_here, b_moves_here);\n    }\n    \n    cout << no_of_moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/661 Div 3/Programs/Remove Smallest.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    \n    int possible = true;\n    \n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        if(A[i] - A[i - 1] > 1)\n        {\n            possible = false;\n            break;\n        }\n    }\n    \n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/674 Div 3/Programs/Number of Subsequences.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long sum_till(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nlong long sum(long long L, long long R)\n{\n    return sum_till(R) - sum_till(L - 1);\n}\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    vector <int> prefix_questions(S.size() + 1, 0);\n    vector <int> prefix_a(S.size() + 1, 0);\n    prefix_a[0] = (S[0] == 'a');\n    prefix_questions[0] = (S[0] == '?');\n    \n    for(int i = 1; i < S.size(); i++)\n    {\n        prefix_a[i] = prefix_a[i - 1] + (S[i] == 'a');\n        prefix_questions[i] = prefix_questions[i - 1] + (S[i] == '?');\n    }\n    \n    vector <int> suffix_questions(S.size() + 1, 0);\n    vector <int> suffix_c(S.size() + 1, 0);\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        suffix_c[i] = suffix_c[i + 1] + (S[i] == 'c');\n        suffix_questions[i] = suffix_questions[i + 1] + (S[i] == '?');\n    }\n    \n    const int MOD = 1e9 + 7;\n    vector <long long> power_3(length + 1, 1);\n    for(int i = 1; i <= length; i++)\n    {\n        power_3[i] = (3*power_3[i - 1])%MOD;\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i < S.size() - 1; i++)\n    {\n        if(S[i] == 'b' || S[i] == '?')\n        {\n            long long a_s = prefix_a[i - 1], c_s = suffix_c[i + 1];\n            long long before_questions = prefix_questions[i - 1], after_questions = suffix_questions[i + 1];\n            \n            long long prefix_value = (a_s*power_3[before_questions])%MOD + (before_questions > 0 ? (before_questions*power_3[before_questions - 1])%MOD : 0);\n            prefix_value %= MOD;\n            \n            long long suffix_value = (c_s*power_3[after_questions])%MOD + (after_questions > 0 ? (after_questions*power_3[after_questions - 1] )%MOD : 0);\n            suffix_value %= MOD;\n        \n            answer = (answer + prefix_value*suffix_value)%MOD;\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Explanations/Array Partition Explanation.txt",
    "content": "Whenever we have to compute triplets,\nit's always a good idea to iterate over the middle to use symmetry.\n\nLet us iterate over A[i]. Suppose A[i] is the minimum of some segment.\n\nLet L[i], R[i] be the left and right border of A[i].\nThey denote the maximum range [L[i], R[i]] in which A[i] can be the minimum.\n\n------\n\nWe can precompute L[i], R[i] in O(n) time using a stack.\n\nInitially, the stack has a 0.\nWe will keep popping the stack till the top is < A[i]\nFinally, the top of the stack will be the first element on the left that is > A[i]\n\nWe do the same thing on the right.\n\n-----\n\nvoid compress_coordinates(int no_of_elements)\n{\n    vector <int> sorted_A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sorted_A[i] = A[i];\n    }\n\n    sort(sorted_A.begin(), sorted_A.end());\n\n    map <int, int> label;\n    label[sorted_A[1]] = 1;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        label[sorted_A[i]] = (sorted_A[i] == sorted_A[i - 1] ? label[sorted_A[i - 1]] : label[sorted_A[i - 1]] + 1);\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = label[A[i]]; //cout << A[i] << \" \";\n\n        indices[A[i]].push_back(i);\n    }\n}\n\n-----\n\nThe prefix either ends at L[i] or at some occurrence of A[i], whichever comes later.\nWe will iterate over all indices p in [L[i], i] such that A[p] = A[i]\n\nAnd check if the maximum in [1, p] = A[p]\n\nWe will also iterate over all indices s in [i, R[i]], such that A[s] = A[i]\nAnd check if the maximum in [s, n] = A[s]\n\n-----\n\n1. In order to store the indices of all the elements in a vector,\nwe will do coordinate compression in order to use the array elements as indices\n\n2. We will use a prefix maximum array and a suffix maximum array in order to get\nthe prefix maximum and suffix maximum in O(1) time.\n\n3. In order to clear the time limit, we will not check every single index of A[i]\nfor every i.\n\nThe prefix maximum has the property that it only increases.\nSuppose (j < k). Then Prefix Maximum[j] <= Prefix Maximum[k]\n\nSo, if A[j] = A[k] = A[i]\n\nAnd Prefix Maximum[k] = A[i], then Prefix Maximum[j] = A[i]\n\nIf we want to find an x, such that Prefix Maximum[x] = A[i],\nwe only need to look at the first occurrence of A[i] in the array.\n\nBut since we need the minimum of the second segment minimum to be A[i],\nwe will look for the first occurrence of A[i] >= (L[i] - 1)\n\nWe will do a similar thing for the suffix.\n\n-----\n\nFor every A[i], we will be checking at most 4 indices\n\n1. The first index to the right of (L[i] - 1)\n2. L[i] - 1\n3. The first index to the left of (R[i] + 1)\n4. R[i] + 1\n\nSo, the entire loop runs in O(n) time, with a possible O(log n) factor for\nfinding the indices closest to (L[i] - 1) and (R[i] + 1)\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        indices[i].clear();\n    }\n\n    compress_coordinates(no_of_elements);\n\n    vector <int> prefix_maximum(no_of_elements + 1);\n    vector <int> suffix_maximum(no_of_elements + 5);\n    compute_prefix_and_suffix_max(no_of_elements, prefix_maximum, suffix_maximum);\n\n    vector <int> left_border(no_of_elements + 1);\n    vector <int> right_border(no_of_elements + 1);\n    compute_borders(no_of_elements, left_border, right_border);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {   //cout << \"For \" << i << \" is minimum in [\" << left_border[i] << \" \" << right_border[i] << \"]\\n\";\n        if(indices[A[i]].size() < 3 || i == indices[A[i]][0] || i == indices[A[i]].back())\n        {\n            continue;\n        }\n\n        if(prefix_maximum[left_border[i] - 1] > A[i] || suffix_maximum[right_border[i] + 1] > A[i])\n        {\n            continue;\n        }\n\n        int p = upper_bound(all(indices[A[i]]), left_border[i] - 2) - indices[A[i]].begin();\n        if(indices[A[i]][p] == i)\n        {\n            p--;\n        }\n\n        int s = lower_bound(all(indices[A[i]]), right_border[i] - 1) - indices[A[i]].begin();\n        if(s == indices[A[i]].size() || indices[A[i]][s] > right_border[i] + 1)\n        {\n            s--;\n        }\n\n        while(s < indices[A[i]].size() && indices[A[i]][s] <= i)\n        {\n            s++;\n        }\n\n        int prefix, suffix;\n        //cout << \"p = \" << indices[A[i]][p] << \" s = \" << indices[A[i]][s] << \"\\n\";\n        int left_possible = false;\n\n        while(p >= 0)\n        {\n            prefix = max(indices[A[i]][p], left_border[i] - 1);\n            //cout << \"Prefix = \" << prefix << \" Maximum = \" << prefix_maximum[prefix] << \"\\n\";\n            if(prefix_maximum[prefix] == A[i])\n            {\n                left_possible = true;\n                break;\n            }\n\n            if(p < left_border[i] - 1)\n            {\n                break;\n            }\n\n            p--;\n        }\n\n        if(!left_possible)\n        {\n            continue;\n        }\n\n        int right_possible = false;\n\n        while(s < indices[A[i]].size())\n        {\n            suffix = min(indices[A[i]][s], right_border[i] + 1);\n            //cout << \"Prefix = \" << suffix<< \" Maximum = \" << suffix_maximum[suffix] << \"\\n\";\n\n            if(suffix_maximum[suffix] == A[i])\n            {\n                right_possible = true;\n                break;\n            }\n\n            if(s > right_border[i] + 1)\n            {\n                break;\n            }\n\n            s++;\n        }\n\n        if(!right_possible)\n        {\n            continue;\n        }\n\n        int part_1 = prefix, part_2 = (suffix - 1) - prefix;\n        int part_3 = no_of_elements - (part_1 + part_2);\n\n        cout << \"YES\\n\";\n        cout << part_1 << \" \" << part_2 << \" \" << part_3 << \"\\n\";\n\n        return;\n    }\n\n    cout << \"NO\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Explanations/Number Into Sequence Explanation.txt",
    "content": "Since A[i] has to be divisible by each A[1, i - 1],\n\nAll A[1, k] must have the same prime factor.\n\nSuppose p^k is the prime with the largest exponent in the prime factorization of N.\n\nWe can have k elements\n\np, p, p, .... , (N/p^{k - 1})\n\n-----\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n\n    long long final_n = n;\n    pair <int, long long> best_prime;\n\n    vector <pair <int, long long> > prime_exponents;\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            int exponent = 0;\n\n            while(n%i == 0)\n            {\n                n /= i;\n                exponent++;\n            }\n\n            prime_exponents.push_back(make_pair(exponent, i));\n\n            best_prime = max(best_prime, prime_exponents.back());\n        }\n    }\n\n    if(n > 1)\n    {\n        prime_exponents.push_back(make_pair(1, n));\n\n        best_prime = max(best_prime, prime_exponents.back());\n    }\n\n    cout << best_prime.first << \"\\n\";\n    for(int i = 1; i < best_prime.first; i++)\n    {\n        cout << best_prime.second << \" \";\n\n        final_n /= best_prime.second;\n    }\n\n    cout << final_n << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Explanations/Number of Simple Paths Explanation.txt",
    "content": "A connected graph with N vertices and N edges has exactly 1 cycle.\n\n-----\n\nWe can prove this with Mathematical Induction.\n\nIt is true for a graph with 2 vertices.\n\nSuppose it is true for a graph with n vertices.\n\nConsider a graph of (n + 1) vertices.\nEither it is a single cycle of length (n + 1), or it will have at least 1 leaf.\nWe can delete the leaf and get a graph of n vertices and n edges, and use the\nInduction Hypothesis.\n\n-----\n\nThe Graph looks like a ring where each vertex is the root of a tree.\n\nSuppose the sizes of the subtree are (S1, S2, ... Sk)\n\nInstead of counting paths, let us count source-destination pairs.\n\nThere are 2 types of pairs of vertices\n\n1. Pairs within the same subtree\n2. Pairs in different subtrees\n\nPairs in the same subtree have only 1 path between them.\nPairs in different subtrees have 2 paths between them because of the cycle.\nThe cycle gives us exactly 2 paths between every pair of roots.\n\nSuppose we are processing the i-th subtree.\nThe number of pairs of different trees =\n\nSi(S1 + S2 + ... + S{i - 1} + S{i + 1} + ... + Sk)\n\nIn order to avoid overcounting this and ensuring each pair is only counted once,\nI only added it with the prefix.\n\nSo pairs between S[3] and S[5],\nwill be added to the total only when we are processing the 5-th subtree\n\n------\n\nvoid solve()\n{\n    cin >> no_of_vertices;\n\n    cycle.clear();\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        graph[i].clear();\n\n        parent[i] = 0;\n        visited[i] = false;\n        lies_on_cycle[i] = false;\n    }\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n\n    long long remaining = 0;\n    long long answer = 0;\n\n    dfs(1, 0);\n\n    for(int i = 0; i < cycle.size(); i++)\n    {\n        int v = cycle[i];\n\n        long long subtree_here = dfs_without_cycle(v, 0);\n\n        long long inside = choose_2(subtree_here);\n        long long inside_outside = 2*(subtree_here*remaining);\n        //cout << \"Multiplying 2 \" << inside << \" \" << remaining << \" = \" << inside_outside << \"\\n\";\n\n        answer += (inside + inside_outside);\n\n        remaining += subtree_here;\n    }\n\n    cout << answer << \"\\n\";\n}\n\n-----\n\nHere is how to DFS to find a cycle.\n\nKeep track of number of times a vertex is visited and the parent of each vertex.\n\nWhen we are visiting a vertex for the second time, we have found a cycle and must go back.\n\nvoid dfs(int v, int parent_v)\n{\n    if(visited[v] == 2)\n    {\n        return ;\n    }\n\n    if(visited[v] == 1)\n    {\n        lies_on_cycle[v] = true;\n        cycle.push_back(v);\n\n        int u = parent_v;\n\n        while(u != v)\n        {\n            cycle.push_back(u);\n\n            lies_on_cycle[u] = true;\n            u = parent[u];\n\n            visited[u] = 2;\n        }\n\n        return;\n    }\n\n    visited[v] = 1;\n    parent[v] = parent_v;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        dfs(child_v, v);\n    }\n\n    visited[v] = 2;\n}\n\n-----\n\nIn order to DFS to find the size of the subtree rooted at v,\ndo a normal DFS but ignore the neighbours of v on the cycle\n\nint dfs_without_cycle(int v, int parent_v)\n{\n    int count = 1;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n\n        if(child_v == parent_v || lies_on_cycle[child_v])\n        {\n            continue;\n        }\n\n        count += dfs_without_cycle(child_v, v);\n    }\n\n    return count;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Explanations/Sequence Transformation Explanation.txt",
    "content": "We will condense contiguous segments of 1 element into 1 element.\n\nEither they will be deleted together or they will never be touched.\n\nNow, let us look at the frequency of each segment.\n\nFor each element A[i],\nwe will count the number of operations required to make this the last element.\n\nIf the frequency of segment[A[i]] is N,\nThen we will need to delete (N + 1) segments in general.\n\nWe will need to delete (N - 1) segments that lie intermediately\n1 prefix\n1 suffix\n\nWe need to separately check if A[i] is in the prefix or the suffix and update the number of operations accordingly.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    map <int, int> segment_frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] != A[i - 1])\n        {\n            segment_frequency[A[i]]++;\n        }\n    }\n\n    int minimum_operations = no_of_elements;\n    for(map <int, int> :: iterator it = segment_frequency.begin(); it != segment_frequency.end(); it++)\n    {\n        int operations_here = (it->second) + 1;\n\n        if(A[1] == it->first)\n        {\n            operations_here--;\n        }\n\n        if(A[no_of_elements] == it->first)\n        {\n            operations_here--;\n        }\n\n        minimum_operations = min(minimum_operations, operations_here);\n    }\n\n    cout << minimum_operations << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Explanations/Special Permutation Explanation.txt",
    "content": "I printed one cyclic rotation of the matrix\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << i%no_of_elements + 1 << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Explanations/Unique Bid Auction Explanation.txt",
    "content": "Look for the minimum integer who's frequency is 1\n\nWe can also do this by inserting everything into a set and printing the first element of the set.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    map <int, int> frequency;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        frequency[A[i]]++;\n    }\n\n    const int oo = 1e9 + 9;\n    int winner = -1, answer = oo;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(frequency[A[i]] == 1 && A[i] < answer)\n        {\n            answer = A[i];\n\n            winner = i;\n        }\n    }\n\n    cout << winner << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Programs/Array Partition.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n#include <stack>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nvector <int> indices[MAX_N];\nvector <int> A(MAX_N);\n\nvoid compress_coordinates(int no_of_elements)\n{\n    vector <int> sorted_A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sorted_A[i] = A[i];\n    }\n    \n    sort(sorted_A.begin(), sorted_A.end());\n    \n    map <int, int> label;\n    label[sorted_A[1]] = 1;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        label[sorted_A[i]] = (sorted_A[i] == sorted_A[i - 1] ? label[sorted_A[i - 1]] : label[sorted_A[i - 1]] + 1);\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = label[A[i]]; //cout << A[i] << \" \";\n        \n        indices[A[i]].push_back(i);\n    }\n}\n\nvoid compute_prefix_and_suffix_max(int no_of_elements, vector <int> &prefix_maximum, vector <int> &suffix_maximum)\n{\n   for(int i = 1; i <= no_of_elements; i++)\n   {\n       prefix_maximum[i] = max(prefix_maximum[i - 1], A[i]);\n   }\n   \n   \n   for(int i = no_of_elements; i >= 1; i--)\n   {\n       suffix_maximum[i] = max(suffix_maximum[i + 1], A[i]);\n   }\n}\n\nvoid compute_borders(int no_of_elements, vector <int> &left_border, vector <int> &right_border)\n{\n    stack <pair <int, int> > left_S;\n    left_S.push(make_pair(0, 0));\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        while(left_S.top().first >= A[i])\n        {   //cout << left_S.top().first << \" is greater than \" << i << \"\\n\";\n            left_S.pop();\n        }\n        \n        left_border[i] = left_S.top().second + 1; //cout << \"Left \" << i << \" is \" << left_border[i] << \"\\n\";\n        \n        left_S.push(make_pair(A[i], i));\n    }\n        \n    stack <pair <int, int> > right_S;\n    right_S.push(make_pair(0, no_of_elements + 1));\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        while(right_S.top().first >= A[i])\n        {\n            right_S.pop();\n        }\n        \n        right_border[i] = right_S.top().second - 1; //cout << \"Right \" << i << \" = \" << right_border[i] << \"\\n\";\n        \n        right_S.push(make_pair(A[i], i));\n    }\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        indices[i].clear();\n    }\n    \n    compress_coordinates(no_of_elements);\n    \n    vector <int> prefix_maximum(no_of_elements + 1);\n    vector <int> suffix_maximum(no_of_elements + 5);\n    compute_prefix_and_suffix_max(no_of_elements, prefix_maximum, suffix_maximum);\n    \n    vector <int> left_border(no_of_elements + 1);\n    vector <int> right_border(no_of_elements + 1);\n    compute_borders(no_of_elements, left_border, right_border);\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {   //cout << \"For \" << i << \" is minimum in [\" << left_border[i] << \" \" << right_border[i] << \"]\\n\";\n        if(indices[A[i]].size() < 3 || i == indices[A[i]][0] || i == indices[A[i]].back())\n        {\n            continue;\n        }\n        \n        if(prefix_maximum[left_border[i] - 1] > A[i] || suffix_maximum[right_border[i] + 1] > A[i])\n        {\n            continue;\n        }\n        \n        int p = upper_bound(all(indices[A[i]]), left_border[i] - 2) - indices[A[i]].begin();\n        if(indices[A[i]][p] == i)\n        {\n            p--;\n        }\n        \n        int s = lower_bound(all(indices[A[i]]), right_border[i] - 1) - indices[A[i]].begin();\n        if(s == indices[A[i]].size() || indices[A[i]][s] > right_border[i] + 1)\n        {\n            s--;\n        }\n        \n        while(s < indices[A[i]].size() && indices[A[i]][s] <= i)\n        {\n            s++;\n        }\n        \n        int prefix, suffix;\n        //cout << \"p = \" << indices[A[i]][p] << \" s = \" << indices[A[i]][s] << \"\\n\";\n        int left_possible = false;\n        \n        while(p >= 0)\n        {\n            prefix = max(indices[A[i]][p], left_border[i] - 1);\n            //cout << \"Prefix = \" << prefix << \" Maximum = \" << prefix_maximum[prefix] << \"\\n\";\n            if(prefix_maximum[prefix] == A[i])\n            {\n                left_possible = true;\n                break;\n            }\n            \n            if(p < left_border[i] - 1)\n            {\n                break;\n            }\n            \n            p--;\n        }\n        \n        if(!left_possible)\n        {\n            continue;\n        }\n        \n        int right_possible = false;\n        \n        while(s < indices[A[i]].size())\n        {\n            suffix = min(indices[A[i]][s], right_border[i] + 1);\n            //cout << \"Prefix = \" << suffix<< \" Maximum = \" << suffix_maximum[suffix] << \"\\n\";\n            \n            if(suffix_maximum[suffix] == A[i])\n            {\n                right_possible = true;\n                break;\n            }\n            \n            if(s > right_border[i] + 1)\n            {\n                break;\n            }\n            \n            s++;\n        }\n        \n        if(!right_possible)\n        {\n            continue;\n        }\n        \n        int part_1 = prefix, part_2 = (suffix - 1) - prefix;\n        int part_3 = no_of_elements - (part_1 + part_2);\n        \n        cout << \"YES\\n\";\n        cout << part_1 << \" \" << part_2 << \" \" << part_3 << \"\\n\";\n        \n        return;\n    }\n    \n    cout << \"NO\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n    {\n        solve();\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Programs/Number Into Sequence.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n    \n    long long final_n = n;\n    pair <int, long long> best_prime;\n    \n    vector <pair <int, long long> > prime_exponents;\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            int exponent = 0;\n            \n            while(n%i == 0)\n            {\n                n /= i;\n                exponent++;\n            }\n            \n            prime_exponents.push_back(make_pair(exponent, i));\n            \n            best_prime = max(best_prime, prime_exponents.back());\n        }\n    }\n    \n    if(n > 1)\n    {\n        prime_exponents.push_back(make_pair(1, n));\n        \n        best_prime = max(best_prime, prime_exponents.back());\n    }\n    \n    cout << best_prime.first << \"\\n\";\n    for(int i = 1; i < best_prime.first; i++)\n    {\n        cout << best_prime.second << \" \";\n        \n        final_n /= best_prime.second;\n    }\n    \n    cout << final_n << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n        \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Programs/Number of Simple Paths.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5;\nint no_of_vertices;\nvector <int> graph[MAX_N];\nvector <int> parent(MAX_N, 0);\nvector <int> visited(MAX_N, false);\nvector <int> lies_on_cycle(MAX_N, false);\nvector <int> cycle;\n\nvoid dfs(int v, int parent_v)\n{\n    if(visited[v] == 2)\n    {\n        return ;\n    }\n    \n    if(visited[v] == 1)\n    {\n        lies_on_cycle[v] = true;\n        cycle.push_back(v);\n        \n        int u = parent_v;\n        \n        while(u != v)\n        {\n            cycle.push_back(u);\n            \n            lies_on_cycle[u] = true;\n            u = parent[u];\n            \n            visited[u] = 2;\n        }\n        \n        return;\n    }\n    \n    visited[v] = 1;\n    parent[v] = parent_v;\n    \n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n    }\n    \n    visited[v] = 2;\n}\n\nint dfs_without_cycle(int v, int parent_v)\n{\n    int count = 1;\n    \n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n        \n        if(child_v == parent_v || lies_on_cycle[child_v])\n        {\n            continue;\n        }\n        \n        count += dfs_without_cycle(child_v, v);\n    }\n    \n    return count;\n}\n\nlong long choose_2(long long n)\n{\n    return (n*(n - 1))/2;\n}\n\nvoid solve()\n{\n    cin >> no_of_vertices;\n    \n    cycle.clear();\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        graph[i].clear();\n        \n        parent[i] = 0;\n        visited[i] = false;\n        lies_on_cycle[i] = false;\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n    \n    long long remaining = 0;\n    long long answer = 0;\n    \n    dfs(1, 0);\n    \n    for(int i = 0; i < cycle.size(); i++)\n    {\n        int v = cycle[i];\n        \n        long long subtree_here = dfs_without_cycle(v, 0);\n        \n        long long inside = choose_2(subtree_here);\n        long long inside_outside = 2*(subtree_here*remaining);\n        //cout << \"Multiplying 2 \" << inside << \" \" << remaining << \" = \" << inside_outside << \"\\n\";\n        \n        answer += (inside + inside_outside);\n        \n        remaining += subtree_here;\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Programs/Sequence Transformation.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    map <int, int> segment_frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] != A[i - 1])\n        {\n            segment_frequency[A[i]]++;\n        }\n    }\n    \n    int minimum_operations = no_of_elements;\n    for(map <int, int> :: iterator it = segment_frequency.begin(); it != segment_frequency.end(); it++)\n    {\n        int operations_here = (it->second) + 1;\n        \n        if(A[1] == it->first)\n        {\n            operations_here--;\n        }\n        \n        if(A[no_of_elements] == it->first)\n        {\n            operations_here--;\n        }\n        \n        minimum_operations = min(minimum_operations, operations_here);\n    }\n    \n    cout << minimum_operations << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Programs/Special Permutation.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << i%no_of_elements + 1 << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/686 Div 3/Programs/Unique Bid Auction.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    map <int, int> frequency;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        frequency[A[i]]++;\n    }\n    \n    const int oo = 1e9 + 9;\n    int winner = -1, answer = oo;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(frequency[A[i]] == 1 && A[i] < answer)\n        {\n            answer = A[i];\n            \n            winner = i;\n        }\n    }\n    \n    cout << winner << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Div 3/Explanations/Number of Subsequences Explanation.txt",
    "content": "Let us iterate over the middle character. Let us fix the middle character at position i, \n\nThis means that either S[i] = B or S[i] = ?\n\n-----\n\nNow, we must arrange the prefix in such a way that there is at least 1 A and arrange the suffix in such a way there is at least 1 C. \n\n-----\n\nSuppose there are a A's and q ?'s in the prefix of length i. \n\nNow, we must count the number of substrings possible here such that we get at least one A. \n\nThere are two possibilities. \n\n1. The A comes from one of the A's.\n   There are 'a' different indices from which it can come. Each question mark can be replaced with any of the 3 characters (a, b, c). \n   \n   a.3^q\n \n 2. The A comes from one of the question marks. Each of the q question marks can be converted to an A and the other (q - 1) Question Marks can be converted to any of the 3 options. \n \n q.3^{q - 1}\n \n So, the total ways of choosing the prefix = (a.3^q + q.3^{q - 1})\n \n Similarly, the total ways of choosing the suffix = (c.3^q + q.3^{q - 1})\n \n We will multiply the number of ways of choosing the prefix with the number of ways of choosing the suffix to get the number of sequences centered at S[i].\n \n -----\n \n We will add them all to get the answer. \n \n -----\n \n #include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long sum_till(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nlong long sum(long long L, long long R)\n{\n    return sum_till(R) - sum_till(L - 1);\n}\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    vector <int> prefix_questions(S.size() + 1, 0);\n    vector <int> prefix_a(S.size() + 1, 0);\n    prefix_a[0] = (S[0] == 'a');\n    prefix_questions[0] = (S[0] == '?');\n    \n    for(int i = 1; i < S.size(); i++)\n    {\n        prefix_a[i] = prefix_a[i - 1] + (S[i] == 'a');\n        prefix_questions[i] = prefix_questions[i - 1] + (S[i] == '?');\n    }\n    \n    vector <int> suffix_questions(S.size() + 1, 0);\n    vector <int> suffix_c(S.size() + 1, 0);\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        suffix_c[i] = suffix_c[i + 1] + (S[i] == 'c');\n        suffix_questions[i] = suffix_questions[i + 1] + (S[i] == '?');\n    }\n    \n    const int MOD = 1e9 + 7;\n    vector <long long> power_3(length + 1, 1);\n    for(int i = 1; i <= length; i++)\n    {\n        power_3[i] = (3*power_3[i - 1])%MOD;\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i < S.size() - 1; i++)\n    {\n        if(S[i] == 'b' || S[i] == '?')\n        {\n            long long a_s = prefix_a[i - 1], c_s = suffix_c[i + 1];\n            long long before_questions = prefix_questions[i - 1], after_questions = suffix_questions[i + 1];\n            \n            long long prefix_value = (a_s*power_3[before_questions])%MOD + (before_questions > 0 ? (before_questions*power_3[before_questions - 1])%MOD : 0);\n            prefix_value %= MOD;\n            \n            long long suffix_value = (c_s*power_3[after_questions])%MOD + (after_questions > 0 ? (after_questions*power_3[after_questions - 1] )%MOD : 0);\n            suffix_value %= MOD;\n        \n            answer = (answer + prefix_value*suffix_value)%MOD;\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Explanations/Berry Jam Explanation.txt",
    "content": "Let us make a few observations. \n\nWe want to minimize the number of removals. This is the same as maximising the amount that we choose. \nIn the end, we will be left with some prefix and with some suffix. \n\nSuppose we take (x1, y1) from the prefix and (x2, y2) from the suffix. \n\nx1 + x2 = y1 + y2\n\nWe can also write it as (x1 - y1) = (y2 - y1)\n\nWe will maintain the prefix frequency of (x1 - y1) for each i. \nWe will also maintain the suffix frequency of (y2 - x2) and also the index at which it reaches the given value.\n\nFor each i, we will check that if we take i elements from the prefix, how many elements of the suffix do we have to take ? \n\n(It is possible that we will not get a good selection even if we select the entire suffix and we will deal with this case.)\n\nPlease refer my code for more doubts.\n\n-----\n\nvoid solve()\n{\n    int no_of_jars;\n    cin >> no_of_jars;\n    \n    vector <long long> A(2*no_of_jars + 1);\n    for(int i = 1; i <= 2*no_of_jars; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int suffix_1 = 0, suffix_2 = 0;\n    map <long long, int> suffix_point;\n    for(int i = 2*no_of_jars; i > no_of_jars; i--)\n    {\n        suffix_1 += (A[i] == 1);\n        suffix_2 += (A[i] == 2);\n    \n        suffix_point[suffix_1 - suffix_2] = i;\n    }\n    \n    int maximum_chosen = 0;\n    int prefix_1 = 0, prefix_2 = 0;\n    for(int i = 0; i <= no_of_jars; i++)\n    {\n        prefix_1 += (A[i] == 1);\n        prefix_2 += (A[i] == 2);\n        \n        if(prefix_1 == prefix_2)\n        {\n            maximum_chosen = max(maximum_chosen, i);\n        }\n        \n        if(suffix_point[prefix_2 - prefix_1] != 0)\n        {\n            int chosen_here = i  + (2*no_of_jars - (suffix_point[prefix_2 - prefix_1] - 1));\n            \n            maximum_chosen = max(maximum_chosen, chosen_here);\n        }\n    }\n    \n    int minimum_removals = 2*no_of_jars - maximum_chosen;\n    \n    cout << minimum_removals << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Explanations/Cards Explanation.txt",
    "content": "Temporary\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Explanations/Shuffle Hashing Explanation.txt",
    "content": "We can check if 2 strings are permutations of each other by comparing the frequency of all 26 alphabets.\n\nWe will go through every substring of length |P| in H and check if it is a permutation of P.\n\n-----\n\nvoid solve()\n{\n    string password, hash;\n    cin >> password >> hash;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <int> password_frequency(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < password.size(); i++)\n    {\n        password_frequency[password[i] - 'a']++;\n    }\n\n    int possible = false;\n    for(int i = 0; i + password.size() <= hash.size() && !possible; i++)\n    {\n        vector <int> hash_frequency(NO_OF_ALPHABETS, 0);\n\n        for(int j = 0; j < password.size(); j++)\n        {\n            hash_frequency[hash[i + j] - 'a']++;\n        }\n\n        possible = true;\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            if(password_frequency[alpha] != hash_frequency[alpha])\n            {\n                possible = false;\n            }\n        }\n\n    }\n\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Explanations/Tests for Problem D Explanation.txt",
    "content": "The right label for each vertex is more than the number of children it has.\nThen, one by one we will start labelling the children backwards so that they all intersect.\n\n\n-----\n\nvoid dfs(int v, int parent_v)\n{   //cout << \"At \" << v << \"\\n\";\n    int no_of_children = tree[v].size() - (parent_v == 0 ? 0 : 1);\n\n    available += no_of_children + 1;\n\n    right_label[v] = available;\n    //cout << \"Size \" << v << \" = \" << tree[v].size() << \"\\n\";\n    for(int i = 0, child_no = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        child_no++;\n\n        left_label[child_v] = right_label[v] - child_no;\n\n        dfs(child_v, v);\n    }\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Programs/A and B.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint possible(int x, int d)\n{\n    long long sum = x*(x + 1)/2;\n    \n    return (sum >= d && sum%2 == d%2);\n}\n\nvoid solve()\n{\n    int a, b;\n    cin >> a >> b;\n    \n    int moves = 0;\n    while(!possible(moves, abs(a - b)))\n    {\n        moves++;\n    }\n    \n    cout << moves << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Programs/Berry Jam.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_jars;\n    cin >> no_of_jars;\n    \n    vector <long long> A(2*no_of_jars + 1);\n    for(int i = 1; i <= 2*no_of_jars; i++)\n    {\n        cin >> A[i];\n    }\n    \n    int suffix_1 = 0, suffix_2 = 0;\n    map <long long, int> suffix_point;\n    for(int i = 2*no_of_jars; i > no_of_jars; i--)\n    {\n        suffix_1 += (A[i] == 1);\n        suffix_2 += (A[i] == 2);\n    \n        suffix_point[suffix_1 - suffix_2] = i;\n    }\n    \n    int maximum_chosen = 0;\n    int prefix_1 = 0, prefix_2 = 0;\n    for(int i = 0; i <= no_of_jars; i++)\n    {\n        prefix_1 += (A[i] == 1);\n        prefix_2 += (A[i] == 2);\n        \n        if(prefix_1 == prefix_2)\n        {\n            maximum_chosen = max(maximum_chosen, i);\n        }\n        \n        if(suffix_point[prefix_2 - prefix_1] != 0)\n        {\n            int chosen_here = i  + (2*no_of_jars - (suffix_point[prefix_2 - prefix_1] - 1));\n            \n            maximum_chosen = max(maximum_chosen, chosen_here);\n        }\n    }\n    \n    int minimum_removals = 2*no_of_jars - maximum_chosen;\n    \n    cout << minimum_removals << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Programs/Shuffle Hashing.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    string password, hash;\n    cin >> password >> hash;\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <int> password_frequency(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < password.size(); i++)\n    {\n        password_frequency[password[i] - 'a']++;\n    }\n    \n    int possible = false;\n    for(int i = 0; i + password.size() <= hash.size() && !possible; i++)\n    {\n        vector <int> hash_frequency(NO_OF_ALPHABETS, 0);\n\n        for(int j = 0; j < password.size(); j++)\n        {\n            hash_frequency[hash[i + j] - 'a']++;\n        }\n       \n        possible = true;\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            if(password_frequency[alpha] != hash_frequency[alpha])\n            { \n                possible = false;\n            }\n        }\n        \n    }\n    \n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 78/Programs/Tests for Problem D.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5;\nint available = 1;\nvector <int> tree[MAX_N];\nint left_label[MAX_N], right_label[MAX_N];\n\nvoid dfs(int v, int parent_v)\n{   //cout << \"At \" << v << \"\\n\";\n    int no_of_children = tree[v].size() - (parent_v == 0 ? 0 : 1);\n    \n    available += no_of_children + 1;\n\n    right_label[v] = available;\n    //cout << \"Size \" << v << \" = \" << tree[v].size() << \"\\n\";\n    for(int i = 0, child_no = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        child_no++;\n        \n        left_label[child_v] = right_label[v] - child_no;\n        \n        //cout << \"Child = \" << child_v << \"\\n\";\n        dfs(child_v, v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n    \n    int no_of_edges = no_of_vertices - 1;\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    left_label[1] = available;\n    \n    dfs(1, 0);\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cout << left_label[i] << \" \" << right_label[i] << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 79/Explanations/New Year Garland Explanation.txt",
    "content": "Let us assume there are (a1, a2, a3) stones.\nAnd a1 < a2 < a3\n\nIf a3 > a1 + a2 + 1, there have to be 2 consecutive flowers of a3.\n\nOtherwise, we will first place the a3 flowers.\n\nThen, we will put the flowers of type a1 in between the flowers from one end\nand flowers of type a2 in another end.\n \n-----\n\nvoid solve()\n{\n    long long red, green, blue;\n    cin >> red >> green >> blue;\n\n    long long total = red + green + blue;\n    long long maximum = max_3(red, green, blue);\n    long long remaining_sum = total - maximum;\n\n    cout << (maximum <= remaining_sum + 1 ? \"Yes\\n\" : \"No\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 79/Explanations/Stack of Presents Explanation.txt",
    "content": "Here is the optimal idea. \n\nEvery time we scan through the stack, we will place the gifts in such a way \nthat any future query that can be answered will be answered. \n\nWe will pick up the maximum index in A at each time. \n\nEvery time we go to B[j], we will check if the index of B[j] < maximum. \n\nIf yes, then it will be at the top of the stack when we have to pick it up. \n\nElse, if the index k > maximum, then we will update the maximum and take (2k + 1) seconds for this.\n------\n\nvoid solve()\n{\n    int stack_presents, sent_presents;\n    cin >> stack_presents >> sent_presents;\n    \n    vector <int> A(stack_presents + 1);\n    vector <int> A_index(stack_presents + 1);\n    for(int i = 1; i <= stack_presents; i++)\n    {\n        cin >> A[i];\n        \n        A_index[A[i]] = i;\n    }\n    \n    vector <int> B(sent_presents + 1);\n    for(int i = 1; i <= sent_presents; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int max_inserted = 0;\n    long long total_time = 0;\n    for(int i = 1; i <= sent_presents; i++)\n    {\n        int effective_index = A_index[B[i]] - (i - 1);\n        \n        if(max_inserted > A_index[B[i]])\n        {\n            effective_index = 1;\n        }\n        \n        total_time += 2*(effective_index - 1) + 1;\n        \n        max_inserted = max(max_inserted, A_index[B[i]]);\n    }\n    \n    cout << total_time << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 79/Explanations/Verse for Santa Explanation.txt",
    "content": "We have to look for any 1 point i, where the prefix sum (i) - prefix maximum(i) <= k\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, maximum_seconds;\n    cin >> no_of_elements >> maximum_seconds;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> sum_till(no_of_elements + 1, 0);\n    vector <long long> max_till(no_of_elements + 1, 0);\n    vector <long long> max_index(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + A[i];\n\n        if(A[i] > max_till[i - 1])\n        {\n            max_till[i] = A[i];\n            max_index[i] = i;\n        }\n        else\n        {\n            max_till[i] = max_till[i - 1];\n            max_index[i] = max_index[i - 1];\n        }\n    }\n\n    if(sum_till[no_of_elements] <= maximum_seconds)\n    {\n        cout << \"0\\n\";\n\n        return;\n    }\n\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        if(sum_till[i] - max_till[i] <= maximum_seconds)\n        {\n            cout << max_index[i] << \"\\n\";\n\n            return;\n        }\n    }\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 79/Programs/New Year Garland.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long max_3(long long a, long long b, long long c)\n{\n    return max(a, max(b, c));\n}\n\nvoid solve()\n{\n    long long red, green, blue;\n    cin >> red >> green >> blue;\n    \n    long long total = red + green + blue;\n    long long maximum = max_3(red, green, blue);\n    long long remaining_sum = total - maximum;\n    \n    cout << (maximum <= remaining_sum + 1 ? \"Yes\\n\" : \"No\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 79/Programs/Stack of Presents.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int stack_presents, sent_presents;\n    cin >> stack_presents >> sent_presents;\n    \n    vector <int> A(stack_presents + 1);\n    vector <int> A_index(stack_presents + 1);\n    for(int i = 1; i <= stack_presents; i++)\n    {\n        cin >> A[i];\n        \n        A_index[A[i]] = i;\n    }\n    \n    vector <int> B(sent_presents + 1);\n    for(int i = 1; i <= sent_presents; i++)\n    {\n        cin >> B[i];\n    }\n    \n    int max_inserted = 0;\n    long long total_time = 0;\n    for(int i = 1; i <= sent_presents; i++)\n    {\n        int effective_index = A_index[B[i]] - (i - 1);\n        \n        if(max_inserted > A_index[B[i]])\n        {\n            effective_index = 1;\n        }\n        \n        total_time += 2*(effective_index - 1) + 1;\n        \n        max_inserted = max(max_inserted, A_index[B[i]]);\n    }\n    \n    cout << total_time << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 79/Programs/Verse for Santa.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, maximum_seconds;\n    cin >> no_of_elements >> maximum_seconds;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> sum_till(no_of_elements + 1, 0);\n    vector <long long> max_till(no_of_elements + 1, 0);\n    vector <long long> max_index(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + A[i];\n        \n        if(A[i] > max_till[i - 1])\n        {\n            max_till[i] = A[i];\n            max_index[i] = i;\n        }\n        else\n        {\n            max_till[i] = max_till[i - 1];\n            max_index[i] = max_index[i - 1];\n        }\n    }\n    \n    if(sum_till[no_of_elements] <= maximum_seconds)\n    {\n        cout << \"0\\n\";\n        \n        return;\n    }\n    \n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        if(sum_till[i] - max_till[i] <= maximum_seconds)\n        {\n            cout << max_index[i] << \"\\n\";\n            \n            return;\n        }\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Explanations/Deadline Explanation.txt",
    "content": "It can be proven that the actual answer will be near square root(d).\n\n(We can check this by taking the derivative of the function and setting it to 0).\n\nI did a heuristic where I just checked the first 10^6 integers as it is guaranteed to be within the square root of d.\n\n-----\n\nvoid solve()\n{\n    int n, d;\n    cin >> n >> d;\n\n    if(d <= n)\n    {\n        cout << \"YES\\n\";\n\n        return;\n    }\n\n    const int N = 2e6;\n    for(int x = 1; x <= min(n, N); x++)\n    {\n        int optimised_d = ceil(d, x + 1);\n        //cout << \"d = \" << optimised_d << \" x = \" << x << \"\\n\";\n\n        if(optimised_d + x <= n)\n        {\n            cout << \"YES\\n\";\n            return;\n        }\n    }\n\n    cout << \"NO\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Explanations/Minimax Problem Explanation.txt",
    "content": "Let us try to binary search the answer.\n\nHow do we check if it is possible to get x as the minimum element of 2 arrays after such an operation ? \n\nWe can create a bitmask corresponding to each array. \nA[i] = 1 if A[i] >= x\nA[i] = 0 if A[i] < x\n\nWe will get two bitmasks. \nWhen we perform the bitwise OR of the two masks, we will get a 1 if the resulting array has an element >= x and a 0 otherwise.\n\nSo, to check if a given value of x is possible, we will create a 8-bit bitmask for each array. \nWe will then check if it is possible for us to have 2 arrays such that their bitwise OR results in a bitmask having all ones - \n11111111\n\nIf yes, then it is possible. \n\nWe will binary search for the best value of x.\nWe will maintain the invariant that it is always possible to have the minimum >= L and it is never possible to have the minimum >= R\n\nUltimately, L is the best value that the minimum can have.\n\n-----\n\nint possible(int x, int &i, int &j)\n{\n    map <int, int> map_index;\n    \n    for(int i = 1; i <= no_of_arrays; i++)\n    {\n        int mask = 0;\n        \n        for(int j = 1; j <= no_of_elements; j++)\n        {\n            if(A[i][j] < x)\n                continue;\n            \n            mask |= (1 << (j - 1));\n        }\n        \n        map_index[mask] = i;\n    }\n    \n    int full_mask = (1 << no_of_elements) - 1;\n    \n    for(auto it = map_index.begin(); it != map_index.end(); it++)\n    {\n        int mask = it->first;\n        \n        for(int m = 0; m <= full_mask; m++)\n        {\n            if((mask|m) == full_mask && map_index.find(m) != map_index.end())\n            {\n                i = map_index[mask];\n                j = map_index[m];\n                \n                return true;\n            }\n        }\n    }\n    \n    return false;\n}\n\nint main()\n{\n    scanf(\"%d %d\", &no_of_arrays, &no_of_elements);\n    \n    for(int i = 1; i <= no_of_arrays; i++)\n    {\n        for(int j = 1; j <= no_of_elements; j++)\n        {\n            scanf(\"%d\", &A[i][j]);\n        }\n    }\n    \n    int left = 0, right = 1e9 + 1;\n    int best_i = 1, best_j = 1;\n    \n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n        \n        if(possible(mid, best_i, best_j))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n    \n    printf(\"%d %d\\n\", best_i, best_j);\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Explanations/Two Arrays Alternate Solution Explanation.txt",
    "content": "https://qr.ae/TVI1Ht\n\nint main()\n{\n    precompute();\n\n    int n, length;\n    cin >> n >> length;\n\n    long long answer = combinations(n + 2*length - 1, 2*length);\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Explanations/Two Arrays Explanation.txt",
    "content": "https://qr.ae/TVI1Ht\n\nint main()\n{\n    precompute();\n\n    int n, length;\n    cin >> n >> length;\n\n    long long answer = 0;\n    for(int a_ending = 1; a_ending <= n; a_ending++)\n    {\n        for(int b_ending = a_ending; b_ending <= n; b_ending++)\n        {\n            answer += (count(1, a_ending, length)*count(b_ending, n, length))%MOD;\n\n            answer %= MOD;\n        }\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Explanations/Yet Another Meme Problem Explanation.txt",
    "content": "a.b + a + b = 10^d a + b, where d is the number of digits of b\n\na.b = a(10^d - 1)\n\nb = 10^d - 1\n\nb is a string of all 9s, and a can be any integer in the range\n\n-----\n\nvoid solve()\n{\n    int a, b;\n    cin >> a >> b;\n\n    //a.b + a + b = 10a + b => a.b = 9a => a.b = 9a => b = 9\n    //a.b + a + b = 100a + b => a.b = 99a => b = 99\n\n    long long no_of_pairs = 0;\n\n    for(long long i = 10; i - 1 <= b; i *= 10)\n    {\n        no_of_pairs += a;\n    }\n\n    cout << no_of_pairs << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Programs/Deadline.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint ceil(int n, int d)\n{\n    return (n/d + (n%d != 0));\n}\n\nvoid solve()\n{\n    int n, d;\n    cin >> n >> d;\n    \n    if(d <= n)\n    {\n        cout << \"YES\\n\";\n        \n        return;\n    }\n    \n    const int N = 2e6;\n    for(int x = 1; x <= min(n, N); x++)\n    {\n        int optimised_d = ceil(d, x + 1);\n        //cout << \"d = \" << optimised_d << \" x = \" << x << \"\\n\";\n        \n        if(optimised_d + x <= n)\n        {\n            cout << \"YES\\n\";\n            return;\n        }\n    }\n    \n    cout << \"NO\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Programs/Minimax Problem.cpp",
    "content": "#include <cstdio>\n#include <map>\n\nusing namespace std;\n\nconst int MAX_A = 3e5 + 5, MAX_N = 8 + 1;\nint no_of_arrays, no_of_elements;\nlong long A[MAX_A][MAX_N];\n\nint possible(int x, int &i, int &j)\n{\n    map <int, int> map_index;\n    \n    for(int i = 1; i <= no_of_arrays; i++)\n    {\n        int mask = 0;\n        \n        for(int j = 1; j <= no_of_elements; j++)\n        {\n            if(A[i][j] < x)\n                continue;\n            \n            mask |= (1 << (j - 1));\n        }\n        \n        map_index[mask] = i;\n    }\n    \n    int full_mask = (1 << no_of_elements) - 1;\n    \n    for(auto it = map_index.begin(); it != map_index.end(); it++)\n    {\n        int mask = it->first;\n        \n        for(int m = 0; m <= full_mask; m++)\n        {\n            if((mask|m) == full_mask && map_index.find(m) != map_index.end())\n            {\n                i = map_index[mask];\n                j = map_index[m];\n                \n                return true;\n            }\n        }\n    }\n    \n    return false;\n}\n\nint main()\n{\n    scanf(\"%d %d\", &no_of_arrays, &no_of_elements);\n    \n    for(int i = 1; i <= no_of_arrays; i++)\n    {\n        for(int j = 1; j <= no_of_elements; j++)\n        {\n            scanf(\"%d\", &A[i][j]);\n        }\n    }\n    \n    int left = 0, right = 1e9 + 1;\n    int best_i = 1, best_j = 1;\n    \n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n        \n        if(possible(mid, best_i, best_j))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n    \n    printf(\"%d %d\\n\", best_i, best_j);\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Programs/Two Arrays Alternate Solution.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MOD = 1e9 + 7;\nlong long factorial[MAX_N + 5], inverse_factorial[MAX_N + 5];\n\nlong long power(long long x, long long p)\n{\n    long long result = 1;\n    \n    while(p)\n    {\n        if(p%2 == 1)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        p /= 2;\n    }\n    \n    return result;\n}\n\nvoid precompute()\n{\n    factorial[0] = 1;\n    for(int i = 1; i <= MAX_N; i++)\n    {\n        factorial[i] = (i*factorial[i - 1])%MOD;\n    }\n    \n    inverse_factorial[MAX_N] = power(factorial[MAX_N], MOD - 2);\n    for(int i = MAX_N - 1; i >= 0; i--)\n    {\n        //i*(i - 1)! = i! => (i - 1)!^ = i!^ i\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\n    }\n}\n\nlong long combinations(long long n, long long k)\n{\n    if(n < k)\n    {\n        return 0;\n    }\n    \n    long long numerator = factorial[n];\n    long long denominator_inverse = (inverse_factorial[k]*inverse_factorial[n - k])%MOD;\n\n    return (numerator*denominator_inverse)%MOD;\n}\n\nint main()\n{\n    precompute();\n    \n    int n, length;\n    cin >> n >> length;\n    \n    long long answer = combinations(n + 2*length - 1, 2*length);\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Programs/Two Arrays.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MOD = 1e9 + 7;\nlong long factorial[MAX_N + 5], inverse_factorial[MAX_N + 5];\n\nlong long power(long long x, long long p)\n{\n    long long result = 1;\n    \n    while(p)\n    {\n        if(p%2 == 1)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        p /= 2;\n    }\n    \n    return result;\n}\n\nvoid precompute()\n{\n    factorial[0] = 1;\n    for(int i = 1; i <= MAX_N; i++)\n    {\n        factorial[i] = (i*factorial[i - 1])%MOD;\n    }\n    \n    inverse_factorial[MAX_N] = power(factorial[MAX_N], MOD - 2);\n    for(int i = MAX_N - 1; i >= 0; i--)\n    {\n        //i*(i - 1)! = i! => (i - 1)!^ = i!^ i\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\n    }\n}\n\nlong long combinations(long long n, long long k)\n{\n    if(n < k)\n    {\n        return 0;\n    }\n    \n    long long numerator = factorial[n];\n    long long denominator_inverse = (inverse_factorial[k]*inverse_factorial[n - k])%MOD;\n    \n    //cout << \"C(\" << n << \",\" << k << \") = \" << (numerator*denominator_inverse)%MOD << endl;\n    return (numerator*denominator_inverse)%MOD;\n}\n\n//Number of strings of length N consisting of numbers in [L, R]\nlong long count(long long left, long long right, long long length)\n{\n    //Either first or last element is fixed\n    long long stars = length - 1;\n    long long bars = right - left;\n    \n    return combinations(stars + bars, stars);\n}\n\nint main()\n{\n    precompute();\n    \n    int n, length;\n    cin >> n >> length;\n    \n    long long answer = 0;\n    for(int a_ending = 1; a_ending <= n; a_ending++)\n    {\n        for(int b_ending = a_ending; b_ending <= n; b_ending++)\n        {\n            answer += (count(1, a_ending, length)*count(b_ending, n, length))%MOD;\n            \n            answer %= MOD;\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 80/Programs/Yet Another Meme Problem.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint digit_count(int n)\n{\n    int count = 0;\n    \n    while(n)\n    {\n        n /= 10;\n        \n        count++;\n    }\n    \n    return count;\n}\n\nvoid solve()\n{\n    int a, b;\n    cin >> a >> b;\n\n    //a.b + a + b = 10a + b => a.b = 9a => a.b = 9a => b = 9\n    //a.b + a + b = 100a + b => a.b = 99a => b = 99\n    \n    long long no_of_pairs = 0;\n    \n    for(long long i = 10; i - 1 <= b; i *= 10)\n    {\n        no_of_pairs += a;\n    }\n    \n    cout << no_of_pairs << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Explanation/Display the Number Explanation.txt",
    "content": "Given two integers, the one with the larger length is always larger.\n\n1. First, we will try to maximise the length\n\n2. The digit with the minimum cost is 1\n\n3. So, we will put as many 1s as possible\n\n4. If n is even, then we can just put all 1s\n\n5. If n is odd, we will have one segment left over. So we can try using it.\n\n6. 7 costs only 3 segments. So, we will replace one of the 1s with 7\n\n7. Out of all the 1s, it is optimal to replace the 1 which comes first from the left as it is the most significant.\n\n------\n\noid solve()\n{\n    int n;\n    scanf(\"%d\", &n);\n\n    int no_of_1s = 0, no_of_7s = 0;\n\n    if(n%2 == 0)\n    {\n        no_of_1s = n/2;\n    }\n    else\n    {\n        no_of_1s = (n - 3)/2;\n        no_of_7s = 1;\n    }\n\n    if(no_of_7s > 0)\n    {\n        printf(\"7\");\n    }\n\n    for(int i = 1; i <= no_of_1s; i++)\n    {\n        printf(\"1\");\n    }\n\n    printf(\"\\n\");\n\n    return;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Explanation/Infinite Prefixes Explanation.txt",
    "content": "Let balance [i] denote the balance of the first i characters.\n\nLet us now check if there is some point at which the balance x can be arrived at the i-th characters\n\nThis means that the entire string will be concatenated some number of times (possibly 0) and then the i-th character will be added.\n\nWhat we are essentially checking is if there is a non-negative integer q such that\n\nq(balance[n]) + balance[i] = x\n\n------\n\nWe will go through the string and for each character S[i], check if it is possible to end at i with balance x after some concatenations.\n\n-----\n\nWhen are there an infinite number of answers ?\n\nThis happens when balance[n] = 0 and at some point balance[i] = x\n\nThis will ensure that every concatenation will result in balance[i] = x as the balance becomes 0 at the end each time\n\n------\n\nvoid solve()\n{\n    int length, balance;\n    cin >> length >> balance;\n\n    string S;\n    cin >> S;\n\n    vector <int> frequency(2, 0);\n    for(int i = 0; i < length; i++)\n    {\n        frequency[S[i] - '0']++;\n    }\n\n    int whole_balance = frequency[0] - frequency[1];\n\n    int no_of_prefixes = (balance == 0 ? 1 : 0);\n\n    frequency[0] = 0; frequency[1] = 0;\n\n    for(int i = 0; i < length; i++)\n    {\n        frequency[S[i] - '0']++;\n\n        int prefix_balance = frequency[0] - frequency[1];\n\n        if(whole_balance != 0 && ((balance - prefix_balance)%whole_balance == 0 && (balance - prefix_balance)/whole_balance >= 0))\n        {\n            no_of_prefixes++;\n        }\n\n        if(whole_balance == 0 && prefix_balance == balance)\n        {\n            cout << \"-1\\n\";\n\n            return;\n        }\n    }\n\n    cout << no_of_prefixes << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Explanation/Obtain the String Explanation.txt",
    "content": "We will be greedy in constructing the string.\n\n1. Initially we have matches 0 characters\n2. We will then look for the earliest location of T[0]\n3. Then, we will look for the earliest location in [0, n] in S for T[0]. Let this position be p.\n4. Then, we will look for the earliest location in [p, n] in S for T[1]\n5. If T[1] is not present in [p, n] but is in [0, p - 1], we will go back and start another subsequence.\n\n-----\n\nvoid solve()\n{\n    string S, T;\n    cin >> S >> T;\n\n    const int NO_OF_ALPHABETS = 26;\n\n    vector <vector <int> > locations(NO_OF_ALPHABETS);\n    for(int i = 0; i < S.size(); i++)\n    {\n        locations[S[i] - 'a'].push_back(i);\n    }\n\n    int operations = 1, last_matched = -1;\n\n    for(int i = 0; i < T.size(); i++)\n    {\n        if(locations[T[i] - 'a'].size() == 0)\n        {\n            cout << \"-1\\n\";\n\n            return;\n        }\n\n        auto it = upper_bound(locations[T[i] - 'a'].begin(), locations[T[i] - 'a'].end(), last_matched);\n\n        //cout << \"At \"<< T[i] << \"\\n\";\n\n        if(it == locations[T[i] - 'a'].end())\n        {\n            operations++;\n\n            last_matched = locations[T[i] - 'a'][0];\n        }\n        else\n        {\n            last_matched = *it;\n        }\n    }\n\n    cout << operations << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Explanation/Same GCDs Explanation.txt",
    "content": "1. If gcd(a, m) = gcd(a + x, m), then x is a multiple of m\n\n2. a = m = 0 (mod g). This means that x has to be = 0 (mod g)\n\n3. We only have to be careful of the case when gcd(a + x, m) = q.g i.e. some multiple of g > 1\n\n4. We can divide everything by g. Then, gcd(a' + x', m') = 1 \n\n5. Given that gcd(a', m') = 1\n\n\n-----\n\n1. Now, we need to count the number of integers gcd(a' + x', m') = 1\n\n2. gcd(a' + x', m') = gcd( (a' + x') (mod m'), m')\n\n3. gcd(a' + x', m) = 1 only if gcd( (a' + x') (mod m'), m') = 1\n\n4. This means we have to count the number of integers that are coprime to m'. As x only goes from [0, m), this means we only need to consider (m' - 1) integers smaller than m'\n\n5. This is the Euler Totient of m'\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long gcd(long long x, long long y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n    \n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nlong long totient(long long n)\n{\n    long long totient = 1;\n    \n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            while(n%i == 0)\n            {\n                n /= i;\n                totient *= i;\n            }\n            \n            totient /= i;\n            totient *= (i - 1);\n        }\n    }\n    \n    if(n > 1)\n    {\n        totient *= 1*(n - 1);\n    }\n    \n    return totient;\n}\n\nvoid solve()\n{\n    long long a, m;\n    cin >> a >> m;\n    \n    long long g = gcd(a, m);\n    \n    long long answer = totient(m/g);\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Programs/Display the Number.cpp",
    "content": "#include <iostream>\n#include <cstdio>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    scanf(\"%d\", &n);\n    \n    int no_of_1s = 0, no_of_7s = 0;\n    \n    if(n%2 == 0)\n    {\n        no_of_1s = n/2;\n    }\n    else\n    {\n        no_of_1s = (n - 3)/2;\n        no_of_7s = 1;\n    }\n    \n    if(no_of_7s > 0)\n    {\n        printf(\"7\");\n    }\n    \n    for(int i = 1; i <= no_of_1s; i++)\n    {\n        printf(\"1\");\n    }\n    \n    printf(\"\\n\");\n    \n    return;\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Programs/Infinite Prefixes.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length, balance;\n    cin >> length >> balance;\n    \n    string S;\n    cin >> S;\n    \n    vector <int> frequency(2, 0);\n    for(int i = 0; i < length; i++)\n    {\n        frequency[S[i] - '0']++;\n    }\n    \n    int whole_balance = frequency[0] - frequency[1];\n    \n    int no_of_prefixes = (balance == 0 ? 1 : 0);\n    \n    frequency[0] = 0; frequency[1] = 0;\n    \n    for(int i = 0; i < length; i++)\n    {\n        frequency[S[i] - '0']++;\n        \n        int prefix_balance = frequency[0] - frequency[1];\n        \n        if(whole_balance != 0 && ((balance - prefix_balance)%whole_balance == 0 && (balance - prefix_balance)/whole_balance >= 0))\n        {\n            no_of_prefixes++;\n        }\n        \n        if(whole_balance == 0 && prefix_balance == balance)\n        {\n            cout << \"-1\\n\";\n            \n            return;\n        }\n    }\n    \n    cout << no_of_prefixes << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Programs/Obtain the String.cpp",
    "content": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin, (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    string S, T;\n    cin >> S >> T;\n    \n    const int NO_OF_ALPHABETS = 26;\n    \n    vector <vector <int> > locations(NO_OF_ALPHABETS);\n    for(int i = 0; i < S.size(); i++)\n    {\n        locations[S[i] - 'a'].push_back(i);\n    }\n    \n    int operations = 1, last_matched = -1;\n    \n    for(int i = 0; i < T.size(); i++)\n    {\n        if(locations[T[i] - 'a'].size() == 0)\n        {\n            cout << \"-1\\n\";\n            \n            return;\n        }\n        \n        auto it = upper_bound(locations[T[i] - 'a'].begin(), locations[T[i] - 'a'].end(), last_matched);\n        \n        //cout << \"At \"<< T[i] << \"\\n\";\n        \n        if(it == locations[T[i] - 'a'].end())\n        {\n            operations++;\n            \n            last_matched = locations[T[i] - 'a'][0];\n        }\n        else\n        {\n            last_matched = *it;\n        }\n    }\n    \n    cout << operations << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 81/Programs/Same GCDs.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long gcd(long long x, long long y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n    \n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nlong long totient(long long n)\n{\n    long long totient = 1;\n    \n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            while(n%i == 0)\n            {\n                n /= i;\n                totient *= i;\n            }\n            \n            totient /= i;\n            totient *= (i - 1);\n        }\n    }\n    \n    if(n > 1)\n    {\n        totient *= 1*(n - 1);\n    }\n    \n    return totient;\n}\n\nvoid solve()\n{\n    long long a, m;\n    cin >> a >> m;\n    \n    long long g = gcd(a, m);\n    \n    long long answer = totient(m/g);\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Explanations/Erasing Zeroes Explanation.txt",
    "content": "We will count the number of 0s in between the leftmost 1 and the rightmost 1\n\n----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    int left_one = -1, right_one = -1;\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        if(S[i] == '1')\n        {\n            left_one = i;\n        }\n    }\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '1')\n        {\n            right_one = i;\n        }\n    }\n\n    int zeroes = 0;\n    for(int i = left_one; i <= right_one; i++)\n    {\n        if(S[i] == '0')\n        {\n            zeroes++;\n        }\n    }\n\n    cout << zeroes << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Explanations/National Project Explanation.txt",
    "content": "Let us notice that if we can finish it in x days, then we can also finish it in (x + 1) days\n\nIf we cannot finish it in x days, then we cannot finish it in (x - 1) days\n\nThis enables us to use binary search !\n\n------\n\nFor a given x, we will check if it is possible to finish !\n\nint possible(long long x, long long n, long long g, long long b)\n{\n   long long half = ceil(n, 2);\n\n    long long no_of_cycles = x/(g + b);\n\n    long long extra = x - no_of_cycles*(g + b);\n    long long extra_good = 0, extra_bad = 0;\n\n    if(extra > 0)\n    {\n        extra_good = min(g, extra);\n\n        extra -= extra_good;\n    }\n\n    if(extra > 0)\n    {\n        extra_bad = min(b, extra);\n\n        extra -= extra_bad;\n    }\n\n    long long total_good = no_of_cycles*g + extra_good;\n    long long total_bad = no_of_cycles*b + extra_bad;\n\n    if(total_good < half|| total_good + total_bad < n)\n    {\n        return false;\n    }\n\n    return true;\n}\n\n-----\n\nWe will do binary search over x and find the best possible x\n\nWe will maintain the invariant that it is not possible in <= L days and\nalways possible in >= R days\n\nWhen (R - L = 1), it is possible\n\n-----\n\nvoid solve()\n{\n    long long no_of_days, good_days, bad_days;\n    cin >> no_of_days >> good_days >> bad_days;\n\n    const long long oo = 1e18;\n    long long left = 0, right = oo;\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n\n        if(possible(mid, no_of_days, good_days, bad_days))\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n\n    cout << right << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Explanations/Perfect Keyboard Explanation.txt",
    "content": "1. Draw a graph \nThe vertices are the alphabets and the edges are drawn between consecutive characters. \nWe have to be careful about not adding the same edge twice. This is very important.\n\n    for(int i = 1; i < password.size(); i++)\n    {\n        if(adjacency[password[i] - 'a'][password[i - 1] - 'a'] == false)\n        {\n            adjacency[password[i] - 'a'][password[i - 1] - 'a'] = true;\n            adjacency[password[i - 1] - 'a'][password[i] - 'a'] = true;\n                                         \n            graph[password[i] - 'a'].push_back(password[i - 1] - 'a');\n            graph[password[i - 1] - 'a'].push_back(password[i] - 'a');\n            \n            degree[password[i] - 'a']++;\n            degree[password[i - 1] - 'a']++;\n        }\n        \n    }\n\n----\n\n2. If any vertex has degree > 2, it is not possible as any key can only have 2 neighbours\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(degree[alpha] > 2)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n\n-----\n\n3. Now, we must look at each connected component of the graph seperately. \nWe must find the component number of each vertex. We can do this by performing a series of DFS \n\n    int component = 1;\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(component_no[alpha] == 0)\n        {\n            dfs(alpha, -1, component++);\n        }\n    }\n    \n-----\n\nHere is the DFS itself \n\nvoid dfs(int v, int parent_v, int c)\n{\n    //cout << \"V = \" << v << \" C = \" << c << \"\\n\";\n    component_no[v] = c;\n    \n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n        \n        if(child_v == parent_v || component_no[child_v] == c)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v, c);\n    }\n}\n\n-----\n\n4. Every component will be printed together. \nSo, first we will print characters of component 1, then characters of component 2, and so on. \n\n-----\n\n5. How to print characters of a given component ? \nThere have to be 2 vertices in this component of degree 1 and every other vertex must have degree 2. \nWe will start from one of the vertices of degree 1 and keep going till we reach the vertex of degree 2\n\nIf the component is of size 1, then we can just print it\nOtherwise, we will look for the first border and then DFS till we reach the second border\n\nfor(int c = 1; c < component; c++)\n    {\n        vector <int> this_component;\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            if(component_no[alpha] == c)\n            {\n                this_component.push_back(alpha);\n            }\n        }\n        \n        if(this_component.size() == 1)\n        {\n            keyboard += (char)('a' + this_component[0]);\n            used[this_component[0]] = true;\n            continue;\n        }\n        \n        int border_1 = -1, border_2 = -1;\n        for(int i = 0; i < this_component.size(); i++)\n        {\n            if(degree[this_component[i]] == 1)\n            {\n                if(border_1 == -1)\n                    border_1 = this_component[i];\n                else\n                    border_2 = this_component[i];\n            }\n        }\n        \n        if(border_1 == -1 || border_2 == -1)\n        {\n            cout << \"NO\\n\";\n            \n            return;\n        }\n        \n        keyboard += (char)('a' + border_1);\n        used[border_1] = true;\n        \n        while(keyboard.back() - 'a' != border_2)\n        {\n            for(int i = 0; i < graph[keyboard.back() - 'a'].size(); i++)\n            {\n                if(!used[graph[keyboard.back() - 'a'][i]])\n                {\n                    int next = graph[keyboard.back() - 'a'][i];\n                    \n                    keyboard += (char)('a' + next);\n                    \n                    used[next] = true;\n                    \n                    break;\n                }\n            }\n        }\n        \n    }\n   \n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Programs/Erasing Zeroes.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    int left_one = -1, right_one = -1;\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        if(S[i] == '1')\n        {\n            left_one = i;\n        }\n    }\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '1')\n        {\n            right_one = i;\n        }\n    }\n    \n    int zeroes = 0;\n    for(int i = left_one; i <= right_one; i++)\n    {\n        if(S[i] == '0')\n        {\n            zeroes++;\n        }\n    }\n    \n    cout << zeroes << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Programs/Fill the Bag.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0);\n}\n\nvoid solve()\n{\n    long long n, no_of_boxes;\n    cin >> n >> no_of_boxes;\n    \n    const int MAX_BITS = 61;\n    \n    long long sum = 0;\n    vector <long long> frequency(MAX_BITS, 0);\n    for(int i = 1; i <= no_of_boxes; i++)\n    {\n        long long box;\n        cin >> box;\n        \n        for(int bit = 0; bit < MAX_BITS; bit++)\n        {\n            if( (1LL << bit) == box)\n            {\n                frequency[bit]++;\n            }\n        }\n        \n        sum += box;\n    }\n    \n    if(sum < n)\n    {\n        cout << \"-1\\n\";\n        \n        return;\n    }\n    \n    int minimum_divisions = 0;\n    for(int bit = 0; bit < MAX_BITS; bit++)\n    {\n        if(bit >= 1)\n            frequency[bit] += frequency[bit - 1]/2;\n        \n        if(is_bit_set(n, bit) && frequency[bit] == 0)\n        {\n            int source;\n        \n            for(source = bit; source < MAX_BITS; source++)\n            {\n                if(frequency[source] >= 1)\n                {\n                    break;\n                }\n            }\n            \n            //cout << \"Source = \" << source << \" Bit = \" << bit << \"\\n\";\n            for(int i = source; i > bit; i--)\n            {\n                frequency[i]--;\n                frequency[i - 1] += 2;\n                \n                minimum_divisions++;\n            }\n        }\n        \n        if(is_bit_set(n, bit))\n        {\n            frequency[bit]--;\n        }\n    }\n    \n    cout << minimum_divisions << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Programs/National Project.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d + (n%d != 0));\n}\n\nint possible(long long x, long long n, long long g, long long b)\n{\n   long long half = ceil(n, 2);\n    \n    long long no_of_cycles = x/(g + b);\n    \n    long long extra = x - no_of_cycles*(g + b);\n    long long extra_good = 0, extra_bad = 0;\n    \n    if(extra > 0)\n    {\n        extra_good = min(g, extra);\n        \n        extra -= extra_good;\n    }\n    \n    if(extra > 0)\n    {\n        extra_bad = min(b, extra);\n        \n        extra -= extra_bad;\n    }\n    \n    long long total_good = no_of_cycles*g + extra_good;\n    long long total_bad = no_of_cycles*b + extra_bad;\n    \n    if(total_good < half|| total_good + total_bad < n)\n    {\n        return false;\n    }\n    \n    return true;\n}\n\nvoid solve()\n{\n    long long no_of_days, good_days, bad_days;\n    cin >> no_of_days >> good_days >> bad_days;\n    \n    const long long oo = 1e18;\n    long long left = 0, right = oo;\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n\n        if(possible(mid, no_of_days, good_days, bad_days))\n        {\n            right = mid;\n        }\n        else\n        {   \n            left = mid;\n        }\n    }\n\n    cout << right << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 82/Programs/Perfect Keyboard.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int NO_OF_ALPHABETS = 26;\nvector <int> degree(NO_OF_ALPHABETS, 0);\nvector <int> graph[NO_OF_ALPHABETS];\nvector <int> component_no(NO_OF_ALPHABETS, 0);\n\nvoid dfs(int v, int parent_v, int c)\n{\n    //cout << \"V = \" << v << \" C = \" << c << \"\\n\";\n    component_no[v] = c;\n    \n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child_v = graph[v][i];\n        \n        if(child_v == parent_v || component_no[child_v] == c)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v, c);\n    }\n}\n\nvoid solve()\n{\n    string password;\n    cin >> password;\n    \n    const int NO_OF_ALPHABETS = 26;\n    vector <vector <int> > adjacency(NO_OF_ALPHABETS,\n                                     vector <int> (NO_OF_ALPHABETS, false));\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        degree[alpha] = 0;\n        \n        graph[alpha].clear();\n        \n        component_no[alpha] = 0;\n    }\n    \n    for(int i = 1; i < password.size(); i++)\n    {\n        if(adjacency[password[i] - 'a'][password[i - 1] - 'a'] == false)\n        {\n            adjacency[password[i] - 'a'][password[i - 1] - 'a'] = true;\n            adjacency[password[i - 1] - 'a'][password[i] - 'a'] = true;\n                                         \n            graph[password[i] - 'a'].push_back(password[i - 1] - 'a');\n            graph[password[i - 1] - 'a'].push_back(password[i] - 'a');\n            \n            degree[password[i] - 'a']++;\n            degree[password[i - 1] - 'a']++;\n        }\n        \n    }\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(degree[alpha] > 2)\n        {   \n            cout << \"NO\\n\";\n            return;\n        }\n    }\n    \n    int component = 1;\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(component_no[alpha] == 0)\n        {\n            dfs(alpha, -1, component++);\n        }\n    }\n    \n    string keyboard;\n    vector <int> components;\n    vector <int> used(NO_OF_ALPHABETS, false);\n    for(int c = 1; c < component; c++)\n    {\n        vector <int> this_component;\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            if(component_no[alpha] == c)\n            {\n                this_component.push_back(alpha);\n            }\n        }\n        \n        if(this_component.size() == 1)\n        {\n            keyboard += (char)('a' + this_component[0]);\n            used[this_component[0]] = true;\n            continue;\n        }\n        \n        int border_1 = -1, border_2 = -1;\n        for(int i = 0; i < this_component.size(); i++)\n        {\n            if(degree[this_component[i]] == 1)\n            {\n                if(border_1 == -1)\n                    border_1 = this_component[i];\n                else\n                    border_2 = this_component[i];\n            }\n        }\n        \n        if(border_1 == -1 || border_2 == -1)\n        {\n            cout << \"NO\\n\";\n            \n            return;\n        }\n        \n        keyboard += (char)('a' + border_1);\n        used[border_1] = true;\n        \n        while(keyboard.back() - 'a' != border_2)\n        {\n            for(int i = 0; i < graph[keyboard.back() - 'a'].size(); i++)\n            {\n                if(!used[graph[keyboard.back() - 'a'][i]])\n                {\n                    int next = graph[keyboard.back() - 'a'][i];\n                    \n                    keyboard += (char)('a' + next);\n                    \n                    used[next] = true;\n                    \n                    break;\n                }\n            }\n        }\n        \n    }\n   \n    cout << \"YES\\n\";\n    cout << keyboard << \"\\n\";\n    return;\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Explanations/Adding Powers Explanation.txt",
    "content": "We will precompute all the powers of k we need\n\nThen, we will go through each element of the array.\n\nWe will write it in base K. If any digit is > 1, then it is not possible\n\nWe will keep track of all the powers we have used so far and ensure there is no repetition\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> power;\n    power.push_back(1);\n\n    while(power.back() <= 1e16/k)\n    {\n        power.push_back(power.back()*k);\n    }\n\n    int possible = true;\n    map <long long, int> used;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long x = A[i];\n\n        for(int p = power.size() - 1; p >= 0 && x > 0; p--)\n        {   //cout << \"X = \" << x << \" P = \" << power[p] << \"\\n\";\n            if(x < power[p])\n            {\n                continue;\n            }\n\n            if(used[p])\n            {\n                possible = false;\n                break;\n            }\n\n            x -= power[p];\n\n            if(x >= power[p])\n            {\n                possible = false;\n                break;\n            }\n\n            used[p] = true;\n        }\n    }\n\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Explanations/Array Shrinking Explanation.txt",
    "content": "Let final(L, R) be the final element in [L, R] if it is possible\nto reduce [L, R] to a single element and - 1 otherwise.\n\nWe can build this recursively.\n\nIt is possible to reduce [L, R] to a single element if there exists an i such that\n[L, i] is reducible and [i + 1, R] is reducible and\nfinal[L, i] = final[i + 1, R]\n\n-----\n\nWe will build up final(L, R) for all (L, R) pairs in O(n^3) time\n\nNow let Answer(i) be the minimum number of parts we can divide the first i\nelements into\n\nA segment [L, R] is said to be a part if it can be reduced to 1 number\n\nf(i) = min(1 + f(j - 1)), for all j such that [j, i] is reducible to 1 number\n\n-----\n\nThe answer is f(n)\n\n------\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int NOT_REDUCIBLE = -1, oo = 1e9;\n    vector <vector <int> > final_element(no_of_elements + 1, vector <int> (no_of_elements + 1));\n    for(int length = 1; length <= no_of_elements; length++)\n    {\n        for(int left = 1, right = left + length - 1; right <= no_of_elements; left++, right++)\n        {\n            final_element[left][right] = NOT_REDUCIBLE;\n\n            if(length == 1)\n            {\n                final_element[left][right] = A[left];\n                continue;\n            }\n\n            for(int i = left; i < right; i++)\n            {\n                if(final_element[left][i] != NOT_REDUCIBLE && final_element[left][i] == final_element[i + 1][right])\n                {\n                    final_element[left][right] = final_element[left][i] + 1;\n                }\n            }\n        }\n    }\n\n    vector <int> minimum_parts(no_of_elements + 1, oo);\n    minimum_parts[0] = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = 1; j <= i; j++)\n        {\n            if(final_element[j][i] == NOT_REDUCIBLE)\n            {\n                continue;\n            }\n\n            minimum_parts[i] = min(minimum_parts[i], minimum_parts[j - 1] + 1);\n        }\n    }\n\n    cout << minimum_parts[no_of_elements] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Explanations/Bogosort Explanation.txt",
    "content": "We will sort A in descending order\n\nFor any (i < j), (A[i] >= A[j])\n\nSo, A[i] - i != A[j] - j\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n    reverse(all(A));\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Explanations/Count the Arrays Explanation.txt",
    "content": "First, of all we should choose (n - 1) distinct integers from m integers.\n\nThis can be done in C(m, n - 1)\n\nSecondly, we should choose one element which occurs 2 times.\nThis cannot be the maximum integer but can be any of the other integers.\nSo there are (n - 2) ways of doing this\n\nNow, each of the integers, except the maximum and the 2 duplicates can either\ncoming in the ascending part or the descending part.\nSo, there are 2^{n - 3} ways of doing this\n\n1. We select integers -> C(m, n - 1)\n2. We choose the duplicates -> (n - 2)\n3. We choose which side each of the (n - 3) integers are -> 2^{n - 3}\n\n-----\n\nint main()\n{\n    precompute_factorials();\n\n    long long no_of_elements, m;\n    cin >> no_of_elements >> m;\n\n    if(no_of_elements == 2)\n    {\n        cout << \"0\\n\";\n\n        return 0;\n    }\n\n    long long answer = (choose(m, no_of_elements - 1)*(no_of_elements - 2))%MOD;\n    answer *= power(2, no_of_elements - 3);\n    answer %= MOD;\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Explanations/Two Regular Polygons Explanation.txt",
    "content": "The inscribed polygon must also be a regular polygon so that means\nit's vertices must be equally spaced\n\nThis means that m must evenly divide n\n\n-----\n\nvoid solve()\n{\n    int original_vertices, new_vertices;\n    cin >> original_vertices >> new_vertices;\n\n    cout << (original_vertices%new_vertices == 0 ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Programs/Adding Powers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> power;\n    power.push_back(1);\n    \n    while(power.back() <= 1e16/k)\n    {\n        power.push_back(power.back()*k);\n    }\n    \n    int possible = true;\n    map <long long, int> used;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long x = A[i];\n        \n        for(int p = power.size() - 1; p >= 0 && x > 0; p--)\n        {   //cout << \"X = \" << x << \" P = \" << power[p] << \"\\n\";\n            if(x < power[p])\n            {\n                continue;\n            }\n            \n            if(used[p])\n            {\n                possible = false;\n                break;\n            }\n            \n            x -= power[p];\n            \n            if(x >= power[p])\n            {\n                possible = false;\n                break;\n            }\n            \n            used[p] = true;\n        }\n    }\n               \n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Programs/Array Shrinking.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int NOT_REDUCIBLE = -1, oo = 1e9;\n    vector <vector <int> > final_element(no_of_elements + 1, vector <int> (no_of_elements + 1));\n    for(int length = 1; length <= no_of_elements; length++)\n    {\n        for(int left = 1, right = left + length - 1; right <= no_of_elements; left++, right++)\n        {\n            final_element[left][right] = NOT_REDUCIBLE;\n            \n            if(length == 1)\n            {\n                final_element[left][right] = A[left];\n                continue;\n            }\n            \n            for(int i = left; i < right; i++)\n            {\n                if(final_element[left][i] != NOT_REDUCIBLE && final_element[left][i] == final_element[i + 1][right])\n                {\n                    final_element[left][right] = final_element[left][i] + 1;\n                }\n            }\n        }\n    }\n    \n    vector <int> minimum_parts(no_of_elements + 1, oo);\n    minimum_parts[0] = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int j = 1; j <= i; j++)\n        {\n            if(final_element[j][i] == NOT_REDUCIBLE)\n            {\n                continue;\n            }\n            \n            minimum_parts[i] = min(minimum_parts[i], minimum_parts[j - 1] + 1);\n        }\n    }\n    \n    cout << minimum_parts[no_of_elements] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Programs/Bogosort.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin() + 1, (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    reverse(all(A));\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Programs/Count the Arrays.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 998244353, MAX_N = 5e5 + 5;\nvector <long long> factorials(MAX_N + 1, 0), inverse_factorials(MAX_N + 1, 0);\n\nlong long power(long long x, long long p)\n{\n    long long answer = 1;\n    \n    while(p)\n    {\n        if(p%2 == 1)\n        {\n            answer = (answer*x)%MOD;\n        }\n        \n        x = (x*x)%MOD;\n        p = p/2;\n    }\n    \n    return answer;\n}\n\nlong long inverse(long long n)\n{\n    return power(n, MOD - 2);\n}\n\nvoid precompute_factorials()\n{\n    factorials[0] = 1;\n    for(int i = 1; i < MAX_N; i++)\n    {\n        factorials[i] = (factorials[i - 1]*i)%MOD;\n    }\n    \n    //i*(i - 1)! = i!\n    inverse_factorials[MAX_N - 1] = inverse(factorials[MAX_N - 1]);\n    for(int i = MAX_N - 2; i >= 0; i--)\n    {\n        inverse_factorials[i] = ((i + 1)*inverse_factorials[i + 1])%MOD;\n    }\n}\n\nlong long choose(long long n, long long r)\n{\n    long long numerator = factorials[n];\n    long long inverse_denominator = (inverse_factorials[r]*inverse_factorials[n - r])%MOD;\n    \n    return (numerator*inverse_denominator)%MOD;\n}\n\nint main()\n{\n    precompute_factorials();\n    \n    long long no_of_elements, m;\n    cin >> no_of_elements >> m;\n    \n    if(no_of_elements == 2)\n    {\n        cout << \"0\\n\";\n        \n        return 0;\n    }\n    \n    long long answer = (choose(m, no_of_elements - 1)*(no_of_elements - 2))%MOD;\n    answer *= power(2, no_of_elements - 3);\n    answer %= MOD;\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 83/Programs/Two Regular Polygons.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int original_vertices, new_vertices;\n    cin >> original_vertices >> new_vertices;\n    \n    cout << (original_vertices%new_vertices == 0 ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 84/Explanations/Count the Blocks Explanation.txt",
    "content": "Let us suppose we are dealing with blocks of length i\n\n1. How many ways are there of making this particular block ?\n\n10\n\n2. How many ways are there to choose it's neighbour ?\n\nThe neighbour must be a different digit.\n\nIf i = n, then there is no neighbour\n\nOtherwise, if the block is at the beginning or the end, there is 1 neighbour\nIf the block is in the middle, there are 2 neighbours\n\nWe will deal with both cases separately.\nEach neighbour can take on any of 9 choices\n\n3. Where are the positions where we can place the block ?\n\nIf the block is in the beginning, it can be placed in 2 ways.\n\nIf the block is in the middle, then it can be placed in (n - i - 1) ways.\nIt can't be placed in any of the last (n - i) places as there isn't enough room\nIt can't be placed in the beginning too.\nThat's why it is (n - i - 1)\n\n------\n\nThe remaining digits can be filled in any order apart from the block and it's neighbour\n\n------\n\ni = n, then 10 ways\nEnd = 2.10.9.10^(n - i - 1)\nMiddle = (n - i - 2).10.9^2.10^(n - i - 2)\n\n----\n\nPlease note that we do not have to worry about overcounting because if a block\noccurs 2 times in the same number, then the block should be counted twice\n\n-----\n\nint main()\n{\n    int length;\n    cin >> length;\n\n    const int MOD = 998244353;\n    for(int i = 1; i <= length; i++)\n    {\n        if(i == length)\n        {\n            cout << \"10\\n\";\n\n            break;\n        }\n\n        long long no_of_spots = 2, ways_for_block = 10, neighbour = 9;\n        long long remaining = power(10, length - i - 1, MOD);\n\n        long long corners = (no_of_spots*ways_for_block)*neighbour;\n        corners = (corners*remaining)%MOD;\n\n        no_of_spots = length - i - 1, ways_for_block = 10, neighbour = 9*9;\n        remaining = power(10, length - i - 2, MOD);\n\n        long long middle = (no_of_spots*ways_for_block)*neighbour;\n        middle = (middle*remaining)%MOD;\n\n        long long blocks_here = (corners + middle)%MOD;\n        cout << blocks_here << \" \";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 84/Explanations/Sum of Odd Integers Explanation.txt",
    "content": "The minimum sum we can get is the sum of the first k odd integers \n\nn has to be >= that \n\nAfter that, we can increase the last odd integer in steps of 2 as much as we want.\n\nThe sum of the first k odd integers and the total sum have to have the same parity.\n\n-----\n\n#include <iostream>\n \nusing namespace std;\n \nvoid solve()\n{\n    long long n, no_of_summands;\n    cin >> n >> no_of_summands;\n    \n    //k(k + 1)/2\n    long long min_sum = (no_of_summands/2)*(2*no_of_summands - 1 + 1) + (no_of_summands%2)*no_of_summands;\n    //cout << \"S = \" << min_sum << \"\\n\";\n    cout << (min_sum <= n && min_sum%2 == n%2 ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 84/Programs/Count the Blocks.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long power(long long x, long long p, long long mod)\n{\n    long long answer = 1;\n    \n    while(p)\n    {\n        if(p%2)\n        {\n            answer = (answer*x)%mod;\n        }\n        \n        x = (x*x)%mod;\n        p = p/2;\n    }\n    \n    return answer;\n}\n\nint main()\n{\n    int length;\n    cin >> length;\n    \n    const int MOD = 998244353;\n    for(int i = 1; i <= length; i++)\n    {\n        if(i == length)\n        {\n            cout << \"10\\n\";\n            \n            break;\n        }\n        \n        long long no_of_spots = 2, ways_for_block = 10, neighbour = 9;\n        long long remaining = power(10, length - i - 1, MOD);\n        \n        long long corners = (no_of_spots*ways_for_block)*neighbour;\n        corners = (corners*remaining)%MOD;\n        \n        no_of_spots = length - i - 1, ways_for_block = 10, neighbour = 9*9;\n        remaining = power(10, length - i - 2, MOD);\n        \n        long long middle = (no_of_spots*ways_for_block)*neighbour;\n        middle = (middle*remaining)%MOD;\n        \n        long long blocks_here = (corners + middle)%MOD;\n        cout << blocks_here << \" \";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 84/Programs/Sum of Odd Integers.cpp",
    "content": "#include <iostream>\n \nusing namespace std;\n \nvoid solve()\n{\n    long long n, no_of_summands;\n    cin >> n >> no_of_summands;\n    \n    //k(k + 1)/2\n    long long min_sum = (no_of_summands/2)*(2*no_of_summands - 1 + 1) + (no_of_summands%2)*no_of_summands;\n    //cout << \"S = \" << min_sum << \"\\n\";\n    cout << (min_sum <= n && min_sum%2 == n%2 ? \"YES\\n\" : \"NO\\n\");\n}\n \nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Explanations/Circle of Monsters Explanation.txt",
    "content": "Observation - For any given monster, if it's neighbour is killed before it,\nthe number of bullets can only be reduced.\n\nIt cannot increase.\n\n-----\n\nStep 1 - We will count the total cost when every monster has his neighbour\nkilled first\n\nlong long total = 0;\n    for(int i = 1; i <= no_of_monsters; i++)\n    {\n        if(i == 1)\n        {\n            total += (B[no_of_monsters] >= A[1] ? 0 : A[1] - B[no_of_monsters]);\n\n            continue;\n        }\n\n        total += (B[i - 1] >= A[i] ? 0 : A[i] - B[i - 1]);\n    }\n\n-----\n\nStep 2 - Only 1 element should be killed without it's neighbour being killed first\n\nThere is only 1 element at most which should be killed 'alone'\n\nIf the i-th element is killed first, then we will be spending A[i] on it\n\nWe have counted that we will be spending (B[i - 1] - A[i]) bullets on A[i]\n\nIf i-th element is first, the total increases by [A[i] - (B[i - 1] - A[i])]\n\nWe will choose the element which causes the total to increase the least\n\n-----\n\n    long long effective_hit = max(A[1] - B[no_of_monsters], 0LL);\n    long long best_first = A[1] - effective_hit;\n    for(int i = 2; i <= no_of_monsters; i++)\n    {\n        effective_hit = max(A[i] - B[i - 1], 0LL);\n\n        best_first = min(best_first, A[i] - effective_hit);\n    }\n\n    total += best_first;\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Explanations/Divisor Paths Explanation.txt",
    "content": "Claim - The optimal path from x to y is\n\nx -> gcd(x, y) -> y\n\nEvery edge corresponds to 2 things - Multiplying by a prime or dividing by a prime\n\nTo go from x to y, we will have to remove every factor that x has and y does not\nAnd then add every factor that y has and x does not\n\nSuppose we divide by some prime p which both x and y have, we have to multiply it again\nThis adds 2p to our total path length\n\nSuppose we multiply by some prime that y does not have, we have to later divide by p too\nThis also adds 2p to our total path length.\n\nThis clearly shows that it is never optimal to add or remove any extra factors.\nWe will start from x and go to gcd(x, y) and go from there to y\n\n-----\n\nNow, let us see how to count the number of paths from X to G\n\nLet us look at each prime factor seperately\n\nLet us suppose we have to multiply G by\n\np1^a1 p2^a2 ... pk^ak\n\nin order to get X\n\n----\n\nWe have to make a total of (a1 + a2 + ... + ak) steps\nThis can be done in (a1 + a2 + ... + ak)! ways\n\nBut, we can interchange any two steps of multiplying by the same prime and get the same path\nSo, we have to divide by\n\n(a1)! (a2)! ... (ak)!\n\n-----\n\nWe will precompute the factorials and inverse factorials beforehand along with the prime factors of D\n\n----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 998244353, MAX_N = 1e6 + 5;\n\nvector <long long> primes, factorial(MAX_N), inverse_factorial(MAX_N);\n\nlong long gcd(long long x, long long y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n\n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nlong long power_mod(long long x, long long power)\n{\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%MOD;\n\n        x = (x*x)%MOD;\n\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nvoid factorise(long long d)\n{\n    for(long long i = 2; i*i <= d; i++)\n    {\n        if(d%i == 0)\n        {\n            primes.push_back(i);\n\n            while(d%i == 0)\n            {\n                d /= i;\n            }\n        }\n    }\n\n    if(d > 1)\n    {\n        primes.push_back(d);\n    }\n}\n\nvoid precompute_factorial()\n{\n    factorial[0] = 1;\n    for(int i = 1; i < MAX_N; i++)\n    {\n        factorial[i] = (i*factorial[i - 1])%MOD;\n    }\n\n    //i*(i - 1)! = i! => (i - 1)!^ = i!^i\n    inverse_factorial[MAX_N - 1] = power_mod(factorial[MAX_N - 1], MOD - 2);\n    for(int i = MAX_N - 2; i >= 0; i--)\n    {\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\n    }\n}\n\n//Here y is a divisor of x, by convention\nlong long get_count(long long x, long long y)\n{\n    if(x%y != 0)\n    {\n        return -1;\n    }\n\n    vector <int> path;\n\n    for(int i = 0; i < primes.size(); i++)\n    {\n        int x_exponent = 0, y_exponent = 0;\n\n        if(x%primes[i] != 0)\n        {\n            continue;\n        }\n\n        while(y%primes[i] == 0)\n        {\n            y /= primes[i];\n\n            y_exponent++;\n        }\n\n        while(x%primes[i] == 0)\n        {\n            x /= primes[i];\n\n            x_exponent++;\n        }\n\n        path.push_back(x_exponent - y_exponent);\n    }\n\n    int total_steps = 0;\n    for(int i = 0; i < path.size(); i++)\n    {\n        total_steps += path[i];\n    }\n\n    long long answer = factorial[total_steps];\n    for(int i = 0; i < path.size(); i++)\n    {\n        answer = (answer*inverse_factorial[path[i]])%MOD;\n    }\n\n    return answer;\n}\n\nint main()\n{\n    precompute_factorial();\n\n    long long d;\n    int no_of_queries;\n    cin >> d >> no_of_queries;\n\n    factorise(d);\n\n    while(no_of_queries--)\n    {\n        long long x, y;\n        cin >> x >> y;\n\n        long long path_1 = get_count(x, gcd(x, y));\n        long long path_2 = get_count(y, gcd(x, y));\n\n        long long answer = (path_1*path_2)%MOD;\n\n        cout << answer << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Explanations/Level Statistics Explanation.txt",
    "content": "We just need to simulate and check the conditions\n\nP[i - 1] <= P[i] and C[i - 1] <= C[i] and (C[i] - C[i - 1] <= P[i] - P[i - 1])\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> P(no_of_elements + 1);\n    vector <int> C(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> P[i] >> C[i];\n    }\n\n    int possible = true;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(P[i - 1] > P[i] || C[i - 1] > C[i])\n        {\n            possible = false;\n        }\n\n        if(C[i] - C[i - 1] > P[i] - P[i - 1])\n        {\n            possible = false;\n        }\n    }\n\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Explanations/Middle Class Explanation.txt",
    "content": "Let us sort the elements in descending order\n\nA[1] >= A[2] >= A[3] >= .... >= A[N]\n\nIf we apply the operation on [1, i], then A[1] = A[2] = ... = A[i] = Sum/i\n\nThis means, that it is possible to make the first i people >= x\n\nIf Sum[1, i] >= i*x\n\nWe will check the length of the maximum such prefix we can make >= x\n\n-----\n\nThis is the optimal way.\nIf we replace any of the elements by a smaller element, the segment average\ncan only decrease\n\n-----\n\nvoid solve()\n{\n    long long no_of_elements, x;\n    cin >> no_of_elements >> x;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    long long sum = 0;\n    int answer = 0;\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        sum += A[i];\n\n        if(sum < (answer + 1)*x)\n        {\n            break;\n        }\n\n        answer++;\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Explanations/Minimum Euler Cycle Explanation.txt",
    "content": "For n = 7, the optimal strategy looks like this  \n\n1 2 1 3 1 4 1 5 1 6 1 7 \n2 3 2 4 2 5 2 6 2 7\n3 4 3 5 3 6 3 7\n4 5 4 6 4 7\n5 6 5 7\n6 7 \n1\n\nLet us call each of these steps a 'segment' \n\nSegment 1 - 1 2 1 3 1 4 1 5 1 6 1 7 \nSegment 2 - 2 3 2 4 2 5 2 6 2 7 \nSegment 3 - 3 4 3 5 3 6 3 7\nSegment 4 - 4 5 4 6 4 7\nSegment 5 - 5 6 5 7 \nSegment 6 - 6 7 \nSegment 7 - 1\n\nApart from the last segment, segment i has 2(7 - i) elements \n\n-----\n\nWe can utilise this pattern to print all the integers from i = L to i = R\n\nFirst, we will find out which 'segment' L is in \nThe point inside the segment where L is will be called the in_point. \nFor convenience, in_point will always point to the even position \n(The odd positions in a segment will always be the segment number)\n\n-----\n\nvoid solve()\n{\n    int n;\n    long long left, right;\n    scanf(\"%d %I64d %I64d\",&n, &left, &right);\n    \n    long long segment = 0, in_point = 0;\n    for(long long i = 1, sum = 0; i <= n; i++)\n    {\n        long long new_sum = sum + 2*(n - i);\n        \n        if(i == n)\n        {\n            new_sum++;\n        }\n        \n        if(new_sum >= left)\n        {\n            segment = i;\n            \n            in_point = (left - sum)/2 + i + (left - sum)%2;\n            \n            break;\n        }\n        \n        sum = new_sum;\n    }\n    \n    for(long long i = left; i <= right; )\n    {\n        if(segment == n)\n        {\n            printf(\"1 \");\n            \n            break;\n        }\n        \n        if(i%2 == 0)\n        {\n            printf(\"%I64d \", in_point);\n            \n            in_point++;\n            \n            i++;\n        }\n        else\n        {\n            printf(\"%I64d \", segment);\n            \n            i++;\n            \n            if(i > right)\n            {\n                break;\n            }\n            \n            printf(\"%I64d \", in_point);\n            \n            in_point++;\n            \n            i++;\n        }\n        \n        if(in_point == n + 1)\n        {\n            segment++;\n            \n            in_point = segment + 1;\n        }\n    }\n    \n    printf(\"\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Programs/Circle of Monsters.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_monsters;\n    scanf(\"%d\", &no_of_monsters);\n    \n    vector <long long> A(no_of_monsters + 1), B(no_of_monsters + 1);\n    for(int i = 1; i <= no_of_monsters; i++)\n    {\n        scanf(\"%I64d %I64d\", &A[i], &B[i]);\n    }\n    \n    long long total = 0;\n    for(int i = 1; i <= no_of_monsters; i++)\n    {\n        if(i == 1)\n        {\n            total += (B[no_of_monsters] >= A[1] ? 0 : A[1] - B[no_of_monsters]);\n            \n            continue;\n        }\n        \n        total += (B[i - 1] >= A[i] ? 0 : A[i] - B[i - 1]);\n    }\n    \n    long long effective_hit = max(A[1] - B[no_of_monsters], 0LL);\n    long long best_first = A[1] - effective_hit;\n    for(int i = 2; i <= no_of_monsters; i++)\n    {\n        effective_hit = max(A[i] - B[i - 1], 0LL);\n        \n        best_first = min(best_first, A[i] - effective_hit);\n    }\n    \n    total += best_first;\n    \n    printf(\"%I64d\\n\", total);\n}\n\nint main()\n{\n    int no_of_test_cases;\n    scanf(\"%d\", &no_of_test_cases);\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Programs/Divisor Paths.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 998244353, MAX_N = 1e6 + 5;\n\nvector <long long> primes, factorial(MAX_N), inverse_factorial(MAX_N);\n\nlong long gcd(long long x, long long y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n    \n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nlong long power_mod(long long x, long long power)\n{\n    long long result = 1;\n    \n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        \n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nvoid factorise(long long d)\n{\n    for(long long i = 2; i*i <= d; i++)\n    {\n        if(d%i == 0)\n        {\n            primes.push_back(i);\n            \n            while(d%i == 0)\n            {\n                d /= i;\n            }\n        }\n    }\n    \n    if(d > 1)\n    {\n        primes.push_back(d);\n    }\n}\n\nvoid precompute_factorial()\n{\n    factorial[0] = 1;\n    for(int i = 1; i < MAX_N; i++)\n    {\n        factorial[i] = (i*factorial[i - 1])%MOD;\n    }\n    \n    //i*(i - 1)! = i! => (i - 1)!^ = i!^i\n    inverse_factorial[MAX_N - 1] = power_mod(factorial[MAX_N - 1], MOD - 2);\n    for(int i = MAX_N - 2; i >= 0; i--)\n    {\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\n    }\n}\n\n//Here y is a divisor of x, by convention\nlong long get_count(long long x, long long y)\n{\n    if(x%y != 0)\n    {\n        return -1;\n    }\n    \n    vector <int> path;\n    \n    for(int i = 0; i < primes.size(); i++)\n    {\n        int x_exponent = 0, y_exponent = 0;\n        \n        if(x%primes[i] != 0)\n        {\n            continue;\n        }\n        \n        while(y%primes[i] == 0)\n        {\n            y /= primes[i];\n            \n            y_exponent++;\n        }\n        \n        while(x%primes[i] == 0)\n        {\n            x /= primes[i];\n            \n            x_exponent++;\n        }\n        \n        path.push_back(x_exponent - y_exponent);\n    }\n    \n    int total_steps = 0;\n    for(int i = 0; i < path.size(); i++)\n    {\n        total_steps += path[i];\n    }\n   \n    long long answer = factorial[total_steps];\n    for(int i = 0; i < path.size(); i++)\n    {   \n        answer = (answer*inverse_factorial[path[i]])%MOD;\n    }\n    \n    return answer;\n}\n\nint main()\n{\n    precompute_factorial();\n    \n    long long d;\n    int no_of_queries;\n    cin >> d >> no_of_queries;\n    \n    factorise(d);\n    \n    while(no_of_queries--)\n    {\n        long long x, y;\n        cin >> x >> y;\n        \n        long long path_1 = get_count(x, gcd(x, y));\n        long long path_2 = get_count(y, gcd(x, y));\n        \n        long long answer = (path_1*path_2)%MOD;\n        \n        cout << answer << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Programs/Level Statistics.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> P(no_of_elements + 1);\n    vector <int> C(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> P[i] >> C[i];\n    }\n    \n    int possible = true;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(P[i - 1] > P[i] || C[i - 1] > C[i])\n        {\n            possible = false;\n        }\n        \n        if(C[i] - C[i - 1] > P[i] - P[i - 1])\n        {\n            possible = false;\n        }\n    }\n    \n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Programs/Middle Class.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    long long no_of_elements, x;\n    cin >> no_of_elements >> x;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    \n    long long sum = 0;\n    int answer = 0;\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        sum += A[i];\n        \n        if(sum < (answer + 1)*x)\n        {\n            break;\n        }\n            \n        answer++;\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 85/Programs/Minimum Euler Cycle.cpp",
    "content": "#include <cstdio>\n\nusing namespace std;\n\nvoid solve()\n{\n    int n;\n    long long left, right;\n    scanf(\"%d %I64d %I64d\",&n, &left, &right);\n    \n    long long segment = 0, in_point = 0;\n    for(long long i = 1, sum = 0; i <= n; i++)\n    {\n        long long new_sum = sum + 2*(n - i);\n        \n        if(i == n)\n        {\n            new_sum++;\n        }\n        \n        if(new_sum >= left)\n        {\n            segment = i;\n            \n            in_point = (left - sum)/2 + i + (left - sum)%2;\n            \n            break;\n        }\n        \n        sum = new_sum;\n    }\n    \n    for(long long i = left; i <= right; )\n    {\n        if(segment == n)\n        {\n            printf(\"1 \");\n            \n            break;\n        }\n        \n        if(i%2 == 0)\n        {\n            printf(\"%I64d \", in_point);\n            \n            in_point++;\n            \n            i++;\n        }\n        else\n        {\n            printf(\"%I64d \", segment);\n            \n            i++;\n            \n            if(i > right)\n            {\n                break;\n            }\n            \n            printf(\"%I64d \", in_point);\n            \n            in_point++;\n            \n            i++;\n        }\n        \n        if(in_point == n + 1)\n        {\n            segment++;\n            \n            in_point = segment + 1;\n        }\n    }\n    \n    printf(\"\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    scanf(\"%d\", &no_of_test_cases);\n    \n    while(no_of_test_cases--)\n    {\n        solve();\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 86/Explanations/Binary Period Explanation.txt",
    "content": "If the string consists of only 0s or only 1s, then the period is 1 and we can print S as it is\n\nOtherwise, we can always achieve a period of 2.\n\nIt is always possible to make the string 0101010101 or 101010101\n\nWhenever we are about to add S[i], we will check if S[i] = S[i - 1]. If yes, then we will put in the other character in between.\n\nIf (S[i] != S[i - 1]), then we will add S[i] as it is.\n\nThis ensures that S is a subsequence of T and that T has period 2\n\nT cannot have period 1 so period 2 is the minimum\n\n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    if(is_periodic(S, 1))\n    {\n        cout << S << \"\\n\";\n\n        return;\n    }\n\n    string answer;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(answer.size() == 0 || S[i] != answer.back())\n        {\n            answer += S[i];\n        }\n        else\n        {\n            answer += other(S[i]);\n            answer += S[i];\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 86/Explanations/Road to Zero Explanation.txt",
    "content": "If the cost for making 2 single hits is less than 1 double hit, then we will use all single hits \n\nOtherwise, we will make as many double hits as we can and then use single hits.\n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long x, y, single, both;\n    cin >> x >> y >> single >> both;\n    \n    long long total = 0;\n    if(2*single <= both)\n    {\n        total = (x + y)*single;\n    }\n    else\n    {\n        total += min(x, y)*both;\n        \n        total += (max(x, y) - min(x, y))*single;\n    }\n    \n    cout << total << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 86/Explanations/Yet Another Counting Problem Explanation.txt",
    "content": "Claim - Let us write 1 if an integer satisfies the property\n\n(x mod a) mod b != (x mod b) mod a\n\nAnd write a 0 otherwise.\n\nThis pattern will be cyclic about the LCM(A, B)\n\n-----\n\nFor example, if A = 4, B = 6\n\n0 0 0 0 0 1 1 1 1 1 1 0\n\nThis is the pattern for [1, 12] and this pattern continually repeats\n\n-----\n\nProof -\n\nx mod a = (x mod LCM) mod a\nx mod b = (x mod LCM) mod b\n\nSo, (x mod a) mod b = ( (x mod LCM) mod a ) mod b\nand (x mod b) mod a = ( (x mod LCM) mod b ) mod a\n\nWhether (x mod a) mod b = (x mod b) mod a is true or not,\nit remains the same if we replace x by (x mod LCM)\n\n-----\n\nSo, it is clear that the patter in cyclic over LCM\n\n-----\n\nNow, to answer each query, We will find the Count(R) - Count(L - 1)\n\nHow to find Count(x) ?\n\nWhere Count(x) is the number of 1's till x\n\nThe pattern is cyclic about LCM so we will find out the number of 'complete cycles' till x\n\nThis is equal to (X/LCM)\n\nEvery complete cycle has Count(LCM) ones\n\nAnd then we will have Count(X mod LCM) ones\n\nSo, all we have to do is precompute the number of 1s in [1, LCM] and then\n\n(X/LCM) C[LCM] + C[LCM mod X]\n\n-----\n\nlong long gcd(long long x, long long y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n\n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nlong long get_count(vector <long long> &sum, long long lcm, long long N)\n{\n    long long full_cycles = N/lcm;\n\n    return full_cycles*sum[lcm] + sum[N%lcm];\n}\n\nvoid solve()\n{\n    int a, b, no_of_queries;\n    cin >> a >> b >> no_of_queries;\n\n    if(a > b)\n    {\n        swap(a, b);\n    }\n\n    long long lcm = (a*b)/gcd(a, b);\n    vector <long long> good_integers_sum(lcm + 1, 0);\n    for(int i = 1; i <= lcm; i++)\n    {\n        good_integers_sum[i] = good_integers_sum[i - 1] + ( (i%a)%b != (i%b)%a );\n    }\n\n    while(no_of_queries--)\n    {\n        long long left, right;\n        cin >> left >> right;\n\n        long long answer = get_count(good_integers_sum, lcm, right) - get_count(good_integers_sum, lcm, left - 1);\n\n        cout << answer << \" \";\n    }\n\n    cout << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 86/Programs/Binary Period.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint is_periodic(string S, int period)\n{\n    for(int i = 0; i < S.size(); i++)\n    {   //cout << \"Comparing \" << S[i] << \" and \" << S[i%period] << \"\\n\";\n        if(S[i] != S[i%period])\n        {\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nchar other(char ch)\n{\n    return (ch == '0' ? '1' : '0');\n}\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    if(is_periodic(S, 1))\n    {\n        cout << S << \"\\n\";\n        \n        return;\n    }\n    \n    string answer;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(answer.size() == 0 || S[i] != answer.back())\n        {\n            answer += S[i];\n        }\n        else\n        {\n            answer += other(S[i]);\n            answer += S[i];\n        }\n    }\n    \n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 86/Programs/Road to Zero.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long x, y, single, both;\n    cin >> x >> y >> single >> both;\n    \n    long long total = 0;\n    if(2*single <= both)\n    {\n        total = (x + y)*single;\n    }\n    else\n    {\n        total += min(x, y)*both;\n        \n        total += (max(x, y) - min(x, y))*single;\n    }\n    \n    cout << total << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 86/Programs/Yet Another Counting Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long gcd(long long x, long long y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n    \n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nlong long get_count(vector <long long> &sum, long long lcm, long long N)\n{\n    long long full_cycles = N/lcm;\n    \n    return full_cycles*sum[lcm] + sum[N%lcm];\n}\n\nvoid solve()\n{\n    int a, b, no_of_queries;\n    cin >> a >> b >> no_of_queries;\n    \n    if(a > b)\n    {\n        swap(a, b);\n    }\n    \n    long long lcm = (a*b)/gcd(a, b);\n    vector <long long> good_integers_sum(lcm + 1, 0);\n    for(int i = 1; i <= lcm; i++)\n    {\n        good_integers_sum[i] = good_integers_sum[i - 1] + ( (i%a)%b != (i%b)%a );\n    }\n    \n    while(no_of_queries--)\n    {\n        long long left, right;\n        cin >> left >> right;\n        \n        long long answer = get_count(good_integers_sum, lcm, right) - get_count(good_integers_sum, lcm, left - 1);\n        \n        cout << answer << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Explanations/01 Game Explanation.txt",
    "content": "We will either delete all the 1s or all the 0s\n\nEach deletion will remove 1 of each.\nSo the number of deletions is equal to the number of 1s or 0s, whichever is minimum\n\nWe just have to check the parity of the total number of moves to determine the winner. \n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    int zeroes = 0, ones = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '0')\n        {\n            zeroes++;\n        }\n        else\n        {\n            ones++;\n        }\n    }\n\n    int no_of_moves = min(zeroes, ones);\n\n    cout << (no_of_moves%2 == 1 ? \"DA\\n\" : \"NET\\n\");\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Explanations/Donut Shops Explanation.txt",
    "content": "If the cost of 1 donut is less than the cost of a box, then the answer is 1\nOtherwise, it is impossible to buy donuts to be cheaper.\n\nAs for the second shop, we will try to buy a box. If it is cheaper, then that is the answer.\nOtherwise, it is not possible\n\n-----\n\nvoid solve()\n{\n    long long cost, box_size, box_cost;\n    cin >> cost >> box_size >> box_cost;\n\n    int answer_1 = (cost < box_cost ? 1 : -1);\n    int answer_2 = (cost*box_size > box_cost ? box_size : -1);\n\n    cout << answer_1 << \" \" << answer_2 << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Explanations/Maximum Sum on Even Positions Explanation.txt",
    "content": "We can extend the idea of Kandane's algorithm.\n\nWe will keep track of the sum of the even positions and the amount the sum will increase by\nIf the segment we flip ends at i, what does the even position sum change by ?\n\nIf i is even, the sum changes by (A[i - 1] - A[i] + max(0, changes[i - 2]))\n\nIf i is odd, the sum changes by (-A[i] + A[i - 1] + max(0, changes[i - 2]))\n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    long long sum = 0;\n    for(int i = 0; i < no_of_elements; i += 2)\n    {\n        sum += A[i];\n    }\n\n    vector <long long> max_changes_here(no_of_elements + 1);\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(i == 1)\n        {\n            max_changes_here[i] = A[i] - A[i - 1];\n\n            continue;\n        }\n\n        if(i%2 == 1)\n        {\n            max_changes_here[i] = max(A[i] - A[i - 1], A[i] - A[i - 1] + max_changes_here[i - 2]);\n        }\n        else\n        {\n            max_changes_here[i] = max(-A[i] + A[i - 1], -A[i] + A[i - 1] + max_changes_here[i - 2]);\n        }\n    }\n\n    long long max_changes = 0;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        max_changes = max(max_changes, max_changes_here[i]);\n    }\n\n    sum += max_changes;\n\n    cout << sum << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Explanations/Pluses and Minuses Explanation.txt",
    "content": "If we perform i iterations in the second loop, res will increase by i each time\n\nWe need to know the initial balance necessary to go through the array without the sum being 0\n\nIf the balance goes below 0 at some point, we update the initial balance and try again \n\n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    long long res = 0;\n    for(long long i = 0, balance = 0, initial_balance = 0; i < S.size(); i++)\n    {\n        if(S[i] == '+')\n        {\n            balance++;\n        }\n        else\n        {\n            balance--;\n        }\n\n        if(initial_balance + balance < 0)\n        {\n            int no_of_retries = abs(initial_balance + balance);\n\n            initial_balance += no_of_retries;\n\n            res += no_of_retries*(i + 1);\n        }\n    }\n\n    res += S.size();\n\n    cout << res << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Programs/01 Game.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    int zeroes = 0, ones = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '0')\n        {\n            zeroes++;\n        }\n        else\n        {\n            ones++;\n        }\n    }\n    \n    int no_of_moves = min(zeroes, ones);\n    \n    cout << (no_of_moves%2 == 1 ? \"DA\\n\" : \"NET\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Programs/Donut Shops.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long cost, box_size, box_cost;\n    cin >> cost >> box_size >> box_cost;\n    \n    int answer_1 = (cost < box_cost ? 1 : -1);\n    int answer_2 = (cost*box_size > box_cost ? box_size : -1);\n    \n    cout << answer_1 << \" \" << answer_2 << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Programs/Maximum Sum on Even Positions.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long sum = 0;\n    for(int i = 0; i < no_of_elements; i += 2)\n    {\n        sum += A[i];\n    }\n    \n    vector <long long> max_changes_here(no_of_elements + 1);\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(i == 1)\n        {\n            max_changes_here[i] = A[i] - A[i - 1];\n            \n            continue;\n        }\n        \n        if(i%2 == 1)\n        {\n            max_changes_here[i] = max(A[i] - A[i - 1], A[i] - A[i - 1] + max_changes_here[i - 2]);\n        }\n        else\n        {\n            max_changes_here[i] = max(-A[i] + A[i - 1], -A[i] + A[i - 1] + max_changes_here[i - 2]);\n        }\n    }\n    \n    long long max_changes = 0;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        max_changes = max(max_changes, max_changes_here[i]);\n    }\n    \n    sum += max_changes;\n    \n    cout << sum << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 90/Programs/Pluses and Minuses.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    long long res = 0;\n    for(long long i = 0, balance = 0, initial_balance = 0; i < S.size(); i++)\n    {\n        if(S[i] == '+')\n        {\n            balance++;\n        }\n        else\n        {\n            balance--;\n        }\n        \n        if(initial_balance + balance < 0)\n        {\n            int no_of_retries = abs(initial_balance + balance);\n            \n            initial_balance += no_of_retries;\n            \n            res += no_of_retries*(i + 1); \n        }\n    }\n    \n    res += S.size();\n    \n    cout << res << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 92/Explanations/Good String Explanation.txt",
    "content": "t2 t3 t4 ... tn t1\ntn t1 t2 ... t(n - 2) t(n - 1)\n\nt2 = tn = t4 = t6 = ...\nt1 = t3 = t4 = t7 = t9 = ...\n\nThe even characters are the same\nThe odd characters are the same\n\nThere can be at most two characters\n\nWe will check both possibilities -\n\n1. When there is only one digit\n\nThis is the digit with the highest frequency\n\n2. When there are two digits (x, y)\n\nWe will find the longest alternating subsequence of (x, y) for all 100 pairs\nThis will cause 10^7 iterations\n\nWhen it is alternating, the length of the subsequence has to be even\n\n-----\n\nint get_length(int x, int y, string &S)\n{\n    int length = 0;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(length%2 == 0)\n        {\n            if(S[i] == '0' + x)\n            {\n                length++;\n            }\n        }\n        else\n        {\n            if(S[i] == '0' + y)\n            {\n                length++;\n            }\n        }\n    }\n\n    if(length%2 == 1)\n    {\n        length--;\n    }\n\n    return length;\n}\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    const int NO_OF_DIGITS = 10;\n    vector <int> frequency(NO_OF_DIGITS, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        frequency[S[i] - '0']++;\n    }\n\n    sort(frequency.begin(), frequency.end());\n    reverse(frequency.begin(), frequency.end());\n\n    int maximum_length = frequency[0];\n\n    for(int i = 0; i < NO_OF_DIGITS; i++)\n    {\n        for(int j = 0; j < NO_OF_DIGITS; j++)\n        {\n            maximum_length = max(maximum_length, get_length(i, j, S));\n        }\n    }\n\n    int minimum_deletions = S.size() - maximum_length;\n\n    cout << minimum_deletions << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 92/Programs/Good String.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint get_length(int x, int y, string &S)\n{\n    int length = 0;\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        if(length%2 == 0)\n        {\n            if(S[i] == '0' + x)\n            {\n                length++;\n            }\n        }\n        else\n        {\n            if(S[i] == '0' + y)\n            {\n                length++;\n            }\n        }\n    }\n    \n    if(length%2 == 1)\n    {\n        length--;\n    }\n    \n    return length;\n}\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    const int NO_OF_DIGITS = 10;\n    vector <int> frequency(NO_OF_DIGITS, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        frequency[S[i] - '0']++;\n    }\n    \n    sort(frequency.begin(), frequency.end());\n    reverse(frequency.begin(), frequency.end());\n    \n    int maximum_length = frequency[0];\n    \n    for(int i = 0; i < NO_OF_DIGITS; i++)\n    {\n        for(int j = 0; j < NO_OF_DIGITS; j++)\n        {\n            maximum_length = max(maximum_length, get_length(i, j, S));\n        }\n    }\n    \n    int minimum_deletions = S.size() - maximum_length;\n    \n    cout << minimum_deletions << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Explanations/Bad Triangle Explanation.txt",
    "content": "If there is a solution, then (A[1], A[2], A[n]) is also a solution.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    if(A[1] + A[2] <= A[no_of_elements])\n    {\n        cout << \"1 2 \" << no_of_elements << \"\\n\";\n\n        return ;\n    }\n\n    cout << \"-1\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Explanations/Colored Rectangles Explanation.txt",
    "content": "Let us maintain a DP.\n\nLet f(i, j, k) be the maximum among the first i reds, first j greens and first k blues\nLet us sort the Reds, Greens and Blues before this.\n\nTo determine, f(i, j, k), we will consider all 3 values -\n\n1. R[i]G[j] + f(i - 1, j - 1, k)\n2. G[j]B[k] + f(i, j - 1, k - 1)\n3. B[k]R[i] + f(i - 1, j, k - 1)\n\nWe also have to handle the base case of 0s carefully \n\n-----\n\nint main()\n{\n    int red, green, blue;\n    cin >> red >> green >> blue;\n\n    vector <long long> R(red + 1);\n    for(int i = 1; i <= red; i++)\n    {\n        cin >> R[i];\n    }\n    sort(all(R));\n\n    vector <long long> G(green + 1);\n    for(int i = 1; i <= green; i++)\n    {\n        cin >> G[i];\n    }\n    sort(all(G));\n\n    vector <long long> B(blue + 1);\n    for(int i = 1; i <= blue; i++)\n    {\n        cin >> B[i];\n    }\n    sort(all(B));\n\n    for(int i = 0; i <= red; i++)\n    {\n        for(int j = 0; j <= green; j++)\n        {\n            for(int k = 0; k <= blue; k++)\n            {\n                if( (i == 0 && j == 0 && k == 0) || (any_two_zero(i, j, k)) )\n                {\n                    max_till[i][j][k] = 0;\n                    continue;\n                }\n\n                if(i == 0)\n                {\n                    max_till[i][j][k] = G[j]*B[k] + max_till[i][j - 1][k - 1];\n                    continue;\n                }\n\n                if(j == 0)\n                {\n                    max_till[i][j][k] = B[k]*R[i] + max_till[i - 1][j][k - 1];\n                    continue;\n                }\n\n                if(k == 0)\n                {   //cout << \"R = \" << R[i] << \" and B = \" << B[j] << \"\\n\";\n                    max_till[i][j][k] = R[i]*G[j] + max_till[i - 1][j - 1][k];\n                    //cout << \"F(\" << i << \",\" << j << \",\" << k << \") = \" << max_till[i][j][k] << \"\\n\";\n                    continue;\n                }\n\n                max_till[i][j][k] = R[i]*G[j] + max_till[i - 1][j - 1][k];\n\n                max_till[i][j][k] = max(max_till[i][j][k], G[j]*B[k] + max_till[i][j - 1][k - 1]);\n\n                max_till[i][j][k] = max(max_till[i][j][k], B[k]*R[i] + max_till[i - 1][j][k - 1]);\n\n                //cout << \"F(\" << i << \",\" << j << \",\" << k << \") = \" << max_till[i][j][k] << \"\\n\";\n            }\n        }\n    }\n\n    cout << max_till[red][green][blue] << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Explanations/Good Subarrays Explanation.txt",
    "content": "Sum[R] - Sum[L - 1] = R - (L - 1)\n\nSum[R] - R = Sum[L - 1] - (L - 1)\n\n-----\n\nLet us define a quantity called f(i)\n\nf(i) = Sum[i] - i\n\nWe have to count the number of pairs (i, j) in F where the values are the same.\nThis can be done with a simple frequency map\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    string S;\n    cin >> S;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = S[i - 1] - '0';\n    }\n\n    vector <long long> sum_till(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + A[i];\n    }\n\n    long long no_of_pairs = 0;\n    map <long long, int> frequency;\n    frequency[0] = 1;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long value_here = sum_till[i] - i;\n\n        no_of_pairs += frequency[value_here];\n\n        frequency[value_here]++;\n    }\n\n    cout << no_of_pairs << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Explanations/Substring Removal Game Explanation.txt",
    "content": "Let us store the lengths of all the segments of contiguous characters\n\nThe players take the greatest length available at each move\n\n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    int current_length = 0;\n    vector <int> lengths;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '1')\n        {\n            current_length++;\n\n            if(i + 1 == S.size())\n            {\n                lengths.push_back(current_length);\n            }\n        }\n        else\n        {\n            if(current_length > 0)\n            {\n                lengths.push_back(current_length);\n\n                current_length = 0;\n            }\n        }\n    }\n\n    sort(lengths.begin(), lengths.end());\n    reverse(lengths.begin(), lengths.end());\n\n    int total = 0;\n    for(int i = 0; i < lengths.size(); i += 2)\n    {\n        total += lengths[i];\n    }\n\n    cout << total << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Programs/Bad Triangle.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    if(A[1] + A[2] <= A[no_of_elements])\n    {\n        cout << \"1 2 \" << no_of_elements << \"\\n\";\n        \n        return ;\n    }\n    \n    cout << \"-1\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Programs/Colored Rectangles.cpp",
    "content": "#include <iostream>\n#include <queue>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 222;\nlong long max_till[MAX_N][MAX_N][MAX_N];\n\nint any_two_zero(int r, int g, int b)\n{\n    int zeroes = (r == 0) + (g == 0) + (b == 0);\n    \n    return (zeroes >= 2);\n}\n\nint main()\n{\n    int red, green, blue;\n    cin >> red >> green >> blue;\n    \n    vector <long long> R(red + 1);\n    for(int i = 1; i <= red; i++)\n    {\n        cin >> R[i];\n    }\n    sort(all(R));\n    \n    vector <long long> G(green + 1);\n    for(int i = 1; i <= green; i++)\n    {\n        cin >> G[i];\n    }\n    sort(all(G));\n    \n    vector <long long> B(blue + 1);\n    for(int i = 1; i <= blue; i++)\n    {\n        cin >> B[i];\n    }\n    sort(all(B));\n    \n    for(int i = 0; i <= red; i++)\n    {\n        for(int j = 0; j <= green; j++)\n        {\n            for(int k = 0; k <= blue; k++)\n            {\n                if( (i == 0 && j == 0 && k == 0) || (any_two_zero(i, j, k)) )\n                {\n                    max_till[i][j][k] = 0;\n                    continue;\n                }\n                \n                if(i == 0)\n                {\n                    max_till[i][j][k] = G[j]*B[k] + max_till[i][j - 1][k - 1];\n                    continue;\n                }\n                \n                if(j == 0)\n                {\n                    max_till[i][j][k] = B[k]*R[i] + max_till[i - 1][j][k - 1];\n                    continue;\n                }\n                \n                if(k == 0)\n                {   //cout << \"R = \" << R[i] << \" and B = \" << B[j] << \"\\n\";\n                    max_till[i][j][k] = R[i]*G[j] + max_till[i - 1][j - 1][k];\n                    //cout << \"F(\" << i << \",\" << j << \",\" << k << \") = \" << max_till[i][j][k] << \"\\n\";\n                    continue;\n                }\n                \n                max_till[i][j][k] = R[i]*G[j] + max_till[i - 1][j - 1][k];\n                \n                max_till[i][j][k] = max(max_till[i][j][k], G[j]*B[k] + max_till[i][j - 1][k - 1]);\n                \n                max_till[i][j][k] = max(max_till[i][j][k], B[k]*R[i] + max_till[i - 1][j][k - 1]);\n                \n                //cout << \"F(\" << i << \",\" << j << \",\" << k << \") = \" << max_till[i][j][k] << \"\\n\";\n            }\n        }\n    }\n    \n    cout << max_till[red][green][blue] << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Programs/Good Subarrays.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    string S;\n    cin >> S;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = S[i - 1] - '0';\n    }\n    \n    vector <long long> sum_till(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + A[i];\n    }\n    \n    long long no_of_pairs = 0;\n    map <long long, int> frequency;\n    frequency[0] = 1;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long value_here = sum_till[i] - i;\n        \n        no_of_pairs += frequency[value_here];\n        \n        frequency[value_here]++;\n    }\n    \n    cout << no_of_pairs << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Educational Rounds/Educational Round 93/Programs/Substring Removal Game.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n    \n    int current_length = 0;\n    vector <int> lengths;\n    \n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '1')\n        {\n            current_length++;\n            \n            if(i + 1 == S.size())\n            {\n                lengths.push_back(current_length);\n            }\n        }\n        else\n        {\n            if(current_length > 0)\n            {\n                lengths.push_back(current_length);\n                \n                current_length = 0;\n            }\n        }\n    }\n    \n    sort(lengths.begin(), lengths.end());\n    reverse(lengths.begin(), lengths.end());\n    \n    int total = 0;\n    for(int i = 0; i < lengths.size(); i += 2)\n    {\n        total += lengths[i];\n    }\n    \n    cout << total << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Good Bye 2019/Explanations/Card Game Explanation.txt",
    "content": "We just need to check which array has the greater maximum.\n\nvoid solve()\n{\n    int no_of_elements, a_cards, b_cards;\n    cin >> no_of_elements >> a_cards >> b_cards;\n\n    int a_max = 0;\n    for(int i = 1; i <= a_cards; i++)\n    {\n        int x;\n        cin >> x;\n        a_max = max(a_max, x);\n    }\n\n    int b_max = 0;\n    for(int i = 1; i <= b_cards; i++)\n    {\n        int x;\n        cin >> x;\n        b_max = max(b_max, x);\n    }\n\n    cout << (a_max > b_max ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "2020/Good Bye 2019/Explanations/Interesting Subarray Explanation",
    "content": "Fact - If there is an interesting subarray, then there is an interesting subarray of length 2.\n\nProof -\n\nLet us suppose that there are 2 consecutive elements A[i], A[i + 1] such that\n|A[i] - A[i + 1]| >= 2\n\nThis satisfies our condition and there is at least one interesting subarray.\n\n------\n\nNow, let us suppose that there is no such subarray of length 2 in the array.\n\nThis means that for every pair (i, i + 1), the difference is atmost 1.\n\n|A[i] - A[i + 1]| >= 1\n\nFor any given subarray of length k, the difference in between the smallest and largest element < k\n\nSo, there can be no interesting subarray in the array.\n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(abs(A[i + 1] - A[i]) >= 2)\n        {\n            cout << \"YES\\n\";\n            cout << i << \" \" << i + 1 << \"\\n\";\n\n            return;\n        }\n    }\n\n    cout << \"NO\\n\";\n}\n"
  },
  {
    "path": "2020/Good Bye 2019/Explanations/Make Good Explanation.txt",
    "content": "Let us look at the sum of the first N integers. \n\nS = A1 + A2 + ... + An\nXOR = A1^A2^...^An\n\nAs an attempt, let us try to make XOR = 0.\n\nLet us append a new element to the sequence, A(n + 1) = X\n\nS = S + X\nX = X^X = 0\n\nAs we know, 0^x = x\n\nNow, let us append another element to the sequence, A(n + 2) = S + X\n\nS = S + X + (S + X) = 2(S + X)\nX = 0^(S + X) = (S + X)\n\nThis fulfils the objective. \n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long sum = 0, array_xor = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum += A[i];\n        \n        array_xor ^= A[i];\n    }\n    \n    if(array_xor == 0)\n    {\n        cout << \"1\\n\";\n        cout << sum + array_xor << \"\\n\";\n        return;\n    }\n    else\n    {\n        cout << \"2\\n\";\n        cout << array_xor << \" \" << sum + array_xor << \"\\n\";\n        return;\n    }\n}\n"
  },
  {
    "path": "2020/Good Bye 2019/Programs/Card Game.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, a_cards, b_cards;\n    cin >> no_of_elements >> a_cards >> b_cards;\n    \n    int a_max = 0;\n    for(int i = 1; i <= a_cards; i++)\n    {\n        int x;\n        cin >> x;\n        a_max = max(a_max, x);\n    }\n    \n    int b_max = 0;\n    for(int i = 1; i <= b_cards; i++)\n    {\n        int x;\n        cin >> x;\n        b_max = max(b_max, x);\n    }\n    \n    cout << (a_max > b_max ? \"YES\\n\" : \"NO\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Good Bye 2019/Programs/Interesting Subarray.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(abs(A[i + 1] - A[i]) >= 2)\n        {\n            cout << \"YES\\n\";\n            cout << i << \" \" << i + 1 << \"\\n\";\n            \n            return;\n        }\n    }\n\n    cout << \"NO\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Good Bye 2019/Programs/Make Good.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long sum = 0, array_xor = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum += A[i];\n        \n        array_xor ^= A[i];\n    }\n    \n    if(array_xor == 0)\n    {\n        cout << \"1\\n\";\n        cout << sum + array_xor << \"\\n\";\n        return;\n    }\n    else\n    {\n        cout << \"2\\n\";\n        cout << array_xor << \" \" << sum + array_xor << \"\\n\";\n        return;\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Explanations/New Year and Ascent Sequences Explanation.txt",
    "content": "Let us call a sequence an A sequence if \nthere is an ascent in the sequence. \n\nLet us call a sequence a D sequence if there is no ascent and it is in \ndescending order.\n\n-----\n\nNow, there are 4 types of pairs - \n\n1. A-A\n2. A-D\n3. D-A\n4. D-D\n\nLet us count each type of pairs individually. \n\n----\n\nLet there be a A-sequences and d D-sequences\n\n----\n\nIf a sequence has an ascent, then it can be appended with itself and it will be a good sequence. \n\nIt can also be appended to any other A-sequence and it will be good. \n\nIf there are a A-sequences, then the number of A-A pairs is \n\na + a(a - 1)\n\n---\n\nA-D pairs\n\nThis count is a.d\n\n----\n\nD-A pairs \n\nThis count is d.a\n\n----\n\nAll A-D and D-A pairs are good since there is guaranteed to be at least one asecnt in each pair. \n\n----\n\nNow, let us suppose we only have D-sequences. \nFor every sequence, let us have the maximum and minimum element. \n\nIf the minimum element of sequence i, is m, then sequence i forms a good pair \nwith any sequence who's maximum element is > m. \n\nWe will keep track of the frequency of each maximum and the suffix sum of the frequency. \n\nThis way, we can get maximum_suffix_frequency[m + 1] can be gotten in O(1) time. \n\nPlease refer my code for further clarification. \n\n-----\n\nint main()\n{\n    int no_of_sequences;\n    cin >> no_of_sequences;\n    \n    const int oo = 1e6;\n    vector <int> minimum, maximum;\n    \n    long long ascent_sequences = 0, non_ascent_sequences = 0;\n    for(int i = 1; i <= no_of_sequences; i++)\n    {\n        int length;\n        cin >> length;\n        \n        vector <int> A(length + 1);\n        for(int j = 1; j <= length; j++)\n        {\n            cin >> A[j];\n        }\n        \n        int has_ascent = false;\n        for(int j = 2; j <= length; j++)\n        {\n            if(A[j - 1] < A[j])\n            {\n                has_ascent = true;\n                break;\n            }\n        }\n        \n        if(has_ascent)\n        {\n            ascent_sequences++;\n        }\n        else\n        {\n            non_ascent_sequences++;\n            maximum.push_back(A[1]);\n            minimum.push_back(A[length]);\n        }\n    }\n    \n    vector <int> maximum_frequency(oo + 5, 0);\n    for(int i = 0; i < non_ascent_sequences; i++)\n    {\n        maximum_frequency[maximum[i]]++;\n    }\n    \n    vector <int> maximum_suffix_sum(oo + 5, 0);\n    for(int i = oo; i >= 0; i--)\n    {\n        maximum_suffix_sum[i] = maximum_frequency[i] + maximum_suffix_sum[i + 1];\n    }\n   \n    long long no_of_pairs = ascent_sequences +\n                            ascent_sequences*(ascent_sequences - 1) + 2*ascent_sequences*non_ascent_sequences;\n    \n    for(int i = 0; i < non_ascent_sequences; i++)\n    {\n        no_of_pairs += maximum_suffix_sum[minimum[i] + 1];\n    }\n    \n    cout << no_of_pairs << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Explanations/New Year and Conferences Explanation.txt",
    "content": "We can actually interpret this as a question about rectangles.\n\nInterpret the output as (x1, x2), (y1, y2).\n\nThe question is now to check if there are 2 rectangles who's X intersects but Y does not.\n\nWe will sort the rectangles by X.\n\nWe will go through the rectangles in sorted order.\nWe will look at the current Y.\nWe have to check that the Y intersects with all the corresponding Y's that the X intersects with.\n\nWe can do this by\n\n1. Maintaining a set of all Y's which the current X intersects with.\n2. Check if y1 >= smallest Y in the set\n3. Check if y2 <= largest Y in the set\n4. Also when we are at y2, we will remove it from the set\n5. When we are at y1, we will insert y into the set\n\n-----\n\nWe will once check if any two rectangles have intersecting X's and not intersecting Y's\nThen, we will check if we have intersecting Y's and not intersecting X's\n\n-----\n\nint same_intersections(vector <int> start_a, vector <int> end_a, vector <int> start_b,  vector <int> end_b)\n{\n    multiset <int> starts, ends;\n\n    vector <event> events;\n    for(int i = 0; i < start_a.size(); i++)\n    {\n        events.push_back(event(start_a[i], start_b[i], end_b[i], true));\n        events.push_back(event(end_a[i] + 1, start_b[i], end_b[i], false));\n    }\n\n    sort(all(events));\n\n    for(int i = 0; i < events.size(); i++)\n    {\n        if(events[i].is_entry)\n        {\n            if(!starts.empty())\n            {\n                int last_start = *starts.rbegin();\n                int earliest_end = *ends.begin();\n\n                if(earliest_end < events[i].start || last_start > events[i].end)\n                {\n                    return false;\n                }\n            }\n                \n            starts.insert(events[i].start);\n            ends.insert(events[i].end);\n        }\n        else\n        {\n            starts.erase(starts.find(events[i].start));\n            ends.erase(ends.find(events[i].end));\n        }\n    }\n\n    return true;\n}\n\nint main()\n{\n    int no_of_lectures;\n    cin >> no_of_lectures;\n\n    vector <int> start_a(no_of_lectures), start_b(no_of_lectures), end_a(no_of_lectures), end_b(no_of_lectures);\n    for(int i = 0; i < no_of_lectures; i++)\n    {\n        cin >> start_a[i] >> end_a[i] >> start_b[i] >> end_b[i];\n    }\n\n    cout << (same_intersections(start_a, end_a, start_b, end_b) && same_intersections(start_b, end_b, start_a, end_a) ? \"YES\\n\" : \"NO\\n\");\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Explanations/New Year and Naming Explanation",
    "content": "For each query, we just have to print\n\nS[y%n] + S[y%m] concatenated.\n\n-----\n\nint main()\n{\n    int S_strings, T_strings;\n    cin >> S_strings >> T_strings;\n\n    vector <string> S(S_strings);\n    for(int i = 0; i < S_strings; i++)\n    {\n        cin >> S[i];\n    }\n\n    vector <string> T(T_strings);\n    for(int i = 0; i < T_strings; i++)\n    {\n        cin >> T[i];\n    }\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n    {\n        int year;\n        cin >> year;\n        cout << S[(year - 1)%S_strings] << T[(year - 1)%T_strings] << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Explanations/New Year and Permutation Explanation.txt",
    "content": "Let us look at a segment of length L. It can be rearranged in L! ways.\n\nThe entire segment can be made (N - L + 1)! ways.\n\nOf course, there are (N - L + 1) segments of length L.\n\nLet us count the number of framed sequences of length 1, 2, 3 and so on.\n\nWe will use the above reasoning.\n\n------\n\nint main()\n{\n    long long n, mod;\n    cin >> n >> mod;\n\n    vector <long long> factorial(n + 1);\n    factorial[0] = 1;\n    for(int i = 1; i <= n; i++)\n    {\n        factorial[i] = (factorial[i - 1]*i)%mod;\n    }\n\n    long long sum = 0;\n\n    for(int length = 1; length <= n; length++)\n    {\n        long long no_of_segments = n - length + 1;\n\n        long long ways_for_one_segment = (factorial[n - length + 1]*factorial[length])%mod;\n\n        sum += (no_of_segments*ways_for_one_segment)%mod;\n    }\n\n    cout << sum%mod << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Programs/New Year and Ascent Sequences.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_sequences;\n    cin >> no_of_sequences;\n    \n    const int oo = 1e6;\n    vector <int> minimum, maximum;\n    \n    long long ascent_sequences = 0, non_ascent_sequences = 0;\n    for(int i = 1; i <= no_of_sequences; i++)\n    {\n        int length;\n        cin >> length;\n        \n        vector <int> A(length + 1);\n        for(int j = 1; j <= length; j++)\n        {\n            cin >> A[j];\n        }\n        \n        int has_ascent = false;\n        for(int j = 2; j <= length; j++)\n        {\n            if(A[j - 1] < A[j])\n            {\n                has_ascent = true;\n                break;\n            }\n        }\n        \n        if(has_ascent)\n        {\n            ascent_sequences++;\n        }\n        else\n        {\n            non_ascent_sequences++;\n            maximum.push_back(A[1]);\n            minimum.push_back(A[length]);\n        }\n    }\n    \n    vector <int> maximum_frequency(oo + 5, 0);\n    for(int i = 0; i < non_ascent_sequences; i++)\n    {\n        maximum_frequency[maximum[i]]++;\n    }\n    \n    vector <int> maximum_suffix_sum(oo + 5, 0);\n    for(int i = oo; i >= 0; i--)\n    {\n        maximum_suffix_sum[i] = maximum_frequency[i] + maximum_suffix_sum[i + 1];\n    }\n   \n    long long no_of_pairs = ascent_sequences +\n                            ascent_sequences*(ascent_sequences - 1) + 2*ascent_sequences*non_ascent_sequences;\n    \n    for(int i = 0; i < non_ascent_sequences; i++)\n    {\n        no_of_pairs += maximum_suffix_sum[minimum[i] + 1];\n    }\n    \n    cout << no_of_pairs << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Programs/New Year and Conferences.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nstruct event\n{\n    int time, start, end, is_entry;\n    \n    event(){}\n    \n    event(int T, int S, int E, int is_E)\n    {\n        time = T; start = S; end = E; is_entry = is_E;\n    }\n    \n    int operator <(const event &E)\n    {\n        if(time == E.time)\n        {\n            return (is_entry < E.is_entry);\n        }\n        \n        return (time < E.time);\n    }\n};\n\nint same_intersections(vector <int> start_a, vector <int> end_a, vector <int> start_b,  vector <int> end_b)\n{\n    multiset <int> starts, ends;\n    \n    vector <event> events;\n    for(int i = 0; i < start_a.size(); i++)\n    {\n        events.push_back(event(start_a[i], start_b[i], end_b[i], true));\n        events.push_back(event(end_a[i] + 1, start_b[i], end_b[i], false));\n    }\n    \n    sort(all(events));\n    \n    for(int i = 0; i < events.size(); i++)\n    {\n        if(events[i].is_entry)\n        {\n            if(!starts.empty())\n            {\n                int last_start = *starts.rbegin();\n                int earliest_end = *ends.begin();\n                \n                if(earliest_end < events[i].start || last_start > events[i].end)\n                {\n                    return false;\n                }\n                \n                starts.insert(events[i].start);\n                ends.insert(events[i].end);\n            }\n        }\n        else\n        {\n            starts.erase(starts.find(events[i].start));\n            ends.erase(ends.find(events[i].end));\n        }\n    }\n    \n    return true;\n}\n\nint main()\n{\n    int no_of_lectures;\n    cin >> no_of_lectures;\n    \n    vector <int> start_a(no_of_lectures), start_b(no_of_lectures), end_a(no_of_lectures), end_b(no_of_lectures);\n    for(int i = 0; i < no_of_lectures; i++)\n    {\n        cin >> start_a[i] >> end_a[i] >> start_b[i] >> end_b[i];\n    }\n    \n    cout << (same_intersections(start_a, end_a, start_b, end_b) && same_intersections(start_b, end_b, start_a, end_a) ? \"YES\\n\" : \"NO\\n\");\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Programs/New Year and Naming.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int S_strings, T_strings;\n    cin >> S_strings >> T_strings;\n    \n    vector <string> S(S_strings);\n    for(int i = 0; i < S_strings; i++)\n    {\n        cin >> S[i];\n    }\n    \n    vector <string> T(T_strings);\n    for(int i = 0; i < T_strings; i++)\n    {\n        cin >> T[i];\n    }\n    \n    int no_of_queries;\n    cin >> no_of_queries;\n    \n    while(no_of_queries--)\n    {\n        int year;\n        cin >> year;\n        cout << S[(year - 1)%S_strings] << T[(year - 1)%T_strings] << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Hello 2020/Programs/New Year and Permutation.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    long long n, mod;\n    cin >> n >> mod;\n    \n    vector <long long> factorial(n + 1);\n    factorial[0] = 1;\n    for(int i = 1; i <= n; i++)\n    {\n        factorial[i] = (factorial[i - 1]*i)%mod;\n    }\n    \n    long long sum = 0;\n    \n    for(int length = 1; length <= n; length++)\n    {\n        long long no_of_segments = n - length + 1;\n        \n        long long ways_for_one_segment = (factorial[n - length + 1]*factorial[length])%mod;\n        \n        sum += (no_of_segments*ways_for_one_segment)%mod;\n    }\n    \n    cout << sum%mod << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Alternative Thinking Explanation.txt",
    "content": "It is possible to increase the length of the alternating sequence by at most 2.\n\nSuppose we have consecutive 1's or consecutive 0's.\n\nIf we have a substring 00 in our string,\nwe will flip it to either 10 or 01\nIt increases the number of sequences by 2.\n\nIf 00 is at the end or beginning of the string,\nwe increase the number of alternate sequences by 1.\n\nIf it is in the middle, we increase it by 2.\n\n-----\n\nWe can prove this is optimal by considering the impact of the flip on the\ncompressed string where each equal substring is compressed to a single character.\n\nFlipping [L, R] is the same as\n\n1. Flipping [1, R]\n2. Flipping [1, L - 1]\n\n------\n\nThe number of alternating sequences in the prefix will remain the same since\nit is flipped twice.\n\nThe suffix is not flipped at all.\n\nThe only way we can increase the number of characters in our compressed string is\nby flipping a part of a segment.\n\nIf the segment is first or last, we increase by 1\nIf the segment is in the middle, we increase by 2.\n\nIf there is no segment of length > 1, we cannot increase the length of the\nlongest alternating subsequence. \n\n-----\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    int alternating_subsequence = 0;\n    for(int i = 0; i < length; i++)\n    {\n        if(i == 0 || S[i] != S[i - 1])\n        {\n            alternating_subsequence++;\n        }\n    }\n\n    int answer = min(alternating_subsequence + 2, length);\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Ant Colony Explanation.txt",
    "content": "The number of free ants = Number of ants which divide every element in the range.\n\nThis is equal to the frequency of the GCD of the segment.\n\nThe only problem with this is about how we will combine 2 segments.\n\nSuppose, we are combining L and R.\n\nIf gcd(L.gcd, R.gcd) = L.gcd,\n\nThen we can take the frequency of L. Otherwise we can take the frequency of R.\n\nWhat if gcd(L.gcd, R.gcd) < min(L.gcd, R.gcd)\n\nThen, we can take it as 0 for this segment.\n\n-----\n\nThe GCD is always the minimum element of the segment.\n\nSo, if gcd(A, B) < gcd(A) and gcd(B),\n\nThen, it means that gcd(A, B) is not present in either A or B and the frequency is 0\n\n------\n\nWe will create a segment tree that keeps track of the GCD and the GCD Frequency for each segments\n\nWhile answering a query, we will notice that GCD_Frequency elements will be free and have to give the count of the remaining elements.\n\n------\n\nHere is the merge function\n\nstruct node\n{\n    int gcd, gcd_frequency;\n\n    node(){}\n\n    node(int G, int F)\n    {\n        gcd = G; gcd_frequency = F;\n    }\n};\n\nnode merge(node &A, node &B)\n{\n    node C;\n\n    C.gcd = gcd(A.gcd, B.gcd);\n\n    if(A.gcd == B.gcd)\n    {\n        C.gcd_frequency = A.gcd_frequency + B.gcd_frequency;\n    }\n    else if(C.gcd < min(A.gcd, B.gcd))\n    {\n        C.gcd_frequency = 0;\n    }\n    else if(C.gcd == A.gcd)\n    {\n        C.gcd_frequency = A.gcd_frequency;\n    }\n    else if(C.gcd == B.gcd)\n    {\n        C.gcd_frequency = B.gcd_frequency;\n    }\n\n    return C;\n}\n\n------\n\nHere is the build function\n\nvoid build(int n, int left, int right)\n{\n    if(left == right)\n    {\n        tree[n] = node(A[left], 1);\n        return;\n    }\n\n    int mid = (left + right)/2;\n\n    build(LEFT(n), left, mid);\n    build(RIGHT(n), mid + 1, right);\n\n    tree[n] = merge(tree[LEFT(n)], tree[RIGHT(n)]);\n}\n\n------\n\nHere is the Query Function\n\nnode query(int n, int left, int right, int query_left, int query_right)\n{\n    if(query_right < left || right < query_left || right < left)\n    {\n        return node(0, 0);\n    }\n\n    if(query_left <= left && right <= query_right)\n    {\n        return tree[n];\n    }\n\n    int mid = (left + right)/2;\n\n    node left_answer = query(LEFT(n), left, mid, query_left, query_right);\n    node right_answer = query(RIGHT(n), mid + 1, right, query_left, query_right);\n\n    //cout << \" At \" << left << \",\" << right << \" LEFT answer(\" << left << \",\" << mid <<\") = \" << left_answer.gcd << \" RIGHT answer(\" << mid + 1 << \",\" << right << \") = \" << right_answer.gcd << \"\\n\";\n    return merge(left_answer, right_answer);\n}\n\n\n------\n\nHere is how we will answer each query\n\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    build(1, 1, no_of_elements);\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n    {\n        int left, right;\n        cin >> left >> right;\n\n        node answer = query(1, 1, no_of_elements, left, right);\n\n        int free = answer.gcd_frequency;\n\n        int remaining = right - (left - 1) - free;\n\n        cout << remaining << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Anton and Chess Explanation.txt",
    "content": "The king will be in check if the closest piece in a straight line is a rook or queen\nor the closest piece in the diagonal is a bishop or queen.\n\n-----\n\nLet us store a sorted list of all pieces on\n\n1. The row - Same x\n2. The column - Same y\n3. The diagonal - Same (x + y)\n4. The antidiagonal - Same (x - y)\n\nWe will order the pieces on the diagonal by the anti-diagonal value\nand the pieces on the diagonal by the anti-diagonal value.\n\n-----\n\nIt is quite easy to extend this solution to knights.\nKnights can jump over other pieces so the blocking limitation does not apply.\nWe only need to check if there is a knight at a knight's distance from the king.\n\n-----\n\nIn each vector, we will binary search for the closest pieces to the king\nand see if it is the correct attacker.\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint check(int x, vector <pair <long long, char> > &A, char attacker_1, char queen = 'Q')\n{\n    pair <long long, char> king = make_pair(x, 'K');\n\n    int next = upper_bound(all(A), king) - A.begin();\n\n    if(next < A.size() && (A[next].second == attacker_1 || A[next].second == queen))\n    {\n        return true;\n    }\n\n    int before = next - 1;\n\n    if(before >= 0 && (A[before].second == attacker_1 || A[before].second == queen))\n    {\n        return true;\n    }\n\n    return false;\n}\n\nint main()\n{\n    int no_of_black_pieces;\n    cin >> no_of_black_pieces;\n\n    long long king_x, king_y;\n    cin >> king_x >> king_y;\n\n    long long king_diagonal = king_x - king_y;\n    long long king_antidiagonal = king_x + king_y;\n\n    vector <pair <long long, char> > row, column, diagonal, anti_diagonal;\n    for(int i = 1; i <= no_of_black_pieces; i++)\n    {\n        char piece;\n        long long x, y;\n        cin >> piece >> x >> y;\n\n        if(x == king_x)\n        {\n            row.push_back(make_pair(y, piece));\n        }\n        if(y == king_y)\n        {\n            column.push_back(make_pair(x, piece));\n        }\n\n        if(x - y == king_diagonal)\n        {\n            diagonal.push_back(make_pair(x + y, piece));\n        }\n        if(x + y == king_antidiagonal)\n        {\n            anti_diagonal.push_back(make_pair(x - y, piece));\n        }\n    }\n\n    sort(all(row));\n    sort(all(column));\n    sort(all(diagonal));\n    sort(all(anti_diagonal));\n\n    int in_check = false;\n\n    in_check = (check(king_y, row, 'R') ||\n                check(king_x, column, 'R') ||\n                check(king_antidiagonal, diagonal, 'B') ||\n                check(king_diagonal, anti_diagonal,'B') );\n\n    cout << (in_check ? \"YES\" : \"NO\") << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Anton and Ira Explanation.txt",
    "content": "Let us suppose the question was asking us to sort P.\nThe question is actually equivalent to it.\nWe just have to relabel each integer in S so that S = {1, 2, 3, ... , N}\n\n-----\n\nWe will first place N in it's position and then N - 1 and so on.\n\nSuppose N is in position i,\n\nA[i] = N\n\nThere will be at least one integer to the left of A[i] that is <= i\nThere is at least one integer in j in [i + 1, N] that is A[j] <= i\nWhen we encounter such an A[j], we will swap (A[i], A[j])\nThis way both A[i] and A[j] move close to their destinations mutually.\n\nHow do we prove there is always such an integer ?\n\nThere are (N - i) integers > i\nAnd N is not in [i + 1, N]\nSince the number of positions is more than the number of integers,\nthere will be at least 1 integer A[j] such that A[j] <= i\nby the Pigeonhole Principle\n\nThe number of swaps will be |Position[i] - i| summed over all i.\nClearly this is the optimal value.\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> P(no_of_elements + 1), S(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> P[i];\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> S[i];\n    }\n\n    vector <int> label(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        label[S[i]] = i;\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        P[i] = label[P[i]];\n    }\n\n    long long cost = 0;\n    vector <pair <int, int> > swaps;\n\n    for(int current = no_of_elements, i; current >= 1; current--)\n    {\n        for(i = 1; i <= no_of_elements; i++)\n        {\n            if(P[i] == current)\n            {\n                break;\n            }\n        }\n\n        //cout << \"Current = \" << current << \" i = \" << i << \" \\n\";\n        for(int j = i + 1; j <= current; j++)\n        {\n            if(P[j] <= i)\n            {   //cout << \"j = \" << j << \"\\n\";\n\n                swap(P[i], P[j]);\n\n                swaps.push_back(make_pair(i, j));\n\n                cost += (j - i);\n\n                i = j;\n            }\n        }\n    }\n\n    cout << cost << \" \" << swaps.size() << \"\\n\";\n    for(int i = 0; i < swaps.size(); i++)\n    {\n        cout << swaps[i].first << \" \" << swaps[i].second << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Ants in Leaves Explanation.txt",
    "content": "Unlike most tree/graph problems, the solution to this problem can't be\nrecursively broken down to it's children directly.\n\nThe reason is that the problem is not symmetric for the root and it's children.\nIn the root, we allow multiple ants to climb up.\nBut every other vertex only allows 1 ant to climb up at a time.\n\nSo, we will solve the problem for each child of the root independently.\nIt takes 1 more move to move from the child to the root.\nSo answer = max(child) + 1\n\n-----\n\nNow, how do we solve it for the child of the root ?\n\nEach leaf will at least take as much time as it's depth.\nLet us sort the leaves by their depth.\n\ntime[i] = max(depth[i], time[i - 1] + 1)\n\nIt will either take the time as much as it's depth or 1 more than the previous leaf.\n\n-----\n\nvector <int> depths;\n\nvoid dfs(int v, int parent_v, int depth)\n{\n    if(tree[v].size() == 1)\n    {\n        depths.push_back(depth);\n    }\n\n    for(int child_v : tree[v])\n    {\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        dfs(child_v, v, depth + 1);\n    }\n}\n\nint get_answer(int v)\n{\n    dfs(v, 1, 0);\n\n    sort(all(depths));\n\n    vector <int> visit_order(depths.size());\n    for(int i = 0; i < visit_order.size(); i++)\n    {\n        visit_order[i] = depths[i];\n\n        if(i > 0)\n        {\n            visit_order[i] = max(visit_order[i - 1] + 1, visit_order[i]);\n        }\n    }\n\n    depths.clear();\n    //cout << \" Answer here = \" << visit_order.back() << \"\\n\";\n    return visit_order.back();\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n\n    for(int i = 1, no_of_edges = no_of_vertices - 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n\n    int answer = 0;\n\n    for(int child : tree[1])\n    {\n        answer = max(answer, get_answer(child) + 1); //cout << child << \" \";\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Army Creation Explanation.txt",
    "content": "In each range [L, R], let us count only the first K occurrences of each distinct element.\n\nIn order to do this, we need to do something creative.\n\nFor each index i, let K[i] denote the K-th previous occurrence of A[i].\n\nInstead of counting at most K occurrences of each index,\nwe will count an index i\nif and only if K[i] < L\n\nIf K[i] < L, we can be sure that A[i] is one of the first k occurrences of A[i] in [L, R]\n\n-----\n\nLet us build an auxiliary array K\n\nK[i] will contain the index of the K-th previous index of A[i].\n\nWhen we are given a query [L, R]\n\n------\n\n1. Build a Merge Sort Tree on K\n2. For each query, count the number of elements in the range who's value < K\n\nEach such value is one of the first K values in [L, R]\n\nInstead of generating the vector each time, we will binary search each node and count\nthe number of integers < x\n\nWe can do this by finding the first integer >= x\n\nSince the vectors are 0-indexed, this returns the number of integers < x\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 1e5 +5;\nint k_th_ancestor[MAX_N];\nvector <int> indices[MAX_N];\nvector <int> tree[3*MAX_N];\n\nvector <int> merge(vector <int> &L, vector <int> &R)\n{\n    vector <int> answer;\n\n    for(int l = 0, r = 0; l < L.size() || r < R.size(); )\n    {\n        if(l == L.size())\n        {\n            answer.push_back(R[r++]);\n            continue;\n        }\n\n        if(r == R.size())\n        {\n            answer.push_back(L[l++]);\n            continue;\n        }\n\n        if(L[l] <= R[r])\n        {\n            answer.push_back(L[l++]);\n        }\n        else\n        {\n            answer.push_back(R[r++]);\n        }\n    }\n\n    return answer;\n}\n\nvoid build(int n, int left, int right)\n{\n    if(left == right)\n    {\n        tree[n].push_back(k_th_ancestor[left]);\n\n        /*cout << \"n = \" << n  <<\"[\" << left <<\",\" << right << \"]\\n\" << endl;\n        for(int i = 0; i < tree[n].size(); i++)\n        {\n            cout << tree[n][i] << \" \";\n        } cout << \"\\n\";*/\n        return;\n    }\n\n    int mid = (left + right)/2;\n    build(LEFT(n), left, mid);\n    build(RIGHT(n), mid + 1, right);\n\n    tree[n] = merge(tree[LEFT(n)], tree[RIGHT(n)]);\n    /*cout << \"n = \" << n  <<\"[\" << left <<\",\" << right << \"]\\n\" << endl;\n    for(int i = 0; i < tree[n].size(); i++)\n    {\n        cout << tree[n][i] << \" \";\n    } cout << \"\\n\";*/\n}\n\nint query(int n, int left, int right, int query_left, int query_right, int x)\n{\n    if(query_right < left || right < query_left)\n    {\n        return 0;\n    }\n\n    if(query_left <= left && right <= query_right)\n    {\n        return (upper_bound(all(tree[n]), x - 1) - tree[n].begin());\n    }\n\n    int mid = (left + right)/2;\n\n    return (query(LEFT(n), left, mid, query_left, query_right, x) +\n            query(RIGHT(n), mid + 1, right, query_left, query_right, x));\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        indices[A[i]].push_back(i);\n\n        if(indices[A[i]].size() > k)\n        {\n            int k_th_step = indices[A[i]].size() - 1 - k;\n\n            k_th_ancestor[i] = indices[A[i]][k_th_step]; //cout << \" K-th \" << i << \" = \" << k_th_ancestor[i] << \"\\n\";\n        }\n        else\n        {\n            k_th_ancestor[i] = 0;\n        }\n    }\n\n    build(1, 1, no_of_elements);\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    int answer = 0;\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n\n        int left = ((x + answer)%no_of_elements) + 1;\n        int right = ((y + answer)%no_of_elements) + 1;\n        if(left > right)\n        {\n            swap(left, right);\n        }\n\n       // cout << \"L = \" << left << \" R = \" << right << \"\\n\";\n        //vector <int> range = query(1, 1, no_of_elements, left, right);\n        /*cout << \"Size = \" << range.size() << \"\\n\";\n        for(int i = 0; i < range.size(); i++)\n        {\n            cout << range[i] << \" \";\n        }\n        cout << \"\\n\";*/\n\n        answer = query(1, 1, no_of_elements, left, right, left);\n\n        cout << answer << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Bargain Explanation.txt",
    "content": "Whenever we are asked to compute a sum,\nwe must try to break it down and count the individual contribution of each term.\n\nIn this case, every cost consists of some prefix of the string concatenated\nwith some suffix of the string.\n\nLet us count the contribution of each digit when it is\n\n1. Part of the prefix\n2. Part of the suffix.\n\n-----\n\nIf a digit is part of the suffix, then it means there is no digit to it's right\nthat is deleted.\n\nSo, if it is the s-th digit from the right, it's value will be\n\n10^s S[s]\n\nHow many strings have this digit in it's suffix ?\n\nWe can remove p(p - 1)/2 + p strings from the prefix,\nwhere p = length of string before S[s]\n\nSo, the total suffix cost of S[s] = p(p + 1)/2 10^s S[s]\n\n-----\n\nNow, let us count the prefix cost of S[i].\nThis means that no character to it's left is deleted.\n\nThis is a little more tricky.\n\nSuppose S[i] is the 5th character from the right. \n"
  },
  {
    "path": "2020/Practice/Explanations/Concatenated Multiples Explanation.txt",
    "content": "What is the value of concatenating A[i] with A[j] ?\n\n10^{length(A[j])} + A[i]\n\nLet f(t, m) be the frequency of remainder m (mod K) if an integer is multiplied by 10^t\n\nWe will iterate from i = 1 to N\nand add\n\nf(length(A[j]), -A[i]) to the answer for each integer.\n\nWe are not allowed to concatenate an integer with itself so we have to be careful about that.\n\n-----\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int MAX_DIGITS = 11;\n    map <long long, int> frequency_mod[MAX_DIGITS];\n    long long answer = 0;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(long long t = 10, d = 1; d < MAX_DIGITS; d++, t = (t*10)%k)\n        {\n            frequency_mod[d][ (A[i]*t)%k ]++;\n\n            //cout << \"D = \" << d << \" M = \" << (A[i]*t)%k << \" = \" << frequency_mod[d][ (A[i]*t)%k ] << \"\\n\";\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long first_part_mod = (0 - A[i]%k + k)%k;\n\n        //cout << \"Need d = \" << no_of_digits(A[i]) << \" with M = \" << first_part_mod << \"\\n\";\n\n        answer += frequency_mod[no_of_digits(A[i])][first_part_mod];\n        //cout << \"Answer = \" << answer << \"\\n\";\n\n        long long t = 1;\n        for(long long d = 1; d <= no_of_digits(A[i]) ;d++)\n        {\n            t = (t*10)%k;\n        }\n\n        if( (t*A[i] + A[i])%k == 0 )\n        {   //cout << \"Self!\\n\";\n            answer--;\n        }\n\n        //cout << \"Answer = \" << answer << \"\\n\";\n    }\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Count Pairs Explanation.txt",
    "content": "We need 1 flash of creativity for this problem.\n\n(A + B)(A^2 + B^2) = k (mod P),\n\nWe need to somehow write LHS = RHS, where both are a function of A and B\n\nSo that, we can utilise the symmetry\n\nWe can multiply both sides by (A - B) !\n\n(A^4 - B^4) = k(A - B) (mod P)\n\nA^4 - kA = B^4 - kB (mod P),\n\nThere we have it !\n\n-----\n\nWe have now found out the effective value of each array element.\n\nWe will track the frequencies of each element and count the number of pairs of each.\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nlong long choose_2(long long n)\n{\n    return (n*(n - 1))/2;\n}\n\nint main()\n{\n    int no_of_elements, p, k;\n    cin >> no_of_elements >> p >> k;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    map <long long, int> value_frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long value = (A[i]*A[i])%p;\n        value = (value*A[i])%p;\n        value = (value*A[i])%p;\n\n        value = (value - k*A[i])%p;\n\n        value = (value + p)%p;\n\n        value_frequency[value]++;\n    }\n\n    long long no_of_pairs = 0;\n    for(auto it = value_frequency.begin(); it != value_frequency.end(); it++)\n    {\n        no_of_pairs += choose_2(it->second);\n    }\n\n    cout << no_of_pairs << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Cram Time Explanation.txt",
    "content": "It is always optimal to use consecutive integers.\n\nLet x be the larget integer such that x(x + 1)/2 <= (a + b),\n\nwe will show that it is always possible to attain x.\n\nWe will fill up i = x down to 1 in descending order in a.\n\nWhen a = a' < i, we will put a' in a, so that a = 0 is completely filled.\n\nSince a is completely filled and x(x + 1)/2 <= (a + b),\nwe can put all the remaining integers in b\n\n-----\n\nPlease note that filling it in ascending order will not work.\nIt might leave gaps.\n\nFor example suppose we are at i and have already placed all integers < i.\n\na = a' < i\n\nNow, we cannot put i in a and since we have already filled all the smaller integers,\nwe can never fill a.\n\nThis leaves a gap.\n\nSo, we have to fill it in descending order. We have to ensure that at least one of the days is completely packed.\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid display(vector <long long> &A)\n{\n    cout << A.size() << \"\\n\";\n\n    for(int i = 0; i < A.size(); i++)\n    {\n        cout << A[i] << \" \";\n    }\n\n    cout << \"\\n\";\n}\n\nint main()\n{\n    long long a, b;\n    cin >> a >> b;\n\n    long long left = 0, right = 1e5;\n    while(right - left > 1)\n    {\n        long long mid = (right + left)/2;\n\n        if(mid*(mid + 1) <= (a + b)*2)\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n\n    vector <long long> day_a, day_b;\n    long long problems = left;\n    for(long long i = problems; i >= 1; i--)\n    {\n        if(a >= i)\n        {\n            day_a.push_back(i);\n            a -= i;\n        }\n        else\n        {\n            for(; i >= 1; i--)\n            {\n                if(i == a)\n                {\n                    day_a.push_back(i);\n                    a -= i;\n                }\n                else\n                {\n                    day_b.push_back(i);\n                    b -= i;\n                }\n            }\n        }\n    }\n\n    display(day_a);\n    display(day_b);\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Cycles Explanation.txt",
    "content": "The idea is to be greedy.\nFirst, we will take a complete graph of K vertices.\n\nA vertex with K vertices has C(K, 3) triangles.\n\nWe will choose the largest K such that C(K, 3) <= E\n\n-----\n\nAfter this, when we add the new vertex, we will connect it to as many vertices as possible so that the number of triangles is <= E\n\nIf we connect this vertex with the first v vertices, then we will be adding C(v, 2) triangles.\n\n-----\n\n1. First take a complete graph\n2. Then, take a new vertex and connect it to the first i vertices so that total edges <= E\n\n-----\n\nint main()\n{\n    int no_of_edges;\n    cin >> no_of_edges;\n\n    int complete_graph = 0;\n    for(int i = 1; ; i++)\n    {\n        if(choose_3(i) > no_of_edges)\n        {\n            complete_graph = i - 1;\n            no_of_edges -= choose_3(complete_graph);\n            break;\n        }\n    }\n\n    vector <int> extra_matching;\n    while(no_of_edges > 0)\n    {\n        for(int i = complete_graph; i >= 0; i--)\n        {\n            if(choose_2(i) <= no_of_edges)\n            {\n                extra_matching.push_back(i);\n\n                no_of_edges -= choose_2(i);\n\n                break;\n            }\n        }\n    }\n\n    memset(graph, 0, sizeof(graph));\n\n    for(int i = 1; i <= complete_graph; i++)\n    {\n        for(int j = i + 1; j <= complete_graph; j++)\n        {\n            add_edge(i, j);\n        }\n    }\n\n    for(int i = 0; i < extra_matching.size(); i++)\n    {\n        int v = complete_graph + i + 1;\n        int v_limit = extra_matching[i];\n\n        for(int w = 1; w <= v_limit; w++)\n        {\n            add_edge(v, w);\n        }\n    }\n\n    int no_of_vertices = complete_graph + extra_matching.size();\n\n    cout << no_of_vertices << \"\\n\";\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        for(int j = 1; j <= no_of_vertices; j++)\n        {\n            cout << graph[i][j];\n        }\n\n        cout << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Elections Explanation.txt",
    "content": "Let us try to iterate over the final number of votes of the winning part.\nIf the winning party has T votes in the end, then\n\n1. Every party with more than T votes has to have less than T votes\n2. Party 1 must have at least T votes\n\n-----\n\nFirst, we will go through all the parties.\nFor each party, which has more than T votes, we will choose it's cheapest votes till it has less than T votes\nThen, we will take the remaining votes, and start choosing the lowest cost till we have >= T votes\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_PARTIES = 3333;\nvector <vector <int> > votes;\n\nlong long cost_if_final_count(int n)\n{\n    int additional_votes = 0;\n\n    long long cost = 0;\n    vector <long long> extra_votes;\n\n    for(int i = 2; i < votes.size(); i++)\n    {\n        for(int j = 0; j < votes[i].size(); j++)\n        {   //cout << \"Party = \" << i << \" Person = \" << j << \"\\n\";\n            if(j + n <= votes[i].size())\n            {\n                additional_votes++;\n                cost += votes[i][j];\n            }\n            else\n            {   //cout << \"Extra \\n\";\n                extra_votes.push_back(votes[i][j]);\n            }\n        }\n    }\n\n    int remaining = n - votes[1].size() - additional_votes;\n    //cout << \"Remaining = \" << remaining << \"\\n\";\n    if(remaining <= 0)\n    {\n        return cost;\n    }\n\n    sort(extra_votes.begin(), extra_votes.end());\n\n    for(int i = 0; i < remaining && i < extra_votes.size(); i++)\n    {\n        cost += extra_votes[i];\n    }\n\n    return cost;\n}\n\nint main()\n{\n    int no_of_voters, no_of_parties;\n    cin >> no_of_voters >> no_of_parties;\n\n    votes.resize(no_of_parties + 1);\n\n    for(int i = 1; i <= no_of_voters; i++)\n    {\n        int party, cost;\n        cin >> party >> cost;\n\n        votes[party].push_back(cost);\n    }\n\n    for(int i = 2; i <= no_of_parties; i++)\n    {\n        sort(votes[i].begin(), votes[i].end());\n    }\n\n    long long answer = 1e18;\n    for(int i = 1; i <= no_of_voters; i++)\n    {   //cout << \"cost \" << i << \" = \" << cost_if_final_count(i) << \"\\n\";\n        answer = min(answer, cost_if_final_count(i));\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Fight Against Traffic Explanation.txt",
    "content": "There are only 1000 vertices, so we can iterate over all pairs of edges.\n\nHow do we check if pair (u, v) is good ?\n\nFirst of all, (u, v) should not already have an edge between them.\n\nSecondly, if we add an edge between (u, v), it should not decrease the shortest distance.\n\nThere are two possible paths.\n\nS -> u -> v -> T\nS -> v -> u -> T\n\nBoth of these should be >= Distance of T from S\n\n-----\n\nTo aid in our calculation, we will precompute,\n\nDistance_source(v) and Distance_target(v), for all vertices v\n\nThe new distance is either\n\nDistance_source(u) + 1 + Distance_target(v) or\nDistance_source(v) + 1 + Distance_target(u)\n\nPlease note that we cannot do this with 1 Distance vector.\nIt is a graph, not a tree and there may be multiple paths from one vertex to another.\n\nFor each vertex, we need to know the shortest distance between each vertex and the source and the target.\n\nWe can do this with two BFS\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <queue>\n#include <set>\n\nusing namespace std;\n\nconst int MAX_N = 1005;\nvector <int> graph[MAX_N];\nset <int> edge_exists[MAX_N];\n\nvoid bfs(int source, vector <int> &distance)\n{\n    queue <int> Q;\n\n    Q.push(source);\n    distance[source] = 0;\n\n    while(!Q.empty())\n    {\n        int u = Q.front();\n        Q.pop();\n\n        for(int i = 0; i < graph[u].size(); i++)\n        {\n            int v = graph[u][i];\n\n            if(distance[v] == -1)\n            {\n                distance[v] = distance[u] + 1;\n\n                Q.push(v);\n            }\n        }\n    }\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n\n    int source, target;\n    cin >> source >> target;\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n\n        edge_exists[u].insert(v);\n        edge_exists[v].insert(u);\n    }\n\n    vector <int> source_distance(no_of_vertices + 1, -1), target_distance(no_of_vertices + 1, -1);\n    bfs(source, source_distance);\n    bfs(target, target_distance);\n\n    int minimum_distance = source_distance[target];\n    long long no_of_good_pairs = 0;\n    for(int u = 1; u <= no_of_vertices; u++)\n    {\n        for(int v = u + 1; v <= no_of_vertices; v++)\n        {\n            if(edge_exists[u].count(v) == 1)\n            {\n                continue;\n            }\n\n            if(source_distance[u] + 1 + target_distance[v] >= minimum_distance &&\n               source_distance[v] + 1 + target_distance[u] >= minimum_distance)\n            {\n                no_of_good_pairs++;\n            }\n        }\n    }\n\n    cout << no_of_good_pairs << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Hacker, Pack your Bags Explanation.txt",
    "content": "Let us treat each left and right border as an 'event'.\n\nAn event has\n\n1. X\n2. Cost\n3. Duration\n4. Is_left -> Indicating if it's left or right\n\n-----\n\nWe will sort the events by their x-point and keep a map\n\nminimum_cost(d) indicates the minimum_cost with duration d\n\n-----\n\n1. When we enter into a left segment, we will check the minimum_cost(d - A[i].duration)\n\n2. When we enter into a right segment, we will update the value of\nminimum_cost(A[i].duration)\n\nThis maintains the invariant that minimum_cost(d) only holds the cost of those\nevents who's right border we have already crossed, ensuring there is no intersection\n\n-----\n\nint main()\n{\n    int no_of_segments, total;\n    cin >> no_of_segments >> total;\n\n    vector <Point> A;\n    for(int i = 1; i <= no_of_segments; i++)\n    {\n        int left, right, x;\n        cin >> left >> right >> x;\n\n        A.push_back(Point(left, x, right - left + 1, true));\n        A.push_back(Point(right, x, right - left + 1, false));\n    }\n\n    sort(A.begin(), A.end(), sort_by_point);\n\n    map <int, int> minimum_cost;\n    const int oo = 2e9 + 7;\n    int answer = oo;\n\n    for(int i = 0; i < 2*no_of_segments; i++)\n    {\n        if(A[i].is_left)\n        {\n            if(minimum_cost.find(total - A[i].duration) != minimum_cost.end())\n            {\n                answer = min(answer, minimum_cost[total - A[i].duration] + A[i].cost);\n            }\n        }\n        else\n        {\n            if(minimum_cost.find(A[i].duration) != minimum_cost.end())\n            {\n                minimum_cost[A[i].duration] = min(minimum_cost[A[i].duration], A[i].cost);\n            }\n            else\n            {\n                minimum_cost[A[i].duration] = A[i].cost;\n            }\n        }\n    }\n\n    cout << (answer >= oo ? -1 : answer) << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Imbalance Array Explanation.txt",
    "content": "For each A[i], let us count the number of subarrays it is the minimum in\nand the number of subarrays it is the maximum in.\n\nSuppose A[L[i], R[i]], is the range in which A[i] is the minimum element.\n\nHow to calculate the number of subarrays ?\nThe left half can end anywhere between L[i], i and the right half can end\nanywhere between i, R[i].\n\nSo we multiply this.\n\n(i - L[i] + 1)(R[i] - i + 1)\n\n-----\n\nA problem arises when we face equal elements.\nHow to deal with this ?\n\nSuppose, we have a subarray [1, 2, 1].\n\nBoth the 1's will be considered the minimum and we will be over counting.\n\nIn order to overcome this, we will place a bijection.\nFor each subarray, we will only consider the leftmost or rightmost maxima and minima.\n\nThis way, each maxima and minima will be counted exactly once.\n\nSo, L[i] is the first index such that A[L[i]] <= A[i]\nAnd R[i] is the first index such that A[R[i]] < A[i]\n\nSo, A[i] cannot have any equal elements on the left but can have equal elements on the right.\n\n-----\n\nWe can compute this with a stack in O(n) time.\n\nvoid compute_max_borders(int n, vector <int> &A, vector <int> &L, vector <int> &R)\n{\n    const int oo = 1e9 + 9;\n\n    stack < pair <int, int> > left_max;\n    left_max.push(make_pair(0, oo));\n    for(int i = 1; i <= n; i++)\n    {\n        while(left_max.top().second < A[i])\n        {\n            left_max.pop();\n        }\n\n        L[i] = left_max.top().first + 1; //Range in which A[i] is maximum\n\n        left_max.push(make_pair(i, A[i]));\n    }\n\n    stack < pair <int, int> > right_max;\n    right_max.push(make_pair(n + 1, oo));\n    for(int i = n; i >= 1; i--)\n    {\n        while(right_max.top().second <= A[i])\n        {\n            right_max.pop();\n        }\n\n        R[i] = right_max.top().first - 1;\n\n        right_max.push(make_pair(i, A[i]));\n\n    }\n}\n\nvoid compute_min_borders(int n, vector <int> &A, vector <int> &L, vector <int> &R)\n{\n    const int oo = 1e9 + 9;\n\n    stack < pair <int, int> > left_min;\n    left_min.push(make_pair(0, -oo));\n    for(int i = 1; i <= n; i++)\n    {\n        while(left_min.top().second > A[i])\n        {\n            left_min.pop();\n        }\n\n        L[i] = left_min.top().first + 1; //cout << \"L \" << i << \" = \" << L[i] << \"\\n\";\n\n        left_min.push(make_pair(i, A[i]));\n    }\n\n    stack < pair <int, int> > right_min;\n    right_min.push(make_pair(n + 1, -oo));\n    for(int i = n; i >= 1; i--)\n    {\n        while(right_min.top().second >= A[i])\n        {\n            right_min.pop();\n        }\n\n        R[i] = right_min.top().first - 1;\n\n        right_min.push(make_pair(i, A[i]));\n    }\n}\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> left_max_border(no_of_elements + 1), right_max_border(no_of_elements + 1);\n    compute_max_borders(no_of_elements, A, left_max_border, right_max_border);\n\n    long long total_maximum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left_half = i - left_max_border[i], right_half = (right_max_border[i] - i);\n        long long no_of_maximas = (left_half + 1)*(right_half + 1);\n\n        total_maximum += no_of_maximas*A[i];\n    }\n\n    vector <int> left_min_border(no_of_elements + 1), right_min_border(no_of_elements + 1);\n    compute_min_borders(no_of_elements, A, left_min_border, right_min_border);\n\n    long long total_minimum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left_half = i - left_min_border[i], right_half = right_min_border[i] - i;\n        long long no_of_minima = (left_half + 1)*(right_half + 1);\n\n        total_minimum += no_of_minima*A[i];\n    }\n\n    long long answer = total_maximum - total_minimum;\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Laboratory Work Explanation.txt",
    "content": "If the Average (X) = Average (Y), then they must have the same sum.\n\nLet us solve the problem on (0, 1, 2) and then map it to the range asked.\n\nWe can use the operation 1 + 1 = 0 + 2 to make the sum invariant\n\nThe number of operations is either min(f[0], f[2]) or f[1]/2, whichever is larger.\n\nThere is another condition that min(Y) = min(X) and max(Y) = max(X)\n\nSo, if f[0] = 0 or f[2] = 0, we cannot change (1, 1) to (0, 2)\n\n-----\n\nint main()\n{\n    int no_of_points;\n    cin >> no_of_points;\n\n    vector <int> X(no_of_points);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> X[i];\n    }\n\n    sort(all(X));\n\n    int minimum = X[0];\n\n    const int MAX_TYPES = 3;\n    vector <int> frequency(MAX_TYPES, 0);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        frequency[X[i] - minimum]++;\n    }\n\n    vector <int> new_frequency(MAX_TYPES, 0);\n    for(int t = 0; t < MAX_TYPES; t++)\n    {\n        new_frequency[t] = frequency[t];\n    }\n\n    if(frequency[1]/2 > min(frequency[0], frequency[2]) && frequency[2] > 0 && frequency[0] > 0)\n    {\n        new_frequency[0] = frequency[0] + frequency[1]/2;\n        new_frequency[1] = frequency[1]%2;\n        new_frequency[2] = frequency[2] + frequency[1]/2;\n    }\n    else if(frequency[1]/2 <= min(frequency[0], frequency[2]))\n    {\n        new_frequency[0] = frequency[0] - min(frequency[0], frequency[2]);\n        new_frequency[1] = frequency[1] + 2*min(frequency[0], frequency[2]);\n        new_frequency[2] = frequency[2] - min(frequency[0], frequency[2]);\n    }\n\n    int equal_elements = 0;\n    for(int t = 0; t < MAX_TYPES; t++)\n    {\n        equal_elements += min(frequency[t], new_frequency[t]);\n    }\n\n    cout << equal_elements << \"\\n\";\n\n    for(int t = 0; t < MAX_TYPES; t++)\n    {\n        for(int i = 0; i < new_frequency[t]; i++)\n        {\n            cout << minimum + t << \" \";\n        }\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Lieges of Legendre Explanation.txt",
    "content": "This is an impartial game.\nLet us try to reduce it to a game of NIM using the Sprague Grundy Theorem.\n\nLet us try to find out the grundy number of f(2n)\n\nf(2n) = mex{f(2n - 1), XOR(f(n), f(n), ... , f(n))}\n\nIf K is even, then f(2n) = mex{f(2n - 1), 0}\nIf K is odd, then f(2n) = mex{f(2n - 1), f(n)}\n\n-----\n\nLet us write out the function for even K\n\nf(0) = 0\nf(1) = mex(f(0)) = 1\nf(2) = mex(f(1), 0) = 2\nf(3) = mex(f(2)) = 0\nf(4) = mex(f(3)) = 1\nf(5) = mex(f(4)) = 0\n\nHere, we can see that f(n) = 1, if n is odd and 0 if n is even > 2\n\nWe can prove this with mathematical induction.\n\nIt is true for f(3), f(4)\nSuppose it is true for f(k), f(k + 1)\n\nf(k + 2) = mex(f(k + 1)) = mex(1) = 0\nf(k + 3) = mex(f(k + 2), 0) = mex(0, 0) = 1\n\n-----\n\nLet us write out the first few values with odd K\n\nf(0) = 0\nf(1) = mex(f(0)) = 1\nf(2) = mex(f(1)) = 0\nf(3) = mex(f(2)) = 1\nf(4) = mex(f(3), f(2)) = 2\nf(5) = mex(f(4)) = 0\nf(6) = mex(f(5), f(3)) = 2\nf(7) = 0\nf(8) = 1\nf(9) = 0\nf(10) = 1\nf(11) = 0\nf(12) = 1\nf(13) = 0\nf(14) = 1\n\nWe see a pattern emerge that\nf(n) = 0 for all odd n > 3 and\nf(n) > 0 for all even n > 2\n\nWe can prove this with Mathematical Induction.\nIt is true for f(5), f(6).\n\nSuppose it is true for f(k), f(k + 1)\n\nf(k + 2) = mex{f(k + 1)} = 0, since f(k + 1) > 0 by the Induction Hypothesis\nf(k + 3) = mex{f(k + 2), f((k + 3)/2)} > 0\n\n-----\n\nFor odd K, we can return the answer as 0 if it is odd > 3\nAnd if it is even, then we will check the value of f(n/2)\n\nIf f(n/2) = 1, then f(n) = 2\nIf f(n/2) > 1, then f(n) = 1\n\nThe only exception is f(4) = 2 even though f(4/2) = 0 because f(3) = 1\nand f(2) = 0\n\nThe time complexity is O(log MAXN)\n\n-----\n\nint get_grundy(int n, int k)\n{\n    if(n == 0)\n    {\n        return 0;\n    }\n\n    if(n == 1)\n    {\n        return 1;\n    }\n\n    if(k%2 == 0)\n    {\n        if(n == 2)\n        {\n            return 2;\n        }\n\n        return (n%2 == 0 ? 1 : 0);\n    }\n    else\n    {\n        if(n%2 == 1)\n        {\n            return (n <= 3 ? 1 : 0);\n        }\n\n        if(n == 2)\n        {\n            return 0;\n        }\n\n        if(n == 4)\n        {\n            return 2;\n        }\n\n        return (get_grundy(n/2, k) == 1 ? 2 : 1);\n    }\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Line Explanation.txt",
    "content": "Ax + By = -C\n\nWe will use the extended gcd algorithm to find x, y such that\n\nAx + By = G\n\nAnd then multiply the whole equation by (-C/G)\n\nIf C is not divisible by G, then it is not possible\n\n-----\n\nlong long extended_gcd(long long A, long long B, long long &x, long long &y)\n{\n    if(B == 0)\n    {\n        x = 1;\n        y = 0;\n        return A;\n    }\n\n    long long x1, y1;\n    long long gcd = extended_gcd(B, A%B, x1, y1);\n\n    y = x1 - (A/B)*y1;\n    x = y1;\n    //cout << \"(\" << A << \",\" << B << \") = \" << x << \",\" << y << \"\\n\";\n    return gcd;\n}\n\nint main()\n{\n    long long A, B, C;\n    cin >> A >> B >> C;\n\n    long long X = 0, Y = 0;\n    long long gcd_A_B = extended_gcd(A, B, X, Y);\n\n    X *= (-C/gcd_A_B);\n    Y *= (-C/gcd_A_B);\n\n    if(C%gcd_A_B == 0)\n        cout << X << \" \" << Y << \"\\n\";\n    else\n        cout << \"-1\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Marina and Vyasa Explanation.txt",
    "content": "Instead of working around the number of difference,\nlet us look at the number of matches.\n\nSuppose there are S characters that are the same i.e. S[i] = T[i]\n\nIf we have to have K differences, we have to have (N - K) matches.\n\nAt first, we will try to match all the characters where they are same.\nIf that is insufficient, we will do the following\n\nFor a given pair,\nS(i), T(i) and S(j), T(j)\n\nAnswer[i] = S[i], Answer[j] = T[j]\n\nThis increases the number of matches by 1.\n\nSo the minimum length of the string should be S + 2(M - S),\nwhere M is the number of matches that we need to make. \n\n------\n\nchar other(char c1, char c2)\n{\n    const int NO_OF_ALPHABETS = 26;\n\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        char current = 'a' + alpha;\n\n        if(current != c1 && current != c2)\n        {\n            return current;\n        }\n    }\n\n    return 'z';\n}\n\nint main()\n{\n    int length, differences;\n    string S, T;\n    cin >> length >> differences >> S >> T;\n\n    int same = 0;\n    for(int i = 0; i < length; i++)\n    {\n        if(S[i] == T[i])\n        {\n            same++;\n        }\n    }\n\n    int matches = length - differences;\n\n    int minimum_length = same + 2*max(matches - same, 0);\n\n    if(minimum_length > length)\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    string answer = S;\n    int a_matches = length, b_matches = same;\n    for(int i = 0; i < length; i++)\n    {\n        if(S[i] != T[i])\n        {\n            if(b_matches < matches)\n            {\n                answer[i] = T[i];\n\n                a_matches--;\n                b_matches++;\n            }\n            else if(a_matches > matches)\n            {\n                answer[i] = other(S[i], T[i]);\n\n                a_matches--;\n            }\n        }\n    }\n\n    for(int i = 0; i < length && (a_matches > matches || b_matches > matches); i++)\n    {\n        if(S[i] == T[i])\n        {\n            answer[i] = other(S[i], T[i]);\n\n            a_matches--;\n            b_matches--;\n        }\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Match Points Explanation.txt",
    "content": "1. We can actually do binary search and check if it is possible to obtain K pairs\n\n2. To check if it is possible to obtain K pairs, we will try to match the first K points with the last K points.\n\n3. How to do the matching ?\nLet us take A[1] and match it with A[n - k + 1]\nSuppose we have two points L1 < L2 and R1 < R2\nThen, it is always best to pair [L1, R1], [L2, R2]\n\nIf [L1, R2] and [L2, R1] are good segments, then even\n[L1, R1] and [L2, R2] are good segments.\n\nAs R1 is paired with a smaller element in L1 and L2 is paired with a larger element R2\n\nUsing this Exchange Argument we can see that it is always best to pair\nA[1], A[n - k + 1]\nA[2], A[n - k + 2]\n.\n.\nA[k], A[n]\n\n-----\n\nint main()\n{\n    int no_of_elements, distance;\n    cin >> no_of_elements >> distance;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    int left_pairs = 0, right_pairs = no_of_elements/2 + 1;\n    while(right_pairs - left_pairs > 1)\n    {\n        int mid = (left_pairs + right_pairs)/2;\n\n        int good_pairs = 0;\n\n        for(int i = 1; i <= mid; i++)\n        {\n            if(A[no_of_elements - mid + i] - A[i] >= distance)\n            {\n                good_pairs++;\n            }\n        }\n\n        if(good_pairs == mid)\n        {\n            left_pairs = mid;\n        }\n        else\n        {\n            right_pairs = mid;\n        }\n    }\n\n    int answer = left_pairs;\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Molly and Chemicals Explanation.txt",
    "content": "The number of perfect powers of any integer will not be too many.\n\nIt will be at most 40, in fact, in the given range.\n\nIf S[R] - S[L] = k^p\n\nWe will keep track of the frequency of prefix sum.\n\nFor every S[R], it will create a good segment with every S[L] = k^p - S[L]\n\nWe will add the frequency of (k^p - S[L]) to the answer\n\n-----\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <long long> powers;\n    precompute(powers, k);\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    map <long long, int> prefix_sum_frequency;\n    long long prefix = 0;\n    prefix_sum_frequency[prefix] = 1;\n\n    long long no_of_segments = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix += A[i];\n\n        for(int j = 0; j < powers.size(); j++)\n        {\n            no_of_segments += prefix_sum_frequency[prefix - powers[j]];\n        }\n\n        prefix_sum_frequency[prefix]++;\n    }\n\n    cout << no_of_segments << \"\\n\";\n\n    return 0;\n}\n\n\n------\n\nvoid precompute(vector <long long> &P, long long k)\n{\n    P.push_back(1);\n\n    if(k == 0 || k == 1)\n    {\n        return;\n    }\n\n    if(k == -1)\n    {\n        P.push_back(-1);\n        return;\n    }\n\n    long long oo = 1e14;\n\n    while(abs(P.back()) <= oo)\n    {   //cout << P.back() << \"\\n\";\n        P.push_back(P.back()*k);\n    }\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Moodular Arithmetic Explanation.txt",
    "content": "Let us study the implication of the functional equation.\n\nSuppose f(n) = x\n\nf(k n) = k x\nf(k^2 n) = k f(k n) = k^2 x\nf(k^3 n) = k f(k^2 n) = k^3 x\nAnd so on\n\nf(k^i n) = k^i f(n)\n\nSo, if we assign f(n) to a value, the values of\nf(kn), f(k^2 n), f(k^3 n), ... , f(k^i n) are determined until\nk^{i + 1} = 1 because (n, kn, k^2 n, ... k^i n are all distinct)\n\nWhat about f(0) ?\nf(0) = k f(0) (mod p)\n(k - 1) f(0) = 0 (mod p)\nThis means that f(0) = 0 since p cannot divide (k - 1) as k <= p\n\nSo, we can divide {1, ... , p - 1} into (p - 1)/m subgroups\nwhere m is the order of k.\n\nIn each subgroup, we can choose one value freely among p options and the rest are determined.\n\nThe answer is p^{(p - 1)/m}\n\n-----\n\nIf k = 0, then f(0) = 0 (mod n)\nThe remaining values can be chosen freely.\nThis can be done in p^{p - 1} ways\n\nIf k = 1, then f(n) = f(n) (mod n)\nThis can be done in p^p ways.\n\n------\n\nint main()\n{\n    int p, k;\n    cin >> p >> k;\n\n    const int MOD = 1e9 + 7;\n    if(k == 0)\n    {\n        cout << power_mod(p, p  - 1, MOD) << \"\\n\";\n        return 0;\n    }\n    if(k == 1)\n    {\n        cout << power_mod(p, p, MOD) << \"\\n\";\n        return 0;\n    }\n\n    cout << power_mod(p, (p - 1)/order(k, p), MOD) << \"\\n\";\n    return 0;\n}\n\n------\n\nWe will use Lagrange's Theorem which says that the order of any subgroup divides the order of the group.\n\nThis will enable us to find out the order of k.\n\nIt must be a factor of (p - 1).\n\n-----\n\nint order(int k, int m)\n{\n    int answer = m - 1;\n\n    for(int i = 1; i*i <= m - 1; i++)\n    {\n        if((m - 1)%i == 0)\n        {\n            if(power_mod(k, i, m) == 1)\n            {\n                answer = min(answer, i);\n            }\n            else if(power_mod(k, (m - 1)/i, m) == 1)\n            {\n                answer = min(answer, (m - 1)/i);\n            }\n        }\n    }\n\n    return answer;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Mouse Hunt Explanation.txt",
    "content": "We are given a 'functional' graph in which every vertex has exactly one edge going out of it.\n\nThere is guaranteed to be at least one cycle.\n\nLet us break the graph into cycles.\n\nEach mouse will visit one of the cycles at least once.\n\nSo, we will put 1 trap in each of the cycle\n\n-----\n\nThe problem is there might be vertices which lead into a cycle.\n\nInstead of 1 → 2 →3 →1, we might have 1 → 2 → 3 → 4 →5 → 3\n\nSo, the dfs gets a little tricky.\n\nWe will maintain two variables for each vertex -\nVisited - Whether it is Visited and\nCurrent_DFS - Indicating if the current vertex has been visited in the current DFS.\n\n-----\n\nWe will begin a DFS when we encounter an unvisited vertex.\n\n1. If we encounter a vertex which is already visited and also in this DFS, then we have found our cycle\n\n2. If we encounter a vertex which was already visited in another DFS, then we have already processed that cycle before so we need not do it again\n\n-----\n\nSo, we will update the cost within the DFS function itself\n\n-----\n\nvoid dfs(int v, int &total_cost)\n{\n    //Cycle Starts here\n    if(current_dfs[v])\n    {\n        int cost_here = cost[v];\n\n        for(int i = to[v]; i != v; i = to[i])\n        {\n            cost_here = min(cost_here, cost[i]);\n        }\n\n        total_cost += cost_here;\n        return;\n    }\n    else if(visits[v]) //It was already linked to a cycle from some other dfs\n    {\n        return;\n    }\n\n    visits[v] = true;\n\n    current_dfs[v] = true;\n\n    dfs(to[v], total_cost);\n\n    current_dfs[v] = false;\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n\n    cost.resize(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> cost[i];\n    }\n\n    to.resize(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> to[i];\n    }\n\n    int total_cost = 0;\n    current_dfs.resize(no_of_vertices + 1, 0);\n    visits.resize(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(!visits[i])\n        {\n            dfs(i, total_cost);\n        }\n    }\n\n    cout << total_cost << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Multiplicity Explanation.txt",
    "content": "Let f(i, j) denote the number of sequences of length j ending at A[i]\n\nNow, j has to be a divisor of A[i] so we need not check all integers,\nbut only the divisors of A[i]\n\nf(i, j) = f(i - 1, j - 1) + f(i - 2, j - 1) + ... + f(1, j - 1)\n\nWe want to know the number of sequences of length (j - 1) ending anywhere before A[i]\n\n-----\n\nWe do not need to do O(n^2) each time.\nJust like the Coin Change DP problem, we can optimise it to O(N) space\n\nWe will maintain a running variable.\n\nLet g(i) be equal to the number of sequences of length i\n\nAs we will be processing the elements in order from 1 to N, we can take advantage of our processing order.\nAt no point in our DP do we ever need to refer to a state from a greater i than the one we are at.\n\nSo, g(i) = g(i - 1), if i is a divisor of the current element\n\n-----\n\nAlso, we cannot factorise the integers in time.\nWe must use a sieve to precompute the divisors of each of the integers\n\n-----\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int MAX = 1e6 + 5;\n    vector <vector <int> > divisors(MAX);\n    for(int i = 1; i < MAX; i++)\n    {\n        for(int multiple = i; multiple < MAX; multiple += i)\n        {\n            divisors[multiple].push_back(i);\n        }\n    }\n\n    const int MOD = 1e9 + 7;\n    vector <long long> no_of_sequences(MAX, 0), sequences_here(MAX, 0);\n    long long total_sequences = 0;\n\n    no_of_sequences[0] = 1;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int d = 0; d < divisors[A[i]].size(); d++)\n        {\n            int m = divisors[A[i]][d];\n\n            sequences_here[m] = no_of_sequences[m - 1];\n        }\n\n        for(int d = 0; d < divisors[A[i]].size(); d++)\n        {\n            int m = divisors[A[i]][d];\n\n            no_of_sequences[m] += sequences_here[m];\n\n            no_of_sequences[m] %= MOD;\n        }\n    }\n\n    for(int i = 1; i < MAX; i++)\n    {\n        total_sequences += no_of_sequences[i];\n\n        total_sequences %= MOD;\n    }\n\n    cout << total_sequences << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Multipliers Explanation.txt",
    "content": "Let N = p1^a1 p2^a2 ... pk^ak\n\nInstead of trying to find out the product of all divisors, let\nus try to find out the exponent of each prime number in the final product\n\nSuppose N = 2^3 3^2 5\n\nLet us look at how many times each exponent of 2 is counted\n\n2.(3) 2.(3.5) 2.(3^2) 2.(3^2 . 5)\n\n2^2.(3) 2^2.(3.5) 2^2.(3^2) 2^2.(3^2 . 5)\n\n2^3.(3) 2^3.(3.5) 2^3.(3^2) 2^3.(3^2 . 5)\n\n----\n\nEach exponent of 2 is paired with - Number of factors of (3^2 5)\n\nWe know that the number of factors of p1^a1 p2^a2 ... pk^ak  is\n\n(a1 + 1) (a2 + 1) ... (ak + 1)\n\nHow many times is each exponent of p1 counted ?\n\n(a2 + 1) (a3 + 1) ... (ak + 1)\n\nThe number of divisors without p1\n\n-----\n\nSo, the net contribution of p1 is\n\n{a1(a1 + 1)/2} (a2 + 1) (a3 + 1) ... (ak + 1)\n\n-----\n\nThis is the same for all prime factors.\n\nIt is easy to do this in 2 linear passes but how do we do this in 1 linear pass ?\n\nWe need to use our creativity to find a beautiful solution in 1 pass through The\nprime factors\n\n-----\n\nLet us remember Fermat's Little Theorem,\n\na^{m - 1} = 1 (mod m)\n\nif m is prime\n\n-----\n\nLet P represent the product of all divisors and d represent the number of divisors\n\nWhen we encounter the first prime factor, P = p1^{a1.(a1 + 1)/2}\nd = (a1 + 1)\n\nLater, when we go to p2,\n\nWe will make P = power(P, (a2 + 1)). power(p2^{a2.(a2 + 1)/2}, d)\nd = d.(a2 + 1)\n\n----\n\nIn general when we arrive at the i-th prime,\n\nWe\n\n1. Raise the product so far of the first (i - 1) factors to the power (ai + 1)\n2. Raise pi^{ai.(ai + 1)/2} to the power d\n3. Update d\n\nThis ensures that each prime is raised to the product of all factors excluding itself\n\n-----\n\nint main()\n{\n    const int MOD = 1e9 + 7;\n    long long product = 1LL;\n\n    int no_of_primes;\n    cin >>  no_of_primes;\n\n    map <int, long long> exponent;\n\n    for(int i = 1; i <= no_of_primes; i++)\n    {\n        int prime_i;\n        scanf(\"%d\", &prime_i);\n\n        exponent[prime_i]++;\n    }\n\n    long long no_of_divisors = 1;\n    for(map <int, long long> :: iterator it = exponent.begin(); it != exponent.end(); it++)\n    {\n        int p = it->first;\n        long long exp = it->second;\n\n        long long divisor_product_here = power_mod(p, (exp*(exp + 1))/2, MOD);\n        product = power_mod(product, exp + 1, MOD)*power_mod(divisor_product_here, no_of_divisors, MOD);\n        product %= MOD;\n\n        no_of_divisors *= (exp + 1);\n        no_of_divisors %= (MOD - 1);\n    }\n\n    cout << product << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/My Pretty Girl Nora Explanation.txt",
    "content": "Suppose we divide it into d stages first and d = a.b\n\nThe number of comparisons will not increase if we divide into a first and then b\n\nThe number of comparisons when there are n people = nd(d - 1)/2d = n(d - 1)/2\n\nWe will use a Sieve to precompute the largest prime factor of every integer.\n\nWe can compute the answer too.\n\nFor every integer, we will see which of it's prime factors is the best first choice.\n\nWe need to be careful about modulo\n\n-----\n\nint main()\n{\n    long long t, left, right;\n    cin >> t >> left >> right;\n\n    const int MOD = 1e9 + 7;\n    vector <long long> largest_prime_factor(right + 1, 0);\n    vector <long long> minimum_comparisons(right + 1, 1e16);\n    minimum_comparisons[1] = 0;\n    for(long long i = 2; i <= right; i++)\n    {\n        if(largest_prime_factor[i] == 0)\n        {\n            largest_prime_factor[i] = i;\n            for(long long multiple = i*i; multiple <= right; multiple += i)\n            {\n                if(largest_prime_factor[multiple] == 0)\n                {\n                    largest_prime_factor[multiple] = i;\n                }\n            }\n        }\n\n        for(int x = i; x != 1; x /= largest_prime_factor[x])\n        {\n            int remaining = i/largest_prime_factor[x];\n\n            long long comparisons_here = (i*(largest_prime_factor[x] - 1))/2 + minimum_comparisons[remaining];\n\n            minimum_comparisons[i] = min(minimum_comparisons[i], comparisons_here);\n        }\n\n        minimum_comparisons[i] %= MOD;\n    }\n\n    long long answer = 0, coefficient = 1;\n    for(int i = left; i <= right; i++)\n    {\n        answer += (coefficient*minimum_comparisons[i])%MOD;\n\n        coefficient = (coefficient*t)%MOD;\n\n        answer %= MOD;\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Optimal Number Permutation Explanation.txt",
    "content": "The sum will always be non negative.\nLet us try to make it 0\n\nThe 1's should be at a distance of (n - 1)\nThe 2's should be at a distance of (n - 2)\nThe 3's should be at a distance of (n - 3)\n.\n.\n.\nThe n's can be at any position since (n - i) = 0\n\n-----\n\nWe will place 1 at (1, n), 3 at (2, n - 1) and so on\nWe will place 2 at (n + 1, 2n - 1), 4 at (n + 2, 2n - 2) and so on\nWe can place the n's anywhere.\n\nSince the distance reduces by 1 at each integer and the distance between\nthe free places reduces by 2 on placing an integer,\nit is a good idea to keep integers of the same parity together.\n\n-----\n\nUltimately, the array will look like all the odd integers in first half and\neven integers in second half with n in the last position and\neither in the middle of the first or second half, depend on it's parity.\n\n-----\n\n10\n1 3 5 7 9 9 7 5 3 1 2 4 6 8 10 8 6 4 2 10\n\n11\n1 3 5 7 9 11 9 7 5 3 1 2 4 6 8 10 10 8 6 4 2 11\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(2*no_of_elements + 1);\n    for(int front = 1, back = no_of_elements, odd = 1; odd <= no_of_elements; front++, back--, odd += 2)\n    {\n        A[front] = A[back] = odd;\n    }\n\n    for(int front = no_of_elements + 1, back = 2*no_of_elements - 1, even = 2; even <= no_of_elements; front++, back--, even += 2)\n    {\n        A[front] = A[back] = even;\n    }\n\n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        if(A[i] == 0)\n        {\n            A[i] = no_of_elements;\n        }\n    }\n\n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Pair of Numbers Explanation.txt",
    "content": "Here is the crucial insight\n\nIf an element in [L, R] divides every other element in it, then it is the GCD\n\nNow, for each segment how do we check if the GCD occurs in it ?\n\nIf the GCD occurs in it, then the GCD is the minimum integer\n\nGCD[L, R] = Min[L, R]\n\nIs the condition we need to check\n\n-----\n\nLet us use Sparse Tables for this as there are no update operations required\n\nWe will do binary search on the length and\nsettle the on the maximum length such that GCD[segment] = Minimum[segment]\n\n-----\n\nAfter finding out the maximum length, we will just collect all of them in a vector\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 3e5 + 5, MAX_L = 20;\nint no_of_elements, A[MAX_N];\nint gcd_table[MAX_N][MAX_L], min_table[MAX_N][MAX_L];\n\nint gcd(int x, int y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n\n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1 << bit)) != 0 );\n}\n\nvoid precompute()\n{\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        gcd_table[i][0] = A[i];\n        min_table[i][0] = A[i];\n    }\n\n    for(int l = 1; l < MAX_L; l++)\n    {\n        int jump = (1 << (l - 1));\n\n        for(int i = 1; i + (1 << l) - 1 <= no_of_elements; i++)\n        {\n            int next = i + jump;\n\n            gcd_table[i][l] = gcd(gcd_table[i][l - 1], gcd_table[next][l - 1]);\n            min_table[i][l] = min(min_table[i][l - 1], min_table[next][l - 1]);\n        }\n    }\n}\n\npair <int, int> compute(int i, int length)\n{\n    int gcd_here = A[i], min_here = A[i];\n    for(int bit = MAX_L; bit >= 0; bit--)\n    {\n        if(is_bit_set(length, bit))\n        {\n            gcd_here = gcd(gcd_here, gcd_table[i][bit]);\n            min_here = min(min_here, min_table[i][bit]);\n\n            i += (1 << bit);\n        }\n    }\n\n    return make_pair(gcd_here, min_here);\n}\n\nint possible(int length)\n{\n    for(int i = 1; i + length - 1 <= no_of_elements; i++)\n    {\n        pair <int, int> answer = compute(i, length);\n\n        int gcd_here = answer.first, minimum_here = answer.second;\n\n        if(gcd_here == minimum_here)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nint main()\n{\n    cin >> no_of_elements;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    precompute();\n\n    int left = 1, right = no_of_elements + 1;\n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n\n        if(possible(mid))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n\n    vector <int> answer;\n    for(int i = 1; i + left - 1 <= no_of_elements; i++)\n    {\n        pair <int, int> answer_here = compute(i, left);\n        int gcd_here = answer_here.first, min_here = answer_here.second;\n\n        if(gcd_here == min_here)\n        {\n            answer.push_back(i);\n        }\n    }\n\n    cout << answer.size() << \" \" << left - 1 << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i] << \" \";\n    }\n\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Pashmak and Graph Explanation.txt",
    "content": "1. We will keep an empty graph and add the edges one by one in ascending order of weight\n\n2. When we add an edge (u, v) then we will update path[v] = max(1 + path[u], path[v])\n\n3. We have to be careful on handling edges of the same weight\n\nSuppose we have multiple edges ending at u and then at v, we can't use both u and v\n\nSo, we will process all edges of the same weigh together\n\n-----\n\nstruct Edge\n{\n    int source, destination, weight;\n\n    int operator <(const Edge &A)\n    {\n        return (weight < A.weight);\n    }\n};\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\n\n    vector <Edge> edge(no_of_edges + 1);\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        scanf(\"%d %d %d\", &edge[i].source, &edge[i].destination, &edge[i].weight);\n    }\n\n    sort(all(edge));\n\n    vector <int> maximum_ending_at(no_of_vertices + 1, 0);\n\n    vector <int> maximum_with_this_weight(no_of_vertices + 1, 0);\n\n    for(int i = 1; i <= no_of_edges; )\n    {\n        int j = i;\n\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\n        {\n            maximum_with_this_weight[edge[j].destination] = 0;\n        }\n\n        //Process all edges having this weight. Have a different vector so you don't interact with equal weights.\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\n        {\n            maximum_with_this_weight[edge[j].destination] = max(maximum_with_this_weight[edge[j].destination], 1 + maximum_ending_at[edge[j].source]);\n        }\n\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\n        {\n            maximum_ending_at[edge[j].destination] = max(maximum_ending_at[edge[j].destination], maximum_with_this_weight[edge[j].destination]);\n        }\n\n        i = j;\n    }\n\n    int maximum_path = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n        maximum_path = max(maximum_path, maximum_ending_at[i]);\n\n    printf(\"%d\\n\", maximum_path);\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Pavel and Triangles Explanation.txt",
    "content": "Let us make 1 observation\n\n2^i > 1  + 2 + 2^2 + ... + 2^{i - 1}\n\nSo, let us look at the largest side of the triangle.\n\nLet it be 2^i\n\nOne of the other two sides also should be = 2^i,\n\nOtherwise, if both sides 2^j and 2^k are < 2^i,\nit will not satisfy the triangle inequality\n\n-----\n\nEvery triangle is of this form\n\n(2^i, 2^j, 2^j) i < j\n(2^i, 2^i, 2^i)\n\n-----\n\nLet us be greedy.\nWe will go through the sticks greedily\n\nFor each i, we will try to pair 2 of it's sticks with as many of the sticks\nremaining in the prefix.\n\nThen, we will try to make as many equilateral triangles as possible\n\n-----\n\nThis solution is always optimal.\nLet us suppose there is some optimal solution where the sticks of our triplet (i, j, j)\nare used in different triplets\n\n(i, k1, k1), (j, k2, k2) and (j, k3, k3) we can swap them to have the same arrangement\n(i, j, j), (k1, k2, k2) and (k1, k3, k3)\nOur solution won't get worse.\n\nWe can apply a similar exchange argument to all cases relating to how many sticks we use \n-----\n\n\nint main()\n{\n    int no_of_sticks;\n    cin >> no_of_sticks;\n\n    vector <int> A(no_of_sticks + 1);\n    for(int i = 1; i <= no_of_sticks; i++)\n    {\n        cin >> A[i];\n    }\n\n    long long no_of_triangles = 0;\n    int remaining_sticks = 0;\n    for(int highest = 1; highest <= no_of_sticks; highest++)\n    {\n        int triangles_here = min(remaining_sticks, A[highest]/2);\n\n        no_of_triangles += triangles_here;\n\n        A[highest] -= 2*triangles_here;\n        remaining_sticks = remaining_sticks - triangles_here;\n\n        no_of_triangles += A[highest]/3;\n        A[highest] %= 3;\n\n        remaining_sticks += A[highest];\n    }\n\n    cout << no_of_triangles << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Plus and XOR Explanation.txt",
    "content": "Observation - X is a submask of Y\n\nWhenever X has a bit set, Y also has a bit set.\n\nIf X has some bits set that Y does not, we can make X[i] = 0 and Y[i] = 1\n\nAnd the sum and XOR would not change.\n\nY = X + (Bits where only Y has a bit)\n\nBut, we can get this value easily from the xor !\n\nX^Y = (Bits where only Y has a bit) = B\n\nSo, Y = X + B\n\nA = X + Y = X + (X + B) = 2X + B\n\nX = (A - B)/2\n\nWe have to check that A and B are non negative, (A - B) is even and X^Y = B\n\nUse unsigned long long instead of long long to avoid overflow\n------\n\nint main()\n{\n    unsigned long long A, B;\n    cin >> A >> B;\n\n    //Y = X + B, A = 2X + B\n    if(A < B || (A - B)%2 != 0)\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    unsigned long long X = (A - B)/2, Y = A - X;\n    //cout << X + Y << \" \" << (X^Y) << \"\\n\";\n    if(X + Y != A || (X^Y) != B)\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    cout << X << \" \" << Y << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Points Explanation.txt",
    "content": "We want to compute (x2 - x1)^2 + (y2 - y1)^2 for every pair.\n\nX and Y is independent so we will compute it differently\n\nLet us look at the X's.\n\nA given X1 is linked with (n - 1) other points\n\n(X1 - X2)^2 = X1^2 + X2^2 - 2X1.X2\n\nX1 is linked with (N - 1) points so each square is counted (N - 1) times.\n\nNow, let us try to calculate the linear term.\n\nEach X1 is multiplied with (X1 + X2 + ... + Xn - X1)\n\nNote that we do not need to put a multiplier of 2 here since we will be adding\nXi.Xj when we at Xi and we will be adding Xj.Xi when we are at Xi\n\nSo, we only have to add it once\n\n------\n\nlong long calculate(vector <long long> &P, int n)\n{\n    long long squares = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        squares += (n - 1)*P[i]*P[i];\n    }\n\n    long long sum = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        sum += P[i];\n    }\n\n    long long linear_term = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        linear_term += P[i]*(sum - P[i]);// 2*P[i]*P[i];\n    }\n\n    return (squares - linear_term);\n}\n\nint main()\n{\n    int no_of_points;\n    cin >> no_of_points;\n\n    vector <long long> X(no_of_points + 1);\n    vector <long long> Y(no_of_points + 1);\n\n    for(int i = 1; i <= no_of_points; i++)\n    {\n        cin >> X[i] >> Y[i];\n    }\n\n    long long distance = calculate(X, no_of_points) + calculate(Y, no_of_points);\n\n    cout << distance << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Prime Number Explanation.txt",
    "content": "The exponent of the i-th numerator will be (Sum - A[i])\n\nThe GCD of the numerator will be the minimum exponent\n\nThe GCD of the fraction will be min(minimum_exponent, sum)\n\n-----\n\nNow, how do we find out the minimum exponent ?\n\nAt first, we will keep track of all the exponents.\n\nIf the smallest exponent E[1] occurs x times or 2x times or any multiple of x times,\nThen, we can combine x terms of E[1] to get a new exponent of (E[1] + 1)\n\nfrequency[E[1] + 1] += frequency[E[1]]/x\n\nWe do this till frequency[E[1]] is not a multiple of x\n\nThen, the GCD of the numerator is E[1]\n\n-----\n\nWe can use a Set for our purpose\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n#include <set>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long mod)\n{\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%mod;\n\n        x = (x*x)%mod;\n        power = power/2;\n    }\n\n    return result;\n}\n\nint main()\n{\n    int no_of_elements, x;\n    cin >> no_of_elements >> x;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    long long sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum += A[i];\n    }\n\n    set <long long> S;\n    map <long long, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[sum - A[i]]++;\n\n        S.insert(sum - A[i]);\n    }\n\n    const int MOD = 1e9 + 7;\n    long long answer;\n    for(auto it = S.begin(); ; it++)\n    {\n        while(frequency[*(S.begin())]%x == 0)\n        {\n            long long exponent = *(S.begin());\n\n            long long new_exponent = exponent + 1;\n\n            frequency[new_exponent] += frequency[exponent]/x;\n\n            S.insert(new_exponent);\n\n            S.erase(exponent);\n        }\n\n        if(frequency[*( S.begin() )] != 0)\n        {\n            answer = min(sum, *( S.begin() ));\n\n            break;\n        }\n    }\n\n    cout << power_mod(x, answer, MOD) << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Ramesses and Corner Inversion Explanation.txt",
    "content": "Let us look for an invariant in this operation.\n\nIn 1 operation, we will be flipping 2 elements of a row and 2 elements of a column.\n\nThis means that\n(0,0) -> (1, 1)\n(0,1) -> (1, 0)\n(1, 1) -> (1, 1)\n\nAll these operations preserve the sum (mod 2)\n\nWe have to check if the parity of all rows and columns are the same in A and B\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid read(vector <vector <int> > &A)\n{\n    for(int i = 1; i < A.size(); i++)\n    {\n        for(int j = 1; j < A[0].size(); j++)\n        {\n            cin >> A[i][j];\n        }\n    }\n}\n\nvoid compute(vector <vector <int> > &A, vector <int> &row_sum, vector <int> &column_sum)\n{\n    for(int i = 1; i < A.size(); i++)\n    {\n        for(int j = 1; j < A[0].size(); j++)\n        {\n            row_sum[i] += A[i][j];\n            column_sum[j] += A[i][j];\n        }\n    }\n}\n\nint main()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    vector <vector <int> > A(rows + 1, vector <int> (columns + 1));\n    read(A);\n\n    vector <vector <int> > B(rows + 1, vector <int> (columns + 1));\n    read(B);\n\n    vector <int> A_row_sum(rows + 1), A_column_sum(columns + 1);\n    compute(A, A_row_sum, A_column_sum);\n\n    vector <int> B_row_sum(rows + 1), B_column_sum(columns + 1);\n    compute(B, B_row_sum, B_column_sum);\n\n    int row_and_column_same_parity = true;\n\n    for(int i = 1; i <= rows; i++)\n    {\n        if(A_row_sum[i]%2 != B_row_sum[i]%2)\n        {\n            row_and_column_same_parity = false;\n        }\n    }\n\n    for(int j = 1; j <= columns; j++)\n    {\n        if(A_column_sum[j]%2 != B_column_sum[j]%2)\n        {\n            row_and_column_same_parity = false;\n        }\n    }\n\n    cout << (row_and_column_same_parity ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Scheme.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 15;\nvector <int> graph[MAX_N];\nvector <int> visited(MAX_N, false);\nvector <int> incoming(MAX_N, 0);\n\nvector <int> beginning;\nvector <int> ending;\n\nvoid dfs(int v)\n{\n    visited[v] = true;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n\n        if(visited[child])\n        {\n            ending.push_back(child);\n\n            return;\n        }\n\n        dfs(child);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        int destination;\n        scanf(\"%d\", &destination);\n\n        graph[i].push_back(destination);\n        incoming[destination]++;\n    }\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(incoming[i] == 0)\n        {\n            beginning.push_back(i);\n\n            dfs(i);\n        }\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(!visited[i])\n        {\n            beginning.push_back(i);\n            \n            dfs(i);\n        }\n    }\n\n    int no_of_sinks = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(incoming[i] == 0)\n        {\n            no_of_sinks++;\n        }\n    }\n    \n    int simple_cycle = (no_of_sinks == 0 && beginning.size() == 1);\n    \n    int new_edges = (simple_cycle ? 0 : beginning.size());\n    printf(\"%d\\n\", new_edges);\n\n    for(int i = 0; i < new_edges; i++)\n    {\n        printf(\"%d %d \\n\",ending[i], beginning[(i + 1)%new_edges]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Secret Passwords Explanation.txt",
    "content": "1. Let us draw a graph where each alphabet is a vertex\n\n2. We will draw an edge between two alphabets if they occur in the same word\n\n3. The number of components in this graph is the number of equivalent passwords.\n\n-----\n\n1. I did this by creating a bitmask corresponding to each word\n\n2. If a word has two bits set - B1 and B2, connect (B1, B2) using a DSU structure\n\n3. Each time we perform a 'unite' operation, the number of connected components reduces by 1\n\n4. We need to be careful of 1 thing. In the beginning we created a DSU of 26 vertices\n\nBut all 26 alphabets might not be used.\nThe alphabets that are not used will be single components\n\n5. So, the answer is the number of components in our graph -\nthe number of unused alphabets\n\n-----\n\nint main()\n{\n    int no_of_words;\n    cin >> no_of_words;\n\n    vector <int> used(NO_OF_ALPHABETS, false);\n    DSU dsu(NO_OF_ALPHABETS);\n\n    for(int i = 1; i <= no_of_words; i++)\n    {\n        string word;\n        cin >> word;\n\n        int mask = 0;\n        for(int j = 0; j < word.size(); j++)\n        {\n            mask |= (1 << (word[j] - 'a'));\n\n            used[word[j] - 'a'] = true;\n        }\n\n        for(int bit_1 = 0; bit_1 < NO_OF_ALPHABETS; bit_1++)\n        {\n            for(int bit_2 = 0; bit_2 < NO_OF_ALPHABETS; bit_2++)\n            {\n                if(!is_set(mask, bit_1) || !is_set(mask, bit_2) || dsu.get_parent(bit_1) == dsu.get_parent(bit_2))\n                {\n                    continue;\n                }\n\n                dsu.unite(bit_1, bit_2);\n            }\n        }\n    }\n\n    int unused_alphabets = 0;\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(!used[alpha])\n        {\n            unused_alphabets++;\n        }\n    }\n\n    int actual_components = dsu.no_of_components - unused_alphabets;\n\n    cout << actual_components << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Segments Explanation.txt",
    "content": "The idea is to treat each entry and exit as an 'event' and sort all the events.\n\n When we meet an 'ending', we put a nail on it.\n This satisfies all the segments which are open.\n So we will remove all the open segments from our list.\n----\n\nint main()\n{\n    int no_of_segments;\n    cin >> no_of_segments;\n\n    vector <segment> S;\n    for(int i = 0; i < no_of_segments; i++)\n    {\n        int left, right;\n        cin >> left >> right;\n\n        if(left > right)\n        {\n            swap(left, right);\n        }\n\n        S.push_back(segment(left, ENTRY, i));\n        S.push_back(segment(right, EXIT, i));\n    }\n\n    sort(all(S), sort_by_left);\n\n    vector <int> already_handled(no_of_segments, false);\n    vector <int> meeting_points;\n\n    stack <int> handled_indices;\n\n    for(int i = 0; i < 2*no_of_segments; i++)\n    {\n        if(already_handled[S[i].index])\n        {\n            continue;\n        }\n\n        if(S[i].type == ENTRY)\n        {\n            handled_indices.push(S[i].index);\n        }\n        else if(S[i].type == EXIT)\n        {\n            meeting_points.push_back(S[i].point);\n\n            while(handled_indices.size() > 0)\n            {\n                already_handled[handled_indices.top()] = true;\n\n                handled_indices.pop();\n            }\n        }\n    }\n\n    cout << meeting_points.size() << \"\\n\";\n    for(int i = 0; i < meeting_points.size(); i++)\n    {\n        cout << meeting_points[i] << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Special Segments of Permutation Explanation.txt",
    "content": "Let us try to brute force this problem.\n\nLet Left_border[i] represent the first index on the left of P[i] that is > P[i]\n\nLet Right_border[i] represent the first index on the right\n\nWe will go through each j in the Left_border and if it is P[j],\n\nCheck if (P[i] - P[j]) is present in [i, Right_border[i]]\n\n------\n\nint get_count(int left_1, int right_1, int left_2, int right_2, int total_sum)\n{\n    if(right_2 - left_2 < right_1 - left_1)\n    {\n        swap(right_1, right_2);\n        swap(left_1, left_2);\n    }\n\n    int count = 0;\n    for(int i = left_1; i <= right_1; i++)\n    {\n        int remaining = total_sum - permutation[i];\n\n        if(1 <= remaining && remaining <= no_of_elements &&\n           left_2 <= position[remaining] && position[remaining] <= right_2)\n        {\n            count++;\n        }\n    }\n\n    return count;\n}\n\n\n-----\n\nThis approach looks like it is O(n^2) but\nit is actually O(N log N) provided\nwe choose the smaller segment among the left and right border each time\n\nLet us look at the largest element of the array.\nIt divides the array into 2 segments of length - m1, m2\nwhere m1 + m2 = n - 1\nThe minimum of m1, m2 <= n/2\n\nSo the number of comparisons done in n/2\n\nNow, let us look at the largest elements of segments m1 and m2\nThey will lead to m1/2 <= n/4 and m2/2 <= n/2 comparisons\n\nThe number of comparisons for these 3 elements is n(1/2 + 1/4 + 1/2)\n\nSimilarly, we will go to the largest elements in the remaining segments.\nEach element will have a number of comparisons of the form n/2^i, i >= 1\n\nSo, finally, the time complexity will be n x O(log n) = O(n log n)\n\n-----\n\nAlthough we are processing the elements from i = 1 to n,\nthe time complexity is easier to process if we visit the elements in descending order.\n\nThat's what makes this problem and this complexity analysis so beautiful !\n\n-----\n\nNow, how do we find out the left and right border of each i ?\n\nWe can do it with a linear scan and a stack.\n\nInitially, the stack is empty.\n\nWhen we encounter P[i], we will pop the top of the stack as long as\nstack.top < P[i]\n\nAnd then we will push P[i]\n\nWe have popped off all indices j, such that P[j] < P[i]\n\nThis is optimal, because any future index k, such that j < i < k and P[j] > P[k]\n\nWill be better matched to i instead as\n\nP[i] > P[j] > P[k]\n\n-----\n\nint main()\n{\n    cin >> no_of_elements;\n\n    permutation.resize(no_of_elements + 1);\n    position.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> permutation[i];\n\n        position[permutation[i]] = i;\n    }\n\n    vector <int> left_border(no_of_elements + 1);\n    stack <pair <int, int> > left_S;\n    left_S.push(make_pair(no_of_elements + 1, 0));\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        while(left_S.top().first < permutation[i])\n        {\n            left_S.pop();\n        }\n\n        left_border[i] = left_S.top().second + 1;\n\n        left_S.push(make_pair(permutation[i], i));\n    }\n\n    stack <pair <int, int> > right_S;\n    vector <int> right_border(no_of_elements + 1);\n    right_S.push(make_pair(no_of_elements + 1, no_of_elements + 1));\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        while(right_S.top().first < permutation[i])\n        {\n            right_S.pop();\n        }\n\n        right_border[i] = right_S.top().second - 1;\n\n        right_S.push(make_pair(permutation[i], i));\n    }\n\n    int no_of_special_segments = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        no_of_special_segments += get_count(left_border[i], i - 1, i + 1, right_border[i], permutation[i]); //cout << \"i = \" << permutation[i] << \" Count = \" << no_of_special_segments << \"\\n\";\n    }\n\n    cout << no_of_special_segments << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/The Sum of the k-th Powers Explanation.txt",
    "content": "Let f(n, k) = 1^k + 2^k + ... + n^k\n\nf(n, k) is a polynomial of degree k + 1.\n\nWe can invoke the Fundamental Theorem of Algebra and interpolate it\nby getting the value of this function at (k + 2) points.\n\n-----\n\nIf n <= (k + 2), we can give the answer directly.\n\nOtherwise, we will perform Lagrangian Interpolation in O(k) time.\n\n-----\n\nProof that f(n, k) is a polynomial of degree (k + 1) by Mathematical Induction\n\nf(n, 1) = n^2/2 + n/2 is a polynomial of degree 2.\n\nLet it be true for f(n, k)\n\nLet us take the derivative of f(n, k + 1) with respect to k\n\nf'(n, k + 1) = k(1^k + 2^k + ... + n^k) = k.f(n, k)\n\nSince the derivative is a polynomial of degree (k + 1),\n\nf(n, k + 1) is a polynomial function of degree (k + 2).\n\nThis means that we can perform Lagrangian Interpolation on it.\n\n-----\n\nHow do we perform Lagrangian Interpolation in O(k) time ?\n\nThe numerator is\n\n(n - 1)(n - 2) ... (n - (i - 1)) (n - (i + 1)) ... (n - (k + 1))\n\nWhat happens when we transition from i to i + 1 ?\n\nWe must remove (n - (i + 1)) from the product and put (n - i) back into the product.\n\nThe denominator is a little more tricky.\nAt first, it is\n\n(1 - 2)(1 - 3) .... (1 - (k + 1))\n\nThen, it becomes\n(2 - 1) (2 - 3) .... (2 - (k + 1))\n\nSince the values that we have sampled the function at {1, 2, ... , k + 1}\nare contiguous, we can take advantage of it.\n\nThe running product increases by 1 at each step.\n\nWe will keep track of the smallest and largest term in the denominator product.\nAt each step, we will remove the smallest term, and add a (largest + 1) term into the product.\n\nThere is a special case here.\nThe denominator will never have a term of 0.\n\nSo if either smallest or largest points to 0, increase it by 1 again.\nAlso, ensure that the terms are never negative as we are dealing with MOD.\n\n-----\n\nint main()\n{\n    long long n, power;\n    cin >> n >> power;\n\n    //f(i) = 1^k + 2^k + ... + i^k\n    vector <long long> value(power + 3, 0);\n    for(int i = 1; i <= power + 2; i++)\n    {\n        value[i] = (value[i - 1] + power_mod(i, power))%MOD;\n    }\n\n    if(n <= power + 2)\n    {\n        cout << value[n] << \"\\n\";\n        return 0;\n    }\n\n    long long numerator = 1, denominator = 1;\n    long long largest = (1 - 2 + MOD)%MOD, smallest = (1 - (power + 2) + MOD)%MOD;\n    for(int i = 2; i <= power + 2; i++)\n    {\n        numerator = (numerator*(n - i))%MOD;\n\n        denominator = (denominator*(1 - i + MOD))%MOD;\n    }\n\n    long long answer = value[1]*numerator;\n    answer = (answer*inverse(denominator))%MOD;\n\n    for(int i = 2; i <= power + 2; i++)\n    {\n        numerator = (numerator*inverse(n - i))%MOD;\n        numerator = (numerator*(n - (i - 1)))%MOD;\n\n        largest = (largest + 1)%MOD;\n        if(largest == 0)\n        {\n            largest = (largest + 1)%MOD;\n        }\n\n        if(smallest == 0)\n        {\n            smallest = (smallest + 1)%MOD;\n        }\n\n        denominator = (denominator*inverse(smallest))%MOD;\n        denominator = (denominator*(largest))%MOD;// cout << \"Remove small = \" << smallest << \" largest = \" << largest << \" D = \" << denominator << \"\\n\";\n\n       smallest = (smallest + 1)%MOD;\n\n\n\n        long long current_term = (numerator*inverse(denominator))%MOD;\n        current_term = (value[i]*current_term)%MOD;\n\n        answer = (answer + current_term)%MOD;\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/The Treasure of Segments Explanation.txt",
    "content": "Let us count the number of deletions we have to make for each segment.\n\nFor there to be no segments outside a segment [L, R], there should be\nno segment ending before L and beginning after R.\n\nThese segments are disjoint.\n\nSo, we will do binary search to count the number of segments such that\n\n1. R[i] < L\n2. R < L[i]\n\nFor each [L, R]\n\n-----\n\nvoid solve()\n{\n    int no_of_segments;\n    cin >> no_of_segments;\n\n    vector <int> sorted_left(no_of_segments + 1), sorted_right(no_of_segments + 1);\n    vector <int> left(no_of_segments + 1), right(no_of_segments + 1);\n    for(int i = 1; i <= no_of_segments; i++)\n    {\n        cin >> left[i] >> right[i];\n\n        sorted_left[i] = left[i];\n        sorted_right[i] = right[i];\n    }\n\n    sort(all(sorted_left));\n    sort(all(sorted_right));\n\n    int minimum_deletions = no_of_segments;\n    for(int i = 1; i <= no_of_segments; i++)\n    {\n        int after_right = no_of_segments - (upper_bound(all(sorted_left), right[i]) - sorted_left.begin()) + 1;\n        int before_left = lower_bound(all(sorted_right), left[i]) - sorted_right.begin() - 1;\n\n        //cout << \"For [\" << left[i] << \",\" << right[i] << \"] Before Left = \" << before_left << \" and after right = \" << after_right << \"\\n\";\n        int deletions_here = after_right + before_left;\n\n        minimum_deletions = min(minimum_deletions, deletions_here);\n    }\n\n    cout << minimum_deletions << \"\\n\";\n}\n"
  },
  {
    "path": "2020/Practice/Explanations/Winter is Here Explanation.txt",
    "content": "Let us try to count the contribution of all sequences who's GCD = G\n\nNow, suppose there are n elements which are divisible by G.\n\nWhat is the contribution of each such sequence ?\n\nThe contribution is\n\n1. C(n, 1) + 2. C(n, 2) + 3. C(n, 3) + ... + n. C(n, n)\n= sum k C(n, k) = sum k n/k sum(n - 1, k - 1) = n 2^{n - 1}\n\nLet this be f(n)\n\n-----\n\nNow, there is a problem here.\n\nThis is all the sequences which are divisible by G.\n\nBut, they might also be divisible by 2G, 3G or some other multiple of G,\nwhich means G might not be it's GCD\n\nTo resolve this issue,\nWe will start from G = 10^6 and then go downwards to 2\n\nWhen we are at G = i, we will maintain the invariant that we have calculated\nf(i + 1), f(i + 2), ... , f(10^6)\n\nf(G) = n 2^{n - 1} - f(2G) - f(3G) - ....\n\nThis will give us exactly the contribution of all sequences who's GCD = G\n\n-----\n\nint main()\n{\n    const int MAX_N = 1e6 + 5, MOD = 1e9 + 7;\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> multiple_count(MAX_N, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        multiple_count[A[i]]++;\n    }\n\n    for(int m = 1; m < MAX_N; m++)\n    {\n        for(int multiple = 2*m; multiple < MAX_N; multiple += m)\n        {\n            multiple_count[m] += multiple_count[multiple];\n        }\n    }\n\n    vector <long long> answer(MAX_N, 0);\n    for(int m = MAX_N - 1; m >= 1; m--)\n    {\n        answer[m] = multiple_count[m]*power_mod(2, multiple_count[m] - 1, MOD);\n\n        answer[m] %= MOD; //cout << answer[m] << \"\\n\";\n\n        for(int multiple = 2*m; multiple < MAX_N; multiple += m)\n        {\n            answer[m] = (answer[m] - answer[multiple] + MOD)%MOD;\n        }\n        //cout << answer[m] << \"\\n\";\n        //cout << \"Answer \" << m << \" = \" << answer[m] << \"\\n\";\n    }\n\n    long long total_answer = 0;\n    for(int m = 2; m < MAX_N; m++)\n    {\n        total_answer = (total_answer + answer[m]*m)%MOD;\n    }\n\n    cout << total_answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Alternative Thinking.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n    \n    int alternating_subsequence = 0;\n    for(int i = 0; i < length; i++)\n    {\n        if(i == 0 || S[i] != S[i - 1])\n        {\n            alternating_subsequence++;\n        }\n    }\n    \n    int answer = min(alternating_subsequence + 2, length);\n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Ant Colony.cpp",
    "content": "#include <iostream>\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n\nusing namespace std;\n\nstruct node\n{\n    int gcd, minimum, minimum_frequency;\n    \n    node(){}\n    \n    node(int G, int M, int F)\n    {\n        gcd = G; minimum = M; minimum_frequency = F;\n    }\n};\n\nconst int MAX_N = 1e5 + 5, oo = 1e9 + 9;\nnode tree[4*MAX_N];\nint A[MAX_N];\n\nint gcd(int a, int b)\n{\n    if(min(a, b) == 0)\n    {\n        return max(a, b);\n    }\n    \n    return gcd(max(a, b)%min(a, b), min(a, b));\n}\n\nnode merge(node &A, node &B)\n{\n    node C;\n    \n    C.gcd = gcd(A.gcd, B.gcd);\n    \n    if(A.minimum == B.minimum)\n    {\n        C.minimum = A.minimum;\n        C.minimum_frequency = A.minimum_frequency + B.minimum_frequency;\n    }\n    else if(A.minimum < B.minimum)\n    {\n        C.minimum = A.minimum;\n        C.minimum_frequency = A.minimum_frequency;\n    }\n    else if(B.minimum < A.minimum)\n    {\n        C.minimum = B.minimum;\n        C.minimum_frequency = B.minimum_frequency;\n    }\n    \n    return C;\n}\n\nvoid build(int n, int left, int right)\n{\n    if(left == right)\n    {\n        tree[n] = node(A[left], A[left], 1);\n        return;\n    }\n    \n    int mid = (left + right)/2;\n    \n    build(LEFT(n), left, mid);\n    build(RIGHT(n), mid + 1, right);\n    \n    tree[n] = merge(tree[LEFT(n)], tree[RIGHT(n)]);\n}\n\nnode query(int n, int left, int right, int query_left, int query_right)\n{\n    if(query_right < left || right < query_left || right < left)\n    {\n        return node(0, oo, 0);\n    }\n    \n    if(query_left <= left && right <= query_right)\n    {\n        return tree[n];\n    }\n    \n    int mid = (left + right)/2;\n    \n    node left_answer = query(LEFT(n), left, mid, query_left, query_right);\n    node right_answer = query(RIGHT(n), mid + 1, right, query_left, query_right);\n    \n    //cout << \" At \" << left << \",\" << right << \" LEFT answer(\" << left << \",\" << mid <<\") = \" << left_answer.gcd << \" RIGHT answer(\" << mid + 1 << \",\" << right << \") = \" << right_answer.gcd << \"\\n\";\n    return merge(left_answer, right_answer);\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    build(1, 1, no_of_elements);\n    \n    int no_of_queries;\n    cin >> no_of_queries;\n    \n    while(no_of_queries--)\n    {\n        int left, right;\n        cin >> left >> right;\n        \n        node answer = query(1, 1, no_of_elements, left, right);\n        \n        int free = 0;\n        //cout << \"GCD = \" << answer.gcd << \" \" << \"Minimum = \" << answer.minimum << \"\\n\";\n        \n        if(answer.gcd == answer.minimum)\n        {\n            free = answer.minimum_frequency;\n        }\n        \n        int remaining = right - (left - 1) - free;\n        \n        cout << remaining << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Anton and Chess.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint check(int x, vector <pair <long long, char> > &A, char attacker_1, char queen = 'Q')\n{\n    pair <long long, char> king = make_pair(x, 'K');\n    \n    int next = upper_bound(all(A), king) - A.begin();\n    \n    if(next < A.size() && (A[next].second == attacker_1 || A[next].second == queen))\n    {\n        return true;\n    }\n    \n    int before = next - 1;\n    \n    if(before >= 0 && (A[before].second == attacker_1 || A[before].second == queen))\n    {\n        return true;\n    }\n    \n    return false;\n}\n\nint main()\n{\n    int no_of_black_pieces;\n    cin >> no_of_black_pieces;\n    \n    long long king_x, king_y;\n    cin >> king_x >> king_y;\n    \n    long long king_diagonal = king_x - king_y;\n    long long king_antidiagonal = king_x + king_y;\n    \n    vector <pair <long long, char> > row, column, diagonal, anti_diagonal;\n    for(int i = 1; i <= no_of_black_pieces; i++)\n    {\n        char piece;\n        long long x, y;\n        cin >> piece >> x >> y;\n        \n        if(x == king_x)\n        {\n            row.push_back(make_pair(y, piece));\n        }\n        if(y == king_y)\n        {\n            column.push_back(make_pair(x, piece));\n        }\n        \n        if(x - y == king_diagonal)\n        {\n            diagonal.push_back(make_pair(x + y, piece));\n        }\n        if(x + y == king_antidiagonal)\n        {\n            anti_diagonal.push_back(make_pair(x - y, piece));\n        }\n    }\n    \n    sort(all(row));\n    sort(all(column));\n    sort(all(diagonal));\n    sort(all(anti_diagonal));\n    \n    int in_check = false;\n    \n    in_check = (check(king_y, row, 'R') ||\n                check(king_x, column, 'R') ||\n                check(king_antidiagonal, diagonal, 'B') ||\n                check(king_diagonal, anti_diagonal,'B') );\n    \n    cout << (in_check ? \"YES\" : \"NO\") << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Anton and Ira.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> P(no_of_elements + 1), S(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> P[i];\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> S[i];\n    }\n    \n    vector <int> label(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        label[S[i]] = i;\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        P[i] = label[P[i]];\n    }\n    \n    long long cost = 0;\n    vector <pair <int, int> > swaps;\n    \n    for(int current = no_of_elements, i; current >= 1; current--)\n    {\n        for(i = 1; i <= no_of_elements; i++)\n        {\n            if(P[i] == current)\n            {\n                break;\n            }\n        }\n        \n        //cout << \"Current = \" << current << \" i = \" << i << \" \\n\";\n        for(int j = i + 1; j <= current; j++)\n        {\n            if(P[j] <= i)\n            {   //cout << \"j = \" << j << \"\\n\";\n                \n                swap(P[i], P[j]);\n                \n                swaps.push_back(make_pair(i, j));\n                \n                cost += (j - i);\n                \n                i = j;\n            }\n        }\n    }\n    \n    cout << cost << \" \" << swaps.size() << \"\\n\";\n    for(int i = 0; i < swaps.size(); i++)\n    {\n        cout << swaps[i].first << \" \" << swaps[i].second << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Ants in Leaves.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5;\nvector <int> tree[MAX_N];\n\nvector <int> depths;\n\nvoid dfs(int v, int parent_v, int depth)\n{\n    if(tree[v].size() == 1)\n    {\n        depths.push_back(depth);\n    }\n    \n    for(int child_v : tree[v])\n    {\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v, depth + 1);\n    }\n}\n\nint get_answer(int v)\n{\n    dfs(v, 1, 0);\n    \n    sort(all(depths));\n    \n    vector <int> visit_order(depths.size());\n    for(int i = 0; i < visit_order.size(); i++)\n    {\n        visit_order[i] = depths[i];\n        \n        if(i > 0)\n        {\n            visit_order[i] = max(visit_order[i - 1] + 1, visit_order[i]);\n        }\n    }\n    \n    depths.clear();\n    //cout << \" Answer here = \" << visit_order.back() << \"\\n\";\n    return visit_order.back();\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    for(int i = 1, no_of_edges = no_of_vertices - 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n    \n    int answer = 0;\n    \n    for(int child : tree[1])\n    {\n        answer = max(answer, get_answer(child) + 1); //cout << child << \" \";\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Army Creation.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 1e5 +5;\nint k_th_ancestor[MAX_N];\nvector <int> indices[MAX_N];\nvector <int> tree[3*MAX_N];\n\nvector <int> merge(vector <int> &L, vector <int> &R)\n{\n    vector <int> answer;\n    \n    for(int l = 0, r = 0; l < L.size() || r < R.size(); )\n    {\n        if(l == L.size())\n        {\n            answer.push_back(R[r++]);\n            continue;\n        }\n        \n        if(r == R.size())\n        {\n            answer.push_back(L[l++]);\n            continue;\n        }\n        \n        if(L[l] <= R[r])\n        {\n            answer.push_back(L[l++]);\n        }\n        else\n        {\n            answer.push_back(R[r++]);\n        }\n    }\n    \n    return answer;\n}\n\nvoid build(int n, int left, int right)\n{\n    if(left == right)\n    {\n        tree[n].push_back(k_th_ancestor[left]);\n        \n        /*cout << \"n = \" << n  <<\"[\" << left <<\",\" << right << \"]\\n\" << endl;\n        for(int i = 0; i < tree[n].size(); i++)\n        {\n            cout << tree[n][i] << \" \";\n        } cout << \"\\n\";*/\n        return;\n    }\n    \n    int mid = (left + right)/2;\n    build(LEFT(n), left, mid);\n    build(RIGHT(n), mid + 1, right);\n    \n    tree[n] = merge(tree[LEFT(n)], tree[RIGHT(n)]);\n    /*cout << \"n = \" << n  <<\"[\" << left <<\",\" << right << \"]\\n\" << endl;\n    for(int i = 0; i < tree[n].size(); i++)\n    {\n        cout << tree[n][i] << \" \";\n    } cout << \"\\n\";*/\n}\n\nint query(int n, int left, int right, int query_left, int query_right, int x)\n{\n    if(query_right < left || right < query_left)\n    {\n        return 0;\n    }\n    \n    if(query_left <= left && right <= query_right)\n    {\n        return (upper_bound(all(tree[n]), x - 1) - tree[n].begin());\n    }\n    \n    int mid = (left + right)/2;\n    \n    return (query(LEFT(n), left, mid, query_left, query_right, x) +\n            query(RIGHT(n), mid + 1, right, query_left, query_right, x));\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n        \n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        indices[A[i]].push_back(i);\n        \n        if(indices[A[i]].size() > k)\n        {\n            int k_th_step = indices[A[i]].size() - 1 - k;\n            \n            k_th_ancestor[i] = indices[A[i]][k_th_step]; //cout << \" K-th \" << i << \" = \" << k_th_ancestor[i] << \"\\n\";\n        }\n        else\n        {\n            k_th_ancestor[i] = 0;\n        }\n    }\n    \n    build(1, 1, no_of_elements);\n    \n    int no_of_queries;\n    cin >> no_of_queries;\n    \n    int answer = 0;\n    \n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n        \n        int left = ((x + answer)%no_of_elements) + 1;\n        int right = ((y + answer)%no_of_elements) + 1;\n        if(left > right)\n        {\n            swap(left, right);\n        }\n        \n       // cout << \"L = \" << left << \" R = \" << right << \"\\n\";\n        //vector <int> range = query(1, 1, no_of_elements, left, right);\n        /*cout << \"Size = \" << range.size() << \"\\n\";\n        for(int i = 0; i < range.size(); i++)\n        {\n            cout << range[i] << \" \";\n        }\n        cout << \"\\n\";*/\n        \n        answer = query(1, 1, no_of_elements, left, right, left);\n        \n        cout << answer << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Bargain.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long mod)\n{\n    long long result = 1LL;\n    \n    while(power > 0)\n    {\n        if(power%2 == 1)\n        {\n            result = (result*x)%mod;\n        }\n        \n        power = power >> 1;\n        x = (x*x)%mod;\n    }\n    \n    return result;\n}\n\nlong long inverse(long long x, long long mod)\n{\n    return power_mod(x, mod - 2, mod);\n}\n\nlong long choose_2(long long n, long long mod)\n{\n    return ((n*(n + 1))/2)%mod;\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n    \n    const int MOD = 1e9 + 7;\n    vector <long long> suffix_cost(S.size() + 5);\n    for(int i = S.size() - 1, suffix = 0; i >= 0; i--, suffix++)\n    {\n        suffix_cost[i] = power_mod(10, suffix, MOD)*(S[i] - '0');\n        \n        suffix_cost[i] %=  MOD;\n        \n        suffix_cost[i] *= choose_2(i, MOD);\n        \n        suffix_cost[i] %= MOD; \n    }\n    \n    vector <long long> multiplier(S.size() + 5, 0);\n    for(int i = 1; i <= S.size(); i++)\n    {\n        multiplier[i] = (multiplier[i - 1] + (i)*power_mod(10, i - 1, MOD))%MOD;\n    }\n    \n    vector <long long> prefix_cost(S.size() + 1, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        prefix_cost[i] = ((multiplier[S.size() - 1 - i])*(S[i] - '0'))%MOD;\n        \n        //cout << \"Prefix Cost \" << i << \" = \" << prefix_cost[i] << \"\\n\";\n    }\n    \n    long long answer = 0;\n    for(int i = 0; i < S.size(); i++)\n    {\n        answer += (prefix_cost[i] + suffix_cost[i])%MOD;\n                \n        answer %= MOD;\n    }\n\n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Concatenated Multiples.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint no_of_digits(int n)\n{\n    int count = 0;\n    \n    while(n)\n    {\n        count++;\n        \n        n /= 10;\n    }\n    //cout << \"N = \" << n << \" Count = \" << count << \"\\n\";\n    return count;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int MAX_DIGITS = 11;\n    map <long long, int> frequency_mod[MAX_DIGITS];\n    long long answer = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(long long t = 10, d = 1; d < MAX_DIGITS; d++, t = (t*10)%k)\n        {\n            frequency_mod[d][ (A[i]*t)%k ]++;\n            \n            //cout << \"D = \" << d << \" M = \" << (A[i]*t)%k << \" = \" << frequency_mod[d][ (A[i]*t)%k ] << \"\\n\";\n        }\n    }\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long first_part_mod = (0 - A[i]%k + k)%k;\n        \n        //cout << \"Need d = \" << no_of_digits(A[i]) << \" with M = \" << first_part_mod << \"\\n\";\n        \n        answer += frequency_mod[no_of_digits(A[i])][first_part_mod];\n        //cout << \"Answer = \" << answer << \"\\n\";\n        \n        long long t = 1;\n        for(long long d = 1; d <= no_of_digits(A[i]) ;d++)\n        {\n            t = (t*10)%k;\n        }\n        \n        if( (t*A[i] + A[i])%k == 0 )\n        {   //cout << \"Self!\\n\";\n            answer--;\n        }\n        \n        //cout << \"Answer = \" << answer << \"\\n\";\n    }\n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Count Pairs.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nlong long choose_2(long long n)\n{\n    return (n*(n - 1))/2;\n}\n\nint main()\n{\n    int no_of_elements, p, k;\n    cin >> no_of_elements >> p >> k;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    map <long long, int> value_frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long value = (A[i]*A[i])%p;\n        value = (value*A[i])%p;\n        value = (value*A[i])%p;\n        \n        value = (value - k*A[i])%p;\n        \n        value = (value + p)%p;\n        \n        value_frequency[value]++;\n    }\n    \n    long long no_of_pairs = 0;\n    for(auto it = value_frequency.begin(); it != value_frequency.end(); it++)\n    {\n        no_of_pairs += choose_2(it->second);\n    }\n    \n    cout << no_of_pairs << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Cram Time.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid display(vector <long long> &A)\n{\n    cout << A.size() << \"\\n\";\n    \n    for(int i = 0; i < A.size(); i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n}\n\nint main()\n{\n    long long a, b;\n    cin >> a >> b;\n    \n    long long left = 0, right = 1e5;\n    while(right - left > 1)\n    {\n        long long mid = (right + left)/2;\n        \n        if(mid*(mid + 1) <= (a + b)*2)\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n    \n    vector <long long> day_a, day_b;\n    long long problems = left;\n    for(long long i = problems; i >= 1; i--)\n    {\n        if(a >= i)\n        {\n            day_a.push_back(i);\n            a -= i;\n        }\n        else\n        {\n            for(; i >= 1; i--)\n            {\n                if(i == a)\n                {\n                    day_a.push_back(i);\n                    a -= i;\n                }\n                else\n                {\n                    day_b.push_back(i);\n                    b -= i;\n                }\n            }\n        }\n    }\n    \n    display(day_a);\n    display(day_b);\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Cycles.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 105;\nint graph[MAX_N][MAX_N];\n\nlong long choose_3(long long n)\n{\n    return (n*(n - 1)*(n - 2))/6;\n}\n\nlong long choose_2(long long n)\n{\n    return (n*(n - 1))/2;\n}\n\nvoid add_edge(int u, int v)\n{\n    graph[u][v] = 1;\n    graph[v][u] = 1;\n}\n\nint main()\n{\n    int no_of_edges;\n    cin >> no_of_edges;\n    \n    int complete_graph = 0;\n    for(int i = 1; ; i++)\n    {\n        if(choose_3(i) > no_of_edges)\n        {\n            complete_graph = i - 1;\n            no_of_edges -= choose_3(complete_graph);\n            break;\n        }\n    }\n    \n    vector <int> extra_matching;\n    while(no_of_edges > 0)\n    {\n        for(int i = complete_graph; i >= 0; i--)\n        {\n            if(choose_2(i) <= no_of_edges)\n            {\n                extra_matching.push_back(i);\n                \n                no_of_edges -= choose_2(i);\n                \n                break;\n            }\n        }\n    }\n    \n    memset(graph, 0, sizeof(graph));\n    \n    for(int i = 1; i <= complete_graph; i++)\n    {\n        for(int j = i + 1; j <= complete_graph; j++)\n        {\n            add_edge(i, j);\n        }\n    }\n    \n    for(int i = 0; i < extra_matching.size(); i++)\n    {\n        int v = complete_graph + i + 1;\n        int v_limit = extra_matching[i];\n        \n        for(int w = 1; w <= v_limit; w++)\n        {\n            add_edge(v, w);\n        }\n    }\n    \n    int no_of_vertices = complete_graph + extra_matching.size();\n    \n    cout << no_of_vertices << \"\\n\";\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        for(int j = 1; j <= no_of_vertices; j++)\n        {\n            cout << graph[i][j];\n        }\n        \n        cout << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Elections.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_PARTIES = 3333;\nvector <vector <int> > votes;\n\nlong long cost_if_final_count(int n)\n{\n    int additional_votes = 0;\n    \n    long long cost = 0;\n    vector <long long> extra_votes;\n    \n    for(int i = 2; i < votes.size(); i++)\n    {\n        for(int j = 0; j < votes[i].size(); j++)\n        {   //cout << \"Party = \" << i << \" Person = \" << j << \"\\n\";\n            if(j + n <= votes[i].size())\n            {\n                additional_votes++;\n                cost += votes[i][j];\n            }\n            else\n            {   //cout << \"Extra \\n\";\n                extra_votes.push_back(votes[i][j]);\n            }\n        }\n    }\n    \n    int remaining = n - votes[1].size() - additional_votes;\n    //cout << \"Remaining = \" << remaining << \"\\n\";\n    if(remaining <= 0)\n    {\n        return cost;\n    }\n    \n    sort(extra_votes.begin(), extra_votes.end());\n    \n    for(int i = 0; i < remaining && i < extra_votes.size(); i++)\n    {\n        cost += extra_votes[i];\n    }\n    \n    return cost;\n}\n\nint main()\n{\n    int no_of_voters, no_of_parties;\n    cin >> no_of_voters >> no_of_parties;\n    \n    votes.resize(no_of_parties + 1);\n    \n    for(int i = 1; i <= no_of_voters; i++)\n    {\n        int party, cost;\n        cin >> party >> cost;\n        \n        votes[party].push_back(cost);\n    }\n    \n    for(int i = 2; i <= no_of_parties; i++)\n    {\n        sort(votes[i].begin(), votes[i].end());\n    }\n    \n    long long answer = 1e18;\n    for(int i = 1; i <= no_of_voters; i++)\n    {   //cout << \"cost \" << i << \" = \" << cost_if_final_count(i) << \"\\n\";\n        answer = min(answer, cost_if_final_count(i));\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Fight Against Traffic.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <set>\n\nusing namespace std;\n\nconst int MAX_N = 1005;\nvector <int> graph[MAX_N];\nset <int> edge_exists[MAX_N];\n\nvoid bfs(int source, vector <int> &distance)\n{\n    queue <int> Q;\n    \n    Q.push(source);\n    distance[source] = 0;\n    \n    while(!Q.empty())\n    {\n        int u = Q.front();\n        Q.pop();\n        \n        for(int i = 0; i < graph[u].size(); i++)\n        {\n            int v = graph[u][i];\n            \n            if(distance[v] == -1)\n            {\n                distance[v] = distance[u] + 1;\n                \n                Q.push(v);\n            }\n        }\n    }\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n    \n    int source, target;\n    cin >> source >> target;\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].push_back(v);\n        graph[v].push_back(u);\n        \n        edge_exists[u].insert(v);\n        edge_exists[v].insert(u);\n    }\n    \n    vector <int> source_distance(no_of_vertices + 1, -1), target_distance(no_of_vertices + 1, -1);\n    bfs(source, source_distance);\n    bfs(target, target_distance);\n    \n    int minimum_distance = source_distance[target];\n    long long no_of_good_pairs = 0;\n    for(int u = 1; u <= no_of_vertices; u++)\n    {\n        for(int v = u + 1; v <= no_of_vertices; v++)\n        {\n            if(edge_exists[u].count(v) == 1)\n            {\n                continue;\n            }\n            \n            if(source_distance[u] + 1 + target_distance[v] >= minimum_distance &&\n               source_distance[v] + 1 + target_distance[u] >= minimum_distance)\n            {   \n                no_of_good_pairs++;\n            }\n        }\n    }\n    \n    cout << no_of_good_pairs << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Hacker, pack your Bags.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nstruct Point\n{\n    int x, cost, duration, is_left;\n    \n    Point(){}\n    \n    Point(int X, int C, int D, int is_L)\n    {\n        x = X;\n        cost = C;\n        duration = D;\n        is_left = is_L;\n    }\n};\n\nint sort_by_point(Point &A, Point &B)\n{\n    if(A.x == B.x)\n    {\n        return (A.is_left && !B.is_left ? true : false);\n    }\n    \n    return (A.x < B.x);\n}\n\nint main()\n{\n    int no_of_segments, total;\n    cin >> no_of_segments >> total;\n    \n    vector <Point> A;\n    for(int i = 1; i <= no_of_segments; i++)\n    {\n        int left, right, x;\n        cin >> left >> right >> x;\n        \n        A.push_back(Point(left, x, right - left + 1, true));\n        A.push_back(Point(right, x, right - left + 1, false));\n    }\n    \n    sort(A.begin(), A.end(), sort_by_point);\n    \n    map <int, int> minimum_cost;\n    const int oo = 2e9 + 7;\n    int answer = oo;\n    \n    for(int i = 0; i < 2*no_of_segments; i++)\n    {\n        if(A[i].is_left)\n        {\n            if(minimum_cost.find(total - A[i].duration) != minimum_cost.end())\n            {\n                answer = min(answer, minimum_cost[total - A[i].duration] + A[i].cost);\n            }\n        }\n        else\n        {\n            if(minimum_cost.find(A[i].duration) != minimum_cost.end())\n            {\n                minimum_cost[A[i].duration] = min(minimum_cost[A[i].duration], A[i].cost);\n            }\n            else\n            {\n                minimum_cost[A[i].duration] = A[i].cost;\n            }\n        }\n    }\n    \n    cout << (answer >= oo ? -1 : answer) << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Imbalanced Array.cpp",
    "content": "#include <iostream>\n#include <stack>\n#include <vector>\n\nusing namespace std;\n\nvoid compute_max_borders(int n, vector <int> &A, vector <int> &L, vector <int> &R)\n{\n    const int oo = 1e9 + 9;\n    \n    stack < pair <int, int> > left_max;\n    left_max.push(make_pair(0, oo));\n    for(int i = 1; i <= n; i++)\n    {\n        while(left_max.top().second < A[i])\n        {\n            left_max.pop();\n        }\n        \n        L[i] = left_max.top().first + 1; //Range in which A[i] is maximum\n        \n        left_max.push(make_pair(i, A[i]));\n    }\n    \n    stack < pair <int, int> > right_max;\n    right_max.push(make_pair(n + 1, oo));\n    for(int i = n; i >= 1; i--)\n    {\n        while(right_max.top().second <= A[i])\n        {\n            right_max.pop();\n        }\n        \n        R[i] = right_max.top().first - 1;\n        \n        right_max.push(make_pair(i, A[i]));\n        \n    }\n}\n\nvoid compute_min_borders(int n, vector <int> &A, vector <int> &L, vector <int> &R)\n{\n    const int oo = 1e9 + 9;\n    \n    stack < pair <int, int> > left_min;\n    left_min.push(make_pair(0, -oo));\n    for(int i = 1; i <= n; i++)\n    {\n        while(left_min.top().second > A[i])\n        {\n            left_min.pop();\n        }\n        \n        L[i] = left_min.top().first + 1; //cout << \"L \" << i << \" = \" << L[i] << \"\\n\";\n        \n        left_min.push(make_pair(i, A[i]));\n    }\n    \n    stack < pair <int, int> > right_min;\n    right_min.push(make_pair(n + 1, -oo));\n    for(int i = n; i >= 1; i--)\n    {\n        while(right_min.top().second >= A[i])\n        {\n            right_min.pop();\n        }\n        \n        R[i] = right_min.top().first - 1;\n        \n        right_min.push(make_pair(i, A[i]));\n    }\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> left_max_border(no_of_elements + 1), right_max_border(no_of_elements + 1);\n    compute_max_borders(no_of_elements, A, left_max_border, right_max_border);\n    \n    long long total_maximum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left_half = i - left_max_border[i], right_half = (right_max_border[i] - i);\n        long long no_of_maximas = (left_half + 1)*(right_half + 1);\n        \n        total_maximum += no_of_maximas*A[i];\n    }\n    \n    vector <int> left_min_border(no_of_elements + 1), right_min_border(no_of_elements + 1);\n    compute_min_borders(no_of_elements, A, left_min_border, right_min_border);\n    \n    long long total_minimum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long left_half = i - left_min_border[i], right_half = right_min_border[i] - i;\n        long long no_of_minima = (left_half + 1)*(right_half + 1);\n        \n        total_minimum += no_of_minima*A[i];\n    }\n    \n    long long answer = total_maximum - total_minimum;\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Laboratory Work.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_points;\n    cin >> no_of_points;\n    \n    vector <int> X(no_of_points);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        cin >> X[i];\n    }\n    \n    sort(all(X));\n    \n    int minimum = X[0];\n    \n    const int MAX_TYPES = 3;\n    vector <int> frequency(MAX_TYPES, 0);\n    for(int i = 0; i < no_of_points; i++)\n    {\n        frequency[X[i] - minimum]++;\n    }\n    \n    vector <int> new_frequency(MAX_TYPES, 0);\n    for(int t = 0; t < MAX_TYPES; t++)\n    {\n        new_frequency[t] = frequency[t];\n    }\n    \n    if(frequency[1]/2 > min(frequency[0], frequency[2]) && frequency[2] > 0 && frequency[0] > 0)\n    {\n        new_frequency[0] = frequency[0] + frequency[1]/2;\n        new_frequency[1] = frequency[1]%2;\n        new_frequency[2] = frequency[2] + frequency[1]/2;\n    }\n    else if(frequency[1]/2 <= min(frequency[0], frequency[2]))\n    {\n        new_frequency[0] = frequency[0] - min(frequency[0], frequency[2]);\n        new_frequency[1] = frequency[1] + 2*min(frequency[0], frequency[2]);\n        new_frequency[2] = frequency[2] - min(frequency[0], frequency[2]);\n    }\n    \n    int equal_elements = 0;\n    for(int t = 0; t < MAX_TYPES; t++)\n    {\n        equal_elements += min(frequency[t], new_frequency[t]);\n    }\n    \n    cout << equal_elements << \"\\n\";\n    \n    for(int t = 0; t < MAX_TYPES; t++)\n    {\n        for(int i = 0; i < new_frequency[t]; i++)\n        {\n            cout << minimum + t << \" \";\n        }\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Lieges of Legendre.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint get_grundy(int n, int k)\n{\n    if(n == 0)\n    {\n        return 0;\n    }\n    \n    if(n == 1)\n    {\n        return 1;\n    }\n    \n    if(k%2 == 0)\n    {\n        if(n == 2)\n        {\n            return 2;\n        }\n        \n        return (n%2 == 0 ? 1 : 0);\n    }\n    else\n    {\n        if(n%2 == 1)\n        {\n            return (n <= 3 ? 1 : 0);\n        }\n        \n        if(n == 2)\n        {\n            return 0;\n        }\n        \n        if(n == 4)\n        {\n            return 2;\n        }\n        \n        return (get_grundy(n/2, k) == 1 ? 2 : 1);\n    }\n}\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <int> A(no_of_elements + 1);\n    vector <int> grundy(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n        \n        grundy[i] = get_grundy(A[i], k);\n    }\n    \n    int nim_sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        nim_sum ^= grundy[i];\n    }\n    \n    cout << (nim_sum != 0 ? \"Kevin\" : \"Nicky\") << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Line.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <algorithm>\n\nusing namespace std;\n\nlong long extended_gcd(long long A, long long B, long long &x, long long &y)\n{\n    if(B == 0)\n    {\n        x = 1;\n        y = 0;\n        return A;\n    }\n\n    long long x1, y1;\n    long long gcd = extended_gcd(B, A%B, x1, y1);\n    \n    y = x1 - (A/B)*y1;\n    x = y1;\n    //cout << \"(\" << A << \",\" << B << \") = \" << x << \",\" << y << \"\\n\";\n    return gcd;\n}\n\nint main()\n{\n    long long A, B, C;\n    cin >> A >> B >> C;\n\n    long long X = 0, Y = 0;\n    long long gcd_A_B = extended_gcd(A, B, X, Y);\n    \n    X *= (-C/gcd_A_B);\n    Y *= (-C/gcd_A_B);\n    \n    if(C%gcd_A_B == 0)\n        cout << X << \" \" << Y << \"\\n\";\n    else\n        cout << \"-1\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Marina and Vyasa.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nchar other(char c1, char c2)\n{\n    const int NO_OF_ALPHABETS = 26;\n    \n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        char current = 'a' + alpha;\n        \n        if(current != c1 && current != c2)\n        {\n            return current;\n        }\n    }\n    \n    return 'z';\n}\n\nint main()\n{\n    int length, differences;\n    string S, T;\n    cin >> length >> differences >> S >> T;\n    \n    int same = 0;\n    for(int i = 0; i < length; i++)\n    {\n        if(S[i] == T[i])\n        {\n            same++;\n        }\n    }\n    \n    int matches = length - differences;\n   \n    int minimum_length = same + 2*max(matches - same, 0);\n    \n    if(minimum_length > length)\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    string answer = S;\n    int a_matches = length, b_matches = same;\n    for(int i = 0; i < length; i++)\n    {\n        if(S[i] != T[i])\n        {\n            if(b_matches < matches)\n            {\n                answer[i] = T[i];\n            \n                a_matches--;\n                b_matches++;\n            }\n            else if(a_matches > matches)\n            {\n                answer[i] = other(S[i], T[i]);\n                \n                a_matches--;\n            }\n        }\n    }\n    \n    for(int i = 0; i < length && (a_matches > matches || b_matches > matches); i++)\n    {\n        if(S[i] == T[i])\n        {\n            answer[i] = other(S[i], T[i]);\n            \n            a_matches--;\n            b_matches--;\n        }\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Match Points.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, distance;\n    cin >> no_of_elements >> distance;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    sort(all(A));\n    \n    int left_pairs = 0, right_pairs = no_of_elements/2 + 1;\n    while(right_pairs - left_pairs > 1)\n    {\n        int mid = (left_pairs + right_pairs)/2;\n        \n        int good_pairs = 0;\n        \n        for(int i = 1; i <= mid; i++)\n        {\n            if(A[no_of_elements - mid + i] - A[i] >= distance)\n            {\n                good_pairs++;\n            }\n        }\n        \n        if(good_pairs == mid)\n        {\n            left_pairs = mid;\n        }\n        else\n        {\n            right_pairs = mid;\n        }\n    }\n    \n    int answer = left_pairs;\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Molly and Chemicals.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid precompute(vector <long long> &P, long long k)\n{\n    P.push_back(1);\n    \n    if(k == 0 || k == 1)\n    {\n        return;\n    }\n    \n    if(k == -1)\n    {\n        P.push_back(-1);\n        return;\n    }\n    \n    long long oo = 1e14;\n    \n    while(abs(P.back()) <= oo)\n    {   //cout << P.back() << \"\\n\";\n        P.push_back(P.back()*k);\n    }\n}\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    vector <long long> powers;\n    precompute(powers, k);\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    map <long long, int> prefix_sum_frequency;\n    long long prefix = 0;\n    prefix_sum_frequency[prefix] = 1;\n    \n    long long no_of_segments = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix += A[i];\n        \n        for(int j = 0; j < powers.size(); j++)\n        {\n            no_of_segments += prefix_sum_frequency[prefix - powers[j]];\n        }\n        \n        prefix_sum_frequency[prefix]++;\n    }\n    \n    cout << no_of_segments << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Moodular Arithmetic.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long m)\n{\n    long long result = 1;\n    \n    while(power > 0)\n    {\n        if(power%2 == 1)\n            result = (result*x)%m;\n        \n        x = (x*x)%m;\n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nint order(int k, int m)\n{\n    int answer = m - 1;\n    \n    for(int i = 1; i*i <= m - 1; i++)\n    {\n        if((m - 1)%i == 0)\n        {\n            if(power_mod(k, i, m) == 1)\n            {\n                answer = min(answer, i);\n            }\n            else if(power_mod(k, (m - 1)/i, m) == 1)\n            {\n                answer = min(answer, (m - 1)/i);\n            }\n        }\n    }\n    \n    return answer;\n}\n\nint main()\n{\n    int p, k;\n    cin >> p >> k;\n    \n    const int MOD = 1e9 + 7;\n    if(k == 0)\n    {\n        cout << power_mod(p, p  - 1, MOD) << \"\\n\";\n        return 0;\n    }\n    if(k == 1)\n    {\n        cout << power_mod(p, p, MOD) << \"\\n\";\n        return 0;\n    }\n    \n    cout << power_mod(p, (p - 1)/order(k, p), MOD) << \"\\n\";\n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Practice/Programs/Mouse Hunt.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvector <int> cost, to, visits, current_dfs;\nvector < vector <int> > cycle;\n\nvoid dfs(int v, int &total_cost)\n{\n    //Cycle Starts here\n    if(current_dfs[v])\n    {\n        int cost_here = cost[v];\n        \n        for(int i = to[v]; i != v; i = to[i])\n        {   \n            cost_here = min(cost_here, cost[i]);\n        }\n        \n        total_cost += cost_here;\n        return;\n    }\n    else if(visits[v]) //It was already linked to a cycle from some other dfs\n    {\n        return;\n    }\n    \n    visits[v] = true;\n    \n    current_dfs[v] = true;\n    \n    dfs(to[v], total_cost);\n    \n    current_dfs[v] = false;\n}\n\nint main()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n    \n    cost.resize(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> cost[i];\n    }\n    \n    to.resize(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> to[i];\n    }\n    \n    int total_cost = 0;\n    current_dfs.resize(no_of_vertices + 1, 0);\n    visits.resize(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(!visits[i])\n        {\n            dfs(i, total_cost);\n        }\n    }\n    \n    cout << total_cost << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Multiplicity.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int MAX = 1e6 + 5;\n    vector <vector <int> > divisors(MAX);\n    for(int i = 1; i < MAX; i++)\n    {\n        for(int multiple = i; multiple < MAX; multiple += i)\n        {\n            divisors[multiple].push_back(i);\n        }\n    }\n    \n    const int MOD = 1e9 + 7;\n    vector <long long> no_of_sequences(MAX, 0), sequences_here(MAX, 0);\n    long long total_sequences = 0;\n    \n    no_of_sequences[0] = 1;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int d = 0; d < divisors[A[i]].size(); d++)\n        {\n            int m = divisors[A[i]][d];\n            \n            sequences_here[m] = no_of_sequences[m - 1];\n        }\n        \n        for(int d = 0; d < divisors[A[i]].size(); d++)\n        {\n            int m = divisors[A[i]][d];\n            \n            no_of_sequences[m] += sequences_here[m];\n            \n            no_of_sequences[m] %= MOD;\n        }\n    }\n    \n    for(int i = 1; i < MAX; i++)\n    {\n        total_sequences += no_of_sequences[i];\n        \n        total_sequences %= MOD;\n    }\n    \n    cout << total_sequences << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Multipliers.cpp",
    "content": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\n#define PHI(x) 500000002\n\nlong long power_mod(long long x, long long power, long long mod)\n{\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%mod;\n\n        x = (x*x)%mod;\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nlong long ceil(long long n, long long x)\n{\n    long long quotient = n/x;\n    long long remainder = n%x;\n\n    return (quotient + (remainder > 0));\n}\n\nint main()\n{\n    const int MOD = 1e9 + 7;\n    long long product = 1LL;\n\n    int no_of_primes;\n    cin >>  no_of_primes;\n\n    map <int, long long> exponent;\n\n    for(int i = 1; i <= no_of_primes; i++)\n    {\n        int prime_i;\n        scanf(\"%d\", &prime_i);\n\n        exponent[prime_i]++;\n    }\n\n    long long no_of_divisors = 1;\n    for(map <int, long long> :: iterator it = exponent.begin(); it != exponent.end(); it++)\n    {\n        int p = it->first;\n        long long exp = it->second;\n\n        long long divisor_product_here = power_mod(p, (exp*(exp + 1))/2, MOD);\n        product = power_mod(product, exp + 1, MOD)*power_mod(divisor_product_here, no_of_divisors, MOD);\n        product %= MOD;\n        \n        no_of_divisors *= (exp + 1);\n        no_of_divisors %= (MOD - 1);\n    }\n\n    cout << product << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/My Pretty Girl Nora.cpp",
    "content": "#include <iostream>\n#include <vector>\nusing namespace std;\n\nint main()\n{\n    long long t, left, right;\n    cin >> t >> left >> right;\n    \n    const int MOD = 1e9 + 7;\n    vector <long long> largest_prime_factor(right + 1, 0);\n    vector <long long> minimum_comparisons(right + 1, 1e16);\n    minimum_comparisons[1] = 0;\n    for(long long i = 2; i <= right; i++)\n    {\n        if(largest_prime_factor[i] == 0)\n        {\n            largest_prime_factor[i] = i;\n            for(long long multiple = i*i; multiple <= right; multiple += i)\n            {\n                if(largest_prime_factor[multiple] == 0)\n                {\n                    largest_prime_factor[multiple] = i;\n                }\n            }\n        }\n        \n        for(int x = i; x != 1; x /= largest_prime_factor[x])\n        {\n            int remaining = i/largest_prime_factor[x];\n            \n            long long comparisons_here = (i*(largest_prime_factor[x] - 1))/2 + minimum_comparisons[remaining];\n            \n            minimum_comparisons[i] = min(minimum_comparisons[i], comparisons_here);\n        }\n        \n        minimum_comparisons[i] %= MOD;\n    }\n    \n    long long answer = 0, coefficient = 1;\n    for(int i = left; i <= right; i++)\n    {\n        answer += (coefficient*minimum_comparisons[i])%MOD;\n        \n        coefficient = (coefficient*t)%MOD;\n        \n        answer %= MOD;\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Optimal Number Permutation.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(2*no_of_elements + 1);\n    for(int front = 1, back = no_of_elements, odd = 1; odd <= no_of_elements; front++, back--, odd += 2)\n    {\n        A[front] = A[back] = odd;\n    }\n    \n    for(int front = no_of_elements + 1, back = 2*no_of_elements - 1, even = 2; even <= no_of_elements; front++, back--, even += 2)\n    {\n        A[front] = A[back] = even;\n    }\n    \n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        if(A[i] == 0)\n        {\n            A[i] = no_of_elements;\n        }\n    }\n    \n    for(int i = 1; i <= 2*no_of_elements; i++)\n    {\n        cout << A[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Pair of Numbers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 3e5 + 5, MAX_L = 20;\nint no_of_elements, A[MAX_N];\nint gcd_table[MAX_N][MAX_L], min_table[MAX_N][MAX_L];\n\nint gcd(int x, int y)\n{\n    if(min(x, y) == 0)\n    {\n        return max(x, y);\n    }\n    \n    return gcd(max(x, y)%min(x, y), min(x, y));\n}\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1 << bit)) != 0 );\n}\n\nvoid precompute()\n{\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        gcd_table[i][0] = A[i];\n        min_table[i][0] = A[i];\n    }\n    \n    for(int l = 1; l < MAX_L; l++)\n    {\n        int jump = (1 << (l - 1));\n        \n        for(int i = 1; i + (1 << l) - 1 <= no_of_elements; i++)\n        {\n            int next = i + jump;\n            \n            gcd_table[i][l] = gcd(gcd_table[i][l - 1], gcd_table[next][l - 1]);\n            min_table[i][l] = min(min_table[i][l - 1], min_table[next][l - 1]);\n        }\n    }\n}\n\npair <int, int> compute(int i, int length)\n{\n    int gcd_here = A[i], min_here = A[i];\n    for(int bit = MAX_L; bit >= 0; bit--)\n    {\n        if(is_bit_set(length, bit))\n        {\n            gcd_here = gcd(gcd_here, gcd_table[i][bit]);\n            min_here = min(min_here, min_table[i][bit]);\n            \n            i += (1 << bit);\n        }\n    }\n    \n    return make_pair(gcd_here, min_here);\n}\n\nint possible(int length)\n{   //cout << \"Length = \" << length << \"\\n\";\n    for(int i = 1; i + length - 1 <= no_of_elements; i++)\n    {\n        pair <int, int> answer = compute(i, length);\n        //cout << \"Computed\\n\";\n        int gcd_here = answer.first, minimum_here = answer.second;\n        //cout << \"GCD[\" << i << \",\" << i + length - 1 << \"] = \" << gcd_here << \"\\n\";\n        //cout << \"Min[\" << i << \",\" << i + length - 1 << \"] = \" << minimum_here << \"\\n\";\n        if(gcd_here == minimum_here)\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nint main()\n{\n    cin >> no_of_elements;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    precompute();\n    \n    int left = 1, right = no_of_elements + 1;\n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n        \n        if(possible(mid))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n    \n    vector <int> answer;\n    for(int i = 1; i + left - 1 <= no_of_elements; i++)\n    {\n        pair <int, int> answer_here = compute(i, left);\n        int gcd_here = answer_here.first, min_here = answer_here.second;\n        \n        if(gcd_here == min_here)\n        {\n            answer.push_back(i);\n        }\n    }\n    \n    cout << answer.size() << \" \" << left - 1 << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Pashmak and Graph.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\nusing namespace std;\r\n\r\nstruct Edge\r\n{\r\n    int source, destination, weight;\r\n\r\n    int operator <(const Edge &A)\r\n    {\r\n        return (weight < A.weight);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    vector <Edge> edge(no_of_edges + 1);\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        scanf(\"%d %d %d\", &edge[i].source, &edge[i].destination, &edge[i].weight);\r\n    }\r\n\r\n    sort(all(edge));\r\n\r\n    vector <int> maximum_ending_at(no_of_vertices + 1, 0);\r\n\r\n    vector <int> maximum_with_this_weight(no_of_vertices + 1, 0);\r\n    \r\n    for(int i = 1; i <= no_of_edges; )\r\n    {\r\n        int j = i;\r\n\r\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\r\n        {\r\n            maximum_with_this_weight[edge[j].destination] = 0;\r\n        }\r\n        \r\n        //Process all edges having this weight. Have a different vector so you don't interact with equal weights.\r\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\r\n        {\r\n            maximum_with_this_weight[edge[j].destination] = max(maximum_with_this_weight[edge[j].destination], 1 + maximum_ending_at[edge[j].source]);\r\n        }\r\n\r\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\r\n        {\r\n            maximum_ending_at[edge[j].destination] = max(maximum_ending_at[edge[j].destination], maximum_with_this_weight[edge[j].destination]);\r\n        }\r\n\r\n        i = j;\r\n    }\r\n\r\n    int maximum_path = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        maximum_path = max(maximum_path, maximum_ending_at[i]);\r\n\r\n    printf(\"%d\\n\", maximum_path);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2020/Practice/Programs/Pavel and Triangles.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_sticks;\n    cin >> no_of_sticks;\n    \n    vector <int> A(no_of_sticks + 1);\n    for(int i = 1; i <= no_of_sticks; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long no_of_triangles = 0;\n    int remaining_sticks = 0;\n    for(int highest = 1; highest <= no_of_sticks; highest++)\n    {\n        int triangles_here = min(remaining_sticks, A[highest]/2);\n        \n        no_of_triangles += triangles_here;\n        \n        A[highest] -= 2*triangles_here;\n        remaining_sticks = remaining_sticks - triangles_here;\n        \n        no_of_triangles += A[highest]/3;\n        A[highest] %= 3;\n        \n        remaining_sticks += A[highest];\n    }\n    \n    cout << no_of_triangles << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Plus and Xor.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    unsigned long long A, B;\n    cin >> A >> B;\n    \n    //Y = X + B, A = 2X + B\n    if(A < B || (A - B)%2 != 0)\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    unsigned long long X = (A - B)/2, Y = A - X;\n    //cout << X + Y << \" \" << (X^Y) << \"\\n\";\n    if(X + Y != A || (X^Y) != B)\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    cout << X << \" \" << Y << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Points.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long calculate(vector <long long> &P, int n)\n{\n    long long squares = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        squares += (n - 1)*P[i]*P[i];\n    }\n    \n    long long sum = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        sum += P[i];\n    }\n    \n    long long linear_term = 0;\n    for(int i = 1; i <= n; i++)\n    {\n        linear_term += P[i]*(sum - P[i]);// 2*P[i]*P[i];\n    }\n    \n    return (squares - linear_term);\n}\n\nint main()\n{\n    int no_of_points;\n    cin >> no_of_points;\n    \n    vector <long long> X(no_of_points + 1);\n    vector <long long> Y(no_of_points + 1);\n    \n    for(int i = 1; i <= no_of_points; i++)\n    {\n        cin >> X[i] >> Y[i];\n    }\n    \n    long long distance = calculate(X, no_of_points) + calculate(Y, no_of_points);\n    \n    cout << distance << \"\\n\";\n    return 0;\n}\n\n"
  },
  {
    "path": "2020/Practice/Programs/Prime Number.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n#include <set>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long mod)\n{\n    long long result = 1;\n    \n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%mod;\n        \n        x = (x*x)%mod;\n        power = power/2;\n    }\n    \n    return result;\n}\n\nint main()\n{\n    int no_of_elements, x;\n    cin >> no_of_elements >> x;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    long long sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum += A[i];\n    }\n    \n    set <long long> S;\n    map <long long, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[sum - A[i]]++;\n        \n        S.insert(sum - A[i]);\n    }\n    \n    const int MOD = 1e9 + 7;\n    long long answer;\n    for(auto it = S.begin(); ; it++)\n    {\n        while(frequency[*(S.begin())]%x == 0)\n        {\n            long long exponent = *(S.begin());\n            \n            long long new_exponent = exponent + 1;\n            \n            frequency[new_exponent] += frequency[exponent]/x;\n            \n            S.insert(new_exponent);\n            \n            S.erase(exponent);\n        }\n        \n        if(frequency[*( S.begin() )] != 0)\n        {\n            answer = min(sum, *( S.begin() ));\n            \n            break;\n        }\n    }\n    \n    cout << power_mod(x, answer, MOD) << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Ramesses and Corner Inversion.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid read(vector <vector <int> > &A)\n{\n    for(int i = 1; i < A.size(); i++)\n    {\n        for(int j = 1; j < A[0].size(); j++)\n        {\n            cin >> A[i][j];\n        }\n    }\n}\n\nvoid compute(vector <vector <int> > &A, vector <int> &row_sum, vector <int> &column_sum)\n{\n    for(int i = 1; i < A.size(); i++)\n    {\n        for(int j = 1; j < A[0].size(); j++)\n        {\n            row_sum[i] += A[i][j];\n            column_sum[j] += A[i][j];\n        }\n    }\n}\n\nint main()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    vector <vector <int> > A(rows + 1, vector <int> (columns + 1));\n    read(A);\n    \n    vector <vector <int> > B(rows + 1, vector <int> (columns + 1));\n    read(B);\n    \n    vector <int> A_row_sum(rows + 1), A_column_sum(columns + 1);\n    compute(A, A_row_sum, A_column_sum);\n    \n    vector <int> B_row_sum(rows + 1), B_column_sum(columns + 1);\n    compute(B, B_row_sum, B_column_sum);\n    \n    int row_and_column_same_parity = true;\n    \n    for(int i = 1; i <= rows; i++)\n    {\n        if(A_row_sum[i]%2 != B_row_sum[i]%2)\n        {\n            row_and_column_same_parity = false;\n        }\n    }\n    \n    for(int j = 1; j <= columns; j++)\n    {\n        if(A_column_sum[j]%2 != B_column_sum[j]%2)\n        {\n            row_and_column_same_parity = false;\n        }\n    }\n    \n    cout << (row_and_column_same_parity ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Scheme.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 15;\nvector <int> graph[MAX_N];\nvector <int> visited(MAX_N, false);\nvector <int> incoming(MAX_N, 0);\n\nvector <int> beginning;\nvector <int> ending;\n\nvoid dfs(int v)\n{\n    visited[v] = true;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n\n        if(visited[child])\n        {\n            ending.push_back(child);\n\n            return;\n        }\n\n        dfs(child);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        int destination;\n        scanf(\"%d\", &destination);\n\n        graph[i].push_back(destination);\n        incoming[destination]++;\n    }\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(incoming[i] == 0)\n        {\n            beginning.push_back(i);\n\n            dfs(i);\n        }\n    }\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(!visited[i])\n        {\n            beginning.push_back(i);\n            \n            dfs(i);\n        }\n    }\n\n    int no_of_sinks = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(incoming[i] == 0)\n        {\n            no_of_sinks++;\n        }\n    }\n    \n    int simple_cycle = (no_of_sinks == 0 && beginning.size() == 1);\n    \n    int new_edges = (simple_cycle ? 0 : beginning.size());\n    printf(\"%d\\n\", new_edges);\n\n    for(int i = 0; i < new_edges; i++)\n    {\n        printf(\"%d %d \\n\",ending[i], beginning[(i + 1)%new_edges]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Secret Passwords.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int NO_OF_ALPHABETS = 26;\nstruct DSU\n{\n    int parent[NO_OF_ALPHABETS];\n    int no_of_components = NO_OF_ALPHABETS;\n    \n    DSU() {}\n\n    DSU(int n)\n    {\n        for(int i = 0; i <= n; i++)\n        {\n            parent[i] = i;\n        }\n\n    }\n\n    int get_parent(int n)\n    {\n        while(n != parent[n])\n        {\n            parent[n] = parent[parent[n]];\n\n            n = parent[n];\n        }\n\n        return n;\n    }\n\n    void unite(int x, int y)\n    {\n        int parent_x = get_parent(x), parent_y = get_parent(y);\n\n        if(parent_x == parent_y)\n            return;\n\n        parent[parent_x] = parent[parent_y];\n        \n        no_of_components--;\n    }\n};\n\nint is_set(long long n, int bit)\n{\n    return ((n&(1 << bit)) != 0);\n}\n\nint main()\n{\n    int no_of_words;\n    cin >> no_of_words;\n    \n    vector <int> used(NO_OF_ALPHABETS, false);\n    DSU dsu(NO_OF_ALPHABETS);\n    \n    for(int i = 1; i <= no_of_words; i++)\n    {\n        string word;\n        cin >> word;\n        \n        int mask = 0;\n        for(int j = 0; j < word.size(); j++)\n        {\n            mask |= (1 << (word[j] - 'a'));\n            \n            used[word[j] - 'a'] = true;\n        }\n        \n        for(int bit_1 = 0; bit_1 < NO_OF_ALPHABETS; bit_1++)\n        {\n            for(int bit_2 = 0; bit_2 < NO_OF_ALPHABETS; bit_2++)\n            {\n                if(!is_set(mask, bit_1) || !is_set(mask, bit_2) || dsu.get_parent(bit_1) == dsu.get_parent(bit_2))\n                {\n                    continue;\n                }\n                \n                dsu.unite(bit_1, bit_2);\n            }\n        }\n    }\n    \n    int unused_alphabets = 0;\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n    {\n        if(!used[alpha])\n        {\n            unused_alphabets++;\n        }\n    }\n    \n    int actual_components = dsu.no_of_components - unused_alphabets;\n    \n    cout << actual_components << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Segments.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <stack>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int ENTRY = 1, EXIT = 2;\n\nstruct segment\n{\n    int point, type, index;\n    \n    segment(){}\n    \n    segment(int P, int T, int I)\n    {\n        point = P; type = T; index = I;\n    }\n};\n\nint sort_by_left(segment &S_1, segment &S_2)\n{\n    if(S_1.point == S_2.point)\n    {\n        return (S_1.type < S_2.type);\n    }\n    \n    return (S_1.point < S_2.point);\n}\n\nint main()\n{\n    int no_of_segments;\n    cin >> no_of_segments;\n  \n    vector <segment> S;\n    for(int i = 0; i < no_of_segments; i++)\n    {\n        int left, right;\n        cin >> left >> right;\n        \n        if(left > right)\n        {\n            swap(left, right);\n        }\n        \n        S.push_back(segment(left, ENTRY, i));\n        S.push_back(segment(right, EXIT, i));\n    }\n    \n    sort(all(S), sort_by_left);\n    \n    vector <int> already_handled(no_of_segments, false);\n    vector <int> meeting_points;\n    \n    stack <int> handled_indices;\n    \n    for(int i = 0; i < 2*no_of_segments; i++)\n    {\n        if(already_handled[S[i].index])\n        {\n            continue;\n        }\n        \n        if(S[i].type == ENTRY)\n        {\n            handled_indices.push(S[i].index);\n        }\n        else if(S[i].type == EXIT)\n        {\n            meeting_points.push_back(S[i].point);\n            \n            while(handled_indices.size() > 0)\n            {\n                already_handled[handled_indices.top()] = true;\n                \n                handled_indices.pop();\n            }\n        }\n    }\n    \n    cout << meeting_points.size() << \"\\n\";\n    for(int i = 0; i < meeting_points.size(); i++)\n    {\n        cout << meeting_points[i] << \" \";\n    }\n    cout << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Special Segments of Permutation.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <stack>\n\nusing namespace std;\n\nint no_of_elements;\nvector <int> permutation;\nvector <int> position;\n\nint get_count(int left_1, int right_1, int left_2, int right_2, int total_sum)\n{\n    if(right_2 - left_2 < right_1 - left_1)\n    {\n        swap(right_1, right_2);\n        swap(left_1, left_2);\n    }\n    \n    int count = 0;\n    for(int i = left_1; i <= right_1; i++)\n    {\n        int remaining = total_sum - permutation[i];\n        \n        if(1 <= remaining && remaining <= no_of_elements &&\n           left_2 <= position[remaining] && position[remaining] <= right_2)\n        {\n            count++;\n        }\n    }\n    \n    return count;\n}\n\nint main()\n{\n    cin >> no_of_elements;\n    \n    permutation.resize(no_of_elements + 1);\n    position.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> permutation[i];\n        \n        position[permutation[i]] = i;\n    }\n    \n    vector <int> left_border(no_of_elements + 1);\n    stack <pair <int, int> > left_S;\n    left_S.push(make_pair(no_of_elements + 1, 0));\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        while(left_S.top().first < permutation[i])\n        {\n            left_S.pop();\n        }\n        \n        left_border[i] = left_S.top().second + 1;\n        \n        left_S.push(make_pair(permutation[i], i));\n    }\n    \n    stack <pair <int, int> > right_S;\n    vector <int> right_border(no_of_elements + 1);\n    right_S.push(make_pair(no_of_elements + 1, no_of_elements + 1));\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        while(right_S.top().first < permutation[i])\n        {\n            right_S.pop();\n        }\n        \n        right_border[i] = right_S.top().second - 1;\n        \n        right_S.push(make_pair(permutation[i], i));\n    }\n    \n    int no_of_special_segments = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        no_of_special_segments += get_count(left_border[i], i - 1, i + 1, right_border[i], permutation[i]); \n    }\n    \n    cout << no_of_special_segments << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/The Sum of the k-th Powers.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 1e9 + 7;\n\nlong long power_mod(long long x, long long power)\n{\n    long long result = 1;\n    \n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nlong long inverse(long long x)\n{\n    return power_mod(x, MOD - 2);\n}\n\nint main()\n{\n    long long n, power;\n    cin >> n >> power;\n    \n    //f(i) = 1^k + 2^k + ... + i^k\n    vector <long long> value(power + 3, 0);\n    for(int i = 1; i <= power + 2; i++)\n    {\n        value[i] = (value[i - 1] + power_mod(i, power))%MOD;\n    }\n    \n    if(n <= power + 2)\n    {\n        cout << value[n] << \"\\n\";\n        return 0;\n    }\n    \n    long long numerator = 1, denominator = 1;\n    long long largest = (1 - 2 + MOD)%MOD, smallest = (1 - (power + 2) + MOD)%MOD;\n    for(int i = 2; i <= power + 2; i++)\n    {\n        numerator = (numerator*(n - i))%MOD; \n        \n        denominator = (denominator*(1 - i + MOD))%MOD;\n    }\n    \n    long long answer = value[1]*numerator;\n    answer = (answer*inverse(denominator))%MOD;\n    \n    for(int i = 2; i <= power + 2; i++)\n    {\n        numerator = (numerator*inverse(n - i))%MOD;\n        numerator = (numerator*(n - (i - 1)))%MOD;\n        \n        largest = (largest + 1)%MOD;\n        if(largest == 0)\n        {\n            largest = (largest + 1)%MOD;\n        }\n        \n        if(smallest == 0)\n        {\n            smallest = (smallest + 1)%MOD;\n        }\n        \n        denominator = (denominator*inverse(smallest))%MOD;\n        denominator = (denominator*(largest))%MOD;// cout << \"Remove small = \" << smallest << \" largest = \" << largest << \" D = \" << denominator << \"\\n\";\n        \n       smallest = (smallest + 1)%MOD;\n        \n       \n                       \n        long long current_term = (numerator*inverse(denominator))%MOD;\n        current_term = (value[i]*current_term)%MOD;\n        \n        answer = (answer + current_term)%MOD;\n    }\n    \n    cout << answer << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/The Treasure of Segments.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_segments;\n    cin >> no_of_segments;\n    \n    vector <int> sorted_left(no_of_segments + 1), sorted_right(no_of_segments + 1);\n    vector <int> left(no_of_segments + 1), right(no_of_segments + 1);\n    for(int i = 1; i <= no_of_segments; i++)\n    {\n        cin >> left[i] >> right[i];\n        \n        sorted_left[i] = left[i];\n        sorted_right[i] = right[i];\n    }\n    \n    sort(all(sorted_left));\n    sort(all(sorted_right));\n    \n    int minimum_deletions = no_of_segments;\n    for(int i = 1; i <= no_of_segments; i++)\n    {\n        int after_right = no_of_segments - (upper_bound(all(sorted_left), right[i]) - sorted_left.begin()) + 1;\n        int before_left = lower_bound(all(sorted_right), left[i]) - sorted_right.begin() - 1;\n        \n        //cout << \"For [\" << left[i] << \",\" << right[i] << \"] Before Left = \" << before_left << \" and after right = \" << after_right << \"\\n\";\n        int deletions_here = after_right + before_left;\n        \n        minimum_deletions = min(minimum_deletions, deletions_here);\n    }\n    \n    cout << minimum_deletions << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "2020/Practice/Programs/Winter is Here.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long power_mod(long long x, long long power, long long mod)\n{\n    long long result = 1;\n    \n    while(power > 0)\n    {\n        if(power%2 == 1)\n            result = (result*x)%mod;\n        \n        x = (x*x)%mod;\n        power = power/2;\n    }\n    \n    return result;\n}\n\nint main()\n{\n    const int MAX_N = 1e6 + 5, MOD = 1e9 + 7;\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> multiple_count(MAX_N, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        multiple_count[A[i]]++;\n    }\n    \n    for(int m = 1; m < MAX_N; m++)\n    {\n        for(int multiple = 2*m; multiple < MAX_N; multiple += m)\n        {\n            multiple_count[m] += multiple_count[multiple];\n        }\n    }\n    \n    vector <long long> answer(MAX_N, 0);\n    for(int m = MAX_N - 1; m >= 1; m--)\n    {\n        answer[m] = multiple_count[m]*power_mod(2, multiple_count[m] - 1, MOD);\n        \n        answer[m] %= MOD; //cout << answer[m] << \"\\n\";\n        \n        for(int multiple = 2*m; multiple < MAX_N; multiple += m)\n        {\n            answer[m] = (answer[m] - answer[multiple] + MOD)%MOD;\n        }\n        //cout << answer[m] << \"\\n\";\n        //cout << \"Answer \" << m << \" = \" << answer[m] << \"\\n\";\n    }\n    \n    long long total_answer = 0;\n    for(int m = 2; m < MAX_N; m++)\n    {\n        total_answer = (total_answer + answer[m]*m)%MOD;\n    }\n    \n    cout << total_answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2021/Combined Divisions/Deltix Round Summer 2021/Explanations/Take a Guess Explanation.txt",
    "content": "- The idea behind remembering this identity is that every bit that is set in both integers is counted twice and every bit that is set in only one of them is counted once.\n- Use this identity to find the first $3$ elements in $6$ steps and then find the remaining array elements with $2$ steps a piece.\n\n\ncpp\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint ask(int i, int j, string S)\n{\n    int answer;\n    cout << S << \" \" << i << \" \" << j << \"\\n\";\n    cout.flush();\n    cin >> answer;\n\n    return answer;\n}\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n\n    int and_12 = ask(1, 2, \"and\");\n    int or_12 = ask(1, 2, \"or\");\n    int sum_12 = and_12 + or_12;\n\n    int and_23 = ask(2, 3, \"and\");\n    int or_23 = ask(2, 3, \"or\");\n    int sum_23 = and_23 + or_23;\n\n    int and_31 = ask(3, 1, \"and\");\n    int or_31 = ask(3, 1, \"or\");\n    int sum_31 = and_31 + or_31;\n\n    A[1] = (sum_12 - sum_23 + sum_31)/2;\n    A[2] = sum_12 - A[1];\n    A[3] = sum_23 - A[2]; //cout << A[1] << \" \" << A[2] << \" \" << A[3] << \"\\n\";\n\n    for(int i = 4; i <= no_of_elements; i++)\n    {\n        int and_1i = ask(1, i, \"and\");\n        int or_1i = ask(1, i, \"or\");\n        int sum_1i = and_1i + or_1i;\n\n        A[i] = sum_1i - A[1];//cout << A[i] << \"\\n\";\n    }\n\n    sort(all(A));\n\n    cout << \"finish \" << A[k] << \"\\n\";\n    return 0;\n}\n```\n"
  },
  {
    "path": "2021/Combined Divisions/Deltix Round Summer 2021/Programs/Take a Guess.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint ask(int i, int j, string S)\n{\n    int answer;\n    cout << S << \" \" << i << \" \" << j << \"\\n\";\n    cout.flush();\n    cin >> answer;\n\n    return answer;\n}\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <int> A(no_of_elements + 1);\n\n    int and_12 = ask(1, 2, \"and\");\n    int or_12 = ask(1, 2, \"or\");\n    int sum_12 = and_12 + or_12;\n\n    int and_23 = ask(2, 3, \"and\");\n    int or_23 = ask(2, 3, \"or\");\n    int sum_23 = and_23 + or_23;\n\n    int and_31 = ask(3, 1, \"and\");\n    int or_31 = ask(3, 1, \"or\");\n    int sum_31 = and_31 + or_31;\n\n    A[1] = (sum_12 - sum_23 + sum_31)/2;\n    A[2] = sum_12 - A[1];\n    A[3] = sum_23 - A[2]; //cout << A[1] << \" \" << A[2] << \" \" << A[3] << \"\\n\";\n\n    for(int i = 4; i <= no_of_elements; i++)\n    {\n        int and_1i = ask(1, i, \"and\");\n        int or_1i = ask(1, i, \"or\");\n        int sum_1i = and_1i + or_1i;\n\n        A[i] = sum_1i - A[1];//cout << A[i] << \"\\n\";\n    }\n\n    sort(all(A));\n\n    cout << \"finish \" << A[k] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/694/Explanations/Strange Definition Explanation.txt",
    "content": "XY must also be a perfect square\n"
  },
  {
    "path": "2021/Div 2/694/Explanations/Strange Housing Explanation.txt",
    "content": "- We have to choose some non-adjacent vertices in the graph such that when we delete all edges that are not connected to one of these vertices, we still are connected.\n- Colour vertex $1$ white\n    - Colour all the children of a white vertex black.\n        - Black vertices lie between two white children. This is the invariant that we are maintaining.\n    - Colour all the grand children of the white vertex as white.\n        - It is important to colour all the grand children of white vertex as white rather than visit a black vertex and paint all of it's children white. \n          The reason is that some black vertices might be connected to each other. So, we would end up repainting them white, which would not be correct.\n- If there is some vertex which is uncoloured in the end, then it means that the graph was not connected in the beginning\n\n------\n\nvoid solve()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n \n    vector <vector <int> > graph(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n \n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n \n    const int UNCOLOURED = -1, BLACK = 0, WHITE = 1;\n    vector <int> colour(no_of_vertices + 1, UNCOLOURED);\n    queue <int> Q;\n    colour[1] = WHITE;\n    for(int child : graph[1])\n    {\n        colour[child] = BLACK;\n \n        Q.push(child);\n    }\n \n    while(!Q.empty())\n    {\n        int v = Q.front(); Q.pop();\n \n        for(int child : graph[v])\n        {\n            if(colour[child] == UNCOLOURED)\n            {\n                colour[child] = WHITE;\n \n                for(int grandchild : graph[child])\n                {\n                    colour[grandchild] = BLACK;\n \n                    Q.push(grandchild);\n                }\n            }\n        }\n    }\n \n    vector <int> answer;\n    for(int i = 1; i  <= no_of_vertices; i++)\n    {\n        if(colour[i] == WHITE)\n        {\n            answer.push_back(i);\n        }\n \n        if(colour[i] == UNCOLOURED)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n \n    cout << \"YES\\n\";\n    cout << answer.size() << \"\\n\";\n    for(int v :  answer)\n    {\n        cout << v << \" \";\n    }\n \n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/694/Explanations/Strange Shuffle Explanation.txt",
    "content": "# $A[p + i] + A[p - i] = 2k$ is invariant\n\n- In the beginning, $A[p + 1] = k + k/2$ and $A[p - 1] = k/2 + 0$\n    - $A[p + 1] + A[p - 1] = 2k$\n    - After the first second, everybody other than $A[p - 1], A[p], A[p + 1]$ has $k$ cards exactly.\n- Let us say this is true for the first $x$ seconds. In the $x + 1$ second, $A[p + x + 1]$\n- Everybody to the right of the impostor has more than $k$ cards.\n- Suppose there are $10000$ people.\n    - Divide into chunks of $100$\n        - $[1 - 100]$\n        - $[101 - 200]$\n        - $[201 - 300]$\n    - After $101$ operations, there will be $100$ people with more than $k$ cards.\n    - It should have at have spilled over to at least one other chunk.\n    - I will spend $200$ moves ($2$ rounds) only checking the first person of each chunk.\n\n    ---\n\n    - Suppose the impostor is in chunk $73$ at position $64$\n        - After $37$ moves, the infection spreads to chunk $74$\n            - After $1$ move, the infection is in $65$\n            - After $2$ moves, the infection is in $66$\n            - After $36$ moves, the infection is in $100$\n            - After $37$-th move, the infection goes to first person of chunk $74$\n        - When you reach the chunk $74$, you will reach in the $74$th move. So, you are in time to catch the infection.\n        - In this scenario, $100$ moves are sufficient.\n\n        ---\n\n- Suppose the impostor is in chunk $7$ at position $64$\n- After $37$ moves, the infection spreads to chunk $8$\n- But, you are visiting chunk $8$ at second $8$. So, you are too early to catch the infection.\n\nOur strategy is \n\n- At $1$ second we go to chunk $1$\n- At $2$ second, we go to chunk $2$\n\n---\n\n- Use $200$ moves to find out someone who has $> k$ cards\n- Then use binary search to find the first person on his left who has $\\le k$ cards.\n"
  },
  {
    "path": "2021/Div 2/694/Programs/Strange Birthday Party.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include  <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, no_of_items;\n    cin >> no_of_elements >> no_of_items;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> price(no_of_items + 1);\n    for(int i = 1; i <= no_of_items; i++)\n    {\n        cin >> price[i];\n    }\n\n    sort(A.begin(), A.end());\n\n    long long total = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        total += price[A[i]];\n    }\n\n    vector <int> available(no_of_items + 1, true);\n    for(int i = no_of_elements, first = 1; i >= 1 && first < A[i]; i--, first++)\n    {\n        available[first] = false;\n\n        total -= (price[A[i]] - price[first]);\n    }\n\n    cout << total << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/694/Programs/Strange Definition.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include  <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 1e6 + 5;\nvector  <int> primes;\nvector <int> value(MAX_N, 1);\n\nvoid sieve(int n)\n{\n    vector <int> largest_prime_factor(MAX_N, 0);\n\n    for(long long i = 2; i < MAX_N; i++)\n    {\n        if(largest_prime_factor[i] == 0)\n        {\n            for(long long multiple = i; multiple < MAX_N; multiple += i)\n            {\n                largest_prime_factor[multiple] = i;\n            }\n        }\n    }\n\n    for(int i = 2; i < MAX_N; i++)\n    {\n        int current = i, exponent = 0;\n\n        while(current%largest_prime_factor[i] == 0)\n        {\n            current /= largest_prime_factor[i];\n\n            exponent++;\n        }\n\n        value[i] = value[current];\n\n        if(exponent%2 == 1)\n        {\n            value[i] *= largest_prime_factor[i];\n        }\n    }\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    map <int, int> frequency;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        A[i] = value[A[i]];\n\n        frequency[A[i]]++;\n    }\n\n    int even_frequency = 0, max_frequency = frequency[1];\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\n    {\n        if(it->first == 1)\n        {\n            continue;\n        }\n\n        if(it->second%2 == 0)\n        {\n            even_frequency += it->second;\n        }\n\n        max_frequency = max(max_frequency, it->second);\n    }\n\n    int initial_answer = max_frequency;\n    int final_answer = max(max_frequency, frequency[1] + even_frequency);\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n    {\n        long long time;\n        cin >> time;\n\n        int answer = (time == 0 ? initial_answer : final_answer);\n        cout << answer << \"\\n\";\n    }\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    sieve(MAX_N);\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/694/Programs/Strange Housing.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include  <algorithm>\n#include <queue>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n\n    vector <vector <int> > graph(no_of_vertices + 1);\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n\n    const int UNCOLOURED = -1, BLACK = 0, WHITE = 1;\n    vector <int> colour(no_of_vertices + 1, UNCOLOURED);\n    queue <int> Q;\n    colour[1] = WHITE;\n    for(int child : graph[1])\n    {\n        colour[child] = BLACK;\n\n        Q.push(child);\n    }\n\n    while(!Q.empty())\n    {\n        int v = Q.front(); Q.pop();\n\n        for(int child : graph[v])\n        {\n            if(colour[child] == UNCOLOURED)\n            {\n                colour[child] = WHITE;\n\n                for(int grandchild : graph[child])\n                {\n                    colour[grandchild] = BLACK;\n\n                    Q.push(grandchild);\n                }\n            }\n        }\n    }\n\n    vector <int> answer;\n    for(int i = 1; i  <= no_of_vertices; i++)\n    {\n        if(colour[i] == WHITE)\n        {\n            answer.push_back(i);\n        }\n\n        if(colour[i] == UNCOLOURED)\n        {\n            cout << \"NO\\n\";\n            return;\n        }\n    }\n\n    cout << \"YES\\n\";\n    cout << answer.size() << \"\\n\";\n    for(int v :  answer)\n    {\n        cout << v << \" \";\n    }\n\n    cout << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/694/Programs/Strange List.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include  <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long no_of_elements, x;\n    cin >> no_of_elements >> x;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    int stop = false;\n    vector <pair <long long, long long> > value;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        value.push_back(make_pair(A[i], 1));\n    }\n\n    for(int i = 0; !stop; i++)\n    {\n        if(value[i].first%x != 0)\n        {\n            stop = true;\n            break;\n        }\n\n        value.push_back(make_pair(value[i].first/x, value[i].second*x));\n    }\n\n    long long total = 0;\n    for(int i = 0; i < value.size(); i++)\n    {\n        total += value[i].first*value[i].second;\n    }\n\n    cout << total << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/694/Programs/Strange Partition.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nvoid solve()\n{\n    int no_of_elements, x;\n    cin >> no_of_elements >> x;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> prefix_beauty(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_beauty[i] = prefix_beauty[i - 1] + ceil(A[i], x);\n    }\n\n    long long suffix_sum = A[no_of_elements];\n    long long min_beauty = prefix_beauty[no_of_elements], max_beauty = prefix_beauty[no_of_elements];\n    for(int i = no_of_elements - 1; i >= 1; i--)\n    {\n        suffix_sum += A[i];\n\n        min_beauty = min(min_beauty, prefix_beauty[i - 1] + ceil(suffix_sum, x));\n\n        max_beauty = max(max_beauty, prefix_beauty[i - 1] + ceil(suffix_sum, x));\n    }\n\n    cout << min_beauty << \" \" << max_beauty << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/694/Programs/Strange Shuffle.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n#include <cmath>\n\nusing namespace std;\n\nint ask(int i)\n{\n    int answer;\n    cout << \"? \" << i << \"\\n\";\n    cout.flush();\n    cin >> answer;\n    \n    return answer;\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    int block_size = floor(sqrt(no_of_elements));\n    int first_greater = 0;\n    for(int round = 1; round <= 2 && first_greater == 0; round++)\n    {\n        for(int i = 1; i <= block_size && first_greater == 0; i++)\n        {\n            int cards = ask(i*block_size);\n\n            if(cards > k)\n            {\n                first_greater = i*block_size;\n            }\n        }\n    }\n\n    //A[i - L] > K and A[i - R] <= K\n    int left = 0, right = no_of_elements - 1;\n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n\n        int check = (first_greater - 1 - mid + no_of_elements)%no_of_elements + 1;\n\n        int cards = ask(check);\n\n        if(cards > k)\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n\n    int impostor = (first_greater - 1 - right + no_of_elements)%no_of_elements + 1;\n    cout << \"! \" << impostor << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/708/Explanations/Genius Explanation.txt",
    "content": "The primary insight of this problem is how to visualise the edge weights in between going from one problem to another. \n\nSuppose we go from problem i to problem j, the weight (complexity) will be a string of 1's in binary \nwhere the bits [j, i - 1] will be set. \n\n-----\n\nLet f(i) be the maximum score if the last problem we solve is problem i\n\nFor each i, we will check every possibility for the second last problem j but we have to be careful to do this in such a way \nthat the weights are increasing. \n\nf(i) = max(f(i), f(j) + |S[i] - S[j]|) \n\n-----\n\nWe have to make sure that the last problem we have solved at problem j is of lower weight than [i-j] \nOne of the ways to do this is to add another dimension to the DP. \n\nf(i, k) = Be the maximum score ending at problem i, if the last problem solved was problem k. \n\nSo, for updating f(i, j), we will use all f(j, k) where [k-j] < [j-i] \n\nThe problem with this is, which vertex do we start with ? \nSuppose we are first finding out f(1, _), but the best path to 1, might be 5 -> 10 -> 1\nBut we have not yet computed f(10, 5)\n\nSo, there is a problem regarding which vertex to start with and how to update the transition correctly. \n\n-----\n\nThere is an ingenious insight to solve this issue. \nInstead of iterating over the vertices, we will iterate over the edges. \nWe will visit the edges in ascending order of their weight. \n(Our binary interpretation of the edges already told us that they were unique.) \nSince we are visiting the edges in ascending order, we can freely \n\nupdate f(i) = max{f(i), f(j) + |S[i] - S[j]}, and rest assured that the last problem at j was of lower weight than [i-j]. \n\nHowever, since we are iterating over edges and not vertices, we have to be sure to update both vertices. \n\nSo, when we visit edge [i-j] \n\nupdate f(i) = max{f(i), f(j) + |S[i] - S[j]|} and \nf(j) = max{f(j), f(i) + |S[i] - S[j]}\n\n-----\n\nHow to visit the edges in ascending order ? \n\nIterate over the higher bit i from i = 0 to N - 1\nIterate over the lower bit from j = i - 1 to 0\n\n-----\n\nvoid solve()\n{\n    int no_of_problems;\n    cin >> no_of_problems;\n\n    vector <int> tag(no_of_problems + 1), score(no_of_problems + 1);\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        cin >> tag[i];\n    }\n\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        cin >> score[i];\n    }\n\n    vector <long long> score_ending_at(no_of_problems + 1);\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        for(int j = i - 1; j > 0; j--)\n        {\n            if(tag[i] == tag[j])\n            {\n                continue;\n            }\n\n            long long current_i = score_ending_at[i], current_j = score_ending_at[j], score_here = abs(score[i] - score[j]);\n\n            score_ending_at[i] = max(score_ending_at[i], current_j + score_here);\n            score_ending_at[j] = max(score_ending_at[j], current_i + score_here);\n        }\n    }\n\n    long long answer = 0;\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        answer = max(answer, score_ending_at[i]);\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/708/Explanations/M Arrays Explanation.txt.txt",
    "content": "Reduce A[i] to (A[i] mod m) for all elements. \r\n\r\nAfter that, all the 0's go to 1 array. \r\nIf M is even, all the M/2 also go to one array. \r\n\r\nOther wise look at each pair (i, j) such that i + j = 0 (mod m) separetly \r\n\r\nWe will make an array like (i, j, i, j, i) (i) (i) (i) (i) \r\n\r\nThe number of arrays if their frequencies differ by more than 1 is |F[i] - F[j]|\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, m;\r\n    cin >> no_of_elements >> m;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> frequency(m + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        frequency[A[i]%m]++;\r\n    }\r\n\r\n    int arrays = (frequency[0] > 0 ? 1 : 0);\r\n    for(int i = 1, j = m - 1; i <= j; i++, j--)\r\n    {\r\n        if(frequency[i] == 0 && frequency[j] == 0)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(i == j || abs(frequency[i] - frequency[j]) <= 1)\r\n        {\r\n            arrays++;\r\n        }\r\n        else\r\n        {\r\n            arrays += abs(frequency[i] - frequency[j]);\r\n        }\r\n    }\r\n\r\n    cout << arrays << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/708/Explanations/Meximization Explanation.txt.txt",
    "content": "1. Print the unique elements in ascending order. \r\n\tThis is the optimal way. The MEX is the highest at each prefix in this way \r\n\r\n2. Print the remaining elements in any order. \r\n\tIt does not impact the MEX \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> frequency(101, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    for(int i = 0; i <= 100; i++)\r\n    {\r\n        if(frequency[i] > 0)\r\n        {\r\n            cout << i << \" \";\r\n\r\n            frequency[i]--;\r\n        }\r\n    }\r\n\r\n\r\n    for(int i = 0; i <= 100; i++)\r\n    {\r\n        while(frequency[i] > 0)\r\n        {\r\n            cout << i << \" \";\r\n\r\n            frequency[i]--;\r\n        }\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/708/Explanations/Square Free Division Explanation.txt.txt",
    "content": "1. Reduce each integer to it's square free form i.e. \r\n\tKeep only those primes which occur an odd number of times in the prime factorisation of n an odd number of times. \r\n\tNow, if PQ is a perfect square, then P = Q\r\n\r\n2. The problem is now reduced to this - \r\n\r\nDivide the array into minimum number of segments after K changes such that each segment consists of distinct elements. \r\n\r\n3. For each i, find out left(i, j). which is the earliest left point of a segment ending at i \r\nthat has only distinct elements after j changes. \r\n\r\n4. Use Left(i, j) to compute f(i, j) which is the minimum number of segments for the first i elements after j changes. \r\nIterate over the number of changes on the last segments and find out the left point accordingly. \r\n\r\n-----\r\n\r\nHow to find out the best left ? \r\n\r\nWe will do an O(n) scan for each k using two pointers L and R. \r\nWe will maintain the invariant that the segment [L, R] has exactly k duplicates and [L, R] is the longest such segment. \r\nLeft(R, k) = L \r\n\r\nAnd then, we will decrease R. \r\n\r\nL and R touch each element once so it is O(n) complexity. \r\n\r\nOverall complexity for this is O(nk)\r\n\r\n\r\nvector <vector <int> > best_left(no_of_elements + 1, vector <int> (no_of_changes + 1));\r\n    for(int change = 0; change <= no_of_changes; change++)\r\n    {\r\n        int left = no_of_elements + 1, right = no_of_elements, duplicates = 0;\r\n\r\n        while(right >= 1)\r\n        {\r\n            while(left >= 1)\r\n            {\r\n                if(duplicates == change && frequency[A[left - 1]] > 0)\r\n                {\r\n                    break;\r\n                }\r\n\r\n                if(frequency[A[left - 1]] > 0)\r\n                {\r\n                    duplicates++;\r\n                }\r\n\r\n                frequency[A[left - 1]]++;\r\n                left--;\r\n            }\r\n\r\n            best_left[right][change] = max(left, 1); //cout << \"For \" << right << \" best \" << left << \"\\n\";\r\n\r\n            if(frequency[A[right]] > 1)\r\n            {\r\n                duplicates--;\r\n            }\r\n\r\n            frequency[A[right]]--;\r\n            right--;\r\n        }\r\n    }\r\n\r\n-----\r\n\r\nHere is how we calculate the DP \r\n\r\nvector <vector <int> > minimum_segments(no_of_elements + 1, vector <int> (no_of_changes + 1, oo));\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        for(int changes = 0; changes <= no_of_changes; changes++)\r\n        {\r\n            if(changes > 0)\r\n            {\r\n                minimum_segments[i][changes] = minimum_segments[i][changes - 1];\r\n            }\r\n\r\n            for(int last_changes = 0; last_changes <= changes; last_changes++)\r\n            {\r\n                int left = best_left[i][last_changes];\r\n\r\n                if(left == 1)\r\n                {\r\n                    minimum_segments[i][changes] = 1;\r\n                    continue;\r\n                }\r\n\r\n                minimum_segments[i][changes] = min(minimum_segments[i][changes],\r\n                                                    minimum_segments[left - 1][changes - last_changes] + 1);\r\n\r\n            }\r\n        }\r\n    }\r\n\r\n"
  },
  {
    "path": "2021/Div 2/708/Explanations/k-LCM Explanation.txt.txt",
    "content": "Pad it with (K - 3) ones and then reuse the solution for (N - (k - 3)) \r\n\r\n1. If n is odd - 1, N/2, N/2 \r\n2. (n mod 4) = 2, - 2, (N - 2)/2, (N - 2)/2, LCM = (N - 2)/2, because (N - 2)/2 is also even\r\n3. (n mod 4) = n/2, n/4, n/4, LCM = n/2\r\n\r\n-----\r\n\r\nvoid solve_3(int n)\r\n{\r\n    switch(n%4)\r\n    {\r\n        case 1 :\r\n        case 3 : cout << \"1 \" << n/2 << \" \" << n/2 << \"\\n\"; return;\r\n \r\n        case 2 : cout << \"2 \" << (n - 2)/2 << \" \" << (n - 2)/2 << \"\\n\"; return;\r\n        case 0 : cout << n/2 << \" \" << n/4 << \" \" << n/4 << \"\\n\"; return;\r\n    }\r\n}\r\n \r\nvoid solve()\r\n{\r\n    int n, k;\r\n    cin >> n >> k;\r\n \r\n    for(int i = 1; i <= k - 3; i++)\r\n    {\r\n        cout << \"1 \";\r\n    }\r\n \r\n    solve_3(n - (k - 3));\r\n}\r\n "
  },
  {
    "path": "2021/Div 2/708/Programs/Genius.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_problems;\n    cin >> no_of_problems;\n\n    vector <int> tag(no_of_problems + 1), score(no_of_problems + 1);\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        cin >> tag[i];\n    }\n\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        cin >> score[i];\n    }\n\n    vector <long long> score_ending_at(no_of_problems + 1);\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        for(int j = i - 1; j > 0; j--)\n        {\n            if(tag[i] == tag[j])\n            {\n                continue;\n            }\n\n            long long current_i = score_ending_at[i], current_j = score_ending_at[j], score_here = abs(score[i] - score[j]);\n\n            score_ending_at[i] = max(score_ending_at[i], current_j + score_here);\n            score_ending_at[j] = max(score_ending_at[j], current_i + score_here);\n        }\n    }\n\n    long long answer = 0;\n    for(int i = 1; i <= no_of_problems; i++)\n    {\n        answer = max(answer, score_ending_at[i]);\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/708/Programs/M Arrays.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, m;\r\n    cin >> no_of_elements >> m;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> frequency(m + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        frequency[A[i]%m]++;\r\n    }\r\n\r\n    int arrays = (frequency[0] > 0 ? 1 : 0);\r\n    for(int i = 1, j = m - 1; i <= j; i++, j--)\r\n    {\r\n        if(frequency[i] == 0 && frequency[j] == 0)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(i == j || abs(frequency[i] - frequency[j]) <= 1)\r\n        {\r\n            arrays++;\r\n        }\r\n        else\r\n        {\r\n            arrays += abs(frequency[i] - frequency[j]);\r\n        }\r\n    }\r\n\r\n    cout << arrays << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/708/Programs/Meximization.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> frequency(101, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    for(int i = 0; i <= 100; i++)\r\n    {\r\n        if(frequency[i] > 0)\r\n        {\r\n            cout << i << \" \";\r\n\r\n            frequency[i]--;\r\n        }\r\n    }\r\n\r\n\r\n    for(int i = 0; i <= 100; i++)\r\n    {\r\n        while(frequency[i] > 0)\r\n        {\r\n            cout << i << \" \";\r\n\r\n            frequency[i]--;\r\n        }\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/708/Programs/Square Free Division.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nconst int MAX_N = 1e7 + 5, oo = 1e9;\nvector  <int> primes;\nvector <int> value(MAX_N, 1);\nvector <int> frequency(MAX_N, 0);\n\nvoid sieve(int n)\n{\n    vector <int> largest_prime_factor(MAX_N, 0);\n\n    for(long long i = 2; i < MAX_N; i++)\n    {\n        if(largest_prime_factor[i] == 0)\n        {\n            for(long long multiple = i; multiple < MAX_N; multiple += i)\n            {\n                largest_prime_factor[multiple] = i;\n            }\n        }\n    }\n\n    for(int i = 2; i < MAX_N; i++)\n    {\n        int current = i, exponent = 0;\n\n        while(current%largest_prime_factor[i] == 0)\n        {\n            current /= largest_prime_factor[i];\n\n            exponent++;\n        }\n\n        value[i] = value[current];\n\n        if(exponent%2 == 1)\n        {\n            value[i] *= largest_prime_factor[i];\n        }\n    }\n}\n\nvoid solve()\n{\n    int no_of_elements, no_of_changes;\n    cin >> no_of_elements >> no_of_changes;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        A[i] = value[A[i]];\n\n        frequency[A[i]] = 0;\n    }\n\n\n    vector <vector <int> > best_left(no_of_elements + 1, vector <int> (no_of_changes + 1));\n    for(int change = 0; change <= no_of_changes; change++)\n    {\n        int left = no_of_elements + 1, right = no_of_elements, duplicates = 0;\n\n        while(right >= 1)\n        {\n            while(left > 1)\n            {\n                if(duplicates == change && frequency[A[left - 1]] > 0)\n                {\n                    break;\n                }\n\n                if(frequency[A[left - 1]] > 0)\n                {\n                    duplicates++;\n                }\n\n                frequency[A[left - 1]]++;\n                left--;\n            }\n\n            best_left[right][change] = left; //cout << \"For \" << right << \" best \" << left << \"\\n\";\n\n            if(frequency[A[right]] > 1)\n            {\n                duplicates--;\n            }\n\n            frequency[A[right]]--;\n            right--;\n        }\n    }\n\n    vector <vector <int> > minimum_segments(no_of_elements + 1, vector <int> (no_of_changes + 1, oo));\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int changes = 0; changes <= no_of_changes; changes++)\n        {\n            if(changes > 0)\n            {\n                minimum_segments[i][changes] = minimum_segments[i][changes - 1];\n            }\n\n            for(int last_changes = 0; last_changes <= changes; last_changes++)\n            {\n                int left = best_left[i][last_changes];\n\n                if(left == 1)\n                {\n                    minimum_segments[i][changes] = 1;\n                    continue;\n                }\n\n                minimum_segments[i][changes] = min(minimum_segments[i][changes],\n                                                    minimum_segments[left - 1][changes - last_changes] + 1);\n\n            }\n        }\n    }\n\n    cout << minimum_segments[no_of_elements][no_of_changes] << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    sieve(MAX_N);\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n    {\n        solve();\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/708/Programs/k-LCM.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve_3(int n)\r\n{\r\n    switch(n%4)\r\n    {\r\n        case 1 :\r\n        case 3 : cout << \"1 \" << n/2 << \" \" << n/2 << \"\\n\"; return;\r\n\r\n        case 2 : cout << \"2 \" << (n - 2)/2 << \" \" << (n - 2)/2 << \"\\n\"; return;\r\n        case 0 : cout << n/2 << \" \" << n/4 << \" \" << n/4 << \"\\n\"; return;\r\n    }\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int n, k;\r\n    cin >> n >> k;\r\n\r\n    for(int i = 1; i <= k - 3; i++)\r\n    {\r\n        cout << \"1 \";\r\n    }\r\n\r\n    solve_3(n - (k - 3));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Explanations/Bananas in a MIrcorwave Explanation.txt.txt",
    "content": "# Visit each banana at most twice\r\n\r\n- Suppose we had to do it naively. How would we do it $?$\r\n    - For each time step, visit all the bananas that we have gotten previously and then perform the current operation $Y$ times and mark their states as visited.\r\n    - We just need one observation.\r\n    - Suppose we start at $b_1$ and are performing addition.\r\n        - We only need to keep going as long as the integers generated weren't reachable.\r\n        - $b_1 + x, b_1 + 2x, b_1 + 3x, \\dots , b_1 + kx$\r\n        - Suppose some $b_k = b_1 + kx$ is already visited.\r\n        - We will stop here and break.\r\n        - The reason is that if when we pick $b_k$ and start performing this same operation $Y$ times, we will get all the same states and more.\r\n            - If we continue applying on $b_1$, we will get $b_1 + (k + 1)x, b_1 + (k + 2)x, \\dots , b_1 + Yx$\r\n            - If we start from $b_k$, we will get $b_k + x, b_k + 2x, \\dots , b_k + Yx$\r\n            - The elements visited after $b_k$ from $b_1$ will be a subset (prefix) of the elements visited starting from $b_k$. So, instead of continuing from $b_1$, we will stop and start afresh from $b_k$\r\n\r\n    ---\r\n\r\n    - Each element is visited at most twice. If we start applying operations from $x$, we would only have visited from the most recent integer in $[x - Y, X]$ that was already visited.\r\n        - So, $x$ is only visited twice.\r\n        - This is similar to a two pointer idea and.\r\n\r\n-----\r\n\r\n\r\nlong long ceil(long long n, long long d)\r\n{\r\n    return (n/d) + (n%d != 0);\r\n}\r\n\r\nlong long operate(int type, long long b, long long x)\r\n{\r\n    switch(type)\r\n    {\r\n        case ADD : return ceil(b*MOD + x, MOD);\r\n\r\n        case MULTIPLY : return ceil(b*x, MOD);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_timesteps, target_bananas;\r\n    cin >> no_of_timesteps >> target_bananas;\r\n\r\n    vector <int> can_get(target_bananas + 1, -1), previous_get(target_bananas + 1, false);\r\n    can_get[0] = 0;\r\n\r\n    for(int i = 1; i <= no_of_timesteps; i++)\r\n    {\r\n        int type;\r\n        long long x, repetition;\r\n        cin >> type >> x >> repetition;\r\n        previous_get = can_get;\r\n\r\n        for(int b = 0; b <= target_bananas; b++)\r\n        {   //cout << \"From \" << b << \"\\n\";\r\n            if(previous_get[b] != -1)\r\n            {\r\n                for(long long t = 1, next = b; t <= repetition; t++)\r\n                {\r\n                    next = operate(type, next, x); //cout << \"Getting \" << next << \"\\n\";\r\n\r\n                    if(next > target_bananas || previous_get[next] != -1)\r\n                    {\r\n                        break;\r\n                    }\r\n\r\n                    can_get[next] = i; //cout << \"Can get \" << next << \" = \" << can_get[next] << \"\\n\";\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= target_bananas; i++)\r\n    {\r\n        cout << can_get[i] << \" \";\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Explanations/Box Fitting Explanation.txt",
    "content": "Maintain a multiset of all the rectangles. \nTry to fill each layer greedily by choosing the largest size that fits. \nIf a layer is full or the smallest layer does not fit in the rectangle, move to the next layer. \n\n-----\n\nvoid solve()\n{\n    int no_of_elements, W;\n    cin >> no_of_elements >> W;\n\n    multiset <int> M;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        M.insert(A[i]);\n    }\n\n    int no_of_levels = 0, base = W, remaining_base = W;\n    while(M.size() > 0)\n    {\n        no_of_levels++;\n\n        remaining_base = base;\n\n        while(remaining_base > 0 && M.size() > 0)\n        {\n            auto it = M.lower_bound(remaining_base);\n\n            if(it != M.begin())\n            {\n                it--;\n            }\n\n            int x = *it; //cout << \"Remaining = \" << remaining_base << \" x = \" << x << \"\\n\";\n\n            if(x > remaining_base)\n            {\n                break;\n            }\n            else\n            {\n                remaining_base -= x;\n\n                M.erase(it);\n            }\n        }\n    }\n\n    cout << no_of_levels << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Explanations/GCD Sum Explanation.txt.txt",
    "content": "Keep checking consecutive integers till we get an integer that meets the condition. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    long long n;\r\n    cin >> n;\r\n\r\n    long long answer = n;\r\n    while(__gcd(answer, sum_of_digits(answer)) == 1)\r\n        answer++;\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Explanations/Two Houses Explanation.txt.txt",
    "content": "# $K_a > K_b \\implies b \\to a$ so only check $a \\to b$\r\n\r\n## Unique Topological Sort on the Strongly Connected Graph\r\n\r\n- This graph has the property that there is an edge between every pair of vertices.\r\n- Let us compress all strongly connected components into a single vertex and look at this graph.\r\n- Just like the original graph, this graph will also have every pair connected.\r\n- Since every pair has a directed graph, for every pair there $(u, v)$, we know which vertex should come first in the topological sort. The topological sort is unique.\r\n\r\n---\r\n\r\n## The indegree of a vertex is also sorted in ascending order in the topological sort\r\n\r\n- Let us consider two adjacent nodes in the topological sort of the SCC graph - $L, R$\r\n- Let $u$ be in $L$ and $v$ be in $R$\r\n- Every pair is connected and the topological sort is unique and these are adjacent nodes so the indegree contribution from the other nodes \r\nto $L$ and $R$ will be equal.\r\n    - So, let us delete all other nodes from the graph and only look at $L$ and $R$\r\n    - $L$ is a $SCC$ so each vertex will have indegree at most $|L| - 1$\r\n        - There can be no incoming edge from any vertex in $R$\r\n    - Each vertex in $R$ will have indegree $\\ge |L|$\r\n        - It has to have incoming edges from every vertex in $L$\r\n\r\n---\r\n\r\n## Reachability\r\n\r\n- If $K_a < K_b$, either $a$ and $b$ are is the same SCC or $b$ is in a SCC to the left of $a$ in the topological sort enumeration\r\n- Either way $a \\to b$\r\n\r\n---\r\n\r\n- Sort all the pairs by $(K_a - K_b)$\r\n    - Process the pairs in descending order of this value\r\n    - For every pair, we are guaranteed that the higher order is reachable from the lower order so only query the other pair.\r\n\r\n-----\r\n\r\n```cpp\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n \r\n    vector <int> indegree(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> indegree[i];\r\n    }\r\n \r\n    vector < pair <int, pair <int, int> > > edges;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        for(int j = i + 1; j <= no_of_vertices; j++)\r\n        {\r\n            int weight = abs(indegree[i] - indegree[j]);\r\n \r\n            pair <int, int> E = make_pair(i, j);\r\n \r\n            edges.push_back(make_pair(weight, E));\r\n        }\r\n    }\r\n \r\n    sort(edges.begin(), edges.end());\r\n    reverse(edges.begin(), edges.end());\r\n \r\n    int answer_u = 0, answer_v = 0;\r\n    for(int i = 0; i < edges.size(); i++)\r\n    {\r\n        int u = edges[i].second.first, v = edges[i].second.second;\r\n \r\n        if(indegree[u] > indegree[v])\r\n        {\r\n            swap(u, v);\r\n        }\r\n \r\n        cout << \"? \" << v << \" \" << u << \"\\n\";\r\n        cout.flush();\r\n \r\n        string reply;\r\n        cin >> reply;\r\n \r\n        if(reply[0] == 'Y')\r\n        {\r\n            answer_u = u; answer_v = v;\r\n            break;\r\n        }\r\n    }\r\n \r\n    cout << \"! \" << answer_u << \" \" << answer_v << \"\\n\";\r\n    return 0;\r\n}\r\n```"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Programs/Bananas in a Microwave.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1e5, ADD = 1, MULTIPLY = 2;\r\n\r\nlong long ceil(long long n, long long d)\r\n{\r\n    return (n/d) + (n%d != 0);\r\n}\r\n\r\nlong long operate(int type, long long b, long long x)\r\n{\r\n    switch(type)\r\n    {\r\n        case ADD : return ceil(b*MOD + x, MOD);\r\n\r\n        case MULTIPLY : return ceil(b*x, MOD);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_timesteps, target_bananas;\r\n    cin >> no_of_timesteps >> target_bananas;\r\n\r\n    vector <int> can_get(target_bananas + 1, -1), previous_get(target_bananas + 1, false);\r\n    can_get[0] = 0;\r\n\r\n    for(int i = 1; i <= no_of_timesteps; i++)\r\n    {\r\n        int type;\r\n        long long x, time;\r\n        cin >> type >> x >> time;\r\n        previous_get = can_get;\r\n\r\n        for(int b = 0; b <= target_bananas; b++)\r\n        {   //cout << \"From \" << b << \"\\n\";\r\n            if(previous_get[b] != -1)\r\n            {\r\n                for(long long t = 1, next = b; t <= time; t++)\r\n                {\r\n                    next = operate(type, next, x); //cout << \"Getting \" << next << \"\\n\";\r\n\r\n                    if(next > target_bananas || previous_get[next] != -1)\r\n                    {\r\n                        break;\r\n                    }\r\n\r\n                    can_get[next] = i; //cout << \"Can get \" << next << \" = \" << can_get[next] << \"\\n\";\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= target_bananas; i++)\r\n    {\r\n        cout << can_get[i] << \" \";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Programs/Box Fitting.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, W;\n    cin >> no_of_elements >> W;\n\n    multiset <int> M;\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        M.insert(A[i]);\n    }\n\n    int no_of_levels = 0, base = W, remaining_base = W;\n    while(M.size() > 0)\n    {\n        no_of_levels++;\n\n        remaining_base = base;\n\n        while(remaining_base > 0 && M.size() > 0)\n        {\n            auto it = M.lower_bound(remaining_base);\n\n            if(it != M.begin())\n            {\n                it--;\n            }\n\n            int x = *it; //cout << \"Remaining = \" << remaining_base << \" x = \" << x << \"\\n\";\n\n            if(x > remaining_base)\n            {\n                break;\n            }\n            else\n            {\n                remaining_base -= x;\n\n                M.erase(it);\n            }\n        }\n    }\n\n    cout << no_of_levels << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Programs/GCD Sum.cpp",
    "content": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nlong long sum_of_digits(long long n)\n{\n    long long sum = 0;\n\n    while(n)\n    {\n        sum += n%10;\n\n        n /= 10;\n    }\n\n    return sum;\n}\n\nvoid solve()\n{\n    long long n;\n    cin >> n;\n\n    long long answer = n;\n    while(__gcd(answer, sum_of_digits(answer)) == 1)\n        answer++;\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/711 CodeCraft 2021/Programs/Two Houses.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    vector <int> indegree(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> indegree[i];\r\n    }\r\n\r\n    vector < pair <int, pair <int, int> > > edges;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        for(int j = i + 1; j <= no_of_vertices; j++)\r\n        {\r\n            int weight = abs(indegree[i] - indegree[j]);\r\n\r\n            pair <int, int> E = make_pair(i, j);\r\n\r\n            edges.push_back(make_pair(weight, E));\r\n        }\r\n    }\r\n\r\n    sort(edges.begin(), edges.end());\r\n    reverse(edges.begin(), edges.end());\r\n\r\n    int answer_u = 0, answer_v = 0;\r\n    for(int i = 0; i < edges.size(); i++)\r\n    {\r\n        int u = edges[i].second.first, v = edges[i].second.second;\r\n\r\n        if(indegree[u] > indegree[v])\r\n        {\r\n            swap(u, v);\r\n        }\r\n\r\n        cout << \"? \" << v << \" \" << u << \"\\n\";\r\n        cout.flush();\r\n\r\n        string reply;\r\n        cin >> reply;\r\n\r\n        if(reply[0] == 'Y')\r\n        {\r\n            answer_u = u; answer_v = v;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << \"! \" << answer_u << \" \" << answer_v << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/712 Div 2/Explanations/3 Colouring Explanation.txt",
    "content": "Let us divide the chessboard into even and odd squares. (Imagine a normal chessboard).\nEven and odd squares never touch each other. \n\nWe will colour the even squares black and the odd squares white, as far as possible.\nWe will use the colour red only if squares of any one parity are completely over. \n\n-----\n\n1. We will try to colour an even cell black or an odd cell white in a given move. \n2. If we cannot do either of these moves, it means either the even or odd cells are completely coloured. \nSo, we will colour cells of the available parity with Red. \n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid display(vector <vector <int> > &grid)\n{\n    for(int i = 1; i < grid.size(); i++)\n    {\n        for(int j = 1; j < grid.size(); j++)\n        {\n            cout << grid[i][j];\n        }\n        cout << \"\\n\";\n    }\n}\n\npair <int, int> colour(vector <vector <int> > &grid, int n, int parity, int col)\n{\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if( (i + j)%2 == parity && grid[i][j] == 0)\n            {\n                grid[i][j] = col;\n\n                return make_pair(i, j);\n            }\n        }\n    }\n\n    return make_pair(0, 0);\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    const int BLACK = 1, WHITE = 2, RED = 3;\n    int available_even =(n*n)/2 + ((n*n)%2 == 1 ? 1 : 0), available_odd = (n*n)/2;\n\n    vector <vector <int> > grid(n + 1, vector <int> (n + 1, 0));\n    for(int i = 1; i <= n*n; i++)\n    {\n        int alice_colour;\n        cin >> alice_colour;\n\n        int bob_colour;\n\n        int parity = (i%2);\n\n        pair <int, int> P;\n\n        switch(alice_colour)\n        {\n            case BLACK : if(available_odd > 0)\n                         {\n                            bob_colour = WHITE;\n                            P = colour(grid, n, 1, WHITE);\n                            available_odd--;\n                         }\n                         else\n                         {\n                             bob_colour = RED;\n                             P = colour(grid, n, 0, RED);\n                             available_even--;\n                         }\n                         break;\n\n            case WHITE : if(available_even > 0)\n                         {\n                            bob_colour = BLACK;\n                            P = colour(grid, n, 0, BLACK);\n                            available_even--;\n                         }\n                         else\n                         {\n                             bob_colour = RED;\n                             P = colour(grid, n, 1, RED);\n                             available_odd--;\n                         }\n                         break;\n\n            case RED : if(available_even > 0)\n                       {\n                            bob_colour = BLACK;\n                            P = colour(grid, n, 0, BLACK);\n                            available_even--;\n                       }\n                       else\n                       {\n                           bob_colour = WHITE;\n                           P = colour(grid, n, 1, WHITE);\n                           available_odd--;\n                       }\n        }\n\n        cout << bob_colour << \" \" << P.first << \" \" << P.second << \"\\n\";\n        cout.flush(); //display(grid);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/712 Div 2/Explanations/Deja Vu Explanation.txt.txt",
    "content": "Insert an A at the first point where S[n - i - 1] is not A \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n \r\n    int all_A = true;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] != 'a')\r\n        {\r\n            all_A = false;\r\n            break;\r\n        }\r\n    }\r\n \r\n    if(all_A)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return;\r\n    }\r\n \r\n    cout << \"YES\\n\";\r\n    int remaining = 0;\r\n    for(int i = 0, j = S.size() - 1; i < S.size(); i++, j--)\r\n    {\r\n        if(S[j] != 'a')\r\n        {\r\n            remaining = i;\r\n            cout << \"a\";\r\n            break;\r\n        }\r\n        else\r\n        {\r\n            cout << S[i];\r\n        }\r\n    }\r\n \r\n    for(int i = remaining; i < S.size(); i++)\r\n    {\r\n        cout << S[i];\r\n    }\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/712 Div 2/Explanations/Flip the Bits Explanation.txt.txt",
    "content": "Keep track of the prefix sum of A \r\n\r\nThere are only certain points in A where we can flip the prefix. \r\n\r\nGo from the suffix to 1 and keep visiting smaller prefixes. Flip a prefix if (A[i] != B[i]) \r\n\r\nKeep a variable 'flip' to simulate the flip. If we flip a segment twice, it is the same as not flipping it.\r\n\r\nSo, if (A[i] = B[i]), make flip = false \r\n\r\n-----\r\n\r\nchar other(char ch)\r\n{\r\n    return (ch == '1' ? '0' : '1');\r\n}\r\n \r\nvoid solve()\r\n{\r\n    int length;\r\n    cin >> length;\r\n \r\n    string A, B;\r\n    cin >> A >> B;\r\n \r\n    vector <int> ones(A.size(), 0);\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        if(i == 0)\r\n        {\r\n            ones[i] = (A[i] == '1');\r\n        }\r\n        else\r\n        {\r\n            ones[i] = ( (A[i] == '1') + ones[i - 1]);\r\n        }\r\n \r\n    }\r\n \r\n    int flip = false;\r\n    for(int i = A.size() - 1; i >= 0; i--)\r\n    {   //cout << \"At \" << i << \"\\n\";\r\n        if(2*ones[i] == i + 1)\r\n        {   //cout << \"Equal \";\r\n            if(flip)\r\n            {\r\n                if(A[i] == B[i])\r\n                {\r\n                    flip = false;\r\n                }\r\n                else\r\n                {\r\n                    A[i] = other(A[i]);\r\n                    flip = true;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if(A[i] != B[i])\r\n                {\r\n                    A[i] = other(A[i]);\r\n                    flip = true;\r\n                }\r\n            }\r\n        }\r\n        else\r\n        {\r\n            if(flip)\r\n            {\r\n                A[i] = other(A[i]);\r\n            }\r\n        }\r\n \r\n       // cout << \"Flip = \" << flip << \" A = \" << A[i] << \"\\n\";\r\n    }\r\n \r\n    int same = true;\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            same = false;\r\n            break;\r\n        }\r\n    }\r\n \r\n    cout << (same ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n "
  },
  {
    "path": "2021/Div 2/712 Div 2/Programs/3 Colouring.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid display(vector <vector <int> > &grid)\n{\n    for(int i = 1; i < grid.size(); i++)\n    {\n        for(int j = 1; j < grid.size(); j++)\n        {\n            cout << grid[i][j];\n        }\n        cout << \"\\n\";\n    }\n}\n\npair <int, int> colour(vector <vector <int> > &grid, int n, int parity, int col)\n{\n    for(int i = 1; i <= n; i++)\n    {\n        for(int j = 1; j <= n; j++)\n        {\n            if( (i + j)%2 == parity && grid[i][j] == 0)\n            {\n                grid[i][j] = col;\n\n                return make_pair(i, j);\n            }\n        }\n    }\n\n    return make_pair(0, 0);\n}\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    const int BLACK = 1, WHITE = 2, RED = 3;\n    int available_even =(n*n)/2 + ((n*n)%2 == 1 ? 1 : 0), available_odd = (n*n)/2;\n\n    vector <vector <int> > grid(n + 1, vector <int> (n + 1, 0));\n    for(int i = 1; i <= n*n; i++)\n    {\n        int alice_colour;\n        cin >> alice_colour;\n\n        int bob_colour;\n\n        int parity = (i%2);\n\n        pair <int, int> P;\n\n        switch(alice_colour)\n        {\n            case BLACK : if(available_odd > 0)\n                         {\n                            bob_colour = WHITE;\n                            P = colour(grid, n, 1, WHITE);\n                            available_odd--;\n                         }\n                         else\n                         {\n                             bob_colour = RED;\n                             P = colour(grid, n, 0, RED);\n                             available_even--;\n                         }\n                         break;\n\n            case WHITE : if(available_even > 0)\n                         {\n                            bob_colour = BLACK;\n                            P = colour(grid, n, 0, BLACK);\n                            available_even--;\n                         }\n                         else\n                         {\n                             bob_colour = RED;\n                             P = colour(grid, n, 1, RED);\n                             available_odd--;\n                         }\n                         break;\n\n            case RED : if(available_even > 0)\n                       {\n                            bob_colour = BLACK;\n                            P = colour(grid, n, 0, BLACK);\n                            available_even--;\n                       }\n                       else\n                       {\n                           bob_colour = WHITE;\n                           P = colour(grid, n, 1, WHITE);\n                           available_odd--;\n                       }\n        }\n\n        cout << bob_colour << \" \" << P.first << \" \" << P.second << \"\\n\";\n        cout.flush(); //display(grid);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/712 Div 2/Programs/Déjà Vu.cpp",
    "content": "#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    int all_A = true;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] != 'a')\r\n        {\r\n            all_A = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(all_A)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    int remaining = 0;\r\n    for(int i = 0, j = S.size() - 1; i < S.size(); i++, j--)\r\n    {\r\n        if(S[j] != 'a')\r\n        {\r\n            remaining = i;\r\n            cout << \"a\";\r\n            break;\r\n        }\r\n        else\r\n        {\r\n            cout << S[i];\r\n        }\r\n    }\r\n\r\n    for(int i = remaining; i < S.size(); i++)\r\n    {\r\n        cout << S[i];\r\n    }\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/712 Div 2/Programs/Flip the Bits.cpp",
    "content": "#include <iostream>\r\n#include <cmath>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nchar other(char ch)\r\n{\r\n    return (ch == '1' ? '0' : '1');\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    vector <int> ones(A.size(), 0);\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        if(i == 0)\r\n        {\r\n            ones[i] = (A[i] == '1');\r\n        }\r\n        else\r\n        {\r\n            ones[i] = ( (A[i] == '1') + ones[i - 1]);\r\n        }\r\n\r\n    }\r\n\r\n    int flip = false;\r\n    for(int i = A.size() - 1; i >= 0; i--)\r\n    {   //cout << \"At \" << i << \"\\n\";\r\n        if(2*ones[i] == i + 1)\r\n        {   //cout << \"Equal \";\r\n            if(flip)\r\n            {\r\n                if(A[i] == B[i])\r\n                {\r\n                    flip = false;\r\n                }\r\n                else\r\n                {\r\n                    A[i] = other(A[i]);\r\n                    flip = true;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                if(A[i] != B[i])\r\n                {\r\n                    A[i] = other(A[i]);\r\n                    flip = true;\r\n                }\r\n            }\r\n        }\r\n        else\r\n        {\r\n            if(flip)\r\n            {\r\n                A[i] = other(A[i]);\r\n            }\r\n        }\r\n\r\n       // cout << \"Flip = \" << flip << \" A = \" << A[i] << \"\\n\";\r\n    }\r\n\r\n    int same = true;\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            same = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (same ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/AND Sequences Explanation.txt.txt",
    "content": "A[1] = AND(A[2], A[3], ... , A[n]) \r\n\r\nSince AND(x, x) = x \r\n\r\nAND(A[1], AND(A[2], A[3], ... , A[n]) ) = AND(A[1], ... , A[n]) = A[1] \r\n\r\nSimilarly, AND(A[1], ... , A[n - 1]) = A[n] \r\n\r\nSo, the AND of the whole array is A[1] = A[n] \r\n\r\n------\r\n\r\nWe will place the array AND at A[1] and at A[n]\r\n\r\nSince the AND of the whole array is x, AND(x, any subset of A) = x \r\n\r\nSo, as long as A[1] = A[n] = x, the AND of every prefix and every suffix is equal\r\n\r\nIf there is any other element at A[1], then A[1] =/= AND(A[2], ... , A[n])\r\n\r\n-----\r\n\r\n1. Find out the frequency of every element. \r\n2. Count the number of ways to place the array AND at the two ends \r\n3. The remaining (n - 2) elements can be permuted in (n - 2)! ways\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    long long array_and = (1LL << 60) - 1;\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        array_and &= A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long answer = choose_2(frequency[array_and], MOD)*factorial(no_of_elements - 2, MOD);\r\n\r\n    answer %= MOD;\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/Add One Explanation.txt.txt",
    "content": "Let f(i) be the length of 10 after i moves. \r\n\r\nHow to build the recurrence for f(i) ? \r\nIn 10 moves, every digit becomes a 2 digit number except the 9, which becomes a 3 digit number (109)\r\n\r\n9 -> \r\n10 -> \r\n21 \r\n32\r\n43\r\n54\r\n65\r\n76\r\n87\r\n98\r\n109\r\n\r\nf(i) = 2f(i - 10) + Number of 9's\r\nf(i) = f(i - 10) + f(i - 10) + Number of 9's\r\nf(i) = f(i - 10) + f(i - 9)\r\n\r\nAfter one move from (i - 10), all the digits remain single digits except 9 which becomes 2 digits \r\nf(i - 9) = f(i - 10) + Number of 9's\r\n\r\n-----\r\n\r\nIn order to find the length of d after i moves, we will first calculate the number of mvoes to make it = 10 \r\nand then use f(i - (10 - d)) \r\n\r\n-----\r\n\r\nvoid precompute()\r\n{\r\n    for(int i = 0; i <= 8; i++)\r\n    {\r\n        length[i] = 2;\r\n    }\r\n\r\n    length[9] = 3;\r\n\r\n    for(int i = 10; i < MAX_N; i++)\r\n    {\r\n        length[i] = (length[i - 9] + length[i - 10])%MOD;\r\n    }\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int n, no_of_operations;\r\n    cin >> n >> no_of_operations;\r\n\r\n    long long answer = 0;\r\n    while(n > 0)\r\n    {\r\n        int digit = n%10;\r\n\r\n        long long this_length = (no_of_operations < 10 - digit ? 1 : length[no_of_operations - (10 - digit)]);\r\n\r\n        //cout << \"D = \" << digit << \" this = \" << this_length << \"\\n\";\r\n\r\n        n /= 10;\r\n\r\n        answer = (answer + this_length)%MOD;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/Arrays and Peaks Explanation.txt.txt",
    "content": "We will put all the peaks in the even positions. \r\n\r\nIf the number of peaks is more than N/2, it is not possible since the first and last elements cannot be peaks. \r\n\r\nIf it is <= N/2, we can just use the even positions\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, no_of_peaks;\r\n    cin >> no_of_elements >> no_of_peaks;\r\n\r\n    if(no_of_peaks > no_of_elements/2 - (no_of_elements%2 == 0))\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        A[i] = i;\r\n    }\r\n\r\n    for(int i = 2, peaks = 0; peaks < no_of_peaks && i < no_of_elements; i += 2, peaks++)\r\n    {\r\n        swap(A[i], A[i + 1]);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << A[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/Cost Equilibrium Explanation.txt.txt",
    "content": "# The sinks must occur before or after the sources\r\n\r\n- The final value $S/n$ is uniquely determined.\r\n    - Elements greater than the final value have to be the source and those smaller have to be the sink\r\n    - The final value, source and sink are determined uniquely.\r\n\r\n## How much does each element contribute to the sum $?$\r\n\r\n- Suppose $A(i)$ is a source and there are $L$ sinks  it contributed to that occur before it and $R$ sinks that occur after it.\r\n    - It will contribute $Li - Ri = (L - R)i$\r\n    - The contribution of each sink or source can be appropriately varied by changing the values it shares with the sinks on the left and right.\r\n    - However, if all the sinks are on the left, it will contribute $Li$ exactly and no more or less.\r\n    - If all the sinks are on the right, it will contribute $-Ri$ exactly and no more or less\r\n- If all the sinks occur after all the sources or vice versa, the cost is uniquely determined.\r\n\r\n---\r\n\r\n## How to count the permutations $?$\r\n\r\n- We can count the number of ways to permute the sinks and sources among themselves using multinomial coefficients. (Since duplicates are allowed).\r\n- The $E$ elements which are already equal to the final value can be placed $N - E + 1$ gaps\r\n    - This is given by stars and bars as it is the number of ways to distribute $E$ stars using $N$ bars. $(N + 1$ gaps $)$\r\n\r\n    $$\\binom{N - E}{E}$$\r\n\r\n- The sinks and sources can be permuted as groups in $2!$ ways so multiply the answer by $2$\r\n\r\n---\r\n\r\n## The Exceptions\r\n\r\n- If there are $0$ sinks or $0$ sources, any permutation of the array is acceptable. So, count all of them using the multinomial coefficient\r\n- If there is exactly $1$ sink or exactly $1$ source, the contribution to the sum will always be the same regardless of how the sinks (or sources) are distributed to it's left or right.\r\n    - $1$ sink or $1$ source is a special case because the cost is uniquely determined.\r\n    - We need to count all permutations in this case too.\r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    map <int, int> frequency;\r\n    long long sum = 0;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        sum += A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    if(sum%no_of_elements != 0)\r\n    {\r\n        cout << \"0\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    int final_value = (sum/no_of_elements);\r\n\r\n    vector <long long> F, source_frequency, sink_frequency;\r\n\r\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        if(it->first > final_value)\r\n        {\r\n            source_frequency.push_back(it->second);\r\n        }\r\n        else if(it->first < final_value)\r\n        {\r\n            sink_frequency.push_back(it->second);\r\n        }\r\n\r\n        F.push_back(it->second);\r\n    }\r\n\r\n    long long answer;\r\n    if(source_frequency.size() == 0 || sink_frequency.size() == 0 ||\r\n       (source_frequency.size() == 1 && source_frequency[0] == 1) || (sink_frequency.size() == 1 && sink_frequency[0] == 1) )\r\n    {\r\n        answer = multinomial(F);\r\n\r\n        cout << answer << \"\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    long long sources = multinomial(source_frequency), sink = multinomial(sink_frequency);\r\n    long long equal_values = frequency[final_value], spaces = no_of_elements - equal_values + 1;\r\n\r\n    long long remaining = stars_and_bars(equal_values, spaces - 1);\r\n\r\n    answer = (sources*sink)%MOD;\r\n    answer = (answer*remaining)%MOD;\r\n    answer = (answer*2)%MOD;;\r\n\r\n    cout << answer << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/GCD and MST Explanation.txt",
    "content": "Let us visit the vertices in ascending order and check how many edges has this as the weight. \n\nIf A[i] >= P, then we will stop because we no longer need to check anything and can just add the P-edges\n\nNow, which vertices will have A[i] as the weight ? \n\nCheck the nearest j to the i as long as A[i, j] or A[j, i] are >= A[i] and divisible by A[i] \n\nWe will add another condition. \n\nMaintain a vector is_connected, which is true if A[i] is connected to the vertex A[i + 1], \neither directly or indirectly. \n\nWhen we are going left, we will stop at the first vertex j where is_connected[i] is true \nSince A[i] has been connected to A[j - 1] already, placing another edge between A[i], A[j] will create a cycle. \nMoreover, we are visiting the weights in ascending order so A[j] has been connected to A[j - 1] with less expensive edges.\n\nWhen we are going right, we will stop at the first vertex j where is_connected[j - 1] is true because this means that \nA[j], A[j - 1] are already connected and A[j] was connected to the tree using lighter edges\n\n-----\n\nvoid solve()\n{\n    int no_of_elements, p;\n    cin >> no_of_elements >> p;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> is_connected_right(no_of_elements + 1, false);\n    vector < pair <int, int> > values;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        values.push_back(make_pair(A[i], i));\n    }\n\n    sort(values.begin(), values.end());\n\n    long long weight = 0;\n    for(int i = 0; i < values.size(); i++)\n    {\n        int gcd = values[i].first, index = values[i].second;\n\n        if(gcd >= p)\n        {\n            break;\n        }\n\n        for(int j = index - 1; j >= 1; j--)\n        {\n            if(A[j] < gcd || A[j]%gcd != 0 || is_connected_right[j])\n            {\n                break;\n            }\n\n            is_connected_right[j] =  true;\n\n            weight += gcd;\n        }\n\n        for(int j = index + 1; j <= no_of_elements; j++)\n        {\n            if(A[j] < gcd || A[j]%gcd != 0 || is_connected_right[j - 1])\n            {\n                break;\n            }\n\n            is_connected_right[j - 1] = true;\n\n            weight += gcd;\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements - 1; i++)\n    {\n        if(!is_connected_right[i])\n        {\n            weight += p;\n        }\n    }\n\n    cout << weight << \"\\n\";\n}\n\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/GCD and MST Explanation.txt.txt",
    "content": "Let us visit the vertices in ascending order and check how many edges has this as the weight. \r\n\r\nIf A[i] >= P, then we will stop because we no longer need to check anything and can just add the P-edges\r\n\r\nNow, which vertices will have A[i] as the weight ? \r\n\r\nCheck the nearest j to the i as long as A[i, j] or A[j, i] are >= A[i] and divisible by A[i] \r\n\r\nWe will add another condition. \r\n\r\nMaintain a vector is_connected, which is true if A[i] is connected to the vertex A[i + 1], \r\neither directly or indirectly. \r\n\r\nWhen we are going left, we will stop at the first vertex j where is_connected[i] is true \r\nSince A[i] has been connected to A[j - 1] already, placing another edge between A[i], A[j] will create a cycle. \r\nMoreover, we are visiting the weights in ascending order so A[j] has been connected to A[j - 1] with less expensive edges.\r\n\r\nWhen we are going right, we will stop at the first vertex j where is_connected[j - 1] is true because this means that \r\nA[j], A[j - 1] are already connected and A[j] was connected to the tree using lighter edges\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, p;\r\n    cin >> no_of_elements >> p;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    vector <int> is_connected_right(no_of_elements + 1, false);\r\n    vector < pair <int, int> > values;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        values.push_back(make_pair(A[i], i));\r\n    }\r\n\r\n    sort(values.begin(), values.end());\r\n\r\n    long long weight = 0;\r\n    for(int i = 0; i < values.size(); i++)\r\n    {\r\n        int gcd = values[i].first, index = values[i].second;\r\n\r\n        if(gcd >= p)\r\n        {\r\n            break;\r\n        }\r\n\r\n        for(int j = index - 1; j >= 1; j--)\r\n        {\r\n            if(A[j] < gcd || A[j]%gcd != 0 || is_connected_right[j])\r\n            {\r\n                break;\r\n            }\r\n\r\n            is_connected_right[j] =  true;\r\n\r\n            weight += gcd;\r\n        }\r\n\r\n        for(int j = index + 1; j <= no_of_elements; j++)\r\n        {\r\n            if(A[j] < gcd || A[j]%gcd != 0 || is_connected_right[j - 1])\r\n            {\r\n                break;\r\n            }\r\n\r\n            is_connected_right[j - 1] = true;\r\n\r\n            weight += gcd;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements - 1; i++)\r\n    {\r\n        if(!is_connected_right[i])\r\n        {\r\n            weight += p;\r\n        }\r\n    }\r\n\r\n    cout << weight << \"\\n\";\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Explanations/Swapping Problem Explanation.txt.txt",
    "content": "Let us interpret the problem geometrically. \r\nWe have some segments [L, R] and must do some swaps to minimize the sum of segments. \r\n\r\nIt is best to swap some segments which intersect. If we swap segments which don't intersect, we will only increase the sum. \r\n\r\nLet us consider two intersecting segments \r\n\r\n[L1, R1], [L2, R2] \r\n\r\nL1 < L2 < R1 < R2 \r\n\r\nHere, if we swap (R1, R2), we will not be reducing the sum of segments. \r\nThe overlap between the two segments will remain [L2, R1] \r\n\r\nIf we have to reduce the sum of segments, we must swap a left with a right \r\n\r\nWe have to swap (L2, R2) \r\n\r\nThe situation is similar if one segment contains the other \r\n\r\nL1 < L2 < R2 < R1 \r\n\r\nIt is always better to swap a left point with a right point rather than 2 lefts or 2 rights\r\n\r\n-----\r\n\r\nSo, we will look at all the segments given to us. \r\n\r\nIf (A[i] < B[i]), we can swap the right \r\nIf (A[i] > B[i]), we can swap the left \r\n\r\nWe must always swap a left segment with a right segment. \r\n\r\nInstead of minimizing the sum, let us try to look for a pair of segments \r\n\r\n1. One is Left and the other is right \r\n2. Maximum overlap\r\n\r\n------\r\n\r\nIn both our sets L and R, we will keep track of the prefix maximum end point of each segment. \r\n\r\nThen, we will iterate over each segment. \r\n\r\nSuppose our current segment is in R, \r\n\r\nwe will look for the first segment in L such that \r\nThe starting point is <= A[i] \r\n\r\nThe ending point is the prefix maximum. \r\n\r\nThe overlap is min(R[i], prefix Maximum Left)\r\n\r\nWe will choose the segment which maximises the overlap. \r\n\r\nWe can use binary search in a map for this. \r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1), B(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> B[i];\r\n    }\r\n\r\n    map <int, int> X, Y;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] <= B[i])\r\n        {\r\n            X[A[i]] = max(X[A[i]], B[i]);\r\n        }\r\n        else\r\n        {\r\n            Y[B[i]] = max(Y[B[i]], A[i]);\r\n        }\r\n    }\r\n\r\n    update_prefix_max(X);\r\n    update_prefix_max(Y);\r\n\r\n    long long overlap = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long overlap_here = 0;\r\n\r\n        if(A[i] <= B[i])\r\n        {\r\n            auto it = Y.upper_bound(A[i]);\r\n\r\n            if(it != Y.begin())\r\n            {\r\n                it--;\r\n                int left = A[i], right = min(it->second, B[i]);\r\n\r\n                overlap_here = right - left;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            auto it = X.upper_bound(B[i]);\r\n\r\n            if(it != X.begin())\r\n            {\r\n                it--;\r\n\r\n                int left = B[i], right = min(it->second, A[i]);\r\n                overlap_here = right - left;\r\n            }\r\n        }\r\n\r\n        overlap = max(overlap, overlap_here);\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer += abs(A[i] - B[i]);\r\n    }\r\n\r\n    answer -= 2*overlap;\r\n\r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Programs/AND Sequences.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nlong long factorial(long long n, long long mod)\r\n{\r\n    long long answer = 1;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        answer = (answer*i)%mod;\r\n    }\r\n\r\n    return answer;\r\n}\r\n\r\nlong long choose_2(long long n, long long mod)\r\n{\r\n    long long answer = n*(n - 1);\r\n\r\n    return (answer%mod);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    long long array_and = (1LL << 60) - 1;\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        array_and &= A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long answer = choose_2(frequency[array_and], MOD)*factorial(no_of_elements - 2, MOD);\r\n\r\n    answer %= MOD;\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Programs/Add One.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 5, MOD = 1e9 + 7;\r\nint length[MAX_N];\r\n\r\nvoid precompute()\r\n{\r\n    for(int i = 0; i <= 8; i++)\r\n    {\r\n        length[i] = 2;\r\n    }\r\n\r\n    length[9] = 3;\r\n\r\n    for(int i = 10; i < MAX_N; i++)\r\n    {\r\n        length[i] = (length[i - 9] + length[i - 10])%MOD;\r\n    }\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int n, no_of_operations;\r\n    cin >> n >> no_of_operations;\r\n\r\n    long long answer = 0;\r\n    while(n > 0)\r\n    {\r\n        int digit = n%10;\r\n\r\n        long long this_length = (no_of_operations < 10 - digit ? 1 : length[no_of_operations - (10 - digit)]);\r\n\r\n        //cout << \"D = \" << digit << \" this = \" << this_length << \"\\n\";\r\n\r\n        n /= 10;\r\n\r\n        answer = (answer + this_length)%MOD;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n    precompute();\r\n\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Programs/Arrays and Peaks.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, no_of_peaks;\r\n    cin >> no_of_elements >> no_of_peaks;\r\n\r\n    if(no_of_peaks > no_of_elements/2 - (no_of_elements%2 == 0))\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        A[i] = i;\r\n    }\r\n\r\n    for(int i = 2, peaks = 0; peaks < no_of_peaks && i < no_of_elements; i += 2, peaks++)\r\n    {\r\n        swap(A[i], A[i + 1]);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << A[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Programs/Cost Equilibrium.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1e9 + 7, MAX_N = 1e5 + 5;\r\nvector <long long> factorial(MAX_N, 0), inverse_factorial(MAX_N, 0);\r\n\r\nlong long power_mod(long long x, long long power, long long mod)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%mod;\r\n\r\n        x = (x*x)%mod;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    factorial[0] = 1;\r\n    for(int i = 1; i < MAX_N; i++)\r\n    {\r\n        factorial[i] = (i*factorial[i - 1])%MOD;\r\n    }\r\n\r\n    //i*(i - 1)! = i!\r\n    inverse_factorial[MAX_N - 1] = power_mod(factorial[MAX_N - 1], MOD - 2, MOD);\r\n    for(int i = MAX_N - 2; i >= 0; i--)\r\n    {\r\n        inverse_factorial[i] = (i + 1)*inverse_factorial[i + 1];\r\n\r\n        inverse_factorial[i] %= MOD;\r\n    }\r\n}\r\n\r\nlong long multinomial(vector <long long> &frequency)\r\n{\r\n    long long total = 0;\r\n    long long numerator = 0, inverse_denominator = 1;\r\n\r\n    for(int i = 0; i < frequency.size(); i++)\r\n    {\r\n        total += frequency[i];\r\n\r\n        inverse_denominator *= inverse_factorial[frequency[i]];\r\n\r\n        inverse_denominator %= MOD;\r\n    }\r\n\r\n    numerator = factorial[total];\r\n\r\n    long long answer = (numerator*inverse_denominator)%MOD;\r\n\r\n    return answer;\r\n}\r\n\r\nlong long stars_and_bars(long long stars, long long bars)\r\n{\r\n    long long numerator = factorial[stars + bars - 1];\r\n    long long inverse_denominator = (inverse_factorial[stars]*inverse_factorial[bars - 1])%MOD;\r\n\r\n    return (numerator*inverse_denominator)%MOD;\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    map <int, int> frequency;\r\n    long long sum = 0;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        sum += A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    if(sum%no_of_elements != 0)\r\n    {\r\n        cout << \"0\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    int final_value = (sum/no_of_elements);\r\n\r\n    vector <long long> F, source_frequency, sink_frequency;\r\n\r\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        if(it->first > final_value)\r\n        {\r\n            source_frequency.push_back(it->second);\r\n        }\r\n        else if(it->first < final_value)\r\n        {\r\n            sink_frequency.push_back(it->second);\r\n        }\r\n\r\n        F.push_back(it->second);\r\n    }\r\n\r\n    long long answer;\r\n    if(source_frequency.size() == 0 || sink_frequency.size() == 0 ||\r\n       (source_frequency.size() == 1 && source_frequency[0] == 1) || (sink_frequency.size() == 1 && sink_frequency[0] == 1) )\r\n    {\r\n        answer = multinomial(F);\r\n\r\n        cout << answer << \"\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    long long sources = multinomial(source_frequency), sink = multinomial(sink_frequency);\r\n    long long equal_values = frequency[final_value], spaces = no_of_elements - equal_values + 1;\r\n\r\n    long long remaining = stars_and_bars(equal_values, spaces);\r\n\r\n    answer = (sources*sink)%MOD;\r\n    answer = (answer*remaining)%MOD;\r\n    answer = (answer*2)%MOD;;\r\n\r\n    cout << answer << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Programs/GCD and MST.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, p;\r\n    cin >> no_of_elements >> p;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    vector <int> is_connected_right(no_of_elements + 1, false);\r\n    vector < pair <int, int> > values;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        values.push_back(make_pair(A[i], i));\r\n    }\r\n\r\n    sort(values.begin(), values.end());\r\n\r\n    long long weight = 0;\r\n    for(int i = 0; i < values.size(); i++)\r\n    {\r\n        int gcd = values[i].first, index = values[i].second;\r\n\r\n        if(gcd >= p)\r\n        {\r\n            break;\r\n        }\r\n\r\n        for(int j = index - 1; j >= 1; j--)\r\n        {\r\n            if(A[j] < gcd || A[j]%gcd != 0 || is_connected_right[j])\r\n            {\r\n                break;\r\n            }\r\n\r\n            is_connected_right[j] =  true;\r\n\r\n            weight += gcd;\r\n        }\r\n\r\n        for(int j = index + 1; j <= no_of_elements; j++)\r\n        {\r\n            if(A[j] < gcd || A[j]%gcd != 0 || is_connected_right[j - 1])\r\n            {\r\n                break;\r\n            }\r\n\r\n            is_connected_right[j - 1] = true;\r\n\r\n            weight += gcd;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements - 1; i++)\r\n    {\r\n        if(!is_connected_right[i])\r\n        {\r\n            weight += p;\r\n        }\r\n    }\r\n\r\n    cout << weight << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/714 Division by Zero 2021/Programs/Swapping Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvoid update_prefix_max(map <int, int> &M)\n{\n    int prefix_max = 0;\n    for(auto it = M.begin(); it != M.end(); it++)\n    {\n        prefix_max = max(prefix_max, it->second);\n\n        it->second = prefix_max;\n    }\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1), B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    map <int, int> X, Y;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] <= B[i])\n        {\n            X[A[i]] = max(X[A[i]], B[i]);\n        }\n        else\n        {\n            Y[B[i]] = max(Y[B[i]], A[i]);\n        }\n    }\n\n    update_prefix_max(X);\n    update_prefix_max(Y);\n\n    long long overlap = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long overlap_here = 0;\n\n        if(A[i] <= B[i])\n        {\n            auto it = Y.upper_bound(A[i]);\n\n            if(it != Y.begin())\n            {\n                it--;\n                int left = A[i], right = min(it->second, B[i]);\n\n                overlap_here = right - left;\n            }\n        }\n        else\n        {\n            auto it = X.upper_bound(B[i]);\n\n            if(it != X.begin())\n            {\n                it--;\n\n                int left = B[i], right = min(it->second, A[i]);\n                overlap_here = right - left;\n            }\n        }\n\n        overlap = max(overlap, overlap_here);\n    }\n\n    long long answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        answer += abs(A[i] - B[i]);\n    }\n\n    answer -= 2*overlap;\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/716 Div 2/Programs/Product 1 mod N.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    vector <int> subsequence;\n    long long product = 1;\n    for(int i = 1; i <= n - 2; i++)\n    {\n        if(__gcd(i, n) == 1)\n        {\n            product = (product*i)%n;\n\n            subsequence.push_back(i);\n        }\n    }\n\n    if(product == n - 1)\n    {\n        product = (product*(n - 1))%n;\n\n        subsequence.push_back(n - 1);\n    }\n\n    cout << subsequence.size() << \"\\n\";\n    for(int i = 0; i < subsequence.size(); i++)\n    {\n        cout << subsequence[i] << \" \";\n    }\n    cout << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/722/Explanations/Parsa and Humungous Tree Explanation.txt",
    "content": "In the optimal value, every vertex will either be set to the left or right extreme. \n\nLet us consider some assignment of values to the tree and let v be some vertex which is not set to it's optimal value. \nWe will show that assigning v = L[v] or v = R[v] will not result in a smaller answer \nAnd the answer will either increase or stay the same. \n\n- Let there be X neighbours with value smaller than v and Y neighbours with a larger value.\n- If X > Y, we can set v = R_v and get a larger answer.\n    - Increasing v by 1, increases the sum by X - Y\n- Similarly, if X < Y, we can set  v = L_v for a larger answer.\n- If X = Y, we can set it to either L_v, R_v and the answer will not change.\n\n-----\n\nLet f(v, L) and f(v, R) be the maximum value for the subtree rooted at v, if v is set \nto L[v] or R[v] respectively. \n\nIn order to transition, we will visit each of it's children c \nand check if it's better for this child to be set to it's left or right extreme. \n\nf(v, L) += max{|L[v] - L[c]| + f(c, L), |L[v] - R[c]| + f(c, R)}\nf(v, R) += max{|R[v] - L[c]| + f(c, L), |R[v] - R[c]| + f(c, R)}\n\n-----\n\nvoid dfs(int v, int parent_v)\n{\n    for(int child_v : tree[v])\n    {\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        dfs(child_v, v);\n\n        long long using_left_value_at_child = abs(left_value[v] - left_value[child_v]) + maximum_at[child_v][L];\n        long long using_right_value_at_child = abs(left_value[v] - right_value[child_v]) + maximum_at[child_v][R];\n\n        maximum_at[v][L] += max(using_left_value_at_child, using_right_value_at_child);\n\n        using_left_value_at_child = abs(right_value[v] - left_value[child_v]) + maximum_at[child_v][L];\n        using_right_value_at_child = abs(right_value[v] - right_value[child_v]) + maximum_at[child_v][R];\n\n        maximum_at[v][R] += max(using_left_value_at_child, using_right_value_at_child);\n    }\n\n    /*cout << \"At \" << v << \" L = \" << left_value[v] << \" Maximum = \" << maximum_at[v][L] << \"\\n\";\n    cout << \"At \" << v << \" R = \" << right_value[v] << \" Maximum = \" << maximum_at[v][R] << \"\\n\";*/\n}\n"
  },
  {
    "path": "2021/Div 2/722/Programs/Parsa and Humungous Tree.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MAX_ENDS = 2, L = 0, R = 1;\nvector <int> tree[MAX_N];\nlong long maximum_at[MAX_N][MAX_ENDS], left_value[MAX_N], right_value[MAX_N];\n\nvoid initialize(int no_of_vertices)\n{\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        tree[i].clear();\n        maximum_at[i][L] = maximum_at[i][R] = 0;\n    }\n}\n\nvoid dfs(int v, int parent_v)\n{\n    for(int child_v : tree[v])\n    {\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        dfs(child_v, v);\n\n        long long using_left_value_at_child = abs(left_value[v] - left_value[child_v]) + maximum_at[child_v][L];\n        long long using_right_value_at_child = abs(left_value[v] - right_value[child_v]) + maximum_at[child_v][R];\n\n        maximum_at[v][L] += max(using_left_value_at_child, using_right_value_at_child);\n\n        using_left_value_at_child = abs(right_value[v] - left_value[child_v]) + maximum_at[child_v][L];\n        using_right_value_at_child = abs(right_value[v] - right_value[child_v]) + maximum_at[child_v][R];\n\n        maximum_at[v][R] += max(using_left_value_at_child, using_right_value_at_child);\n    }\n\n    /*cout << \"At \" << v << \" L = \" << left_value[v] << \" Maximum = \" << maximum_at[v][L] << \"\\n\";\n    cout << \"At \" << v << \" R = \" << right_value[v] << \" Maximum = \" << maximum_at[v][R] << \"\\n\";*/\n}\n\nvoid solve()\n{\n    int no_of_vertices;\n    cin >> no_of_vertices;\n\n    initialize(no_of_vertices);\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        cin >> left_value[i] >> right_value[i];\n    }\n\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].push_back(v);\n        tree[v].push_back(u);\n    }\n\n    dfs(1, 0);\n\n    cout << max(maximum_at[1][L], maximum_at[1][R]) << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/724/Diluc and Kaeye Explanation.txt",
    "content": "If the array is partitioned into K parts, each of which have a ratio of p/q \n\nThe ratio of the whole array is p/q\n\nLook at the ratio of the the current subarray [1, i]. Suppose it is (P/Q) in the lowest terms. \nWe need to search for the rightmost occurrence of the same ratio.\nSuppose it is j \n \nP(i) = 1 + P(j)\n\nWhere P(i) is the number of parts that we can divide [1, i] in. \nThis is optimal because [j + 1, i] is the smallest part with ratio P/Q that ends at i. \nAnd we are adding the maximum number of parts that end at j\n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n \n    vector <int> sum_d(length, 0), sum_k(length, 0);\n    for(int i = 0; i < length; i++)\n    {\n        if(i > 0)\n        {\n            sum_d[i] = sum_d[i - 1];\n            sum_k[i] = sum_k[i - 1];\n        }\n \n        switch(S[i])\n        {\n            case 'D': sum_d[i]++; break;\n            case 'K': sum_k[i]++; break;\n        }\n    }\n \n    map <pair <int, int>, int> last_occurrence;\n    vector <int> answer(length, 1);\n    for(int i = 0; i < length; i++)\n    {\n        pair <int, int> ratio_here = make_pair(sum_d[i], sum_k[i]);\n        ratio_here.first /= __gcd(sum_d[i], sum_k[i]);\n        ratio_here.second /= __gcd(sum_d[i], sum_k[i]);\n \n        if(last_occurrence.find(ratio_here) != last_occurrence.end())\n        {\n            answer[i] = 1 + answer[last_occurrence[ratio_here]];\n        }\n \n        last_occurrence[ratio_here] = i;\n    }\n \n    for(int i = 0; i < length; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/724/Explanations/Diluc and Kaeye Explanation.txt",
    "content": "If the array is partitioned into K parts, each of which have a ratio of p/q \n\nThe ratio of the whole array is p/q\n\nLook at the ratio of the the current subarray [1, i]. Suppose it is (P/Q) in the lowest terms. \nWe need to search for the rightmost occurrence of the same ratio.\nSuppose it is j \n \nP(i) = 1 + P(j)\n\nWhere P(i) is the number of parts that we can divide [1, i] in. \nThis is optimal because [j + 1, i] is the smallest part with ratio P/Q that ends at i. \nAnd we are adding the maximum number of parts that end at j\n\n-----\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n \n    vector <int> sum_d(length, 0), sum_k(length, 0);\n    for(int i = 0; i < length; i++)\n    {\n        if(i > 0)\n        {\n            sum_d[i] = sum_d[i - 1];\n            sum_k[i] = sum_k[i - 1];\n        }\n \n        switch(S[i])\n        {\n            case 'D': sum_d[i]++; break;\n            case 'K': sum_k[i]++; break;\n        }\n    }\n \n    map <pair <int, int>, int> last_occurrence;\n    vector <int> answer(length, 1);\n    for(int i = 0; i < length; i++)\n    {\n        pair <int, int> ratio_here = make_pair(sum_d[i], sum_k[i]);\n        ratio_here.first /= __gcd(sum_d[i], sum_k[i]);\n        ratio_here.second /= __gcd(sum_d[i], sum_k[i]);\n \n        if(last_occurrence.find(ratio_here) != last_occurrence.end())\n        {\n            answer[i] = 1 + answer[last_occurrence[ratio_here]];\n        }\n \n        last_occurrence[ratio_here] = i;\n    }\n \n    for(int i = 0; i < length; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/724/Programs/Diluc and Kaeya.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    vector <int> sum_d(length, 0), sum_k(length, 0);\n    for(int i = 0; i < length; i++)\n    {\n        if(i > 0)\n        {\n            sum_d[i] = sum_d[i - 1];\n            sum_k[i] = sum_k[i - 1];\n        }\n\n        switch(S[i])\n        {\n            case 'D': sum_d[i]++; break;\n            case 'K': sum_k[i]++; break;\n        }\n    }\n\n    map <pair <int, int>, int> last_occurrence;\n    vector <int> answer(length, 1);\n    for(int i = 0; i < length; i++)\n    {\n        pair <int, int> ratio_here = make_pair(sum_d[i], sum_k[i]);\n        ratio_here.first /= __gcd(sum_d[i], sum_k[i]);\n        ratio_here.second /= __gcd(sum_d[i], sum_k[i]);\n\n        if(last_occurrence.find(ratio_here) != last_occurrence.end())\n        {\n            answer[i] = 1 + answer[last_occurrence[ratio_here]];\n        }\n\n        last_occurrence[ratio_here] = i;\n    }\n\n    for(int i = 0; i < length; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n \n"
  },
  {
    "path": "2021/Div 2/724/Programs/Omkar and Bad Story.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    int has_negative = false;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        if(A[i] < 0)\r\n        {\r\n            has_negative = true;\r\n        }\r\n    }\r\n\r\n    if(has_negative)\r\n    {\r\n        cout << \"NO\\n\";\r\n\r\n        return ;\r\n    }\r\n\r\n    int length = 300;\r\n    cout << \"YES\\n\";\r\n    cout << length << \"\\n\";\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        cout << i << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/724/Programs/Omkar and Forest.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long power_mod(long long x, long long power, long long mod)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%mod;\r\n\r\n        x = (x*x)%mod;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int rows, columns;\r\n    cin >> rows >> columns;\r\n\r\n    vector <string> grid(rows);\r\n    for(int i = 0; i < rows; i++)\r\n    {\r\n        cin >> grid[i];\r\n    }\r\n\r\n    const char FREE_SPACE = '#';\r\n    int free_spaces = 0;\r\n    for(int r = 0; r < rows; r++)\r\n    {\r\n        for(int c = 0; c < columns; c++)\r\n        {\r\n            free_spaces += (grid[r][c] == FREE_SPACE);\r\n        }\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long answer = power_mod(2, free_spaces, MOD);\r\n\r\n    if(free_spaces == rows*columns)\r\n    {\r\n        answer = (answer + MOD - 1)%MOD;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 2/724/Programs/Prinzessin der Verurteilung.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_LENGTH = 1e4;\r\nvector <string> lexicographic_order;\r\nvoid precompute()\r\n{\r\n    const int NO_OF_ALPHABETS = 26;\r\n    for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\r\n    {\r\n        string now;\r\n\r\n        now += (char)('a' + alpha);\r\n\r\n        lexicographic_order.push_back(now);\r\n    }\r\n\r\n    for(int p = 0; lexicographic_order.size() < MAX_LENGTH; p++)\r\n    {\r\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\r\n        {\r\n            string now = lexicographic_order[p] + (char)('a' + alpha);\r\n\r\n            lexicographic_order.push_back(now);\r\n        }\r\n    }\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    set <string> distinct;\r\n    for(int left = 0; left < length; left++)\r\n    {\r\n        string current;\r\n\r\n        for(int right = left; right < length; right++)\r\n        {\r\n            current += S[right];\r\n\r\n            distinct.insert(current);\r\n        }\r\n    }\r\n\r\n    for(string current : lexicographic_order)\r\n    {\r\n        if(distinct.count(current) == 0)\r\n        {\r\n            cout << current << \"\\n\";\r\n\r\n            return ;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 2/726/Explanations/Arithemtic Array Explanation.txt.txt",
    "content": "(a1 + a2 + ... + ak)/k = 1 => (a1 + a2 + ... + ak) = k \r\n\r\nIf the sum is < N, then we only need to append one element to make the sum = N + 1 \r\n\r\nIf the sum is > N, we will keep appending 0's till the sum is equal to the number of elements \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    int sum = 0;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n        sum += A[i];\r\n    }\r\n\r\n    int answer = 0;\r\n\r\n    if(sum > no_of_elements)\r\n    {\r\n        answer = sum - no_of_elements;\r\n    }\r\n    else if(sum < no_of_elements)\r\n    {\r\n        answer = 1;\r\n    }\r\n    else if(sum == no_of_elements)\r\n    {\r\n        answer = 0;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/726/Explanations/Bad Boy Explanation.txt.txt",
    "content": "We will choose the end point that is furthest from (i, j), and then put the other yo-yo at the diagonally opposite end.\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int rows, columns, i, j;\r\n    cin >> rows >> columns >> i >> j;\r\n\r\n    int x1 = (2*i <= rows ? rows : 1);\r\n    int y1 = (2*j <= columns ? columns : 1);\r\n\r\n    int x2 = (x1 == 1 ? rows : 1);\r\n    int y2 = (y1 == 1 ? columns : 1);\r\n\r\n    cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/726/Explanations/Challenging Cliffs Explanation.txt.txt",
    "content": "If there are x pairs (A[i], A[i + 1]) such that A[i] <= A[i + 1] \r\nin the original sorted array, we can have (x - 1) such pairs in the answer. \r\n\r\nOriginally, there are (N - 1) such pairs, so the answer will have at least (N - 2)\r\n\r\nFirst, sort the array and choose the pair (A[i], A[i + 1]) that has the minimum A[i + 1] - A[i] \r\nNow, the answer array is this - \r\n\r\nA[i] + A[i + 2, N] + A[1, i - 2] + A[i] \r\n\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(all(A));\r\n    int best_1 = 1;\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] - A[i - 1] < A[best_1 + 1] - A[best_1])\r\n        {\r\n            best_1 = i - 1;\r\n        }\r\n    }\r\n\r\n    vector <int> answer(no_of_elements + 1);\r\n    answer[1] = A[best_1];\r\n    answer[no_of_elements] = A[best_1 + 1];\r\n\r\n    int p = 2;\r\n    for(int i = best_1 + 2; i <= no_of_elements; i++)\r\n    {\r\n        answer[p++] = A[i];\r\n    }\r\n    for(int i = 1; i < best_1; i++)\r\n    {\r\n        answer[p++] = A[i];\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << answer[i] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 2/726/Explanations/Deleting Divisors Explanation.txt.txt",
    "content": "The game ends when n is prime or = 1 \r\nAll primes are odd integers, except 2. \r\n\r\nIf we had a strategy where we could ensure that n is odd after our turn and even before our turn, \r\nwe would ensure that the final state only occurs after our move. \r\n\r\nWe can do this whenever n is not a power of 2 !\r\n\r\n------\r\n\r\nWhen n is not a power of 2, n has at least one odd divisor. \r\nWe will subtract that to give our opponent an odd integer. \r\n\r\nAll of an odd integer's divisors are odd. \r\nSubtracting any of them gives us an even integer. \r\nFurther, we get an even integer that is not a power of 2. \r\n\r\nThe reason is that if d|N => d|(N - d) because N = 0 (mod d) => N - d = 0 (mod d)\r\n\r\nSo, even integers that are not powers of 2 are winning and odd integers are losing. \r\n\r\n------\r\n\r\nWhat happens for 2^p ? \r\nWhen we have a power of 2, subtracting one of it's divisors results in either an even integer that is not a power of 2 or 2^{p - 1} \r\n\r\nConverting it to an integer that is not a power of 2 is a losing move as the other player can win \r\nwith the strategy outlined above. \r\n\r\n2^1 is winning for the second player\r\n2^2 is winning for the first player.\r\n2^3 is winning for the second player and so on. \r\n\r\nSuppose by Mathematical Induction, that all odd powers of 2 are winning for Player 2 and even powers for Player 1 till 2^k\r\n2^{k + 1} is winning for the first player only if 2^k is winning for the second player.\r\n\r\nSo, 2^{k + 1} is winning only if (k + 1) is even.\r\n\r\n------\r\n\r\nPractical Solution During the Contest - Pattern Recognition\r\n\r\n- I precomputed the answer of the first $100$ integers and \r\nfound that the second player was winning all odd integers and the first player was winning all even integers.\r\n- After getting $WA$ on the second test case, I looked for exceptions to this rule till $10^6$. \r\n\r\nI checked if there are any even integers where the second player wins or odd integers where the first player wins.\r\n    - I found out that the second player wins whenever $n = 2^p$ and $p$ is odd\r\n\r\nvoid precompute()\r\n{\r\n    int N = 1e7;\r\n    vector <int> winner(N + 1, 0);\r\n    for(int i = 1; i <= N; i++)\r\n    {\r\n        //cout << i << \" \";\r\n        if(i == 1 || is_prime(i))\r\n        {\r\n            //cout << \" Winner = 2 Prime\\n\";\r\n            winner[i] = 2;\r\n            continue;\r\n        }\r\n \r\n        for(int d = 2; d*d <= i; d++)\r\n        {\r\n            if(i%d != 0)\r\n            {\r\n                continue;\r\n            }\r\n \r\n            if(winner[i - d] == 2 || winner[i - i/d] == 2)\r\n            {\r\n                winner[i] = 1;\r\n                //cout << \"Winner 1\\n\";\r\n                continue;\r\n            }\r\n        }\r\n        if(winner[i] == 0)\r\n            winner[i] = 2;\r\n        //cout << \"Winner 2\\n\";\r\n    }\r\n \r\n    cout << \"***\\n\";\r\n    for(int i = 1; i <= N; i++)\r\n    {\r\n        if(winner[i]%2 == i%2)\r\n        {cout << \"i = \" << i << \" Winner = \" << winner[i] << \"\\n\";\r\n         factorise(i);\r\n        }\r\n    }\r\n}"
  },
  {
    "path": "2021/Div 2/726/Explanations/Erase and Extend (Easy Version) Explanation.txt",
    "content": "The optimal answer consists of some prefix repeated again and again. \nWe will perform some number of deletes and then only perform duplications. \n\nSuppose, we perform a deletion step after a duplication step and then do another duplication, \nif we get a smaller string, we could just do the same deletion before the first deletion step and get a smaller string. \n\nGo through all prefixes and iterate over the final string and choose the minimum\n\n-----\n\nstring concatenate_prefix(string S, int prefix, int k)\n{\n    string answer;\n    for(int i = 0; i < k; i++)\n    {\n        answer += S[i%prefix];\n    }\n    return answer;\n}\n\nint main()\n{\n    int length, k;\n    cin >> length >> k;\n    string S;\n    cin >> S;\n\n    string answer = concatenate_prefix(S, length, k);\n    for(int i = 1; i <= S.size(); i++)\n    {\n        string current = concatenate_prefix(S, i, k);\n        if(current < answer)\n        {\n            answer = current;\n        }\n\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/726/Programs/Arithmetic Array.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    int sum = 0;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n        sum += A[i];\r\n    }\r\n\r\n    int answer = 0;\r\n\r\n    if(sum > no_of_elements)\r\n    {\r\n        answer = sum - no_of_elements;\r\n    }\r\n    else if(sum < no_of_elements)\r\n    {\r\n        answer = 1;\r\n    }\r\n    else if(sum == no_of_elements)\r\n    {\r\n        answer = 0;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/726/Programs/Bad Boy.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int rows, columns, i, j;\r\n    cin >> rows >> columns >> i >> j;\r\n\r\n    int x1 = (2*i <= rows ? rows : 1);\r\n    int y1 = (2*j <= columns ? columns : 1);\r\n\r\n    int x2 = (x1 == 1 ? rows : 1);\r\n    int y2 = (y1 == 1 ? columns : 1);\r\n\r\n    cout << x1 << \" \" << y1 << \" \" << x2 << \" \" << y2 << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 2/726/Programs/Challenging Cliffs.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(all(A));\r\n    int best_1 = 1;\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] - A[i - 1] < A[best_1 + 1] - A[best_1])\r\n        {\r\n            best_1 = i - 1;\r\n        }\r\n    }\r\n\r\n    vector <int> answer(no_of_elements + 1);\r\n    answer[1] = A[best_1];\r\n    answer[no_of_elements] = A[best_1 + 1];\r\n\r\n    int p = 2;\r\n    for(int i = best_1 + 2; i <= no_of_elements; i++)\r\n    {\r\n        answer[p++] = A[i];\r\n    }\r\n    for(int i = 1; i < best_1; i++)\r\n    {\r\n        answer[p++] = A[i];\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << answer[i] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/726/Programs/Deleting Divisors.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_prime(int n)\r\n{\r\n    for(int i = 2; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint is_odd_power_of_2(int n)\r\n{\r\n    int exponent = 0;\r\n\r\n    while(n%2 == 0)\r\n    {\r\n        n /= 2;\r\n        exponent++;\r\n    }\r\n\r\n    return (n == 1 && exponent%2 == 1);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    if(is_prime(n) || n == 1 || is_odd_power_of_2(n))\r\n    {\r\n        cout << \"Bob\\n\";\r\n        return;\r\n    }\r\n\r\n    cout << (n%2 == 1 ? \"Bob\" : \"Alice\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 2/726/Programs/Erase and Extend (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstring concatenate_prefix(string S, int prefix, int k)\n{\n    string answer;\n    for(int i = 0; i < k; i++)\n    {\n        answer += S[i%prefix];\n    }\n    return answer;\n}\n\nint main()\n{\n    int length, k;\n    cin >> length >> k;\n    string S;\n    cin >> S;\n\n    string answer = concatenate_prefix(S, length, k);\n    for(int i = 1; i <= S.size(); i++)\n    {\n        string current = concatenate_prefix(S, i, k);\n        if(current < answer)\n        {\n            answer = current;\n        }\n\n    }\n\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/726/Programs/Figure Fixing.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int UNCOLOURED = -1, RED = 0, BLUE = 1;\r\n\r\nint other(int colour)\r\n{\r\n    return (1 - colour);\r\n}\r\n\r\nint dfs_bipartite_check(vector <vector <int> > &graph, int v, vector <int> &C, int colour)\r\n{\r\n    C[v] = colour; //cout << \"Colour \" << v << \" = \" << C[v] << \"\\n\";\r\n\r\n    for(int child_v : graph[v])\r\n    {\r\n        if(C[child_v] == C[v])\r\n        {   //cout << v << \" and \" << child_v << \" have the same colour\\n\";\r\n            return false;\r\n        }\r\n\r\n        if(C[child_v] == UNCOLOURED)\r\n        {\r\n            if(!dfs_bipartite_check(graph, child_v, C, other(colour)))\r\n            {\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    vector <int> value(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> value[i];\r\n    }\r\n\r\n    vector <int> target(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> target[i];\r\n    }\r\n\r\n    vector <vector <int> > graph(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    vector <int> colour(no_of_vertices + 1, UNCOLOURED);\r\n    int is_bipartite = dfs_bipartite_check(graph, 1, colour, RED);\r\n\r\n    long long red_remaining = 0, blue_remaining = 0, total_remaining = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        switch(colour[i])\r\n        {\r\n            case RED : red_remaining += (target[i] - value[i]); break;\r\n            case BLUE : blue_remaining += (target[i] - value[i]); break;\r\n        }\r\n\r\n        total_remaining += (target[i] - value[i]);\r\n    }\r\n\r\n    int possible; //cout << \"Bipartite = \" << is_bipartite << \"\\n\";\r\n\r\n    if(is_bipartite)\r\n    {\r\n        possible = (red_remaining == blue_remaining);\r\n    }\r\n    else\r\n    {\r\n        possible = (total_remaining%2 == 0);\r\n    }\r\n\r\n    cout << (possible ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/727/Explanations/Constest Start Time Explanation.txt",
    "content": "Every body takes the same amount of time for a contest. A person conflicts only with those people who started after him. \n\nWe need to count the number of new beginnings in [i.x, i.x + T] \nThis is the same as counting the number of multiples of x in [0, T] = (T/x)\n\nHowever, a person will not have (T/x) conflicts if there aren't (T/x) people remaining. \n\nThe last person has 0 conflicts \nThe second last has 1 \nThe third last hast 2 \n.\nThe (T/x)-th has (T/x) - 1 \n\nSo, for the last (T/x) - 1 people, the number of conflicts is \n\n0 + 1 + 2 + 3 + ... + (T/x) - 1 \n\nFor everyone else, the conflicts is (T/x)\n\n------\n\nlong long get_sum(long long n)\n{\n    return (n*(n + 1))/2;\n}\n\nvoid solve()\n{\n    int no_of_contestants, start_time, duration;\n    cin >> no_of_contestants >> start_time >> duration;\n\n    long long answer;\n    long long batch_1 = min(no_of_contestants, duration/start_time);\n\n    answer = get_sum(batch_1 - 1);\n    no_of_contestants -= batch_1;\n\n    long long one_contestant_intersections = duration/start_time;\n    answer += no_of_contestants*(one_contestant_intersections);\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/727/Explanations/Love Song Explanation.txt.txt",
    "content": "Find the frequency of each alphabet in each range. \r\nThe i-th alphabet contributes i x sum(i) to the whole answer\r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int length, no_of_queries;\r\n    string S;\r\n    cin >> length >> no_of_queries >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <vector <int> > frequency(NO_OF_ALPHABETS, vector <int> (length + 1, 0));\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\r\n        {\r\n            frequency[alpha][i] = frequency[alpha][i - 1];\r\n        }\r\n        frequency[S[i - 1] - 'a'][i]++;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        int left, right;\r\n        cin >> left >> right;\r\n\r\n        long long length = 0;\r\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\r\n        {\r\n            long long frequency_here = frequency[alpha][right] - frequency[alpha][left - 1];\r\n\r\n            length += (alpha + 1)*frequency_here;\r\n        }\r\n\r\n        cout << length << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "2021/Div 2/727/Explanations/Price Fixed Explanation.txt.txt",
    "content": "Sort the items in descending order of B. \r\nEach item costs the same so we want to buy as many items for cost 1 as possible. \r\n\r\nGo through the items one by one. \r\n\r\nHave 2 pointers L and R \r\nL points to the first available element in the prefix and R to the suffix. \r\n\r\nAt each point, check if \r\n\r\n1. We have bought enough items to avail the discount at R and buy item R at a discount\r\n2. If not, is it possible to partially buy the items at L and then use the discount for R \r\n3. If not, buy L completely and increment L \r\n\r\n-----\r\n\r\nint sort_by_second(pair <long long, long long> &P, pair <long long, long long> &Q)\r\n{\r\n    if(P.second == Q.second)\r\n    {\r\n        return (P.first > Q.first);\r\n    }\r\n\r\n    return (P.second > Q.second);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <pair <long long, long long> > A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i].first >> A[i].second;\r\n    }\r\n\r\n    sort(A.begin() + 1, A.end(), sort_by_second);\r\n    /*for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << A[i].first << \" \" << A[i].second << \"\\n\";\r\n    }*/\r\n\r\n    long long total = 0, cost = 0;\r\n    for(int left = 1, right = no_of_elements; left <= right; )\r\n    {\r\n        if(total >= A[right].second)\r\n        {\r\n            cost += A[right].first;\r\n            total += A[right].first; //cout << \"Buying R = \" << right << \" Cost = \" << cost << \" Total = \" << total << \"\\n\";\r\n\r\n            right--;\r\n            continue;\r\n        }\r\n\r\n        if(total + A[left].first < A[right].second)\r\n        {\r\n            cost += 2*A[left].first;\r\n            total += A[left].first; //cout << \"Buying L = \" << left << \" Cost = \" << cost << \" Total = \" << total << \"\\n\";\r\n\r\n            left++;\r\n            continue;\r\n        }\r\n\r\n        long long remaining_2 = A[right].second - total;\r\n\r\n        cost += 2*remaining_2;\r\n        total += remaining_2; //cout << \"Buying L = \" << left << \" Cost = \" << cost << \" Total = \" << total;\r\n\r\n        A[left].first -= remaining_2; //cout << \" New Left = \" << A[left].first << \"\\n\";\r\n    }\r\n\r\n    cout << cost << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/727/Explanations/Stable Groups Explanation.txt.txt",
    "content": "Keep track of all differences that are > x \r\n\r\nPut them in a priority queue and work on the smallest difference at each time. \r\n\r\nIn order to split an integer N into parts such that each of them is <= x, we need N/x - 1 cuts\r\n\r\nCheck if there are enough operations to cut the current part and then cut them accordingly.\r\n\r\nIt is similar to the problem Carrots for Rabbits\r\n-----\r\n\r\nlong long ceil(long long numerator, long long denominator)\r\n{\r\n    return (numerator/denominator) + (numerator%denominator != 0);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    long long new_additions, difference;\r\n    cin >> no_of_elements >> new_additions >> difference;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(all(A));\r\n\r\n    priority_queue <long long, vector <long long>, greater <long long> > PQ;\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] - A[i - 1] > difference)\r\n        {\r\n            PQ.push(A[i] - A[i - 1]);\r\n        }\r\n    }\r\n\r\n    while(new_additions > 0 && PQ.size() > 0)\r\n    {\r\n        long long current = PQ.top(); //cout << \"Current = \" << current << \"\\n\";\r\n\r\n        long long required_new_additions = ceil(current,difference) - 1;\r\n\r\n        long long possible_additions = min(required_new_additions, new_additions);\r\n\r\n        if(possible_additions >= required_new_additions)\r\n        {\r\n            PQ.pop();\r\n        }\r\n\r\n        new_additions -= possible_additions; //cout << \"Operations = \" << new_additions << \"\\n\";\r\n    }\r\n\r\n    int groups = PQ.size() + 1;\r\n    cout << groups << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/727/Programs/Contest Start.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long get_sum(long long n)\r\n{\r\n    return (n*(n + 1))/2;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_contestants, start_time, duration;\r\n    cin >> no_of_contestants >> start_time >> duration;\r\n\r\n    long long answer;\r\n    long long batch_1 = min(no_of_contestants, duration/start_time);\r\n\r\n    answer = get_sum(batch_1 - 1);\r\n    no_of_contestants -= batch_1;\r\n\r\n    long long one_contestant_intersections = duration/start_time;\r\n    answer += no_of_contestants*(one_contestant_intersections);\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 2/727/Programs/Love Song.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, no_of_queries;\r\n    string S;\r\n    cin >> length >> no_of_queries >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <vector <int> > frequency(NO_OF_ALPHABETS, vector <int> (length + 1, 0));\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\r\n        {\r\n            frequency[alpha][i] = frequency[alpha][i - 1];\r\n        }\r\n        frequency[S[i - 1] - 'a'][i]++;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        int left, right;\r\n        cin >> left >> right;\r\n\r\n        long long length = 0;\r\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\r\n        {\r\n            long long frequency_here = frequency[alpha][right] - frequency[alpha][left - 1];\r\n\r\n            length += (alpha + 1)*frequency_here;\r\n        }\r\n\r\n        cout << length << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/727/Programs/PriceFixed.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint sort_by_second(pair <long long, long long> &P, pair <long long, long long> &Q)\n{\n    if(P.second == Q.second)\n    {\n        return (P.first > Q.first);\n    }\n\n    return (P.second > Q.second);\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <pair <long long, long long> > A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i].first >> A[i].second;\n    }\n\n    sort(A.begin() + 1, A.end(), sort_by_second);\n    /*for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << A[i].first << \" \" << A[i].second << \"\\n\";\n    }*/\n\n    long long total = 0, cost = 0;\n    for(int left = 1, right = no_of_elements; left <= right; )\n    {\n        if(total >= A[right].second)\n        {\n            cost += A[right].first;\n            total += A[right].first; //cout << \"Buying R = \" << right << \" Cost = \" << cost << \" Total = \" << total << \"\\n\";\n\n            right--;\n            continue;\n        }\n\n        if(total + A[left].first < A[right].second)\n        {\n            cost += 2*A[left].first;\n            total += A[left].first; //cout << \"Buying L = \" << left << \" Cost = \" << cost << \" Total = \" << total << \"\\n\";\n\n            left++;\n            continue;\n        }\n\n        long long remaining_2 = A[right].second - total;\n\n        cost += 2*remaining_2;\n        total += remaining_2; //cout << \"Buying L = \" << left << \" Cost = \" << cost << \" Total = \" << total;\n\n        A[left].first -= remaining_2; //cout << \" New Left = \" << A[left].first << \"\\n\";\n    }\n\n    cout << cost << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/727/Programs/Stable Groups.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <queue>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nlong long ceil(long long numerator, long long denominator)\r\n{\r\n    return (numerator/denominator) + (numerator%denominator != 0);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    long long new_additions, difference;\r\n    cin >> no_of_elements >> new_additions >> difference;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(all(A));\r\n\r\n    priority_queue <long long, vector <long long>, greater <long long> > PQ;\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] - A[i - 1] > difference)\r\n        {\r\n            PQ.push(A[i] - A[i - 1]);\r\n        }\r\n    }\r\n\r\n    while(new_additions > 0 && PQ.size() > 0)\r\n    {\r\n        long long current = PQ.top(); //cout << \"Current = \" << current << \"\\n\";\r\n\r\n        long long required_new_additions = ceil(current,difference) - 1;\r\n\r\n        long long possible_additions = min(required_new_additions, new_additions);\r\n\r\n        if(possible_additions >= required_new_additions)\r\n        {\r\n            PQ.pop();\r\n        }\r\n\r\n        new_additions -= possible_additions; //cout << \"Operations = \" << new_additions << \"\\n\";\r\n    }\r\n\r\n    int groups = PQ.size() + 1;\r\n    cout << groups << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 2/740/Programs/Deep Down Below Binary Search.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint possible(vector <pair <long long, long long> > &L, long long x)\n{\n    for(int i = 0; i < L.size(); i++)\n    {\n        if(x < L[i].first)\n        {\n            return false;\n        }\n\n        x += L[i].second;\n    }\n\n    return true;\n}\n\nvoid solve()\n{\n    int no_of_levels;\n    cin >> no_of_levels;\n\n    vector <pair <long long, long long> > level;\n    for(int i = 1; i <= no_of_levels; i++)\n    {\n        int no_of_monsters;\n        cin >> no_of_monsters;\n\n        long long power = 0, increment = no_of_monsters;\n        for(int j = 1; j <= no_of_monsters; j++)\n        {\n            long long x;\n            cin >> x;\n\n            power = max(power, x + 1 - (j - 1));\n        }\n\n        level.push_back(make_pair(power, increment));\n    }\n\n    sort(level.begin(), level.end());\n\n    long long left = 0, right = 1e18;\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n\n        if(possible(level, mid))\n        {\n            right = mid;\n        }\n        else\n        {\n            left = mid;\n        }\n    }\n\n    cout << right << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n\n\n"
  },
  {
    "path": "2021/Div 2/740/Programs/Deep Down Below.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint possible(vector <pair <long long, long long> > &L, long long x)\n{\n    for(int i = 0; i < L.size(); i++)\n    {\n        if(x < L[i].first)\n        {\n            return false;\n        }\n\n        x += L[i].second;\n    }\n\n    return true;\n}\n\nvoid solve()\n{\n    int no_of_levels;\n    cin >> no_of_levels;\n\n    vector <pair <long long, long long> > level;\n    for(int i = 1; i <= no_of_levels; i++)\n    {\n        int no_of_monsters;\n        cin >> no_of_monsters;\n\n        long long power = 0, increment = no_of_monsters;\n        for(int j = 1; j <= no_of_monsters; j++)\n        {\n            long long x;\n            cin >> x;\n\n            power = max(power, x + 1 - (j - 1));\n        }\n\n        level.push_back(make_pair(power, increment));\n    }\n\n    sort(level.begin(), level.end());\n\n    long long total_increment = 0, power_required = 0;\n    for(int i = 0; i < no_of_levels; i++)\n    {\n        power_required = max(power_required, level[i].first - total_increment);\n        total_increment += level[i].second;\n    }\n\n    cout << power_required << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n\n"
  },
  {
    "path": "2021/Div 2/742/Explanations/Carrying Conundrum Explanation.txt",
    "content": "We are performing regular addition on the odd and even digits seperately . \n\n-----\n\n#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    string n;\n    cin >> n;\n\n    long long odd_places = 0, even_places = 0;\n    for(int i = 0; i < n.size(); i++)\n    {\n        int digit = n[i] - '0';\n\n        switch(i%2)\n        {\n            case 1 : odd_places = odd_places*10 + digit;\n                     break;\n\n            case 0 : even_places = even_places*10 + digit;\n                    break;\n        }\n    }\n\n    long long total_ways = (odd_places + 1)*(even_places + 1) - 2;\n\n    cout << total_ways << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 2/742/Programs/Carrying Conundrum.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    string n;\n    cin >> n;\n\n    long long odd_places = 0, even_places = 0;\n    for(int i = 0; i < n.size(); i++)\n    {\n        int digit = n[i] - '0';\n\n        switch(i%2)\n        {\n            case 1 : odd_places = odd_places*10 + digit;\n                     break;\n\n            case 0 : even_places = even_places*10 + digit;\n                    break;\n        }\n    }\n\n    long long total_ways = (odd_places + 1)*(even_places + 1) - 2;\n\n    cout << total_ways << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 2/750/Explanations/Pchelyonok and Segments Explanation.txt",
    "content": " How to use smaller subproblems to build the solution $?$\n\n- In order to know if we can make the $P$-th partition here, we need to know if it is possible to make $P - 1, P - 2, \\dots , 1$ partitions from $[i + P]$.\n- Let $f(i, P)$ be the maximum sum that the $P$-th partition can have if it begins anywhere on or after $i$ and is followed by all the smaller partitions.\n- $f(i, P) = \\max\\{f(i + 1, P), S[i, i + P - 1]\\}$\n    - We need to be careful and first check that $S[i, i + P - 1] < f(i + P, P - 1)$ in order to maintain the decreasing sum condition.\n\n---\n\n## Why are we taking the maximum sum $?$\n\n- We need to ensure that the sum of the $P$-th segment should be smaller than the $P - 1$ segment.\n- Since, we are going from right to left, we might as well choose the maximum possible sum for each segment greedily.\n- We can use an exchange argument to show that the number of segments will never decrease by choosing a greater sum segment beginning on or after the same index.\n- The answer is the largest $k$ for which $f(1, k) > 0$\n\n---\n\n## Why is this not $O(n^2)$ $?$\n\n- The maximum $k$ is such that $\\frac{k(k + 1)}{2} \\le n \\implies k(k + 1) \\le 2n \\implies k^2 < 2n$\n- So, $k < \\sqrt{2n}$\n- This is actually $O(n \\sqrt{n})$ because of how quickly the triangular numbers grow.\n\n-----\n\n```cpp\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> sum_from(no_of_elements + 5, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        sum_from[i] = A[i] + sum_from[i + 1];\n    }\n\n    long long max_k = get_largest_k(no_of_elements);\n\n    vector <vector <long long> > max_segment_sum(no_of_elements + 5, vector <long long> (max_k + 1));\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        for(int segment_size = 1; segment_size <= max_k; segment_size++)\n        {\n            max_segment_sum[i][segment_size] = max_segment_sum[i + 1][segment_size];\n\n            if(i + segment_size - 1 > no_of_elements)\n            {\n                continue;\n            }\n\n            long long sum_here = sum_from[i] - sum_from[i + segment_size];\n\n            if(segment_size == 1 || sum_here < max_segment_sum[i + segment_size][segment_size - 1])\n            {\n                max_segment_sum[i][segment_size] = max(max_segment_sum[i][segment_size], sum_here);\n            }\n        }\n    }\n\n    int answer = 0;\n    for(int segment_size = max_k; segment_size >= 1; segment_size--)\n    {\n        if(max_segment_sum[1][segment_size] > 0)\n        {\n            answer = segment_size;\n            break;\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n```\n"
  },
  {
    "path": "2021/Div 2/750/Programs/Pchelyonok and Segments.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long get_largest_k(long long n)\n{\n    long long right = n, left = 1;\n\n    while(right - left > 1)\n    {\n        long long mid = (left + right)/2;\n\n        if(mid*1LL*(mid + 1) <= 2*n)\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n\n    return left;\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> sum_from(no_of_elements + 5, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        sum_from[i] = A[i] + sum_from[i + 1];\n    }\n\n    long long max_k = get_largest_k(no_of_elements);\n\n    vector <vector <long long> > max_segment_sum(no_of_elements + 5, vector <long long> (max_k + 1));\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        for(int segment_size = 1; segment_size <= max_k; segment_size++)\n        {\n            max_segment_sum[i][segment_size] = max_segment_sum[i + 1][segment_size];\n\n            if(i + segment_size - 1 > no_of_elements)\n            {\n                continue;\n            }\n\n            long long sum_here = sum_from[i] - sum_from[i + segment_size];\n\n            if(segment_size == 1 || sum_here < max_segment_sum[i + segment_size][segment_size - 1])\n            {\n                max_segment_sum[i][segment_size] = max(max_segment_sum[i][segment_size], sum_here);\n            }\n        }\n    }\n\n    int answer = 0;\n    for(int segment_size = max_k; segment_size >= 1; segment_size--)\n    {\n        if(max_segment_sum[1][segment_size] > 0)\n        {\n            answer = segment_size;\n            break;\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 3/710/Explanations/Double Ended Strings Explanation.txt.txt",
    "content": "Let f(La, Ra, Lb, Rb) be true if A[La][Ra] = B[Lb][Rb] \r\n\r\nf(La, Ra, Lb, Rb) = (A[La] = B[Lb]) + f(La + 1, Ra, Lb + 1, Rb) \r\n\r\nFind out the length of the maximum matching string \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    memset(matches, false, sizeof(matches));\r\n\r\n    int max_length = 0, changes = A.size() + B.size();\r\n    for(int length = 1; length <= min(A.size(), B.size()); length++)\r\n    {\r\n        for(int a_left = 0, a_right = a_left + length - 1; a_right < A.size(); a_left++, a_right++)\r\n        {\r\n            for(int b_left = 0, b_right = b_left + length - 1; b_right < B.size(); b_left++, b_right++)\r\n            {\r\n                if(length == 1)\r\n                {\r\n                    matches[a_left][a_right][b_left][b_right] = (A[a_left] == B[b_left]);\r\n                }\r\n                else\r\n                {\r\n                    matches[a_left][a_right][b_left][b_right] = ( (A[a_left] == B[b_left]) && (matches[a_left + 1][a_right][b_left + 1][b_right]) );\r\n                }\r\n\r\n                if(matches[a_left][a_right][b_left][b_right])\r\n                {\r\n                    max_length = length;\r\n\r\n                    changes = (a_left) + (A.size() - 1 - a_right) + (b_left) + (B.size() - 1 - b_right);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << changes << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 3/710/Explanations/Epic Transformation Explanation.txt.txt",
    "content": "If any pile has > N/2 stones, that pile will remain standing even at the end. \r\n\r\nOtherwise, we are reducing the piles by 2 at each step. \r\nLet us take a stone from the two highest piles.\r\nSince the largest pile has < N/2 stones in the beginning, it will always have < N/2 stones at every step. \r\nWhen the game ends, it cannot have 2 stones\r\n\r\nIn the end, there will be either 0 or 1 stones depending on the parity, which is invariant.\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    map <int, int> frequency;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    vector <int> pile;\r\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        pile.push_back(it->second);\r\n    }\r\n\r\n    sort(pile.begin(), pile.end());\r\n\r\n    if(2*pile.back() > no_of_elements)\r\n    {\r\n        int remaining = no_of_elements - pile.back();\r\n\r\n        cout << no_of_elements - 2*remaining << \"\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    cout << no_of_elements%2 << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 3/710/Explanations/Maximize the Remaining String Explanation.txt",
    "content": "- We will keep track of the suffix frequency of each alphabet.\n- We will iterate over every character in the string.\n    - We will append $S[i]$ to the answer if it is not currently present in the answer.\n    - Before appending it, we will remove all characters in the suffix of the answer that are $< S[i]$ and have suffix frequency $> 0$, \nwhich means that the alphabet occurs later in the string too and we will get a larger string by choosing it's next occurrence.\n\n-----\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector < vector <int> > suffix_frequency(S.size() + 1, vector <int> (NO_OF_ALPHABETS, 0));\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            suffix_frequency[i][alpha] = suffix_frequency[i + 1][alpha];\n        }\n\n        suffix_frequency[i][S[i] - 'a']++;\n    }\n\n    string answer;\n    vector <int> used(NO_OF_ALPHABETS, false);\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(used[S[i] - 'a'])\n        {\n            continue;\n        }\n\n        while(answer.size() > 0 && suffix_frequency[i][answer.back() - 'a'] > 0 && answer.back() < S[i])\n        {\n            used[answer.back() - 'a'] = false;\n\n            answer.pop_back();\n        }\n\n        answer += S[i];\n\n        used[S[i] - 'a'] = true;\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Div 3/710/Explanations/Partial Replacement.txt.txt",
    "content": "We will be greedy. We will try to keep the x's as far as possible but not more than K. \r\nThe question says that it is always guarnateed that no to X's are more than K apart. \r\n\r\nStore the indices of all the X's in a vector and then greedily perform the changes.\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int length, k;\r\n    cin >> length >> k;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    vector <int> positions;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] == '*')\r\n        {\r\n            positions.push_back(i);\r\n        }\r\n    }\r\n\r\n    vector <int> changes;\r\n    changes.push_back(positions[0]);\r\n    for(int i = 0; i < positions.size(); i++)\r\n    {\r\n        if(positions[i] - changes.back() > k)\r\n        {\r\n            changes.push_back(positions[i - 1]);\r\n        }\r\n\r\n        if(i + 1 == positions.size())\r\n        {\r\n            if(positions[i] != changes.back())\r\n            {\r\n                changes.push_back(positions[i]);\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    cout << changes.size() << \"\\n\";\r\n\r\n}"
  },
  {
    "path": "2021/Div 3/710/Explanations/Strange Table Explanation.txt.txt",
    "content": "When they are numbered 'column' wise, the number for cell (r, c) is R(c - 1) + r \r\n\r\nWhen, they are numbered 'row' wise, the number for cell (r, c) is C(r - 1) + c \r\n\r\nFirst, find out (r, c) and then the other number. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    long long rows, columns, x;\r\n    cin >> rows >> columns >> x;\r\n\r\n    long long column_no = (x/rows) + (x%rows != 0);\r\n    long long row_no = x - rows*(column_no - 1);\r\n\r\n    long long new_no = columns*(row_no - 1) + column_no;\r\n\r\n    cout << new_no << \"\\n\";\r\n}\r\n"
  },
  {
    "path": "2021/Div 3/710/Explanations/Triangular Paths Explanation.txt.txt",
    "content": "- It is always possible to travel through the points so let us travel in ascending order of $r$ since we can never go backwards.\r\n- Let us look at the quantity $D = r - c$ for each node.\r\n    - When we move from an even cell to an odd cell, $D$ increases by $1$\r\n    - When we move from an odd cell to an odd cell, $D$ remains the same.\r\n- Let $D_1$ be the difference of the source and $D_2$ the difference of the target.\r\n- If $D_1 = D_2$, then\r\n    - If we are on an odd cell, we just keep sliding till we hit the target. No additional edges.\r\n    - If we are on an even cell, we have to keep making a new edge to $(r + 1, c + 1)$, which will also be even. So it will cost $r_2 - r_1$\r\n\r\n---\r\n\r\n- If $D_1 < D_2$, then\r\n    - We can only increase the value of $D$ by moving from $(r, c) \\to (r + 1, c)$\r\n        - This is the normal even transition.\r\n    - So, we will go along the following path till $D_1 = D_2$\r\n    - $E \\to O \\to E \\to O \\to \\dots \\to O$\r\n    - We don't have to make any edge from $E \\to O$ but have to make half the edges from $O \\to E$\r\n    - Keep in mind that we can add in any number of legal $O \\to O$ transitions in between so that we finish our path on the destination cell $(r_2 - c_2)$\r\n    - If $D_1 - D_2$ is odd, then\r\n        - We will be making exactly half the number of new edges if we begin on an even cell.\r\n        - We will be making one more than half new edges if we begin on an odd cell.\r\n\r\n    ---\r\n\r\n- Make sure that the path ends on an odd cell so we have the situation $D_1 = D_2$ on an odd cell as discussed above so cost is $0$.\r\n\r\n---\r\n\r\n- If $D_1 > D_2$, then the answer is not possible because\r\n    - Either $r_1 > r_2$ or $c_1 > c_2$ and we can never go backwards\r\n\r\n------\r\n\r\nint is_even(long long r, long long c)\r\n{\r\n    return ( (r + c)%2 == 0 );\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector < pair <int, int> > P(no_of_elements + 1, make_pair(1, 1));\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i].first;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i].second;\r\n    }\r\n\r\n    sort(P.begin(), P.end());\r\n\r\n    long long distance = 0;\r\n    for(int i = 0; i + 1 <= no_of_elements; i++)\r\n    {\r\n        int source_difference = P[i].first - P[i].second;\r\n        int target_difference = P[i + 1].first - P[i + 1].second;\r\n        int extra_difference = target_difference - source_difference;\r\n\r\n        if(extra_difference == 0)\r\n        {\r\n            distance += (is_even(P[i].first, P[i].second) ? P[i + 1].first - P[i].first : 0);\r\n\r\n            continue;\r\n        }\r\n\r\n        if(is_even(P[i].first, P[i].second))\r\n        {\r\n            distance += ( extra_difference/2 );\r\n        }\r\n        else\r\n        {\r\n            distance += extra_difference/2 + extra_difference%2;\r\n        }\r\n    }\r\n\r\n    cout << distance << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 3/710/Programs/Double Ended Strings.cpp",
    "content": "\r\n#include <iostream>\r\n#include <vector>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 21;\r\nint matches[MAX_N][MAX_N][MAX_N][MAX_N];\r\n\r\nvoid solve()\r\n{\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    memset(matches, false, sizeof(matches));\r\n\r\n    int max_length = 0, changes = A.size() + B.size();\r\n    for(int length = 1; length <= min(A.size(), B.size()); length++)\r\n    {\r\n        for(int a_left = 0, a_right = a_left + length - 1; a_right < A.size(); a_left++, a_right++)\r\n        {\r\n            for(int b_left = 0, b_right = b_left + length - 1; b_right < B.size(); b_left++, b_right++)\r\n            {\r\n                if(length == 1)\r\n                {\r\n                    matches[a_left][a_right][b_left][b_right] = (A[a_left] == B[b_left]);\r\n                }\r\n                else\r\n                {\r\n                    matches[a_left][a_right][b_left][b_right] = ( (A[a_left] == B[b_left]) && (matches[a_left + 1][a_right][b_left + 1][b_right]) );\r\n                }\r\n\r\n                if(matches[a_left][a_right][b_left][b_right])\r\n                {\r\n                    max_length = length;\r\n\r\n                    changes = (a_left) + (A.size() - 1 - a_right) + (b_left) + (B.size() - 1 - b_right);\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << changes << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 3/710/Programs/Epic Transformation.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <cstring>\r\n#include <map>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    map <int, int> frequency;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    vector <int> pile;\r\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        pile.push_back(it->second);\r\n    }\r\n\r\n    sort(pile.begin(), pile.end());\r\n\r\n    if(2*pile.back() > no_of_elements)\r\n    {\r\n        int remaining = no_of_elements - pile.back();\r\n\r\n        cout << no_of_elements - 2*remaining << \"\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    cout << no_of_elements%2 << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 3/710/Programs/Maximize the Remaining String.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstring>\n#include <map>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\n\nusing namespace std;\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector < vector <int> > suffix_frequency(S.size() + 1, vector <int> (NO_OF_ALPHABETS, 0));\n    for(int i = S.size() - 1; i >= 0; i--)\n    {\n        for(int alpha = 0; alpha < NO_OF_ALPHABETS; alpha++)\n        {\n            suffix_frequency[i][alpha] = suffix_frequency[i + 1][alpha];\n        }\n\n        suffix_frequency[i][S[i] - 'a']++;\n    }\n\n    string answer;\n    vector <int> used(NO_OF_ALPHABETS, false);\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(used[S[i] - 'a'])\n        {\n            continue;\n        }\n\n        while(answer.size() > 0 && suffix_frequency[i][answer.back() - 'a'] > 0 && answer.back() < S[i])\n        {\n            used[answer.back() - 'a'] = false;\n\n            answer.pop_back();\n        }\n\n        answer += S[i];\n\n        used[S[i] - 'a'] = true;\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 3/710/Programs/Partial Replacement.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int length, k;\r\n    cin >> length >> k;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    vector <int> positions;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] == '*')\r\n        {\r\n            positions.push_back(i);\r\n        }\r\n    }\r\n\r\n    vector <int> changes;\r\n    changes.push_back(positions[0]);\r\n    for(int i = 0; i < positions.size(); i++)\r\n    {\r\n        if(positions[i] - changes.back() > k)\r\n        {\r\n            changes.push_back(positions[i - 1]);\r\n        }\r\n\r\n        if(i + 1 == positions.size())\r\n        {\r\n            if(positions[i] != changes.back())\r\n            {\r\n                changes.push_back(positions[i]);\r\n            }\r\n        }\r\n\r\n    }\r\n\r\n    cout << changes.size() << \"\\n\";\r\n\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 3/710/Programs/Strange Table.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    long long rows, columns, x;\r\n    cin >> rows >> columns >> x;\r\n\r\n    long long column_no = (x/rows) + (x%rows != 0);\r\n    long long row_no = x - rows*(column_no - 1);\r\n\r\n    long long new_no = columns*(row_no - 1) + column_no;\r\n\r\n    cout << new_no << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 3/710/Programs/Triangular Paths.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <cstring>\r\n#include <map>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint is_even(long long r, long long c)\r\n{\r\n    return ( (r + c)%2 == 0 );\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector < pair <int, int> > P(no_of_elements + 1, make_pair(1, 1));\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i].first;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i].second;\r\n    }\r\n\r\n    sort(P.begin(), P.end());\r\n\r\n    long long distance = 0;\r\n    for(int i = 0; i + 1 <= no_of_elements; i++)\r\n    {\r\n        int source_difference = P[i].first - P[i].second;\r\n        int target_difference = P[i + 1].first - P[i + 1].second;\r\n        int extra_difference = target_difference - source_difference;\r\n\r\n        if(extra_difference == 0)\r\n        {\r\n            distance += (is_even(P[i].first, P[i].second) ? P[i + 1].first - P[i].first : 0);\r\n\r\n            continue;\r\n        }\r\n\r\n        if(is_even(P[i].first, P[i].second))\r\n        {\r\n            distance += ( extra_difference/2 );\r\n        }\r\n        else\r\n        {\r\n            distance += extra_difference/2 + extra_difference%2;\r\n        }\r\n    }\r\n\r\n    cout << distance << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 3/713/Explanations/A-B Palindrome Explanation.txt.txt",
    "content": "In the first pass, make S[i] = S[n - i] for all i \r\nThese moves are forced \r\n\r\nThe central characters can be either 0 or 1 so don't choose it yet. \r\nThe pairs where both are ? can also be both 0 or 1 so don't choose it yet. \r\n\r\nIn the second pass, make the pairs = 0, 1, whichever is available \r\n\r\nAt last, choose the central character based on availability.\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    vector <int> target(2, 0), frequency(2, 0);\r\n    string S;\r\n    cin >> target[0] >> target[1] >> S;\r\n \r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] != '?')\r\n        {\r\n            frequency[S[i] - '0']++;\r\n        }\r\n    }\r\n \r\n    int palindrome = true;\r\n    for(int front_i = 0, back_i = S.size() - 1; front_i < back_i; front_i++, back_i--)\r\n    {\r\n       if(S[front_i] != '?' && S[back_i] == '?')\r\n        {\r\n            S[back_i] = S[front_i];\r\n            frequency[S[back_i] - '0']++;\r\n \r\n        }\r\n        else if(S[back_i] != '?' && S[front_i] == '?')\r\n        {\r\n            S[front_i] = S[back_i];\r\n            frequency[S[front_i] - '0']++;\r\n        }\r\n \r\n \r\n        if(S[front_i] != S[back_i])\r\n        {\r\n            palindrome = false;\r\n        }\r\n    }\r\n \r\n    for(int front_i = 0, back_i = S.size() - 1; front_i <= back_i; front_i++, back_i--)\r\n    {\r\n        if(front_i == back_i)\r\n        {\r\n            if(S[front_i] == '?')\r\n            {\r\n                if(frequency[0] != target[0])\r\n                {\r\n                    S[front_i] = '0';\r\n                }\r\n                else if(frequency[1] != target[1])\r\n                {\r\n                    S[front_i] = '1';\r\n                }\r\n \r\n                frequency[S[front_i] - '0']++;\r\n            }\r\n \r\n            continue;\r\n        }\r\n \r\n        if(S[front_i] == '?' && S[back_i] == '?')\r\n        {\r\n            if(target[0] - frequency[0] >= 2)\r\n            {\r\n                S[front_i] = S[back_i] = '0';\r\n                frequency[0] += 2;\r\n            }\r\n            else\r\n            {\r\n                S[front_i] = S[back_i] = '1';\r\n                frequency[1] += 2;\r\n            }\r\n        }\r\n    }\r\n \r\n    if(frequency[0] != target[0] || frequency[1] != target[1] || !palindrome)\r\n    {\r\n        cout << \"-1\\n\";\r\n        return;\r\n    }\r\n \r\n    cout << S << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 3/713/Explanations/Almost Rectange Explanation.txt.txt",
    "content": "If the two dots are not on the same row or column, we can complete the rectangle by making new dots on \r\n\r\nA(r1, c2) and A(r2, c1) \r\n\r\nIf they are in the same row or column, we will just an adjacent row or column to make the two dots \r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n \r\n    vector <string> grid(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> grid[i];\r\n    }\r\n \r\n    int r_1 = -1, c_1 = -1, r_2 = -1, c_2 = -1;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        for(int j = 0; j < no_of_elements; j++)\r\n        {\r\n            if(grid[i][j] == '*')\r\n            {\r\n                if(r_1 == -1)\r\n                {\r\n                    r_1 = i; c_1 = j;\r\n                }\r\n                else\r\n                {\r\n                    r_2 = i; c_2 = j;\r\n                }\r\n            }\r\n        }\r\n    }\r\n \r\n    grid[r_1][c_2] = grid[r_2][c_1] = '*';\r\n \r\n    if(r_1 == r_2)\r\n    {\r\n        int r = (r_1 == 0 ? 1 : 0);\r\n        grid[r][c_1] = grid[r][c_2] = '*';\r\n    }\r\n    else if(c_1 == c_2)\r\n    {\r\n        int c = (c_1 == 0 ? 1 : 0);\r\n        grid[r_1][c] = grid[r_2][c] = '*';\r\n    }\r\n \r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cout << grid[i] << \"\\n\";\r\n    }\r\n}\r\n "
  },
  {
    "path": "2021/Div 3/713/Explanations/Corrupted Array Explanation.txt.txt",
    "content": "Let us sort A. \r\n\r\nB[n + 1] must either be the last element or the second last element. \r\n\r\nCheck if it is the second last element. \r\n\r\nIf not, iterate over every possibility for x as it is the last element. \r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n \r\n    vector <int> B(no_of_elements + 3);\r\n    for(int i = 1; i <= no_of_elements + 2; i++)\r\n    {\r\n        cin >> B[i];\r\n    }\r\n \r\n    sort(B.begin(), B.end());\r\n \r\n    vector <long long> sum_till(no_of_elements + 3, 0);\r\n    for(int i = 1; i <= no_of_elements + 2; i++)\r\n    {\r\n        sum_till[i] = sum_till[i - 1] + B[i];\r\n    }\r\n \r\n    int found = false;\r\n    int x = no_of_elements + 1;\r\n    if(sum_till[no_of_elements] == B[no_of_elements + 1])\r\n    {\r\n        found = true;\r\n    }\r\n \r\n    for(int i = 1; i <= no_of_elements + 1; i++)\r\n    {\r\n        if(sum_till[no_of_elements + 1] - B[i] == B[no_of_elements + 2])\r\n        {\r\n            x = i;\r\n \r\n            found = true;\r\n \r\n            break;\r\n        }\r\n    }\r\n \r\n    if(!found)\r\n    {\r\n        cout << \"-1\\n\";\r\n \r\n        return;\r\n    }\r\n \r\n    for(int i = 1; i <= no_of_elements + 1; i++)\r\n    {\r\n        if(i == x)\r\n        {\r\n            continue;\r\n        }\r\n \r\n        cout << B[i] << \" \";\r\n    }\r\n \r\n    cout << \"\\n\";\r\n}\r\n "
  },
  {
    "path": "2021/Div 3/713/Explanations/Education Explanation.txt.txt",
    "content": "Calculate the cost for buying the computer on each day. \r\n\r\n1. Calculate the minimum number of days to reach salary i \r\n2. Keep track of savings \r\n3. Calculate the number of days to buy the computer if this is the final salary (Use savings too)\r\n\r\n-----\r\n\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, computer_cost;\r\n    cin >> no_of_elements >> computer_cost;\r\n \r\n    vector <long long> A(no_of_elements + 1), B(no_of_elements);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n \r\n    for(int i = 1; i <= no_of_elements - 1; i++)\r\n    {\r\n        cin >> B[i];\r\n    }\r\n \r\n    vector <long long> savings(no_of_elements + 1); //Savings on reaching day i\r\n    vector <long long> minimum_days_to_reach(no_of_elements + 1); //Days to reach i. Earn on day f(i) + 1\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long days_here = ceil(B[i - 1] - savings[i - 1], A[i - 1]);\r\n \r\n        savings[i] = days_here*A[i - 1] - (B[i - 1] - savings[i - 1]);\r\n \r\n        minimum_days_to_reach[i] = minimum_days_to_reach[i - 1] + days_here + (i > 1);\r\n    }\r\n \r\n    long long no_of_days = 1e15;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long days_for_this_last_salary = ceil(computer_cost - savings[i], A[i]);\r\n \r\n        no_of_days = min(no_of_days, days_for_this_last_salary + minimum_days_to_reach[i]);\r\n    }\r\n \r\n    cout << no_of_days << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 3/713/Explanations/Short Task Explanation.txt",
    "content": "We will use a sieve to precompute the sum of divisors of each integer \n\nAnd then precompute the smallest integer with X factors for each X in [1, 10^7]\n\n-----\n\n#include <iostream>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 1e7 + 5;\nint divisor_sum[MAX_N], answer[MAX_N];\n\nvoid sieve()\n{\n    memset(divisor_sum, 0, sizeof(divisor_sum));\n    memset(answer, -1, sizeof(answer));\n\n    for(int i = 1; i < MAX_N; i++)\n    {\n        for(int multiple = i; multiple < MAX_N; multiple += i)\n        {\n            divisor_sum[multiple] += i;\n        }\n\n        if(divisor_sum[i] < MAX_N && answer[divisor_sum[i]] == -1)\n        {\n            answer[divisor_sum[i]] = i;\n        }\n    }\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    cout << answer[n] << \"\\n\";\n}\n\nint main()\n{\n    sieve();\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 3/713/Explanations/Spy Detected Explanation.txt.txt",
    "content": "Sort the array A. \r\n\r\nThe unique element is either the first element or the last. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n \r\n    vector < pair<int, int> > A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i].first;\r\n \r\n        A[i].second = i;\r\n    }\r\n \r\n    sort(A.begin(), A.end());\r\n \r\n    int index = (A[1].first == A[2].first ? A[no_of_elements].second : A[1].second);\r\n \r\n    cout << index << \"\\n\";\r\n}"
  },
  {
    "path": "2021/Div 3/713/Programs/A-B Palindrome.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    vector <int> target(2, 0), frequency(2, 0);\r\n    string S;\r\n    cin >> target[0] >> target[1] >> S;\r\n\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] != '?')\r\n        {\r\n            frequency[S[i] - '0']++;\r\n        }\r\n    }\r\n\r\n    int palindrome = true;\r\n    for(int front_i = 0, back_i = S.size() - 1; front_i < back_i; front_i++, back_i--)\r\n    {\r\n       if(S[front_i] != '?' && S[back_i] == '?')\r\n        {\r\n            S[back_i] = S[front_i];\r\n            frequency[S[back_i] - '0']++;\r\n\r\n        }\r\n        else if(S[back_i] != '?' && S[front_i] == '?')\r\n        {\r\n            S[front_i] = S[back_i];\r\n            frequency[S[front_i] - '0']++;\r\n        }\r\n\r\n\r\n        if(S[front_i] != S[back_i])\r\n        {\r\n            palindrome = false;\r\n        }\r\n    }\r\n\r\n    for(int front_i = 0, back_i = S.size() - 1; front_i <= back_i; front_i++, back_i--)\r\n    {\r\n        if(front_i == back_i)\r\n        {\r\n            if(S[front_i] == '?')\r\n            {\r\n                if(frequency[0] != target[0])\r\n                {\r\n                    S[front_i] = '0';\r\n                }\r\n                else if(frequency[1] != target[1])\r\n                {\r\n                    S[front_i] = '1';\r\n                }\r\n\r\n                frequency[S[front_i] - '0']++;\r\n            }\r\n\r\n            continue;\r\n        }\r\n\r\n        if(S[front_i] == '?' && S[back_i] == '?')\r\n        {\r\n            if(target[0] - frequency[0] >= 2)\r\n            {\r\n                S[front_i] = S[back_i] = '0';\r\n                frequency[0] += 2;\r\n            }\r\n            else\r\n            {\r\n                S[front_i] = S[back_i] = '1';\r\n                frequency[1] += 2;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(frequency[0] != target[0] || frequency[1] != target[1] || !palindrome)\r\n    {\r\n        cout << \"-1\\n\";\r\n        return;\r\n    }\r\n\r\n    cout << S << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2021/Div 3/713/Programs/Almost Rectangle.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <string> grid(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> grid[i];\r\n    }\r\n\r\n    int r_1 = -1, c_1 = -1, r_2 = -1, c_2 = -1;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        for(int j = 0; j < no_of_elements; j++)\r\n        {\r\n            if(grid[i][j] == '*')\r\n            {\r\n                if(r_1 == -1)\r\n                {\r\n                    r_1 = i; c_1 = j;\r\n                }\r\n                else\r\n                {\r\n                    r_2 = i; c_2 = j;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    grid[r_1][c_2] = grid[r_2][c_1] = '*';\r\n\r\n    if(r_1 == r_2)\r\n    {\r\n        int r = (r_1 == 0 ? 1 : 0);\r\n        grid[r][c_1] = grid[r][c_2] = '*';\r\n    }\r\n    else if(c_1 == c_2)\r\n    {\r\n        int c = (c_1 == 0 ? 1 : 0);\r\n        grid[r_1][c] = grid[r_2][c] = '*';\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cout << grid[i] << \"\\n\";\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 3/713/Programs/Corrupted Array.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> B(no_of_elements + 3);\r\n    for(int i = 1; i <= no_of_elements + 2; i++)\r\n    {\r\n        cin >> B[i];\r\n    }\r\n\r\n    sort(B.begin(), B.end());\r\n\r\n    vector <long long> sum_till(no_of_elements + 3, 0);\r\n    for(int i = 1; i <= no_of_elements + 2; i++)\r\n    {\r\n        sum_till[i] = sum_till[i - 1] + B[i];\r\n    }\r\n\r\n    int found = false;\r\n    int x = no_of_elements + 1;\r\n    if(sum_till[no_of_elements] == B[no_of_elements + 1])\r\n    {\r\n        found = true;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements + 1; i++)\r\n    {\r\n        if(sum_till[no_of_elements + 1] - B[i] == B[no_of_elements + 2])\r\n        {\r\n            x = i;\r\n\r\n            found = true;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(!found)\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements + 1; i++)\r\n    {\r\n        if(i == x)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        cout << B[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2021/Div 3/713/Programs/Education.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long ceil(long long n, long long d)\r\n{\r\n    if(d == 0 || n <= 0)\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    return (n/d) + (n%d != 0);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, computer_cost;\r\n    cin >> no_of_elements >> computer_cost;\r\n\r\n    vector <long long> A(no_of_elements + 1), B(no_of_elements);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements - 1; i++)\r\n    {\r\n        cin >> B[i];\r\n    }\r\n\r\n    vector <long long> savings(no_of_elements + 1); //Savings on reaching day i\r\n    vector <long long> minimum_days_to_reach(no_of_elements + 1); //Days to reach i. Earn on day f(i) + 1\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long days_here = ceil(B[i - 1] - savings[i - 1], A[i - 1]);\r\n\r\n        savings[i] = days_here*A[i - 1] - (B[i - 1] - savings[i - 1]);\r\n\r\n        minimum_days_to_reach[i] = minimum_days_to_reach[i - 1] + days_here + (i > 1);\r\n    }\r\n\r\n    long long no_of_days = 1e15;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long days_for_this_last_salary = ceil(computer_cost - savings[i], A[i]);\r\n\r\n        no_of_days = min(no_of_days, days_for_this_last_salary + minimum_days_to_reach[i]);\r\n    }\r\n\r\n    cout << no_of_days << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 3/713/Programs/Short Task.cpp",
    "content": "#include <iostream>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 1e7 + 5;\nint divisor_sum[MAX_N], answer[MAX_N];\n\nvoid sieve()\n{\n    memset(divisor_sum, 0, sizeof(divisor_sum));\n    memset(answer, -1, sizeof(answer));\n\n    for(int i = 1; i < MAX_N; i++)\n    {\n        for(int multiple = i; multiple < MAX_N; multiple += i)\n        {\n            divisor_sum[multiple] += i;\n        }\n\n        if(divisor_sum[i] < MAX_N && answer[divisor_sum[i]] == -1)\n        {\n            answer[divisor_sum[i]] = i;\n        }\n    }\n}\n\nvoid solve()\n{\n    int n;\n    cin >> n;\n    cout << answer[n] << \"\\n\";\n}\n\nint main()\n{\n    sieve();\n\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Div 3/713/Programs/Spy Detected.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector < pair<int, int> > A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i].first;\r\n\r\n        A[i].second = i;\r\n    }\r\n\r\n    sort(A.begin(), A.end());\r\n\r\n    int index = (A[1].first == A[2].first ? A[no_of_elements].second : A[1].second);\r\n\r\n    cout << index << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Div 3/744/Programs/Array Optimization by Deque.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\n#define all(v) (v).begin(), (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nint sum_tree[3*MAX_N];\n\nvoid build(int n, int left, int right)\n{\n    if(left == right)\n    {\n        sum_tree[n] = 0;\n        return;\n    }\n\n    int mid = (left + right)/2;\n    build(LEFT(n), left, mid);\n    build(RIGHT(n), mid + 1, right);\n\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\n}\n\nvoid update(int n, int left, int right, int position, int value)\n{\n    if(position < left || right < position)\n    {\n        return;\n    }\n\n    if(left == right)\n    {\n        sum_tree[n] += value;\n\n        return;\n    }\n\n    int mid = (left + right)/2;\n\n    update(LEFT(n), left, mid, position, value);\n    update(RIGHT(n), mid + 1, right, position, value);\n\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\n}\n\nint get_sum(int n, int left, int right, int query_left, int query_right)\n{\n    if(right < left || query_right < left || right < query_left)\n    {\n        return 0;\n    }\n\n    if(query_left <= left && right <= query_right)\n    {\n        return sum_tree[n];\n    }\n\n    int mid = (left + right)/2;\n    int left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\n    int right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\n\n    return (left_sum + right_sum);\n}\n\nvoid compress_coordinates(int no_of_elements, vector <int> &A)\n{\n    vector <int> sorted_A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sorted_A[i] = A[i];\n    }\n\n    sort(sorted_A.begin() + 1, sorted_A.end());\n\n    map <int, int> label;\n    label[sorted_A[1]] = 1;\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        label[sorted_A[i]] = (sorted_A[i] == sorted_A[i - 1] ? label[sorted_A[i - 1]] : label[sorted_A[i - 1]] + 1);\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        A[i] = label[A[i]];\n    }\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    compress_coordinates(no_of_elements, A);\n    build(1, 1, no_of_elements);\n\n    long long inversions = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        //cout << \"Currently \" << A[i] << \"\\n\";\n        int prefix_sum = get_sum(1, 1, no_of_elements, 1, A[i] - 1);\n        int suffix_sum = get_sum(1, 1, no_of_elements, A[i] + 1, no_of_elements);\n        update(1, 1, no_of_elements, A[i], 1);\n        //cout << \"Prefix = \" << prefix_sum << \" Suffix = \" << suffix_sum << \"\\n\";\n\n        inversions += min(prefix_sum, suffix_sum);\n    }\n\n    cout << inversions << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Educational Round 109/Explanations/Permutation Sort Explanation.txt",
    "content": "1. If the array is already sorted, we need 0 moves.\n\n2. Suppose A[1] = 1, then we can apply the operation to [2, N] and sort the array in 1 move \n\n3. In most other cases 2 moves should be enough \n[1, n - 1] and [2, n]\n\n3. If A[1] = n or A[n] = 1, then this will not be enough. \nWe need to do another move to bring 1 or n out of the extreme positions as we are not \nallowed to apply the operation on the entire array. \n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    int sorted = true;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] != i)\n        {\n            sorted = false;\n        }\n    }\n\n    int steps;\n\n    if(sorted)\n    {\n        steps = 0;\n    }\n    else if(A[1] == 1 || A[no_of_elements] == no_of_elements)\n    {\n        steps = 1;\n    }\n    else if(A[no_of_elements] == 1 && A[1] == no_of_elements)\n    {\n        steps = 3;\n    }\n    else\n    {\n        steps = 2;\n    }\n\n    cout << steps << \"\\n\";\n}\n"
  },
  {
    "path": "2021/Educational Round 109/Programs/Permutation Sort.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    int sorted = true;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] != i)\n        {\n            sorted = false;\n        }\n    }\n\n    int steps;\n\n    if(sorted)\n    {\n        steps = 0;\n    }\n    else if(A[1] == 1 || A[no_of_elements] == no_of_elements)\n    {\n        steps = 1;\n    }\n    else if(A[no_of_elements] == 1 && A[1] == no_of_elements)\n    {\n        steps = 3;\n    }\n    else\n    {\n        steps = 2;\n    }\n\n    cout << steps << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n \n"
  },
  {
    "path": "2021/Practice/Explanations/Anton and Making Potions Explanation.txt",
    "content": "1. We can use at most 1 spell of each type. \n2. We will iterate over the reduction spells and find out the best creation spell. \n3. Suppose our current reduction spell costs X and we have M money in total. We can buy a creation spell of cost at most (M - X)\n4. We need to know the best creation spell of cost at most (M - X). We can binary search to find the index i, such that creation cost <= (M - X) and find \nthe prefix maximum of the array. \n\n-----\n\nCalculate the prefix maximum of the sorted creation array\nIterate over each reduction\nWith the remaining money, choose the best creation spell \nThis will minimize time. \n\n-----\n\nI faced an error when I used lower_bound but got AC when I implemented the binary search myself. \nWe also want to test the case where we use 0 reduction spells and 1 creation spell so make an extra reduction spell of cost 0 and value 'X' (The original Time)\n\n-----\n\nint main()\n{\n    int no_of_potions, no_of_spells_1, no_of_spells_2;\n    cin >> no_of_potions >> no_of_spells_1 >> no_of_spells_2;\n\n    long long time, money;\n    cin >> time >> money;\n\n    vector < pair <long long, long long> > reduction(no_of_spells_1 + 1);\n    for(int i = 1; i <= no_of_spells_1; i++)\n    {\n        cin >> reduction[i].second;\n    }\n\n    for(int i = 1; i <= no_of_spells_1; i++)\n    {\n        cin >> reduction[i].first;\n    }\n\n    reduction[0].first = 0, reduction[0].second = time;\n    sort(reduction.begin(), reduction.end());\n\n    vector < pair <long long, long long> > creation(no_of_spells_2 + 1);\n    vector <long long> creation_cost(no_of_spells_2 + 1);\n    for(int i = 1; i <= no_of_spells_2; i++)\n    {\n        cin >> creation[i].second;\n    }\n\n    for(int i = 1; i <= no_of_spells_2; i++)\n    {\n        cin >> creation[i].first;\n\n        creation_cost[i] = creation[i].first;\n    }\n\n    sort(creation.begin(), creation.end());\n    sort(creation_cost.begin(), creation_cost.end());\n\n    vector <long long> prefix_max(no_of_spells_2 + 1);\n    for(int i = 1; i <= no_of_spells_2; i++)\n    {\n        prefix_max[i] = max(prefix_max[i - 1], creation[i].second);\n\n        //cout << \"At i = \" << i << \" Creation Cost = \" << creation[i].first << \" Creation = \" << creation[i].second << \" Best = \" << prefix_max[i] << \"\\n\";\n    }\n\n    long long best_time = time*no_of_potions;\n\n    for(int i = 0; i <= no_of_spells_1; i++)\n    {\n        if(reduction[i].first > money)\n        {\n            break;\n        }\n\n        long long remaining_money = max(0LL, money - reduction[i].first);\n\n        int index;\n        int left = 0, right = creation_cost.size() - 1;\n\n        if(creation_cost[right] <= remaining_money)\n        {\n            index = right;\n        }\n        else\n        {\n            while(right - left > 1)\n            {\n                int mid = (left + right)/2;\n\n                if(creation_cost[mid] > remaining_money)\n                {\n                    right = mid;\n                }\n                else\n                {\n                    left = mid;\n                }\n            }\n\n            index = left;\n        }\n\n        long long new_potions = prefix_max[index], new_time = reduction[i].second;\n\n        long long remaining_potions = max(0LL, no_of_potions - new_potions);\n\n        long long time_here = (remaining_potions*new_time);\n\n        best_time = min(best_time, time_here);\n    }\n\n    cout << best_time << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Practice/Explanations/Anton and Tree Explanation.txt.txt",
    "content": "Let us compress consecutive vertices of the same colour into one vertex. \r\nAfter this transformation, we have a tree where every pair of consecutive vertices have a different colour. \r\n\r\nLet us look at the diameter of the tree - The longest distance between two nodes. \r\n\r\n- Let us look at the diameter of this tree. The length of the diameter reduces by at most $2$ in each step and stops when it is $0$\r\n- Let us make sure that it reduces by exactly $2$ at each step.\r\n- There might be multiple diameters so choose the 'center' of the diameter. Find a vertex $v$ such that the distance to any vertex does not exceed $\\lceil d/2 \\rceil$\r\n    - When we perform the operation on $v$ $\\lceil d/2 \\rceil$ times, the distance from $v$ to any other vertex will be $0$ since it moves one step closer to it's leaves at every step.\r\n    - So, we have shown that it is possible in $\\lceil d/2 \\rceil$ steps and also shown that it cannot happen faster.\r\n\r\n------\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n \r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> colour[i];\r\n    }\r\n \r\n    int no_of_edges = no_of_vertices - 1;\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n \r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n \r\n    int component_no = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(component[i] == 0)\r\n        {\r\n            dfs_component(i, 0, ++component_no);\r\n        }\r\n    }\r\n \r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        for(int child : graph[i])\r\n        {\r\n            int child_component = component[child], this_component = component[i];\r\n \r\n            if(child_component != this_component)\r\n            {   \r\n                component_graph[this_component].push_back(child_component);\r\n                component_graph[child_component].push_back(this_component);\r\n            }\r\n        }\r\n    }\r\n \r\n    int diameter = get_component_graph_diameter(component_no);\r\n \r\n    int answer = ceil(diameter, 2);\r\n \r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}\r\n\r\n------\r\n\r\nTo find the diameter, we \r\n\r\n1. Root the tree arbitrarily and find the furthest node from it u \r\n2. Calculate the distance of the furthest node from u (v)\r\n3. The diameter is u-v\r\n\r\n------\r\n\r\nint get_component_graph_diameter(int n)\r\n{\r\n    const int oo = 1e9;\r\n \r\n    int root = 1;\r\n    vector <int> distance(n + 1, oo);\r\n    distance[root] = 0;\r\n \r\n    queue <int> Q;\r\n    Q.push(root);\r\n    while(Q.size() > 0)\r\n    {\r\n        int v = Q.front(); Q.pop();\r\n \r\n        for(int child_v : component_graph[v])\r\n        {\r\n            if(distance[v] + 1 < distance[child_v])\r\n            {\r\n                distance[child_v] = distance[v] + 1;\r\n                Q.push(child_v);\r\n            }\r\n        }\r\n    }\r\n \r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(distance[i] > distance[root])\r\n        {\r\n            root = i;\r\n        }\r\n    }\r\n \r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        distance[i] = oo;\r\n    }\r\n    distance[root] = 0;\r\n \r\n    Q.push(root);\r\n    while(Q.size() > 0)\r\n    {\r\n        int v = Q.front(); Q.pop();\r\n \r\n        for(int child_v : component_graph[v])\r\n        {   \r\n            if(distance[v] + 1 < distance[child_v])\r\n            {\r\n                distance[child_v] = distance[v] + 1;\r\n                Q.push(child_v);\r\n            }\r\n        }\r\n    }\r\n \r\n    int diameter = 0;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        diameter = max(diameter, distance[i]); \r\n\t\t}\r\n \r\n    return diameter;\r\n}"
  },
  {
    "path": "2021/Practice/Explanations/Counter Attack Explanation.txt.txt",
    "content": "We have to count the number of components in the complement graph. \r\nWe also need a way to query if two vertices are connected. \r\n\r\n\r\nWe will also maintain a set of all unvisited vertices. \r\nPick up the first vertex in the unvisited set. \r\nErase it \r\nKeep traversing the unvisited set till there is a vertex with which there is no edge and then repeat\r\n\r\n-----\r\n\r\nWhy does this work ? \r\n\r\nIt looks like it should time out since we are going through the whole unvisited set for each vertex. \r\n\r\nLet us count the number of times we will pick a vertex from the unvisited set. \r\nWe perform two operations \r\n1. Pick up a vertex \r\n2. Skip it and go to next element in the set\r\n\r\nThere are N vertices in the set and each will be picked one time, after which it will be erased. \r\nHow many times do we pick a vertex and skip it ? \r\nWe will skip a vertex only if it has an edge with the current vertex. \r\nSince there are M edges, we can perform at most M skips.  \r\n\r\nSo the number of 'touches' we do to the unvisited set is O(N + M) \r\nWe do N steps of Type 1 and at most M steps of Type 2\r\n\r\nEach has a O(log N) factor \r\n\r\nHad to optimise the constant factor so used an adjacency vector instead of adjacency set.\r\n\r\n-----\r\n\r\nset <int> unvisited;\r\nvector <int> graph[MAX_N];\r\nvector <vector <int> > components;\r\n\r\nvoid dfs(int v)\r\n{\r\n    unvisited.erase(v);\r\n    //C.push_back(v);\r\n    components.back().push_back(v);\r\n\r\n    for(auto it = unvisited.begin(); it != unvisited.end(); )\r\n    {\r\n        if(binary_search(graph[v].begin(), graph[v].end(), (*it)))\r\n        {\r\n            it++;\r\n        }\r\n        else\r\n        {\r\n            int child = *it;\r\n\r\n            dfs(child);\r\n\r\n            it = unvisited.lower_bound(child);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        unvisited.insert(i);\r\n\r\n        sort(graph[i].begin(), graph[i].end());\r\n    }\r\n\r\n    while(unvisited.size() > 0)\r\n    {\r\n        int v = *(unvisited.begin());\r\n\r\n        vector <int> C;\r\n        components.push_back(C);\r\n        dfs(v);\r\n    }\r\n\r\n    cout << components.size() << \"\\n\";\r\n    for(int c = 0; c < components.size(); c++)\r\n    {\r\n        cout << components[c].size() << \" \";\r\n        for(int v : components[c])\r\n        {\r\n            cout << v << \" \";\r\n        }\r\n\r\n        cout << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Practice/Explanations/Game of Stones Explanation.txt.txt",
    "content": "## Grundy Revision\r\n\r\n- The grundy number of a state from which we cannot make a move is $0$.\r\n    - The grundy number of a state is the $mex$ of the grundy numbers of the states it can transition to.\r\n    - The reason is that it is similar to a pile with that many stones. We can either take some stones or add stones but not leave it as it is.\r\n    - NIM does not change if we are allowed to add stones.\r\n\r\n---\r\n\r\n## Grundy Number of $(N, Mask)$\r\n\r\n- Let $g(n, m)$ be the grundy number of a pile with $n$ stones and $m$ represents a bitmask where the $i$-th bit is set if we are allowed to take $i$ stones from the pile\r\n- When we take $i$ stones from a pile, the size of the pile becomes $(n - i)$ and the mask also does not have the $i$-th bit set anymore.\r\n- We can find out the $g(n, 111 ... 1)$ and find the answer by taking the XOR of all the piles.\r\n\r\n## Why is this practical $?$\r\n\r\n- The bitmasks can be as large as $2^{60}$ so how can we compute them $?$\r\n- We will do it recursively and only evaluate those states which we need.\r\n- Suppose we take a stone of size $25$ from $60$, not only does the size of the pile reduce to $35$, the eligible moves is also at most $35$, so all bits in $[36, 60]$ will be removed.\r\n    - This is a great optimisation and allows us to find the grundy of the states quickly.\r\n\r\n-----\r\n\r\nmap < pair <int, long long>, int > grundy;\r\n\r\nint is_bit_set(long long n, int bit)\r\n{\r\n    return ( (n & (1LL << bit)) != 0);\r\n}\r\n\r\nlong long unset(long long n, int bit)\r\n{\r\n    n ^= (1LL << bit);\r\n\r\n    return n;\r\n}\r\n\r\nint get_grundy(int n, long long mask)\r\n{\r\n    //Not possible to take more than N from this pile - Bits are 0 indexed\r\n    for(int higher_bit = n; higher_bit < MAX_BIT; higher_bit++)\r\n    {\r\n        if(is_bit_set(mask, higher_bit))\r\n        {\r\n            mask = unset(mask, higher_bit);\r\n        }\r\n    }\r\n    //cout << \"State(\" << n << \",\" << mask << \")\\n\";\r\n    pair <int, long long> pair_here = make_pair(n, mask);\r\n\r\n    if(grundy.find(pair_here) != grundy.end())\r\n    {\r\n        return grundy[pair_here];\r\n    }\r\n\r\n    vector <int> visited(MAX_BIT, false);\r\n    for(int bit = 0; bit < n; bit++)\r\n    {\r\n        if(is_bit_set(mask, bit))\r\n        {\r\n            long long new_mask = unset(mask, bit);\r\n            int new_state = get_grundy(n - bit - 1, new_mask); //cout << \"Visited \" << new_state << \"\\n\";\r\n\r\n            visited[new_state] = true;\r\n        }\r\n    }\r\n\r\n    int mex = 0;\r\n    for(int bit = 0; bit < MAX_BIT; bit++)\r\n    {\r\n        if( visited[bit])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        mex = bit;\r\n        break;\r\n    }\r\n\r\n    grundy[pair_here] = mex;\r\n\r\n    return grundy[pair_here];\r\n\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_piles;\r\n    cin >> no_of_piles;\r\n\r\n    grundy[make_pair(0, 0)] = 0;\r\n\r\n    int pile_xor = 0;\r\n    for(int i = 1; i <= no_of_piles; i++)\r\n    {\r\n        int x;\r\n        cin >> x;\r\n\r\n        pile_xor ^= get_grundy(x, (1LL << x) - 1);\r\n    }\r\n\r\n    int second_player_win = (pile_xor == 0);\r\n    cout << (second_player_win ? \"YES\" : \"NO\") << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "2021/Practice/Explanations/Lost Tree Explanation.txt.txt",
    "content": "Let us root the tree at 1. \r\nThere will be some vertices at an odd distance from 1 and some at an even distance \r\n\r\nNo 2 vertices of the same parity are connected. Otherwise, it would lead to a cycle. \r\n\r\nIf we know the neighbours of any one parity (odd or even), we know the neighbours of the other parity too. \r\n\r\nOne of these sets will have <= N/2 elements. \r\nWe will choose the set with lower cardinality. \r\n\r\n-----\r\n\r\nThe reason this works is because trees are bipartite due to the absence of any cycle (of odd length, particularly). \r\n\r\nWe are partitioning it into 2 sets and asking questions with the smaller set. \r\n\r\n-----\r\n\r\nvoid ask(int v, vector <int> &D, int n)\r\n{\r\n    cout << \"? \" << v << \"\\n\";\r\n    cout.flush();\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        cin >> D[i];\r\n    }\r\n}\r\n\r\nvoid add_neighbours(int v, vector <int> &D, vector <vector <int> > &T)\r\n{\r\n    for(int i = 2; i < D.size(); i++)\r\n    {\r\n        if(D[i] == 1)\r\n        {\r\n            T[v].push_back(i);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    vector <vector <int> > tree(no_of_vertices + 1);\r\n    vector <vector <int> > parity(2);\r\n\r\n    vector <int> distance(no_of_vertices + 1);\r\n\r\n    ask(1, distance, no_of_vertices);\r\n    add_neighbours(1, distance, tree);\r\n\r\n    for(int i = 2; i <= no_of_vertices; i++)\r\n    {\r\n        parity[distance[i]%2].push_back(i);\r\n    }\r\n\r\n    vector <int> chosen = (parity[0].size() < parity[1].size() ? parity[0] : parity[1]);\r\n\r\n    for(int v : chosen)\r\n    {\r\n        ask(v, distance, no_of_vertices);\r\n        add_neighbours(v, distance, tree);\r\n    }\r\n\r\n    cout << \"!\\n\";\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        for(int v : tree[i])\r\n        {\r\n            cout << i << \" \" << v << \"\\n\";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "2021/Practice/Explanations/Maximum Absurdity Explanation.txt.txt",
    "content": "Let us first solve the problem for 1 segment. \r\n\r\nLet f1(i) be the maximum segment of length i ending on or before i \r\n\r\nf1(i) = max{f1(i - 1), sum[i - k + 1, i]} \r\n\r\n---- \r\n\r\nNow, we will iterate over every possible beginning of the second segment. \r\n\r\nIf the second segment starts at i, the value is sum[i, i + k - 1]\r\n\r\nWe will match it with f1(i - 1) \r\n\r\nBest_value(i) = f1(i - 1) + sum[i, i + k - 1] \r\n\r\n-----\r\n\r\nWe will choose the maximum of Best_value through the array \r\n\r\nSince we need to give a and b and not just the maximum value, \r\nstore the best possible a in another array parallelly \r\n\r\nbest_a(i) holds the best a for any segment ending on or before i \r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_elements, segment_length;\r\n    cin >> no_of_elements >> segment_length;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    vector <long long> sum_till(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i] = A[i] + sum_till[i - 1];\r\n    }\r\n\r\n    vector <long long> best_segment_1_till(no_of_elements + 1);\r\n    vector <int> best_a(no_of_elements + 1);\r\n    for(int i = segment_length; i <= no_of_elements; i++)\r\n    {\r\n        long long this_segment = sum_till[i] - sum_till[i - segment_length];\r\n        best_segment_1_till[i] = best_segment_1_till[i - 1];\r\n        best_a[i] = best_a[i - 1];\r\n\r\n        if(this_segment > best_segment_1_till[i - 1])\r\n        {\r\n            best_a[i] = i - segment_length + 1;\r\n\r\n            best_segment_1_till[i] = this_segment;\r\n        }\r\n    }\r\n\r\n    long long answer = 0, a, b;\r\n    for(int i = segment_length + 1; i + segment_length - 1 <= no_of_elements; i++)\r\n    {\r\n        long long segment_2 = sum_till[i + segment_length - 1] - sum_till[i - 1];\r\n        //cout << \"i = \" << i << \" 1 = \" << best_segment_1_till[i - 1] << \" 2 = \" << segment_2 << \"\\n\";\r\n\r\n        if(best_segment_1_till[i - 1] + segment_2 > answer)\r\n        {\r\n            answer = best_segment_1_till[i - 1] + segment_2;\r\n\r\n            a = best_a[i - 1];\r\n            b = i;\r\n        }\r\n    }\r\n\r\n    cout << a << \" \" << b << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Practice/Programs/Anton and Making Potions.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_potions, no_of_spells_1, no_of_spells_2;\n    cin >> no_of_potions >> no_of_spells_1 >> no_of_spells_2;\n\n    long long time, money;\n    cin >> time >> money;\n\n    vector < pair <long long, long long> > reduction(no_of_spells_1 + 1);\n    for(int i = 1; i <= no_of_spells_1; i++)\n    {\n        cin >> reduction[i].second;\n    }\n\n    for(int i = 1; i <= no_of_spells_1; i++)\n    {\n        cin >> reduction[i].first;\n    }\n\n    reduction[0].first = 0, reduction[0].second = time;\n    sort(reduction.begin(), reduction.end());\n\n    vector < pair <long long, long long> > creation(no_of_spells_2 + 1);\n    vector <long long> creation_cost(no_of_spells_2 + 1);\n    for(int i = 1; i <= no_of_spells_2; i++)\n    {\n        cin >> creation[i].second;\n    }\n\n    for(int i = 1; i <= no_of_spells_2; i++)\n    {\n        cin >> creation[i].first;\n\n        creation_cost[i] = creation[i].first;\n    }\n\n    sort(creation.begin(), creation.end());\n    sort(creation_cost.begin(), creation_cost.end());\n\n    vector <long long> prefix_max(no_of_spells_2 + 1);\n    for(int i = 1; i <= no_of_spells_2; i++)\n    {\n        prefix_max[i] = max(prefix_max[i - 1], creation[i].second);\n\n        //cout << \"At i = \" << i << \" Creation Cost = \" << creation[i].first << \" Creation = \" << creation[i].second << \" Best = \" << prefix_max[i] << \"\\n\";\n    }\n\n    long long best_time = time*no_of_potions;\n\n    for(int i = 0; i <= no_of_spells_1; i++)\n    {\n        if(reduction[i].first > money)\n        {\n            break;\n        }\n\n        long long remaining_money = max(0LL, money - reduction[i].first);\n\n        int index;\n        int left = 0, right = creation_cost.size() - 1;\n\n        if(creation_cost[right] <= remaining_money)\n        {\n            index = right;\n        }\n        else\n        {\n            while(right - left > 1)\n            {\n                int mid = (left + right)/2;\n\n                if(creation_cost[mid] > remaining_money)\n                {\n                    right = mid;\n                }\n                else\n                {\n                    left = mid;\n                }\n            }\n\n            index = left;\n        }\n\n        long long new_potions = prefix_max[index], new_time = reduction[i].second;\n\n        long long remaining_potions = max(0LL, no_of_potions - new_potions);\n\n        long long time_here = (remaining_potions*new_time);\n\n        best_time = min(best_time, time_here);\n    }\n\n    cout << best_time << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "2021/Practice/Programs/Anton and Tree.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <queue>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 5;\r\nvector <int> graph[MAX_N];\r\nvector <int> colour(MAX_N);\r\nvector <int> component(MAX_N);\r\nvector <int> component_graph[MAX_N];\r\n\r\nint ceil(int n, int d)\r\n{\r\n    return (n/d) + (n%d != 0);\r\n}\r\n\r\nvoid dfs_component(int v, int parent_v, int component_no)\r\n{\r\n    component[v] = component_no;\r\n\r\n    for(int child_v : graph[v])\r\n    {\r\n        if(child_v != parent_v && colour[child_v] == colour[v])\r\n        {\r\n            dfs_component(child_v, v, component_no);\r\n        }\r\n    }\r\n}\r\n\r\nint get_component_graph_diameter(int n)\r\n{\r\n    const int oo = 1e9;\r\n\r\n    /*for(int i = 1; i <= n; i++)\r\n    {\r\n        cout << \"Children of \" << i << \" : \";\r\n\r\n        for(int child_v : component_graph[i])\r\n        {\r\n            cout << child_v << \" \";\r\n        }\r\n\r\n        cout << \"\\n\";\r\n    }*/\r\n\r\n    int root = 1;\r\n    vector <int> distance(n + 1, oo);\r\n    distance[root] = 0;\r\n\r\n    queue <int> Q;\r\n    Q.push(root);\r\n    while(Q.size() > 0)\r\n    {\r\n        int v = Q.front(); Q.pop();\r\n\r\n        for(int child_v : component_graph[v])\r\n        {\r\n            if(distance[v] + 1 < distance[child_v])\r\n            {\r\n                distance[child_v] = distance[v] + 1;\r\n                Q.push(child_v);\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(distance[i] > distance[root])\r\n        {\r\n            root = i;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        distance[i] = oo;\r\n    }\r\n    distance[root] = 0;\r\n\r\n    Q.push(root);\r\n    while(Q.size() > 0)\r\n    {\r\n        int v = Q.front(); Q.pop();\r\n\r\n        for(int child_v : component_graph[v])\r\n        {   //cout << child_v << \" is a child of \" << v << \"\\n\";\r\n            if(distance[v] + 1 < distance[child_v])\r\n            {\r\n                distance[child_v] = distance[v] + 1;\r\n                Q.push(child_v);\r\n            }\r\n        }\r\n    }\r\n\r\n    int diameter = 0;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        diameter = max(diameter, distance[i]); //cout << \"Component \" << i << \" has distance \" << distance[i] << \"\\n\";\r\n    }\r\n\r\n    return diameter;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> colour[i];\r\n    }\r\n\r\n    int no_of_edges = no_of_vertices - 1;\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    int component_no = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(component[i] == 0)\r\n        {\r\n            dfs_component(i, 0, ++component_no);\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        for(int child : graph[i])\r\n        {\r\n            int child_component = component[child], this_component = component[i];\r\n\r\n            if(child_component != this_component)\r\n            {   //cout << \"Edge \" << child_component << \" and \" << this_component << \"\\n\";\r\n                component_graph[this_component].push_back(child_component);\r\n                component_graph[child_component].push_back(this_component);\r\n            }\r\n        }\r\n    }\r\n\r\n    int diameter = get_component_graph_diameter(component_no);\r\n\r\n    int answer = ceil(diameter, 2);\r\n\r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Practice/Programs/Counter Attack.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\nconst int MAX_N = 5e5 + 5;\r\n\r\nset <int> unvisited;\r\nvector <int> graph[MAX_N];\r\nvector <vector <int> > components;\r\n\r\nvoid dfs(int v)\r\n{\r\n    unvisited.erase(v);\r\n    //C.push_back(v);\r\n    components.back().push_back(v);\r\n\r\n    for(auto it = unvisited.begin(); it != unvisited.end(); )\r\n    {\r\n        if(binary_search(graph[v].begin(), graph[v].end(), (*it)))\r\n        {\r\n            it++;\r\n        }\r\n        else\r\n        {\r\n            int child = *it;\r\n\r\n            dfs(child);\r\n\r\n            it = unvisited.lower_bound(child);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        unvisited.insert(i);\r\n\r\n        sort(graph[i].begin(), graph[i].end());\r\n    }\r\n\r\n    while(unvisited.size() > 0)\r\n    {\r\n        int v = *(unvisited.begin());\r\n\r\n        vector <int> C;\r\n        components.push_back(C);\r\n        dfs(v);\r\n    }\r\n\r\n    cout << components.size() << \"\\n\";\r\n    for(int c = 0; c < components.size(); c++)\r\n    {\r\n        cout << components[c].size() << \" \";\r\n        for(int v : components[c])\r\n        {\r\n            cout << v << \" \";\r\n        }\r\n\r\n        cout << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Practice/Programs/Game of Stones.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_BIT = 63;\r\n\r\nmap < pair <int, long long>, int > grundy;\r\n\r\nint is_bit_set(long long n, int bit)\r\n{\r\n    return ( (n & (1LL << bit)) != 0);\r\n}\r\n\r\nlong long unset(long long n, int bit)\r\n{\r\n    n ^= (1LL << bit);\r\n\r\n    return n;\r\n}\r\n\r\nint get_grundy(int n, long long mask)\r\n{\r\n    //Not possible to take more than N from this pile - Bits are 0 indexed\r\n    for(int higher_bit = n; higher_bit < MAX_BIT; higher_bit++)\r\n    {\r\n        if(is_bit_set(mask, higher_bit))\r\n        {\r\n            mask = unset(mask, higher_bit);\r\n        }\r\n    }\r\n    //cout << \"State(\" << n << \",\" << mask << \")\\n\";\r\n    pair <int, long long> pair_here = make_pair(n, mask);\r\n\r\n    if(grundy.find(pair_here) != grundy.end())\r\n    {\r\n        return grundy[pair_here];\r\n    }\r\n\r\n    vector <int> visited(MAX_BIT, false);\r\n    for(int bit = 0; bit < n; bit++)\r\n    {\r\n        if(is_bit_set(mask, bit))\r\n        {\r\n            long long new_mask = unset(mask, bit);\r\n            int new_state = get_grundy(n - bit - 1, new_mask); //cout << \"Visited \" << new_state << \"\\n\";\r\n\r\n            visited[new_state] = true;\r\n        }\r\n    }\r\n\r\n    int mex = 0;\r\n    for(int bit = 0; bit < MAX_BIT; bit++)\r\n    {\r\n        if( visited[bit])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        mex = bit;\r\n        break;\r\n    }\r\n\r\n    grundy[pair_here] = mex;\r\n\r\n    return grundy[pair_here];\r\n\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_piles;\r\n    cin >> no_of_piles;\r\n\r\n    grundy[make_pair(0, 0)] = 0;\r\n\r\n    int pile_xor = 0;\r\n    for(int i = 1; i <= no_of_piles; i++)\r\n    {\r\n        int x;\r\n        cin >> x;\r\n\r\n        pile_xor ^= get_grundy(x, (1LL << x) - 1);\r\n    }\r\n\r\n    int second_player_win = (pile_xor == 0);\r\n    cout << (second_player_win ? \"YES\" : \"NO\") << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Practice/Programs/Lost Tree.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid ask(int v, vector <int> &D, int n)\r\n{\r\n    cout << \"? \" << v << \"\\n\";\r\n    cout.flush();\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        cin >> D[i];\r\n    }\r\n}\r\n\r\nvoid add_neighbours(int v, vector <int> &D, vector <vector <int> > &T)\r\n{\r\n    for(int i = 2; i < D.size(); i++)\r\n    {\r\n        if(D[i] == 1)\r\n        {\r\n            T[v].push_back(i);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    vector <vector <int> > tree(no_of_vertices + 1);\r\n    vector <vector <int> > parity(2);\r\n\r\n    vector <int> distance(no_of_vertices + 1);\r\n\r\n    ask(1, distance, no_of_vertices);\r\n    add_neighbours(1, distance, tree);\r\n\r\n    for(int i = 2; i <= no_of_vertices; i++)\r\n    {\r\n        parity[distance[i]%2].push_back(i);\r\n    }\r\n\r\n    vector <int> chosen = (parity[0].size() < parity[1].size() ? parity[0] : parity[1]);\r\n\r\n    for(int v : chosen)\r\n    {\r\n        ask(v, distance, no_of_vertices);\r\n        add_neighbours(v, distance, tree);\r\n    }\r\n\r\n    cout << \"!\\n\";\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        for(int v : tree[i])\r\n        {\r\n            cout << i << \" \" << v << \"\\n\";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2021/Practice/Programs/Maximum Absurdity.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, segment_length;\r\n    cin >> no_of_elements >> segment_length;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    vector <long long> sum_till(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i] = A[i] + sum_till[i - 1];\r\n    }\r\n\r\n    vector <long long> best_segment_1_till(no_of_elements + 1);\r\n    vector <int> best_a(no_of_elements + 1);\r\n    for(int i = segment_length; i <= no_of_elements; i++)\r\n    {\r\n        long long this_segment = sum_till[i] - sum_till[i - segment_length];\r\n        best_segment_1_till[i] = best_segment_1_till[i - 1];\r\n        best_a[i] = best_a[i - 1];\r\n\r\n        if(this_segment > best_segment_1_till[i - 1])\r\n        {\r\n            best_a[i] = i - segment_length + 1;\r\n\r\n            best_segment_1_till[i] = this_segment;\r\n        }\r\n    }\r\n\r\n    long long answer = 0, a, b;\r\n    for(int i = segment_length + 1; i + segment_length - 1 <= no_of_elements; i++)\r\n    {\r\n        long long segment_2 = sum_till[i + segment_length - 1] - sum_till[i - 1];\r\n        //cout << \"i = \" << i << \" 1 = \" << best_segment_1_till[i - 1] << \" 2 = \" << segment_2 << \"\\n\";\r\n\r\n        if(best_segment_1_till[i - 1] + segment_2 > answer)\r\n        {\r\n            answer = best_segment_1_till[i - 1] + segment_2;\r\n\r\n            a = best_a[i - 1];\r\n            b = i;\r\n        }\r\n    }\r\n\r\n    cout << a << \" \" << b << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Explanations/Good Pairs Explanation.txt.txt",
    "content": "Let us take the minimum and maximum elements of this array \r\n\r\nA[i] - A[1] + A[n] - A[i] = A[n] - A[i] \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int minimum = 1, maximum = 1;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] >= A[maximum])\r\n        {\r\n            maximum = i;\r\n        }\r\n        else if(A[i] < A[minimum])\r\n        {\r\n            minimum = i;\r\n        }\r\n    }\r\n\r\n    cout << minimum << \" \" << maximum << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Explanations/Make Equal with Mod Explanation.txt.txt",
    "content": "Notice that we can never change a 0 or 1 \r\nIf there is a 0 or 1, it will remain 0 or 1 throughout all the operations that we do. \r\n\r\nThe next observation to make is that we can set every element = 0 \r\nWe can start with the largest element and make all elements = 0 by choosing x = max of the current array \r\n\r\nThis works, except when there is a 1 in the array \r\n\r\n-----\r\n\r\nWhen there is a 1 in the array, we can follow a similar algorithm and set all elements = 1, \r\nby choosing X = Array Max - 1 at each step \r\n\r\nThe only exception is when we have 2 consecutive elements. \r\nWhen we have 2 consecutive elements, we can never make both elements = 1 \r\n\r\nWe will finish at a situation where m = 1 and m + 1 = 2 or m = 0 and m + 1 = 2\r\nIn both cases, we can not make 0 or 2 = 1 by any operation\r\n\r\nNow, it is impossible. \r\n\r\n------\r\n\r\nIt is impossible when there is a 1 in the array and there are consecutive elements in the array \r\n\r\nOtherwise, we can make all elements = 0 or 1 depending on whether the array has a 1 or not. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    vector <int> present(3, false);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] <= 2)\r\n        {\r\n            present[A[i]] = true;\r\n        }\r\n    }\r\n\r\n    int possible = true;\r\n    if(present[1])\r\n    {\r\n        sort(A.begin(), A.end());\r\n\r\n        for(int i = 1; i + 1 <= no_of_elements; i++)\r\n        {\r\n            if(A[i] + 1 == A[i + 1])\r\n            {\r\n                possible = false;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Explanations/Subtract Operations Explanation.txt",
    "content": "Suppose we subtract the whole array by X in the first step \n\nEach A2[i] = A[i] - x \n\nSuppose we subtract the whole array by Y = A2[j] in the second step \n\nEach A3[i] = A2[i] - Y = (A[i] - X) - (A[j] - X)\n\nWhere A[i], A2[i] and A3[i] represent the state of A[i] at time 1, 2, 3 respectively\n\nX gets cancelled out twice. \n\nEvery operation cancels out everything that was subtracted in the previous step. \n\nWhat we will be left with in the end is the difference of 2 elements A[i] - A[j] \n\nWe have to check if there is a pair who's difference is K in the original array. \n\n------\n\nvoid solve()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    map <int, int> present;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        present[A[i]] = true;\n    }\n\n    int possible = false;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(present[A[i] - k] || present[A[i] + k])\n        {\n            possible = true;\n            break;\n        }\n    }\n\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\n}\n"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Programs/Good Pairs.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int minimum = 1, maximum = 1;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] >= A[maximum])\r\n        {\r\n            maximum = i;\r\n        }\r\n        else if(A[i] < A[minimum])\r\n        {\r\n            minimum = i;\r\n        }\r\n    }\r\n\r\n    cout << minimum << \" \" << maximum << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Programs/K-good.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nlong long get_odd_part(long long n)\r\n{\r\n    while(n%2 == 0)\r\n    {\r\n        n = n >> 1;\r\n    }\r\n\r\n    return n;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    long long n;\r\n    cin >> n;\r\n\r\n    if(n%2 == 1)\r\n    {\r\n        cout << \"2\\n\";\r\n        return;\r\n    }\r\n\r\n    long long original_n = n;\r\n    long long odd_part = 1, even_part = 1;\r\n    while(n%2 != 1)\r\n    {\r\n        n = n >> 1;\r\n\r\n        even_part *= 2;\r\n    }\r\n    odd_part = n;\r\n    //cout << \"E = \" << even_part << \" O = \" << odd_part << \"\\n\";\r\n\r\n    if(odd_part == 1)\r\n    {\r\n        cout << \"-1\\n\";\r\n        return;\r\n    }\r\n\r\n    cout << min(2*even_part, odd_part) << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Programs/Make Equal With Mod.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> present(3, false);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] <= 2)\n        {\n            present[A[i]] = true;\n        }\n    }\n\n    int possible = true;\n    if(present[1])\n    {\n        sort(A.begin(), A.end());\n\n        for(int i = 1; i + 1 <= no_of_elements; i++)\n        {\n            if(A[i] + 1 == A[i + 1])\n            {\n                possible = false;\n                break;\n            }\n        }\n    }\n\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n \n"
  },
  {
    "path": "2022/Contests/Combined Divisions/CodeTON/Programs/Subtract Operation.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, k;\r\n    cin >> no_of_elements >> k;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    map <int, int> present;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        present[A[i]] = true;\r\n    }\r\n\r\n    int possible = false;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(present[A[i] - k] || present[A[i] + k])\r\n        {\r\n            possible = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/766/Programs/Not Adding.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const int MAX_N = 1e6 + 5;\n    vector <int> is_present(MAX_N, false);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        is_present[A[i]] = true;\n    }\n\n    vector <int> multiple_gcd(MAX_N, 0);\n    for(int i = 1; i < MAX_N; i++)\n    {\n        for(int multiple = i; multiple < MAX_N; multiple += i)\n        {\n            if(is_present[multiple])\n            {\n                multiple_gcd[i] = __gcd(multiple_gcd[i], multiple);\n            }\n        }\n    }\n\n    int new_elements = 0;\n    for(int i = 1; i < MAX_N; i++)\n    {\n        if(!is_present[i] && multiple_gcd[i] == i)\n        {\n            new_elements++;\n        }\n    }\n\n    cout << new_elements << \"\\n\";\n    return 0;\n}\n\n\n\n"
  },
  {
    "path": "2022/Contests/Div 2/766/Programs/Not Assigning.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint other(int p)\r\n{\r\n    return (p + 1)%2;\r\n}\r\n\r\nvoid dfs(vector < vector <int> > &T, int parent_v, int v, map <pair <int, int>, int> &weight, int parity)\r\n{\r\n    for(int child_v : T[v])\r\n    {\r\n        if(child_v == parent_v)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        int x = v, y = child_v;\r\n        if(x > y)\r\n        {\r\n            swap(x, y);\r\n        }\r\n\r\n        weight[make_pair(x, y)] = (parity == 0 ? 2 : 3);\r\n\r\n        dfs(T, v, child_v, weight, other(parity));\r\n    }\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    int no_of_edges = no_of_vertices - 1;\r\n    vector <pair <int, int> > edges;\r\n    vector <vector <int> > tree(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        tree[u].push_back(v);\r\n        tree[v].push_back(u);\r\n\r\n        if(u > v)\r\n        {\r\n            swap(u, v);\r\n        }\r\n\r\n        edges.push_back(make_pair(u, v));\r\n    }\r\n\r\n    int possible = true;\r\n    int root = 1;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(tree[i].size() >= 3)\r\n        {\r\n            possible = false;\r\n            break;\r\n        }\r\n\r\n        if(tree[i].size() == 1)\r\n        {\r\n            root = i;\r\n        }\r\n    }\r\n\r\n    if(!possible)\r\n    {\r\n        cout << \"-1\\n\";\r\n        return;\r\n    }\r\n\r\n    map <pair <int, int>, int > edge_weight;\r\n    dfs(tree, 0, root, edge_weight, 0);\r\n\r\n    for(pair <int, int> edge : edges)\r\n    {\r\n        cout << edge_weight[edge] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/766/Programs/Not Shading.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int rows, columns, x, y;\r\n    cin >> rows >> columns >> x >> y;\r\n\r\n    vector <string> grid(rows);\r\n    for(int i = 0; i < rows; i++)\r\n    {\r\n        cin >> grid[i];\r\n    }\r\n    x--;\r\n    y--;\r\n\r\n    int answer = -1;\r\n\r\n    int black_count = 0, black_row_count = 0, black_column_count = 0;\r\n    for(int r = 0; r < rows; r++)\r\n    {\r\n        for(int c = 0; c < columns; c++)\r\n        {\r\n            if(grid[r][c] == 'B')\r\n            {\r\n                black_count++;\r\n\r\n                if(r == x)\r\n                {\r\n                    black_row_count++;\r\n                }\r\n\r\n                if(c == y)\r\n                {\r\n                    black_column_count++;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    if(grid[x][y] == 'B')\r\n    {\r\n        answer = 0;\r\n    }\r\n    else if(black_row_count > 0 || black_column_count > 0)\r\n    {\r\n        answer = 1;\r\n    }\r\n    else if(black_count > 0)\r\n    {\r\n        answer = 2;\r\n    }\r\n    else\r\n    {\r\n        answer = -1;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/766/Programs/Not Sitting.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int rows, columns;\r\n    cin >> rows >> columns;\r\n\r\n    vector <int> distances;\r\n    int row_distance = 0, column_distance = 0;\r\n    for(int r = 1; r <= rows; r++)\r\n    {\r\n        for(int c = 1; c <= columns; c++)\r\n        {\r\n            row_distance = max(rows - r, r - 1);\r\n            column_distance = max(columns - c, c - 1);\r\n            distances.push_back(row_distance + column_distance);\r\n        }\r\n\r\n    }\r\n\r\n    sort(distances.begin(), distances.end());\r\n\r\n    for(int d : distances)\r\n    {\r\n        cout << d << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Explanations/Meximum Array Explanation.txt",
    "content": "We need the lexicographically maximum sequence. \nThis means that we must be choosing the largest element whenever possible. \n\nWe will choose the Mex of the entire array at every given point in time. \nIf there are multiple MEX, we will look at the \n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> frequency(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n\n    int array_mex = 0;\n    for(int i = 0; i <= no_of_elements; i++)\n    {\n        if(frequency[i] == 0)\n        {\n            array_mex = i;\n            break;\n        }\n    }\n\n    set <int> all_elements, unseen;\n    for(int i = 0; i <= array_mex; i++)\n    {\n        all_elements.insert(i);\n    }\n    unseen = all_elements;\n\n    vector <int> answer;\n    int mex_after_here = array_mex;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]--;\n\n        if(unseen.find(A[i]) != unseen.end())\n        {\n            unseen.erase(A[i]);\n        }\n\n        if(frequency[A[i]] == 0)\n        {\n            mex_after_here = min(mex_after_here, A[i]);\n        }\n\n        if(*(unseen.begin()) == array_mex)\n        {\n            answer.push_back(array_mex);\n            array_mex = mex_after_here;\n\n            unseen = all_elements;\n        }\n    }\n\n    cout << answer.size() << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    cout << \"\\n\";\n}\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/Download More RAM.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, present_RAM;\r\n    cin >> no_of_elements >> present_RAM;\r\n\r\n    vector <pair <int, int> > ram(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> ram[i].first;\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> ram[i].second;\r\n    }\r\n\r\n    sort(ram.begin(), ram.end());\r\n\r\n    int answer = present_RAM;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        if(ram[i].first <= answer)\r\n        {\r\n            answer += ram[i].second;\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/GCD Arrays.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint odd_till(int n)\r\n{\r\n    return (n/2) + n%2;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int left, right, no_of_operations;\r\n    cin >> left >> right >> no_of_operations;\r\n\r\n    int odd_integers = odd_till(right) - odd_till(left - 1);\r\n\r\n    cout << (no_of_operations >= odd_integers || (left == right && left != 1) ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/Game On Sum Easy Version.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long power_mod(long long x, long long power, long long m)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power > 0)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%m;\r\n\r\n        x = (x*x)%m;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nlong long inverse(long long x, long long m)\r\n{\r\n    return power_mod(x, m - 2, m);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    long long no_of_moves, add_moves, range;\r\n    cin >> no_of_moves >> add_moves >> range;\r\n\r\n    const int MOD = 1e9 + 7;\r\n    vector <vector <long long> > score(no_of_moves + 1, vector <long long> (add_moves + 1, 0));\r\n    for(int i = 0; i <= no_of_moves; i++)\r\n    {\r\n        for(int j = 0; j <= add_moves; j++)\r\n        {\r\n            if(i == 0 || j == 0)\r\n            {\r\n                score[i][j] = 0;\r\n                continue;\r\n            }\r\n            if(j == i)\r\n            {\r\n                score[i][j] = (range*j)%MOD;\r\n                continue;\r\n            }\r\n\r\n            score[i][j] = (score[i - 1][j - 1] + score[i - 1][j])%MOD;\r\n            score[i][j] *= inverse(2, MOD);\r\n            score[i][j] %= MOD; //cout << \"F(\" << i << \",\" << j << \") = \" << score[i][j] << \"\\n\";\r\n        }\r\n    }\r\n\r\n    cout << score[no_of_moves][add_moves] << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/Game on Sum Hard Version.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1e9 + 7, MAX_N = 1e6 + 5;\r\nlong long factorial[MAX_N], inverse_factorial[MAX_N];\r\n\r\nlong long power_mod(long long x, long long power, long long m)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power > 0)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%m;\r\n\r\n        x = (x*x)%m;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nlong long inverse(long long x, long long m)\r\n{\r\n    return power_mod(x, m - 2, m);\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    factorial[0] = 1;\r\n    for(int i = 1; i < MAX_N; i++)\r\n    {\r\n        factorial[i] = (i*factorial[i - 1])%MOD;\r\n    }\r\n\r\n    inverse_factorial[MAX_N - 1] = inverse(factorial[MAX_N - 1], MOD);\r\n    for(int i = MAX_N - 2; i >= 0; i--)\r\n    {\r\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\r\n    }\r\n}\r\n\r\nlong long choose(long long n, long long r)\r\n{\r\n    long long numerator = factorial[n];\r\n    long long inverse_denominator = (inverse_factorial[r]*inverse_factorial[n - r])%MOD;\r\n\r\n    return (numerator*inverse_denominator)%MOD;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    long long no_of_moves, add_moves, range;\r\n    cin >> no_of_moves >> add_moves >> range;\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long score = 0;\r\n\r\n    if(add_moves == no_of_moves)\r\n    {\r\n        cout << (range*add_moves)%MOD << \"\\n\";\r\n        return;\r\n    }\r\n\r\n    for(int i = 1; i <= add_moves; i++)\r\n    {\r\n        long long base_case = (i*range)%MOD;\r\n\r\n        long long total_moves = no_of_moves - i;\r\n        long long total_free_moves = total_moves - 1;\r\n        long long total_side_moves = add_moves - i;\r\n\r\n        base_case *= choose(total_free_moves, total_side_moves);\r\n        base_case %= MOD;\r\n        long long power_2 = power_mod(2, total_moves, MOD);\r\n\r\n        //cout << \"i = \" << i << \" Number of paths = C(\" << total_free_moves <<\",\" << total_side_moves << \") = \" << choose(total_free_moves, total_side_moves) << \" 2^i = \" << power_2 << \"\\n\";\r\n        long long contribution = (base_case*inverse(power_2, MOD))%MOD;\r\n\r\n        score += contribution;\r\n        score %= MOD;\r\n    }\r\n    cout << score << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/Grid XOR.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int BLACK = 0, WHITE = 1;\r\n\r\nint get_colour(int x, int y)\r\n{\r\n    return (x + y)%2;\r\n}\r\n\r\nint is_inside(int i, int j, int rows, int columns)\r\n{\r\n    return (1 <= i && i <= rows && 1 <= j && j <= columns);\r\n}\r\n\r\nint get_xor_sum(vector <vector <int> > &G, int n, int colour)\r\n{\r\n    vector <vector <int> > counted(n + 1, vector <int> (n + 1, false));\r\n\r\n    const int NO_OF_NEIGHBOURS = 4;\r\n    int next_x[NO_OF_NEIGHBOURS] = {-1, 0, 0, 1}, next_y[NO_OF_NEIGHBOURS] = {0, 1, -1, 0};\r\n    int xor_sum = 0;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        for(int j = 1; j <= n; j++)\r\n        {\r\n            if(get_colour(i, j) != colour)\r\n            {\r\n                continue;\r\n            }\r\n\r\n            int counted_neighbours = 0;\r\n            for(int k = 0; k < NO_OF_NEIGHBOURS; k++)\r\n            {\r\n                int next_i = i + next_x[k], next_j = j + next_y[k];\r\n\r\n                if(is_inside(next_i, next_j, n, n) && counted[next_i][next_j])\r\n                {\r\n                    counted_neighbours++;\r\n                }\r\n            }\r\n\r\n            if(counted_neighbours == 0)\r\n            {\r\n                xor_sum ^= G[i][j];\r\n\r\n                for(int k = 0; k < NO_OF_NEIGHBOURS; k++)\r\n                {\r\n                    int next_i = i + next_x[k], next_j = j + next_y[k];\r\n\r\n                    if(is_inside(next_i, next_j, n, n))\r\n                    {\r\n                        counted[next_i][next_j] = true;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    return xor_sum;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    vector <vector <int> > grid(n + 1, vector <int> (n + 1, 0));\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        for(int j = 1; j <= n; j++)\r\n        {\r\n            cin >> grid[i][j];\r\n        }\r\n    }\r\n\r\n    int answer = get_xor_sum(grid, n, BLACK)^get_xor_sum(grid, n, WHITE);\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/Meximum Array.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> frequency(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n\n    int array_mex = 0;\n    for(int i = 0; i <= no_of_elements; i++)\n    {\n        if(frequency[i] == 0)\n        {\n            array_mex = i;\n            break;\n        }\n    }\n\n    set <int> all_elements, unseen;\n    for(int i = 0; i <= array_mex; i++)\n    {\n        all_elements.insert(i);\n    }\n    unseen = all_elements;\n\n    vector <int> answer;\n    int mex_after_here = array_mex;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]--;\n\n        if(unseen.find(A[i]) != unseen.end())\n        {\n            unseen.erase(A[i]);\n        }\n\n        if(frequency[A[i]] == 0)\n        {\n            mex_after_here = min(mex_after_here, A[i]);\n        }\n        \n        if(*(unseen.begin()) == array_mex)\n        {\n            answer.push_back(array_mex);\n            array_mex = mex_after_here;\n\n            unseen = all_elements;\n        }\n    }\n\n    cout << answer.size() << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    cout << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2022/Contests/Div 2/767/Programs/Peculiar Movie Preferences.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint is_palindrome(string &S)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] != S[S.size() - 1 - i])\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint check_self(vector <string> &S, int n)\r\n{\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(is_palindrome(S[i]))\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint check_full_concatenation(vector <string> &S, int n)\r\n{\r\n    map <string, int> is_present;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        string reverse_s = S[i];\r\n        reverse(all(reverse_s));\r\n\r\n        if(is_present[reverse_s])\r\n        {\r\n            return true;\r\n        }\r\n\r\n        is_present[S[i]] = true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint check_length_3(vector <string> &S, int n)\r\n{\r\n    map <string, int> is_present;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(S[i].size() == 3)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(S[i].size() == 1)\r\n        {\r\n            is_present[S[i]] = true;\r\n            continue;\r\n        }\r\n\r\n        string last;\r\n        last += S[i][1];\r\n        if(is_present[last])\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    is_present.clear();\r\n\r\n    for(int i = n; i >= 1; i--)\r\n    {\r\n         if(S[i].size() == 3)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(S[i].size() == 1)\r\n        {\r\n            is_present[S[i]] = true;\r\n            continue;\r\n        }\r\n\r\n        string last;\r\n        last += S[i][0];\r\n        if(is_present[last])\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint check_length_4(vector <string> &S, int n)\r\n{\r\n    map <string, int> is_present;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(S[i].size() == 2)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(S[i].size() == 1)\r\n        {\r\n            is_present[S[i]] = true;\r\n            continue;\r\n        }\r\n\r\n        if(S[i][0] == S[i][1])\r\n        {\r\n            string last;\r\n            last += S[i][2];\r\n            if(is_present[last])\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n    }\r\n\r\n    is_present.clear();\r\n\r\n    for(int i = n; i >= 1; i--)\r\n    {\r\n        if(S[i].size() == 2)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(S[i].size() == 1)\r\n        {\r\n            is_present[S[i]] = true;\r\n            continue;\r\n        }\r\n\r\n        if(S[i][1] == S[i][2])\r\n        {\r\n            string last;\r\n            last += S[i][0];\r\n            if(is_present[last])\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint check_length_5(vector <string> &S, int n)\r\n{\r\n    map <string, int> is_present;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(S[i].size() == 1)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(S[i].size() == 2)\r\n        {\r\n            is_present[S[i]] = true;\r\n            continue;\r\n        }\r\n\r\n        string last;\r\n        last += S[i][2];\r\n        last += S[i][1];\r\n        if(is_present[last])\r\n        {\r\n            return true;\r\n        }\r\n\r\n    }\r\n\r\n    is_present.clear();\r\n\r\n    for(int i = n; i >= 1; i--)\r\n    {\r\n        if(S[i].size() == 1)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(S[i].size() == 2)\r\n        {\r\n            is_present[S[i]] = true;\r\n            continue;\r\n        }\r\n\r\n        string last;\r\n        last += S[i][1];\r\n        last += S[i][0];\r\n        if(is_present[last])\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <string> S(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> S[i];\r\n    }\r\n\r\n    int has_awesome_sequence =   check_self(S, no_of_elements)\r\n                              || check_full_concatenation(S, no_of_elements)\r\n                              || check_length_3(S, no_of_elements)\r\n                              || check_length_4(S, no_of_elements)\r\n                              || check_length_5(S, no_of_elements);\r\n\r\n\r\n    cout << (has_awesome_sequence ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/777/Programs/Madoka and Math Dad.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int sum;\n    cin >> sum;\n\n    string answer;\n    for(int i = 0, s = 0; i + 3 <= sum; i += 3, s += 3)\n    {\n        answer += \"21\";\n    }\n\n    switch(sum%3)\n    {\n        case 2 : answer += \"2\"; break;\n        case 1 : if(sum == 1)\n                {\n                    answer = \"1\";\n                }\n                else\n                {\n                    answer = \"1\" + answer;\n                }\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n\n \n"
  },
  {
    "path": "2022/Contests/Div 2/777/Programs/Makoda and Childish Pranks.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int NO_OF_NEIGHBOURS = 4;\nconst char BLACK = '1', WHITE = '0';\nint X[NO_OF_NEIGHBOURS] = {-1, 0, 0, 1}, Y[NO_OF_NEIGHBOURS] = {0, 1, -1, 0};\n\nstruct rectangle\n{\n    int x1, y1, x2, y2;\n\n    rectangle(int X1, int Y1, int X2, int Y2)\n    {\n        x1 = X1 + 1;\n        y1 = Y1 + 1;\n        x2 = X2 + 1;\n        y2 = Y2 + 1;\n    }\n};\n\nvoid solve()\n{\n    int no_of_rows, no_of_columns;\n    cin >> no_of_rows >> no_of_columns;\n\n    vector <string> grid(no_of_rows);\n    for(int i = 0; i < no_of_rows; i++)\n    {\n        cin >> grid[i];\n    }\n\n    if(grid[0][0] == BLACK)\n    {\n        cout << \"-1\\n\";\n        return;\n    }\n\n    vector <rectangle> moves;\n    for(int i = no_of_rows - 1; i >= 0; i--)\n    {\n        for(int j = no_of_columns - 1; j >= 0; j--)\n        {\n            if(grid[i][j] == BLACK)\n            {\n                if(j > 0)\n                {\n                    moves.push_back(rectangle(i, j - 1, i, j));\n                }\n                else if(i > 0)\n                {\n                    moves.push_back(rectangle(i - 1, j, i, j));\n                }\n            }\n        }\n    }\n\n    cout << moves.size() << \"\\n\";\n    for(rectangle current_rectangle : moves)\n    {\n        cout << current_rectangle.x1 << \" \" << current_rectangle.y1 << \" \" << current_rectangle.x2 << \" \" << current_rectangle.y2 << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n\n\n\n\n"
  },
  {
    "path": "2022/Contests/Div 2/778/Explanations/Alice and the Cake Explanation.txt.txt",
    "content": "Notice that the sum of the whole set remains invariant through the process. \r\n\r\nBegin at the initial cake, and perform the operation on the largest piece presently in the set. \r\n\r\nIf the largest element is already present in the original, then discard it and move on to the next greatest element. \r\n\r\nIf the largest element in our set is smaller than the largest element we have not yet reached in the given array, \r\nit is not possible. \r\n\r\n----\r\n\r\nPlease note that it is not possible to begin with the final array and greedily merge the smallest two elements \r\nand see if we finish at the final array \r\n\r\nHere is the counter example - \r\n\r\n6\r\n1 1 1 1 1 1 \r\n\r\nStep 1 - 2 1 1 1 1\r\nStep 2 - 2 2 1 1 \r\nStep 3 - 2 2 2\r\nStep 4 - 4 2 \r\nStep 5 - \r\nNot possible \r\n\r\nBut, actually \r\n\r\nStep 1 - 2 1 1 1 1\r\nStep 2 - 3 1 1 1\r\nStep 3 - 3 2 1\r\nStep 4 - 3 3 \r\nStep 5 - 6\r\n\r\nIt is possible \r\n\r\nIt is not always optimal to merge smallest 2\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    long long sum = 0, minimum = 1e12, maximum = 0;\r\n    multiset <long long> S, original_S;\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        original_S.insert(A[i]);\r\n\r\n        sum += A[i];\r\n        minimum = min(minimum, A[i]);\r\n        maximum = max(maximum, A[i]);\r\n    }\r\n\r\n    S.insert(sum);\r\n\r\n    int possible = true;\r\n    while(S.size() > 0 && *(S.begin()) >= minimum && *(S.rbegin()) >= *(original_S.rbegin()))\r\n    {\r\n        auto it1 = (S.rbegin());\r\n        long long x = *it1;\r\n\r\n        if(original_S.count(x) > 0)\r\n        {\r\n            original_S.erase(original_S.find(x));\r\n            S.erase(S.find(x));\r\n\r\n            continue;\r\n        }\r\n\r\n        S.erase(S.find(x));\r\n        long long new_x = x/2, new_y = x/2 + (x%2 != 0);\r\n\r\n\r\n        S.insert(new_x);\r\n        S.insert(new_y);\r\n    }\r\n\r\n    possible = (S.size() == 0);\r\n\r\n    cout << (possible ? \"YES\" : \"NO\") << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Div 2/778/Explanations/Maximum Cake Tastiness Explanation.txt",
    "content": "We can always perform an operation to make any two elements adjacent. It is always better to make the greatest 2 elements neighbours\n\nThe answer is the sum of the 2 largest elements. \n\n------\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(A.begin() + 1, A.end());\n    reverse(A.begin() + 1, A.end());\n\n    long long sum = A[1] + A[2];\n    cout << sum << \"\\n\";\n}\n"
  },
  {
    "path": "2022/Contests/Div 2/778/Explanations/Prefix Removals Explanation.txt.txt",
    "content": "Let us look at the first element, which does not occur again in the string. \r\nThis element can never be removed. \r\n\r\nEvery element before can be removed by continuously performing operations of length 1. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> frequency(NO_OF_ALPHABETS + 1, 0);\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        frequency[S[i] - 'a']++;\r\n    }\r\n\r\n    int start = 0;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(frequency[S[i] - 'a'] == 1)\r\n        {\r\n            start = i;\r\n            break;\r\n        }\r\n\r\n        frequency[S[i] - 'a']--;\r\n    }\r\n\r\n    string answer;\r\n    for(int i = start; i < S.size(); i++)\r\n    {\r\n        answer += S[i];\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Div 2/778/Programs/Alice and the Cake.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    long long sum = 0, minimum = 1e12, maximum = 0;\r\n    multiset <long long> S, original_S;\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        original_S.insert(A[i]);\r\n\r\n        sum += A[i];\r\n        minimum = min(minimum, A[i]);\r\n        maximum = max(maximum, A[i]);\r\n    }\r\n\r\n    S.insert(sum);\r\n\r\n    int possible = true;\r\n    while(S.size() > 0 && *(S.begin()) >= minimum && *(S.rbegin()) >= *(original_S.rbegin()))\r\n    {\r\n        auto it1 = (S.rbegin());\r\n        long long x = *it1;\r\n\r\n        if(original_S.count(x) > 0)\r\n        {\r\n            original_S.erase(original_S.find(x));\r\n            S.erase(S.find(x));\r\n\r\n            continue;\r\n        }\r\n\r\n        S.erase(S.find(x));\r\n        long long new_x = x/2, new_y = x/2 + (x%2 != 0);\r\n\r\n\r\n        S.insert(new_x);\r\n        S.insert(new_y);\r\n    }\r\n\r\n    possible = (S.size() == 0);\r\n\r\n    cout << (possible ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/778/Programs/Maximum Cake Tastiness.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(A.begin() + 1, A.end());\n    reverse(A.begin() + 1, A.end());\n\n    long long sum = A[1] + A[2];\n    cout << sum << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2022/Contests/Div 2/778/Programs/Prefix Removals.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> frequency(NO_OF_ALPHABETS + 1, 0);\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        frequency[S[i] - 'a']++;\r\n    }\r\n\r\n    int start = 0;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(frequency[S[i] - 'a'] == 1)\r\n        {\r\n            start = i;\r\n            break;\r\n        }\r\n\r\n        frequency[S[i] - 'a']--;\r\n    }\r\n\r\n    string answer;\r\n    for(int i = start; i < S.size(); i++)\r\n    {\r\n        answer += S[i];\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/789/Explanation/Tokitsukaze and All Zero Sequence Explanation.txt.txt",
    "content": "If there is even one 0 in the array, we can make all non-0 elements = 0 in 1 move each. \r\n\r\nIf there is at least one pair of equal elements, we can create a 0 in 1 move and make the other elements 0 in (n - 1) moves. \r\n\r\nOtherwise, we will two elements, make them equal in one move and then use n moves from the case above. \r\nTotal = (n + 1) moves here. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(all(A));\r\n    int non_zero = 0, equal_pairs = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] > 0)\r\n        {\r\n            non_zero++;\r\n        }\r\n\r\n        if(i < no_of_elements && A[i] == A[i + 1])\r\n        {\r\n            equal_pairs++;\r\n        }\r\n    }\r\n\r\n    int answer = 0;\r\n    if(non_zero < no_of_elements)\r\n    {\r\n        answer = non_zero;\r\n    }\r\n    else if(equal_pairs > 0)\r\n    {\r\n        answer = no_of_elements;\r\n    }\r\n    else\r\n    {\r\n        answer = no_of_elements + 1;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Div 2/789/Explanation/Tokitsukaze and Good 01-String (easy version) Explanation.txt.txt",
    "content": "Keep track of the length of the current segment. If the segment size is odd, then flip the border element. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    int minimum_changes = 0;\r\n    int current_segment = 1;\r\n    for(int i = 1; i < S.size(); i++)\r\n    {\r\n        if(S[i] != S[i - 1])\r\n        {\r\n            if(current_segment%2 == 1)\r\n            {\r\n                S[i] = flip(S[i]);\r\n                minimum_changes++;\r\n                current_segment = 2;\r\n            }\r\n            else\r\n            {\r\n                current_segment = 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            current_segment++;\r\n        }\r\n    }\r\n\r\n    cout << minimum_changes << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Div 2/789/Explanation/Tokitsukaze and Strange Inequality Explanation.txt",
    "content": "Whenever we have to count tuples or triplets, the main idea is to fix the middle and then find each half. \n\nIn this, let us try to fix the pair [b, c] \n\nHow do we count the number of tuples (a, b, c, d) when [b, c] is fixed ? \n\n-----\n\nTo do this, let us see the candidates for a and d ? \n\nAll elements in [1, b - 1] which are smaller than A[c] can be 'a'. \n\nAll elements in [c + a, d] which are smaller than A[b] can be 'd'. \n\nThe number of tuples here is \n\na_candidates x d_candidates. \n\n-----\n\nNow, how do we calculate the number of elements in [1, b - 1] smaller than A[c] for every pair (b, c) ? \n\nLet us imagine that we have an empty array - B \n\nWe will insert the elements of A in B in their index, one by one - in ascending order. \n\nFor example, if A = {5, 3, 6, 1, 4, 2}\n\nB = {0, 0, 0, 0, 0, 0} \n{0, 0, 0, 1, 0, 0}\n{0, 0, 0, 1, 0, 2} \n{0, 3, 0, 1, 0, 2} \n{0, 3, 0, 1, 4, 2} \n{5, 3, 0, 1, 4, 2} \n{5, 3, 6, 1, 4, 2} \n\nWe will insert the elements one by one and use it to precalculate \n\nPrefix_smaller(b, c) and Suffix_smaller(b, c) for every pair (b, c) in the array. \n\n----\n\nSuppose we insert A[i] at position i \n\nWe will do the following - \n\n1. First, let c = i\n\nThen iterate over all b in [1, i - 1] and count the number of inserted elements. \n\n2. Then, let b = i\n\nThen iterate over all c in [i + 1, n] and count the number of inserted elements. \n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    vector <int> index(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        index[A[i]] = i;\n    }\n\n    for(int b = 1; b <= no_of_elements; b++)\n    {\n        for(int c = b + 1; c <= no_of_elements; c++)\n        {\n            prefix_smaller[b][c] = suffix_smaller[b][c] = 0;\n        }\n    }\n\n    vector <int> prefix_insertions(no_of_elements + 1, 0);\n    for(int element = 1; element <= no_of_elements; element++)\n    {\n        for(int i = index[element]; i <= no_of_elements; i++)\n        {\n            prefix_insertions[i]++;\n        }\n\n        for(int c = index[element], b = 1; b < c; b++)\n        {\n            prefix_smaller[b][c] = prefix_insertions[b - 1];\n        }\n\n        for(int b = index[element], c = b + 1; c <= no_of_elements; c++)\n        {\n            suffix_smaller[b][c] = prefix_insertions[no_of_elements] - prefix_insertions[c];\n        }\n    }\n\n    long long answer = 0;\n    for(int b = 2; b + 2 <= no_of_elements; b++)\n    {\n        for(int c = b + 1; c + 1 <= no_of_elements; c++)\n        {\n            long long no_of_a = prefix_smaller[b][c], no_of_d = suffix_smaller[b][c];\n            answer += no_of_a*no_of_d;\n        }\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "2022/Contests/Div 2/789/Programs/Tokitsukaze and Good 01-String (easy version).cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nchar flip(char ch)\r\n{\r\n    return (ch == '0' ? '1' : '0');\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    int minimum_changes = 0;\r\n    int current_segment = 1;\r\n    for(int i = 1; i < S.size(); i++)\r\n    {\r\n        if(S[i] != S[i - 1])\r\n        {\r\n            if(current_segment%2 == 1)\r\n            {\r\n                S[i] = flip(S[i]);\r\n                minimum_changes++;\r\n                current_segment = 2;\r\n            }\r\n            else\r\n            {\r\n                current_segment = 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            current_segment++;\r\n        }\r\n    }\r\n\r\n    cout << minimum_changes << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/789/Programs/Tokitsukaze and Strange Inequality.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nconst int MAX_N = 5005;\r\nint prefix_smaller[MAX_N][MAX_N], suffix_smaller[MAX_N][MAX_N];\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> index(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        index[A[i]] = i;\r\n    }\r\n\r\n    for(int b = 1; b <= no_of_elements; b++)\r\n    {\r\n        for(int c = b + 1; c <= no_of_elements; c++)\r\n        {\r\n            prefix_smaller[b][c] = suffix_smaller[b][c] = 0;\r\n        }\r\n    }\r\n\r\n    vector <int> prefix_insertions(no_of_elements + 1, 0);\r\n    for(int element = 1; element <= no_of_elements; element++)\r\n    {\r\n        for(int i = index[element]; i <= no_of_elements; i++)\r\n        {\r\n            prefix_insertions[i]++;\r\n        }\r\n\r\n        for(int c = index[element], b = 1; b < c; b++)\r\n        {\r\n            prefix_smaller[b][c] = prefix_insertions[b - 1];\r\n        }\r\n\r\n        for(int b = index[element], c = b + 1; c <= no_of_elements; c++)\r\n        {\r\n            suffix_smaller[b][c] = prefix_insertions[no_of_elements] - prefix_insertions[c];\r\n        }\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int b = 2; b + 2 <= no_of_elements; b++)\r\n    {\r\n        for(int c = b + 1; c + 1 <= no_of_elements; c++)\r\n        {\r\n            long long no_of_a = prefix_smaller[b][c], no_of_d = suffix_smaller[b][c];\r\n            answer += no_of_a*no_of_d;\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 2/792/Explanations/AvtoBus Explanation.txt",
    "content": "When we want to maximize the number of buses, we will try to maximise the number of 4's.\nWhile trying to minimize, we will try to maximize the number of 6's. \n\nThere is no answer possible if N = 1, 3 (mod 4). \n\nThere are only 2 cases where an answer exists. \nN = 0, 2 (mod 4)\n\n-----\n\nvoid solve()\n{\n    long long no_of_wheels;\n    cin >> no_of_wheels;\n\n    long long minimum, maximum;\n    switch(no_of_wheels%4)\n    {\n        case 0: maximum = no_of_wheels/4;\n                minimum = 2*(no_of_wheels/12) + (no_of_wheels%12 == 6 ? (no_of_wheels%12)/6 : (no_of_wheels%12)/4);\n                          break;\n\n        case 2: if(no_of_wheels == 2)\n                {\n                    cout << \"-1\\n\";\n                    return;\n                }\n                maximum = 1 + (no_of_wheels - 6)/4;\n                no_of_wheels -= 6;\n                minimum = 1 + 2*(no_of_wheels/12) + (no_of_wheels%12 == 6 ? (no_of_wheels%12)/6 : (no_of_wheels%12)/4);\n                break;\n\n        default: cout << \"-1\\n\";\n                 return;\n    }\n\n    cout << minimum << \" \" << maximum << \"\\n\";\n}\n"
  },
  {
    "path": "2022/Contests/Div 2/792/Explanations/Rooks Defenders Explanation.txt.txt",
    "content": "When a rook is placed on cell (x, y) it covers the whole row x and column y. \r\n\r\nFor every cell (x, y) in X1 < x < X and Y1 < y < Y2 to be covered, either \r\n1. All the rows should be covered. \r\n2. All the columns should be covered. \r\n\r\nSuppose both these conditions are not true, then there is at least one cell (x, y) \r\nsuch that row x and column c are not covered. \r\n\r\n-----\r\n\r\nMaintain 2 Arrays of length N representing - \r\n\r\n1. R[i] - Is row i covered \r\n2. C[j] - Is column j covered\r\n\r\nWe will update and find the sums of these ranges using segment trees. \r\n\r\nEach query is answers in O(log n) time. \r\n\r\n----\r\n\r\nvoid update(int n, int left, int right, int index, int value, int tree_index)\r\n{\r\n    if(index < left || right < index)\r\n    {\r\n        return;\r\n    }\r\n\r\n    if(left == right)\r\n    {\r\n        sum_tree[n][tree_index] = value;\r\n        //cout << (tree_index == 0 ? \"Row\" : \"Column\") << \" Sum Tree [\" << left << \",\" << right << \"] = \" << sum_tree[n][tree_index] << \"\\n\";\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right)/2;\r\n    update(LEFT(n), left, mid, index, value, tree_index);\r\n    update(RIGHT(n), mid + 1, right, index, value, tree_index);\r\n\r\n    sum_tree[n][tree_index] = sum_tree[LEFT(n)][tree_index] + sum_tree[RIGHT(n)][tree_index];\r\n    //cout << (tree_index == 0 ? \"Row\" : \"Column\") << \" Sum Tree [\" << left << \",\" << right << \"] = \" << sum_tree[n][tree_index] << \"\\n\";\r\n}\r\n\r\nint get_sum(int n, int left, int right, int query_left, int query_right, int tree_index)\r\n{\r\n    if(query_right < left || right < query_left)\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    if(query_left <= left && right <= query_right)\r\n    {\r\n        return sum_tree[n][tree_index];\r\n    }\r\n\r\n    int mid = (left + right)/2;\r\n    int left_sum = get_sum(LEFT(n), left, mid, query_left, query_right, tree_index);\r\n    int right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right, tree_index);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n\r\n    int n, no_of_queries;\r\n    cin >> n >> no_of_queries;\r\n\r\n    memset(sum_tree, 0, sizeof(sum_tree));\r\n\r\n    const int ROW = 0, COLUMN = 1;\r\n    vector <int> row_attackers(n + 1, 0), column_attackers(n + 1, 0);\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        const int ADD = 1, REMOVE = 2, RECTANGLE = 3;\r\n        int query;\r\n        cin >> query;\r\n\r\n        switch(query)\r\n        {\r\n            case ADD: {\r\n                            int x, y;\r\n                            cin >> x >> y;\r\n\r\n                            row_attackers[x]++;\r\n                            if(row_attackers[x] == 1)\r\n                            {\r\n                                update(1, 1, n, x, 1, ROW);\r\n                            }\r\n\r\n                            column_attackers[y]++;\r\n                            if(column_attackers[y] == 1)\r\n                            {\r\n                                update(1, 1, n, y, 1, COLUMN);\r\n                            }\r\n                      }\r\n                      break;\r\n\r\n            case REMOVE : {\r\n                                int x, y;\r\n                                cin >> x >> y;\r\n\r\n                                row_attackers[x]--;\r\n                                if(row_attackers[x] == 0)\r\n                                {\r\n                                    update(1, 1, n, x, 0, ROW);\r\n                                }\r\n\r\n                                column_attackers[y]--;\r\n                                if(column_attackers[y] == 0)\r\n                                {\r\n                                    update(1, 1, n, y, 0, COLUMN);\r\n                                }\r\n                          }\r\n                          break;\r\n\r\n            case RECTANGLE :{\r\n                                int x1, y1, x2, y2;\r\n                                cin >> x1 >> y1 >> x2 >> y2;\r\n\r\n                                if(x1 > x2)\r\n                                {\r\n                                    swap(x1, x2);\r\n                                }\r\n\r\n                                if(y1 > y2)\r\n                                {\r\n                                    swap(y1, y2);\r\n                                }\r\n\r\n                                int attacked_rows = get_sum(1, 1, n, x1, x2, ROW);\r\n                                int attacked_columns = get_sum(1, 1, n, y1, y2, COLUMN);\r\n                                //cout << \"Rows attacked = \" << attacked_rows << \" Columns attacked = \" << attacked_columns << \"\\n\";\r\n\r\n                                int every_cell_attacked = ( (attacked_rows == x2 - x1 + 1) || (attacked_columns == y2 - y1 + 1) );\r\n                                cout << (every_cell_attacked ? \"Yes\" : \"No\") << \"\\n\";\r\n                          }\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/792/Explanations/Stone Age Problem Explanation.txt.txt",
    "content": "The trick to this problem is to keep track of time. \r\n\r\nKeep an array T, \r\nrecording the time that an element was touched. \r\n\r\nAlso keep track of the last bulk update. \r\n\r\nWhen doing a point update, check whether - \r\n1. T[i] > last_bulk_update_time \r\n\r\n\tIf yes, then the value at A[i], is A[i] \r\n\r\n2. Else, the value at A[i] is the last bulk_update_value\r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    cin >> no_of_elements >> no_of_queries;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    long long sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum += A[i];\r\n    }\r\n\r\n    int last_replace_all_time = -1, last_replace_all_value = 0;\r\n    vector <int> last_touched(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        const int REPLACE_ONE = 1, REPLACE_ALL = 2;\r\n        int query, index, value;\r\n        cin >> query;\r\n\r\n        switch(query)\r\n        {\r\n            case REPLACE_ONE: cin >> index >> value;\r\n                              if(last_touched[index] > last_replace_all_time)\r\n                              {\r\n                                  sum += (value - A[index]);\r\n                              }\r\n                              else\r\n                              {\r\n                                  sum += (value - last_replace_all_value);\r\n                              }\r\n\r\n                              A[index] = value;\r\n                              last_touched[index] = i;\r\n                              break;\r\n\r\n            case REPLACE_ALL: cin >> value;\r\n\r\n                              sum = no_of_elements*1LL*value;\r\n\r\n                              last_replace_all_value = value;\r\n                              last_replace_all_time = i;\r\n        }\r\n\r\n        cout << sum << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/792/Programs/AvtoBus.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    long long no_of_wheels;\r\n    cin >> no_of_wheels;\r\n\r\n    long long minimum, maximum;\r\n    switch(no_of_wheels%4)\r\n    {\r\n        case 0: maximum = no_of_wheels/4;\r\n                minimum = 2*(no_of_wheels/12) + (no_of_wheels%12 == 6 ? (no_of_wheels%12)/6 : (no_of_wheels%12)/4);\r\n                          break;\r\n\r\n        case 2: if(no_of_wheels == 2)\r\n                {\r\n                    cout << \"-1\\n\";\r\n                    return;\r\n                }\r\n                maximum = 1 + (no_of_wheels - 6)/4;\r\n                no_of_wheels -= 6;\r\n                minimum = 1 + 2*(no_of_wheels/12) + (no_of_wheels%12 == 6 ? (no_of_wheels%12)/6 : (no_of_wheels%12)/4);\r\n                break;\r\n\r\n        default: cout << \"-1\\n\";\r\n                 return;\r\n    }\r\n\r\n    cout << minimum << \" \" << maximum << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/792/Programs/Rooks Defenders.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <cstring>\n\nusing namespace std;\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n\nconst int MAX_N = 1e5 + 5;\nint sum_tree[3*MAX_N][2];\n\nvoid update(int n, int left, int right, int index, int value, int tree_index)\n{\n    if(index < left || right < index)\n    {\n        return;\n    }\n\n    if(left == right)\n    {\n        sum_tree[n][tree_index] = value;\n        //cout << (tree_index == 0 ? \"Row\" : \"Column\") << \" Sum Tree [\" << left << \",\" << right << \"] = \" << sum_tree[n][tree_index] << \"\\n\";\n        return;\n    }\n\n    int mid = (left + right)/2;\n    update(LEFT(n), left, mid, index, value, tree_index);\n    update(RIGHT(n), mid + 1, right, index, value, tree_index);\n\n    sum_tree[n][tree_index] = sum_tree[LEFT(n)][tree_index] + sum_tree[RIGHT(n)][tree_index];\n    //cout << (tree_index == 0 ? \"Row\" : \"Column\") << \" Sum Tree [\" << left << \",\" << right << \"] = \" << sum_tree[n][tree_index] << \"\\n\";\n}\n\nint get_sum(int n, int left, int right, int query_left, int query_right, int tree_index)\n{\n    if(query_right < left || right < query_left)\n    {\n        return 0;\n    }\n\n    if(query_left <= left && right <= query_right)\n    {\n        return sum_tree[n][tree_index];\n    }\n\n    int mid = (left + right)/2;\n    int left_sum = get_sum(LEFT(n), left, mid, query_left, query_right, tree_index);\n    int right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right, tree_index);\n\n    return (left_sum + right_sum);\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n\n    int n, no_of_queries;\n    cin >> n >> no_of_queries;\n\n    memset(sum_tree, 0, sizeof(sum_tree));\n\n    const int ROW = 0, COLUMN = 1;\n    vector <int> row_attackers(n + 1, 0), column_attackers(n + 1, 0);\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        const int ADD = 1, REMOVE = 2, RECTANGLE = 3;\n        int query;\n        cin >> query;\n\n        switch(query)\n        {\n            case ADD: {\n                            int x, y;\n                            cin >> x >> y;\n\n                            row_attackers[x]++;\n                            if(row_attackers[x] == 1)\n                            {\n                                update(1, 1, n, x, 1, ROW);\n                            }\n\n                            column_attackers[y]++;\n                            if(column_attackers[y] == 1)\n                            {\n                                update(1, 1, n, y, 1, COLUMN);\n                            }\n                      }\n                      break;\n\n            case REMOVE : {\n                                int x, y;\n                                cin >> x >> y;\n\n                                row_attackers[x]--;\n                                if(row_attackers[x] == 0)\n                                {\n                                    update(1, 1, n, x, 0, ROW);\n                                }\n\n                                column_attackers[y]--;\n                                if(column_attackers[y] == 0)\n                                {\n                                    update(1, 1, n, y, 0, COLUMN);\n                                }\n                          }\n                          break;\n\n            case RECTANGLE :{\n                                int x1, y1, x2, y2;\n                                cin >> x1 >> y1 >> x2 >> y2;\n\n                                if(x1 > x2)\n                                {\n                                    swap(x1, x2);\n                                }\n\n                                if(y1 > y2)\n                                {\n                                    swap(y1, y2);\n                                }\n\n                                int attacked_rows = get_sum(1, 1, n, x1, x2, ROW);\n                                int attacked_columns = get_sum(1, 1, n, y1, y2, COLUMN);\n                                //cout << \"Rows attacked = \" << attacked_rows << \" Columns attacked = \" << attacked_columns << \"\\n\";\n\n                                int every_cell_attacked = ( (attacked_rows == x2 - x1 + 1) || (attacked_columns == y2 - y1 + 1) );\n                                cout << (every_cell_attacked ? \"Yes\" : \"No\") << \"\\n\";\n                          }\n        }\n    }\n\n    return 0;\n}\n \n"
  },
  {
    "path": "2022/Contests/Div 2/792/Programs/Stone Age Problem.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    cin >> no_of_elements >> no_of_queries;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    long long sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum += A[i];\r\n    }\r\n\r\n    int last_replace_all_time = -1, last_replace_all_value = 0;\r\n    vector <int> last_touched(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        const int REPLACE_ONE = 1, REPLACE_ALL = 2;\r\n        int query, index, value;\r\n        cin >> query;\r\n\r\n        switch(query)\r\n        {\r\n            case REPLACE_ONE: cin >> index >> value;\r\n                              if(last_touched[index] > last_replace_all_time)\r\n                              {\r\n                                  sum += (value - A[index]);\r\n                              }\r\n                              else\r\n                              {\r\n                                  sum += (value - last_replace_all_value);\r\n                              }\r\n\r\n                              A[index] = value;\r\n                              last_touched[index] = i;\r\n                              break;\r\n\r\n            case REPLACE_ALL: cin >> value;\r\n\r\n                              sum = no_of_elements*1LL*value;\r\n\r\n                              last_replace_all_value = value;\r\n                              last_replace_all_time = i;\r\n        }\r\n\r\n        cout << sum << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 2/809/Programs/Qpwoeirut And The City.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    const long long oo = 1e18;\n    vector <long long> minimum_cost(no_of_elements + 1, oo), maximum_coverage(no_of_elements + 1, 0);\n    for(int i = 2; i <= no_of_elements - 1; i++)\n    {\n        long long amount_here = max(0, max(A[i - 1], A[i + 1]) + 1 - A[i]);\n\n        if(i < 4)\n        {\n            minimum_cost[i] = amount_here;\n            maximum_coverage[i] = 1;\n        }\n        else if(i >= 4)\n        {\n            //minimum_cost[i] = amount_here + min(minimum_cost[i - 2], minimum_cost[i - 3]);\n\n            if(maximum_coverage[i - 3] == maximum_coverage[i - 2] && minimum_cost[i - 3] < minimum_cost[i - 2])\n            {\n                minimum_cost[i] = amount_here + minimum_cost[i - 3];\n                maximum_coverage[i] = maximum_coverage[i - 3] + 1;\n            }\n            else\n            {\n                minimum_cost[i] = amount_here + minimum_cost[i - 2];\n                maximum_coverage[i] = maximum_coverage[i - 2] + 1;\n            }\n        }\n\n        //cout << \"F(\" << i << \") = \" << minimum_cost[i] << \"\\n\";\n    }\n\n    long long answer;\n\n    if(maximum_coverage[no_of_elements - 1] == maximum_coverage[no_of_elements - 2])\n    {\n        answer = min(minimum_cost[no_of_elements - 1], minimum_cost[no_of_elements - 2]);\n    }\n    else\n    {\n        answer = (maximum_coverage[no_of_elements - 1] > maximum_coverage[no_of_elements - 2] ?\n                  minimum_cost[no_of_elements - 1] : minimum_cost[no_of_elements - 2]);\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n \n"
  },
  {
    "path": "2022/Contests/Div 3/828/Programs/Divisibility by 2^n.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <map>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\nusing namespace std;\r\n\r\nint power_2(int n)\r\n{\r\n    int power = 0;\r\n\r\n    while(n%2 == 0 && n > 0)\r\n    {\r\n        power++;\r\n        n /= 2;\r\n    }\r\n\r\n    return power;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    vector <int> index_power(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        index_power[i] = power_2(i);\r\n    }\r\n\r\n    sort(all(index_power));\r\n    reverse(all(index_power));\r\n\r\n    int total_power = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        total_power += power_2(A[i]);\r\n    }\r\n\r\n    int no_of_operations = 0;\r\n    for(int i = 1; i <= no_of_elements && total_power < no_of_elements && index_power[i] > 0; i++)\r\n    {\r\n        total_power += index_power[i];\r\n        no_of_operations++;\r\n    }\r\n\r\n    const int NOT_POSSIBLE = -1;\r\n    cout << (total_power < no_of_elements ? NOT_POSSIBLE : no_of_operations) << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 3/828/Programs/Divisible Numbers Easy Version.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <map>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long a, b, c, d;\n    cin >> a >> b >> c >> d;\n\n    long long answer_x = -1, answer_y = -1;\n    for(long long x = a + 1; x <= c; x++)\n    {\n        long long complement = (a*b)/__gcd(a*b, x);\n        //cout << \"X = \" << x << \" Complement = \" << complement << \"\\n\";\n\n        long long y = complement;\n\n        for(int i = 1; y <= b; i++)\n        {\n            y = i*complement;\n        }\n        //cout << \"Y = \" << y << \"\\n\";\n        if(y <= d)\n        {\n            answer_x = x, answer_y = y;\n            break;\n        }\n    }\n\n    cout << answer_x << \" \" << answer_y << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "2022/Contests/Div 3/828/Programs/Even-Odd Increments.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    cin >> no_of_elements >> no_of_queries;\r\n\r\n    long long even_sum = 0, odd_sum = 0;\r\n    long long even_count = 0, odd_count = 0;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n\r\n        if(A[i]%2 == 0)\r\n        {\r\n            even_sum += A[i];\r\n            even_count++;\r\n        }\r\n        else if(A[i]%2 == 1)\r\n        {\r\n            odd_sum += A[i];\r\n            odd_count++;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        const int ADD_EVEN = 0, ADD_ODD = 1;\r\n        long long query, value;\r\n        cin >> query >> value;\r\n\r\n        switch(query)\r\n        {\r\n            case ADD_EVEN : {\r\n                                if(value%2 == 0)\r\n                                {\r\n                                    even_sum += even_count*value;\r\n                                }\r\n                                else\r\n                                {\r\n                                    even_sum += even_count*value;\r\n                                    odd_sum += even_sum;\r\n                                    even_sum = 0;\r\n\r\n                                    odd_count += even_count;\r\n                                    even_count = 0;\r\n                                }\r\n\r\n                                break;\r\n                            }\r\n\r\n            case ADD_ODD : {\r\n                                if(value%2 == 0)\r\n                                {\r\n                                    odd_sum += odd_count*value;\r\n                                }\r\n                                else\r\n                                {\r\n                                    odd_sum += odd_count*value;\r\n                                    even_sum += odd_sum;\r\n                                    odd_sum = 0;\r\n\r\n                                    even_count += odd_count;\r\n                                    odd_count = 0;\r\n                                }\r\n\r\n                                break;\r\n\r\n                            }\r\n        }\r\n\r\n        cout << even_sum + odd_sum << \"\\n\";\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Div 3/828/Programs/Number Replacement.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    map <int, char> dictionary;\r\n    int possible = true;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(dictionary[A[i]] != 0)\r\n        {\r\n            if(dictionary[A[i]] != S[i])\r\n            {\r\n                possible = false;\r\n                break;\r\n            }\r\n        }\r\n\r\n        dictionary[A[i]] = S[i];\r\n    }\r\n\r\n    cout << (possible ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Div 3/828/Programs/Traffic Light.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    char symbol;\r\n    cin >> no_of_elements >> symbol;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    const char GREEN = 'g';\r\n    int first_green = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        if(S[i] == GREEN)\r\n        {\r\n            first_green = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    const int NO_GREEN_TO_RIGHT = -1;\r\n    vector <int> nearest_green(no_of_elements + 1, NO_GREEN_TO_RIGHT);\r\n    for(int i = no_of_elements - 1; i >= 0; i--)\r\n    {\r\n        nearest_green[i] = (S[i] == GREEN ? i : nearest_green[i + 1]);\r\n\r\n        if(nearest_green[i] == NO_GREEN_TO_RIGHT)\r\n        {\r\n            nearest_green[i] = first_green;\r\n        }\r\n\r\n        //cout << \"nearest green \" << i << \" = \" << nearest_green[i] << \"\\n\";\r\n    }\r\n\r\n    int answer = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        if(S[i] == symbol)\r\n        {\r\n            int distance = (nearest_green[i] >= i ? nearest_green[i] - i : S.size() - i + first_green);\r\n\r\n            answer = max(answer, distance);\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "2022/Contests/Educational Round 125/Explanations/By Gamers For Gamers Explanation.txt",
    "content": "Let us consider a monster (D, H) and a unit (d, h). \n\nTime taken by monster to kill 1 unit = h/D \nTime taken by unit to kill monster = H/d \n\nWe need to ensure that the time taken by the monster is strictly more than the time we take to kill the monster \n\nh/D > H/d \nh*d > H*D \n\nWe can treat all the monsters as products (D x H)\n\nFor a given unit, we need to find the minimum integer c, such that \n\nh x (c x d) > H x D \n\n-----\n\nAnother condition is that c <= C/C[i] \n\n-----\n\nNow, instead of checking the amount of damage a monster can take, let us try to calculate the maximum \nproduct we can reach with C[i] coins \n\nMaximum_product[C[i]] = max(H[i] x D[i]) initially \n\nThe key insight to propagate this DP is that we can buy multiple sets of the same unit \n\nIf we buy C coin sets of the i-th unit \n\nMaximum_product[C[i] x C] = max(C x H[i] X D[i]) \n\n-----\n\nWe can then binary search the answer for each query \n\n-----\n\nint main()\n{\n    int no_of_elements, max_cost;\n    cin >> no_of_elements >> max_cost;\n\n    vector <long long> cost(no_of_elements + 1), damage(no_of_elements + 1), health(no_of_elements + 1);\n    vector <long long> max_product(max_cost + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> cost[i] >> damage[i] >> health[i];\n\n        max_product[cost[i]] = max(max_product[cost[i]], damage[i]*health[i]);\n    }\n\n\n    for(int c = 1; c <= max_cost; c++)\n    {\n        for(int coin_sets = 1; c*1LL*coin_sets <= max_cost; coin_sets++)\n        {\n            max_product[c*coin_sets] = max(max_product[c*coin_sets], max_product[c]*coin_sets);\n        }\n    }\n\n    vector <long long> max_product_till(max_cost + 1);\n    for(int i = 1; i <= max_cost; i++)\n    {\n        max_product_till[i] = max(max_product[i], max_product_till[i - 1]);\n    }\n\n    int no_of_monsters;\n    cin >> no_of_monsters;\n\n    for(int i = 1; i <= no_of_monsters; i++)\n    {\n        long long damage_here, health_here;\n        cin >> damage_here >> health_here;\n\n        long long product = damage_here*health_here;\n\n        int minimum_coins = upper_bound(all(max_product_till), product) - max_product_till.begin();\n\n        cout << (minimum_coins <= max_cost ? minimum_coins : -1) << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "2022/Contests/Educational Round 125/Explanations/Integer Moves Explanation.txt.txt",
    "content": "We can always reach (x, y) in at most 2 moves \r\n\r\nIf we are at the origin, then we need 0 moves \r\nIf (x^2 + y^2) is a perfect square, then we need only 1 move \r\nOtherwise, we will go from (0, 0) -> (x, 0) -> (y, 0) in 2 moves !\r\n\r\nWe will always need at most 2 moves !\r\n\r\n------\r\n\r\nint is_square(int n)\r\n{\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(i*i == n)\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int x, y;\r\n    cin >> x >> y;\r\n\r\n    int answer = 0;\r\n    if(x == 0 && y == 0)\r\n    {\r\n        answer = 0;\r\n    }\r\n    else if(is_square(x*x + y*y))\r\n    {\r\n        answer = 1;\r\n    }\r\n    else\r\n    {\r\n        answer = 2;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Educational Round 125/Explanations/XY Sequence Explanation.txt.txt",
    "content": "Be greedy and Set A[i] = A[i] + X, unless it exceeds the limit \r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, x, y, max_limit;\r\n    cin >> no_of_elements >> max_limit >> x >> y;\r\n\r\n    long long sum = 0;\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i - 1] + x <= max_limit)\r\n        {\r\n            A[i] = A[i - 1] + x;\r\n        }\r\n        else\r\n        {\r\n            A[i] = A[i - 1] - y;\r\n        }\r\n\r\n        sum += A[i];\r\n    }\r\n\r\n    cout << sum << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Educational Round 125/Programs/Bracket Sequence Deletion.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int minimum_moves = 0, remaining = length;\r\n    for(int i = 0; i  + 1 < length; i++)\r\n    {\r\n        if(S[i] == '(')\r\n        {\r\n            minimum_moves++;\r\n            remaining -= 2;\r\n            i++;\r\n        }\r\n        else if(S[i] == ')')\r\n        {\r\n            int j = i + 1;\r\n            while(j < length && S[j] != ')')\r\n            {\r\n                j++;\r\n            }\r\n\r\n            if(j == length)\r\n            {\r\n                break;\r\n            }\r\n\r\n            minimum_moves++;\r\n            remaining -= (j - i + 1); //cout << \"i = \" << i << \" j = \" << j << \"\\n\";\r\n            i = j;\r\n        }\r\n    }\r\n\r\n    cout << minimum_moves << \" \" << remaining << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Educational Round 125/Programs/By Gamers For Gamers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, max_cost;\n    cin >> no_of_elements >> max_cost;\n\n    vector <long long> cost(no_of_elements + 1), damage(no_of_elements + 1), health(no_of_elements + 1);\n    vector <long long> max_product(max_cost + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> cost[i] >> damage[i] >> health[i];\n\n        max_product[cost[i]] = max(max_product[cost[i]], damage[i]*health[i]);\n    }\n\n\n    for(int c = 1; c <= max_cost; c++)\n    {\n        for(int coin_sets = 1; c*1LL*coin_sets <= max_cost; coin_sets++)\n        {\n            max_product[c*coin_sets] = max(max_product[c*coin_sets], max_product[c]*coin_sets);\n        }\n    }\n\n    vector <long long> max_product_till(max_cost + 1);\n    for(int i = 1; i <= max_cost; i++)\n    {\n        max_product_till[i] = max(max_product[i], max_product_till[i - 1]);\n    }\n\n    int no_of_monsters;\n    cin >> no_of_monsters;\n\n    for(int i = 1; i <= no_of_monsters; i++)\n    {\n        long long damage_here, health_here;\n        cin >> damage_here >> health_here;\n\n        long long product = damage_here*health_here;\n\n        int minimum_coins = upper_bound(all(max_product_till), product) - max_product_till.begin();\n\n        cout << (minimum_coins <= max_cost ? minimum_coins : -1) << \"\\n\";\n    }\n\n    return 0;\n}\n\n\n"
  },
  {
    "path": "2022/Contests/Educational Round 125/Programs/Integer Moves.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint is_square(int n)\r\n{\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(i*i == n)\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int x, y;\r\n    cin >> x >> y;\r\n\r\n    int answer = 0;\r\n    if(x == 0 && y == 0)\r\n    {\r\n        answer = 0;\r\n    }\r\n    else if(is_square(x*x + y*y))\r\n    {\r\n        answer = 1;\r\n    }\r\n    else\r\n    {\r\n        answer = 2;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Educational Round 125/Programs/XY Sequence.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, x, y, max_limit;\r\n    cin >> no_of_elements >> max_limit >> x >> y;\r\n\r\n    long long sum = 0;\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i - 1] + x <= max_limit)\r\n        {\r\n            A[i] = A[i - 1] + x;\r\n        }\r\n        else\r\n        {\r\n            A[i] = A[i - 1] - y;\r\n        }\r\n\r\n        sum += A[i];\r\n    }\r\n\r\n    cout << sum << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 125/EExplanations/Bracket Sequence Deletion Explanation.txt",
    "content": "If we meet a (\r\n\r\nThen () is a regular balanced string \r\n\r\nAnd (( is a palindrome \r\n\r\nNo matter what, (x is always a good string and we will extract it \r\n\r\n-----\r\n\r\nIf we meet a )\r\n\r\nThen, we cannot get a balanced string since it starts with ) \r\n\r\nWe can only get a palindrome \r\n\r\nAll we need to do is find the next closed bracket ! \r\n\r\n) ((((( ... ( ) \r\n\r\nis a palindrome !\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int minimum_moves = 0, remaining = length;\r\n    for(int i = 0; i  + 1 < length; i++)\r\n    {\r\n        if(S[i] == '(')\r\n        {\r\n            minimum_moves++;\r\n            remaining -= 2;\r\n            i++;\r\n        }\r\n        else if(S[i] == ')')\r\n        {\r\n            int j = i + 1;\r\n            while(j < length && S[j] != ')')\r\n            {\r\n                j++;\r\n            }\r\n\r\n            if(j == length)\r\n            {\r\n                break;\r\n            }\r\n\r\n            minimum_moves++;\r\n            remaining -= (j - i + 1); //cout << \"i = \" << i << \" j = \" << j << \"\\n\";\r\n            i = j;\r\n        }\r\n    }\r\n\r\n    cout << minimum_moves << \" \" << remaining << \"\\n\";\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Explanations/Consecutive Points Segment Explanation.txt.txt",
    "content": "The beginning element is either A[i] - 1, A[i], A[i] + 1 \r\n\r\nLet us notice that the first element uniquely determines the whole sequence. \r\n\r\nWe will check if any of these 3 options leads to a consecutive segment.\r\n\r\n-----\r\n\r\nint is_possible(vector <int> &A, int n)\r\n{\r\n    for(int i = 1, current = n; i < A.size(); i++, current++)\r\n    {\r\n        if(abs(A[i] - current) > 1)\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int possible = false;\r\n    for(int beginning = A[1] - 1; beginning <= A[1] + 1; beginning++)\r\n    {\r\n        if(is_possible(A, beginning))\r\n        {\r\n            possible = true;\r\n        }\r\n    }\r\n\r\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Explanations/Dolce Vita Explanation.txt.txt",
    "content": "Let us keep an array which will tell us the maximum number of times we can buy a prefix of length i \r\n\r\nLet P[i] be the perfix sum of A[1, ... i] \r\n\r\nWe can buy the prefix for i days if \r\n\r\nP[i] + (x - 1)i <= Budget \r\n\r\nWe can binary search for the value of x for each array element. \r\n\r\n------\r\n\r\nAfter that, we will try to find out the number of times we have bought a segment ending at i, exactly \r\n\r\nIn order to do this, we will notice that we can buy the prefix ending at i \r\n\r\nno_of_days[i] - no_of_days[i + 1] times. \r\n\r\n-----\r\n\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, budget;\r\n    cin >> no_of_elements >> budget;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(A.begin(), A.end());\r\n\r\n    vector <long long> prefix_sum(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\r\n    }\r\n\r\n    vector <int> no_of_days_used(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(prefix_sum[i] > budget)\r\n        {\r\n            break;\r\n        }\r\n\r\n        long long low = 1, high = 1e9 + 1;\r\n        while(high - low > 1)\r\n        {\r\n            long long mid = (low + high)/2;\r\n\r\n            if(( prefix_sum[i] + (mid - 1)*i ) > budget)\r\n            {\r\n                high = mid;\r\n            }\r\n            else\r\n            {\r\n                low = mid;\r\n            }\r\n        }\r\n\r\n        no_of_days_used[i] = low;\r\n\r\n        //cout << \"i = \" << i << \" Days = \" << no_of_days_used[i] << \"\\n\";\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer += (no_of_days_used[i] - no_of_days_used[i + 1])*i;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Explanations/Insert a Progression Explanation.txt",
    "content": "Let the value of the original array be |A[1] - A[2]| + |A[2] - A[3]| + ... + |A[n - 1] - A[n]| \n\nLet the smallest and largest element of the array be L and R respectively. \n\n-----\n\nLet us notice that if we have an integer x, A[i] < x < A[i + 1], we can place x in between A[i] and A[i + 1] with no change in the cost. \n\n(A[i + 1] - x) + (x - A[i]) = A[i + 1] - A[i]\n\n-----\n\nWe can place all integers in the range [L, R] within the array in such a way that it does not increase the cost. \n\nNow, we only need to deal with the prefix [1, L - 1] and the suffix [R + 1, X] \n\nThere are 3 options for both of these \n\n1. Before the first number \n2. After the last number \n3. In between two numbers. \n\nSuppose we place 1, 2, 3, ... , L - 1 in between A[i - 1] and A[i + 1], let us count the total difference in cost \n\nOld Cost = A[i] - A[i - 1] \nNew Cost = A[i] - (L - 1) + (L - 1) - (L - 1) ... - 1 + (A[i - 1] - 1) = (A[i] - 1) + (A[i - 1] - 1)\nDifference = 2(A[i] - 1)\n\n-----\n\n \nvoid solve()\n{\n    int no_of_elements, extra;\n    cin >> no_of_elements >> extra;\n \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n \n    long long value = 0;\n    long long minimum = A[1], maximum = A[1];\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        minimum = min(minimum, A[i]);\n        maximum = max(maximum, A[i]);\n \n        value += abs(A[i] - A[i - 1]);\n    }\n \n    if(minimum > 1)\n    {\n        long long minimum_contribution = min(A[1] - 1, A[no_of_elements] - 1);\n \n        for(int i = 2; i <= no_of_elements; i++)\n        {\n            minimum_contribution = min(minimum_contribution, (A[i] - 1)*2);\n        }\n \n        value += minimum_contribution;\n    }\n \n    if(maximum < extra)\n    {\n        long long maximum_contribution = min(extra - A[1], extra - A[no_of_elements]);\n \n        for(int i = 2; i <= no_of_elements; i++)\n        {\n            maximum_contribution = min(maximum_contribution, (extra - A[i])*2);\n        }\n \n        value += maximum_contribution;\n    }\n \n    cout << value << \"\\n\";\n}\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Explanations/String Building Explanation.txt.txt",
    "content": "If the length of the segment is even, we can just keep using blocks of 2 \r\nIf the length of the segment is odd, we can use one blocks of 3, after which it is even and reduced to the case above. \r\n\r\nThe only time it is impossible is when the length of the segment is 1. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    int possible = (S.size() == 1 ? false : true);\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(i == 0)\r\n        {\r\n            if(S[i] != S[i + 1])\r\n            {\r\n                possible = false;\r\n            }\r\n            continue;\r\n        }\r\n\r\n        if(i + 1 == S.size())\r\n        {\r\n            if(S[i] != S[i - 1])\r\n            {\r\n                possible = false;\r\n            }\r\n\r\n            break;\r\n        }\r\n\r\n        if(S[i - 1] != S[i] && S[i] != S[i + 1])\r\n        {\r\n            possible = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (possible ? \"YES\" : \"NO\") << \"\\n\";\r\n}"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Programs/Consecutive Points Segment.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint is_possible(vector <int> &A, int n)\r\n{\r\n    for(int i = 1, current = n; i < A.size(); i++, current++)\r\n    {\r\n        if(abs(A[i] - current) > 1)\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int possible = false;\r\n    for(int beginning = A[1] - 1; beginning <= A[1] + 1; beginning++)\r\n    {\r\n        if(is_possible(A, beginning))\r\n        {\r\n            possible = true;\r\n        }\r\n    }\r\n\r\n    cout << (possible ? \"Yes\" : \"No\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Programs/Dolce Vita.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, budget;\r\n    cin >> no_of_elements >> budget;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(A.begin(), A.end());\r\n\r\n    vector <long long> prefix_sum(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\r\n    }\r\n\r\n    vector <int> no_of_days_used(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(prefix_sum[i] > budget)\r\n        {\r\n            break;\r\n        }\r\n\r\n        long long low = 1, high = 1e9 + 1;\r\n        while(high - low > 1)\r\n        {\r\n            long long mid = (low + high)/2;\r\n\r\n            if(( prefix_sum[i] + (mid - 1)*i ) > budget)\r\n            {\r\n                high = mid;\r\n            }\r\n            else\r\n            {\r\n                low = mid;\r\n            }\r\n        }\r\n\r\n        no_of_days_used[i] = low;\r\n\r\n        //cout << \"i = \" << i << \" Days = \" << no_of_days_used[i] << \"\\n\";\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer += (no_of_days_used[i] - no_of_days_used[i + 1])*i;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Programs/Insert a Progression.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements, extra;\n    cin >> no_of_elements >> extra;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    long long value = 0;\n    long long minimum = A[1], maximum = A[1];\n    for(int i = 2; i <= no_of_elements; i++)\n    {\n        minimum = min(minimum, A[i]);\n        maximum = max(maximum, A[i]);\n\n        value += abs(A[i] - A[i - 1]);\n    }\n\n    if(minimum > 1)\n    {\n        long long minimum_contribution = min(A[1] - 1, A[no_of_elements] - 1);\n\n        for(int i = 2; i <= no_of_elements; i++)\n        {\n            minimum_contribution = min(minimum_contribution, (A[i] - 1)*2);\n        }\n\n        value += minimum_contribution;\n    }\n\n    if(maximum < extra)\n    {\n        long long maximum_contribution = min(extra - A[1], extra - A[no_of_elements]);\n\n        for(int i = 2; i <= no_of_elements; i++)\n        {\n            maximum_contribution = min(maximum_contribution, (extra - A[i])*2);\n        }\n\n        value += maximum_contribution;\n    }\n\n    cout << value << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n"
  },
  {
    "path": "2022/Contests/Educational Rounds/Educational Round 127/Programs/String Building.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    int possible = (S.size() == 1 ? false : true);\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(i == 0)\r\n        {\r\n            if(S[i] != S[i + 1])\r\n            {\r\n                possible = false;\r\n            }\r\n            continue;\r\n        }\r\n\r\n        if(i + 1 == S.size())\r\n        {\r\n            if(S[i] != S[i - 1])\r\n            {\r\n                possible = false;\r\n            }\r\n\r\n            break;\r\n        }\r\n\r\n        if(S[i - 1] != S[i] && S[i] != S[i + 1])\r\n        {\r\n            possible = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (possible ? \"YES\" : \"NO\") << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2023/Contests/Div 2/810/Explanations/XOR Triangle Explanation.txt",
    "content": "1. Fact - A triangle is good only if the pairwise AND is non-0. \n\nProof - x+y = x^y + 2(x&y) \n\nx^y counts all bits which are set either in x or y. \nx&y counts all bits which are set in both x and y and therefore needs to be multiplied by 2. \n\nWe also know that if x, y and z form a triangle, then x + y > z \n\nLet the integers we choose be (a, b, c) \n\n(a^b) + (b^c) = (a^b^b^c) + 2[(a^b)&(b^c)] = \n(a^b) + (b^c) = (a^c) + 2[(a^b)&(b^c)] \n\n(a^b) + (b^c) > (a^c) => (a^b)&(b^c) > 0 \n\nWe can prove this cyclically for all 3 variables. \n\n-----\n\nWe have an easier task now. \nWe now have to count the nummber of integers (a, b, c) such that 1 <= a, b, c <= n and \n\n1. (a^b)&(b^c) > 0 \n2. (b^c)&(c^a) > 0 \n3. (c^a)&(a^b) > 0 \n\nWe will use Digit DP with the observation that all of a, b and c will match some prefix of n (possibly of length 0). \n\n-----\n\nWe will represent the triplet as T[0], T[1], T[2] for convenience instead of (a, b, c). \n\nThe state of the DP is f(i, prefix_mask, condition_mask). \nThis represents the number of triplets of consisting of the bits [0, i - 1] of N satsifying the two masks. \nThe reason we are using i to represent the triplets ending with [i - 1] bits is because the string is 0-indexed. \nIt might have been more intuitive if it were 1-indexed. \n\nHere is the elaborate meaning of each variable.\n\n1. i represents the bit of n where we are at now. \n2. prefix_mask is a mask of 3 bits represnting whether each member of the triplet\n is either = or less than the prefix of [0, i - 1]\n3. condition_mask is a mask of 3 bits reprsenting which of 3 conditions is already true in the prefix of length [0, i - 1]\n\nElaborating on how the masks are created. \nLet us suppose \n1. The first [0, i - 1] of T[0] match the first [0, i - 1] bits of N \n2. The first [0, i - 1] of T[1] is smaller than N\n3. The first [0, i - 1] of T[2] match the first [0, i - 1] bits of N \n\nThe prefix mask is 101 \n\nThe condition mask is also similar. A mask of 110 means two of the conditions required for being a good triangle are satisfied. \n-----\n\nThis is a DP where it is easier to calculate the states f(i + 1, _, _) which f(i, _, _) will contribute to then \nbuild f(i, _, _) from f(i - 1, _, _)\n\nWe will iterate over all possibilities of the i-th bit of T[0], T[1], T[2] \n\nIf the first [0, i - 1] bits of N are equal to the first [0, i - 1] bits of T[0], the i-th bit of T[0] can only be [0, N[i]]\nIf the first [0, i - 1] bits of N are smaller than the first [0, i - 1] bits of T[0], the i-th bit of T[0] can be both 0 or 1.\n\nRecalculate the new prefix_mask and new condition_mask and accordingly do \n\nf(i + 1, new_prefix_mask, new_condition_mask) += f(i, prefix_mask, condition_mask)\n\n-----\n\nLet us discuss the base case and the final answer \n\nLet the base case be f(0, 111, 0) = 1\n\nWhen we consider the empty string, it is not possible for a, b, c to be < N so the prefix mask has to be 111 only. \nNone of the conditions are met so the condition mask be 0 \n\nThe empty string N corresponds to prefix 111 and condition 0. \n\nf(0, _, _) = 0 for all other values.\n\n----\n\nThe final answer is when all the bits are used so i = N.size() \nThe prefix mask can be any legal value \nThe condition mask is 111 \n\nAnswer = Sum f(N.size(), p, 111) over all legal values of prefix_mask\n\n\n------\n\nTime limit is tight so do some language level optimizations like global arrays.\n\n------\n\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1 << bit)) != 0 );\n}\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    string S;\n    cin >> S;\n\n    no_of_triplets[0][MAX_MASK][0] = 1;\n    for(int i = 0; i < S.size(); i++)\n    {\n        int prefix = i - 1;\n        for(int prefix_match = 0; prefix_match <= MAX_MASK; prefix_match++)\n        {\n            for(int condition_met = 0; condition_met <= MAX_MASK; condition_met++)\n            {\n                for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                {\n                    limit[bit] = (is_bit_set(prefix_match, bit) ? S[i] : '1') - '0';\n                }\n\n                for(next_bit[0] = 0; next_bit[0] <= limit[0]; next_bit[0]++)\n                {\n                    for(next_bit[1] = 0; next_bit[1] <= limit[1]; next_bit[1]++)\n                    {\n                        for(next_bit[2] = 0; next_bit[2] <= limit[2]; next_bit[2]++)\n                        {\n\n                            for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                            {\n                                triangle_sides[bit] = next_bit[bit]^next_bit[(bit + 1)%NO_OF_TRIANGLE_SIDES];\n                            }\n\n                            int next_prefix_match = 0;\n                            for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                            {\n                                if(is_bit_set(prefix_match, bit) && next_bit[bit] == S[i] - '0')\n                                {\n                                    next_prefix_match |= (1 << bit);\n                                }\n                            }\n\n                            int next_condition_met = 0;\n                            for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                            {\n                                int condition_here = (triangle_sides[bit]&triangle_sides[(bit + 1)%NO_OF_TRIANGLE_SIDES] != 0);\n                                if(is_bit_set(condition_met, bit) || condition_here)\n                                {\n                                    next_condition_met |= (1 << bit);\n                                }\n                            }\n\n                            no_of_triplets[i + 1][next_prefix_match][next_condition_met] += no_of_triplets[i][prefix_match][condition_met];\n                            no_of_triplets[i + 1][next_prefix_match][next_condition_met] %= MOD;\n\n                            /*cout << \"F(\" << i + 1 << \",\" << next_prefix_match << \",\" << next_condition_met << \") = \"\n                            << no_of_triplets[i + 1][next_prefix_match][next_condition_met] << \" added \"\n                            << \"F(\" << i << \",\" << prefix_match << \",\" << condition_met << \") = \"\n                            << no_of_triplets[i][prefix_match][condition_met] << \" Current \"\n                            << next_bit[0] << \" \" << next_bit[1] << \" \" << next_bit[2] << \"\\n\";*/\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    long long answer = 0;\n    for(int prefix_match = 0, all_conditions_met = MAX_MASK; prefix_match <= MAX_MASK; prefix_match++)\n    {\n        answer += no_of_triplets[S.size()][prefix_match][all_conditions_met];\n        answer %= MOD;\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2023/Contests/Div 2/810/Programs/XOR Triangle.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 998244353, MAX_N = 2e5 + 5, MAX_MASK = 7, NO_OF_TRIANGLE_SIDES = 3;\nlong long no_of_triplets[MAX_N][MAX_MASK + 1][MAX_MASK + 1];\nint limit[NO_OF_TRIANGLE_SIDES], next_bit[NO_OF_TRIANGLE_SIDES], triangle_sides[NO_OF_TRIANGLE_SIDES];\n\nint is_bit_set(int n, int bit)\n{\n    return ( (n&(1 << bit)) != 0 );\n}\n\nint main()\n{\n    ios::sync_with_stdio(false);\n    cin.tie(nullptr);\n\n    string S;\n    cin >> S;\n\n    no_of_triplets[0][MAX_MASK][0] = 1;\n    for(int i = 0; i < S.size(); i++)\n    {\n        int prefix = i - 1;\n        for(int prefix_match = 0; prefix_match <= MAX_MASK; prefix_match++)\n        {\n            for(int condition_met = 0; condition_met <= MAX_MASK; condition_met++)\n            {\n                for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                {\n                    limit[bit] = (is_bit_set(prefix_match, bit) ? S[i] : '1') - '0';\n                }\n\n                for(next_bit[0] = 0; next_bit[0] <= limit[0]; next_bit[0]++)\n                {\n                    for(next_bit[1] = 0; next_bit[1] <= limit[1]; next_bit[1]++)\n                    {\n                        for(next_bit[2] = 0; next_bit[2] <= limit[2]; next_bit[2]++)\n                        {\n\n                            for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                            {\n                                triangle_sides[bit] = next_bit[bit]^next_bit[(bit + 1)%NO_OF_TRIANGLE_SIDES];\n                            }\n\n                            int next_prefix_match = 0;\n                            for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                            {\n                                if(is_bit_set(prefix_match, bit) && next_bit[bit] == S[i] - '0')\n                                {\n                                    next_prefix_match |= (1 << bit);\n                                }\n                            }\n\n                            int next_condition_met = 0;\n                            for(int bit = 0; bit < NO_OF_TRIANGLE_SIDES; bit++)\n                            {\n                                int condition_here = (triangle_sides[bit]&triangle_sides[(bit + 1)%NO_OF_TRIANGLE_SIDES] != 0);\n                                if(is_bit_set(condition_met, bit) || condition_here)\n                                {\n                                    next_condition_met |= (1 << bit);\n                                }\n                            }\n\n                            no_of_triplets[i + 1][next_prefix_match][next_condition_met] += no_of_triplets[i][prefix_match][condition_met];\n                            no_of_triplets[i + 1][next_prefix_match][next_condition_met] %= MOD;\n\n                            /*cout << \"F(\" << i + 1 << \",\" << next_prefix_match << \",\" << next_condition_met << \") = \"\n                            << no_of_triplets[i + 1][next_prefix_match][next_condition_met] << \" added \"\n                            << \"F(\" << i << \",\" << prefix_match << \",\" << condition_met << \") = \"\n                            << no_of_triplets[i][prefix_match][condition_met] << \" Current \"\n                            << next_bit[0] << \" \" << next_bit[1] << \" \" << next_bit[2] << \"\\n\";*/\n                        }\n                    }\n                }\n            }\n        }\n    }\n\n    long long answer = 0;\n    for(int prefix_match = 0, all_conditions_met = MAX_MASK; prefix_match <= MAX_MASK; prefix_match++)\n    {\n        answer += no_of_triplets[S.size()][prefix_match][all_conditions_met];\n        answer %= MOD;\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "2023/Contests/Div 2/857/Programs/Buying Gifts.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <set>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1), B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i] >> B[i];\n    }\n\n    vector <pair <int, int> > prices (no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prices[i].first = A[i];\n        prices[i].second = B[i];\n    }\n\n    sort(prices.begin() + 1, prices.end());\n    reverse(prices.begin() + 1, prices.end());\n\n    vector <int> prefix_max(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_max[i] = max(prefix_max[i - 1], prices[i].second);\n    }\n\n    const int oo = 2e9 + 9;\n    int answer = oo;\n    set <int> suffix;\n    vector <int> suffix_next_greater(no_of_elements + 1, oo), suffix_next_lesser(no_of_elements + 1, oo);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        auto it = suffix.lower_bound(prices[i].first);\n\n        if(it != suffix.end())\n        {\n            suffix_next_greater[i] = *it;\n        }\n\n        if(it != suffix.begin())\n        {\n            it--;\n        }\n        suffix_next_lesser[i] = *it;\n\n        suffix.insert(prices[i].second);\n    }\n\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        int answer_here = oo;\n\n        if(i > 1)\n        {\n            answer_here = abs(prices[i].first - prefix_max[i - 1]);\n        }\n\n        if(suffix_next_greater[i] >= prefix_max[i - 1])\n        {\n            answer_here = min(answer_here, abs(prices[i].first - suffix_next_greater[i]));\n        }\n\n        if(suffix_next_lesser[i] >= prefix_max[i - 1])\n        {\n            answer_here = min(answer_here, abs(prices[i].first - suffix_next_lesser[i]));\n        }\n\n        answer = min(answer, answer_here);\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n\n \n"
  },
  {
    "path": "2023/Contests/Div 2/857/Programs/Likes.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int likes = 0, unlikes = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        likes += (A[i] > 0);\r\n        unlikes += (A[i] < 0);\r\n    }\r\n\r\n    vector <int> maximum_likes(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(i <= likes)\r\n        {\r\n            maximum_likes[i] = maximum_likes[i - 1] + 1;\r\n        }\r\n        else\r\n        {\r\n            maximum_likes[i] = maximum_likes[i - 1] - 1;\r\n        }\r\n    }\r\n\r\n    vector <int> minimum_likes(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if( (i + 1)/2 <= unlikes )\r\n        {\r\n            minimum_likes[i] = 1;\r\n            minimum_likes[i + 1] = 0;\r\n            i = i + 1;\r\n        }\r\n        else\r\n        {\r\n            minimum_likes[i] = minimum_likes[i - 1] + 1;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << maximum_likes[i] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << minimum_likes[i] << \" \";\r\n    }\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "2023/Contests/Div 2/857/Programs/Settlement of Guinea Pigs.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_days;\r\n    cin >> no_of_days;\r\n\r\n    vector <int> event(no_of_days + 1);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        cin >> event[i];\r\n    }\r\n\r\n    const int ADOPT = 1, DOCTOR = 2;\r\n    int bought_avaries = 0, half_avaries = 0, free_avaries = 0;\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        switch(event[i])\r\n        {\r\n            case ADOPT :\r\n            {\r\n                if(free_avaries > 0)\r\n                {\r\n                    free_avaries--;\r\n                }\r\n                else\r\n                {\r\n                    bought_avaries++;\r\n                }\r\n\r\n                half_avaries++;\r\n\r\n                break;\r\n            }\r\n\r\n            case DOCTOR :\r\n            {\r\n                int pairs = 0;\r\n                if(half_avaries%2 == 0)\r\n                {\r\n                    pairs = (half_avaries - 2)/2;\r\n\r\n                }\r\n                else\r\n                {\r\n                    pairs = (half_avaries - 1)/2;\r\n                }\r\n\r\n                free_avaries += pairs;\r\n                half_avaries -= 2*pairs;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << bought_avaries << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "2023/Contests/Div 2/857/Programs/The Very Beautiful Blanket.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int rows, columns;\r\n    cin >> rows >> columns;\r\n\r\n    vector <vector <long long> > M(rows + 1, vector <long long> (columns + 1));\r\n    for(int i = 1, cell_no = 0; i <= rows; i++)\r\n    {\r\n        M[i][1] = cell_no++;\r\n        M[i][2] = cell_no++;\r\n    }\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 3; j <= columns; j++)\r\n        {\r\n            long long offset = (j << 9);\r\n            int reference_column = (j%2 == 1 ? 1 : 2);\r\n\r\n            M[i][j] = M[i][reference_column]^offset;\r\n            M[i][j] = M[i][reference_column]^offset;\r\n        }\r\n    }\r\n\r\n    cout << rows*columns << \"\\n\";\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            cout << M[i][j] << \" \";\r\n        }\r\n\r\n        cout << \"\\n\";\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    ios_base::sync_with_stdio(false);\r\n    cin.tie(NULL);\r\n\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Bear_and_Big_Brother.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int limak_weight, bob_weight;\r\n    int year;\r\n\r\n    scanf(\"%d %d\",&limak_weight, &bob_weight);\r\n\r\n    /*Find the first year in which (limak_weight) > (bob_weight). In other words, the first time the condition, limak <= bob fails\r\n    Counting starts from 0 because we first check the weight of brother at the current moment.*/\r\n    for(year = 0; limak_weight <= bob_weight ; year++)\r\n    {\r\n        limak_weight = 3*limak_weight;\r\n        bob_weight = 2*bob_weight;\r\n    }\r\n\r\n    printf(\"%d\\n\",year);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Beautiful_Matrix.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define NO_OF_ROWS 5\r\n#define NO_OF_COLUMNS 5\r\n\r\nvoid read_matrix(short[][NO_OF_COLUMNS],short*, short*);\r\nshort find_no_of_moves_to_centralise_1(short, short, short, short);\r\n\r\nint main()\r\n{\r\n    short matrix[NO_OF_ROWS][NO_OF_COLUMNS], row_of_1, column_of_1, no_of_moves_to_centralise_1;\r\n\r\n    read_matrix(matrix, &row_of_1, &column_of_1); //Passing row of 1 and columns of 1 by reference\r\n    no_of_moves_to_centralise_1 = find_no_of_moves_to_centralise_1(NO_OF_ROWS, NO_OF_COLUMNS,row_of_1, column_of_1);\r\n    printf(\"%hu\\n\",no_of_moves_to_centralise_1);\r\n    return 0;\r\n}\r\n\r\nvoid read_matrix(short matrix[][NO_OF_COLUMNS], short *row_of_1, short *column_of_1) //Here, row of 1 and column of 1 are pointers\r\n{\r\n    short i, j;\r\n\r\n    for(i = 0; i <NO_OF_ROWS; i++)\r\n    {\r\n        for(j = 0; j < NO_OF_COLUMNS; j++)\r\n        {\r\n            scanf(\"%hu\", &matrix[i][j]);\r\n\r\n            if(matrix[i][j] == 1)\r\n            {\r\n                *(row_of_1) = i; //Dereference operator to store the value at the address held by the pointer\r\n                *(column_of_1) = j;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nshort find_no_of_moves_to_centralise_1(short no_of_rows, short no_of_columns, short row_of_1, short column_of_1)\r\n{\r\n    short row_moves, column_moves, total_moves;\r\n\r\n    //Absolute value is taken. Positive values of difference means moving from right to left for rows or top to bottom in columns and negative, otherwise.\r\n    row_moves = abs(row_of_1 - no_of_rows/2);\r\n    column_moves = abs(column_of_1 - no_of_columns/2);\r\n    total_moves = row_moves + column_moves;\r\n\r\n    return total_moves;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Boy_or_Girl.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define MAXIMUM_DISTINCT_LETTERS 27 //26 + 1\r\n#define USERNAME_SIZE_LIMIT 101\r\n#define ADVICE_SIZE_LIMIT 14 //13+1\r\n#define true 1\r\n#define false 0\r\n\r\nvoid prepare_advisory_message(char[], short);\r\nshort check_if_username_is_female(char[]);\r\n\r\nint main()\r\n{\r\n    char message_of_advice[ADVICE_SIZE_LIMIT], username[USERNAME_SIZE_LIMIT];\r\n    short is_a_girl;\r\n\r\n    scanf(\"%s\",username);\r\n\r\n    is_a_girl = check_if_username_is_female(username);\r\n    prepare_advisory_message(message_of_advice, is_a_girl);\r\n    printf(\"%s\\n\",message_of_advice);\r\n    return 0;\r\n}\r\n\r\nshort check_if_username_is_female(char username[])\r\n{\r\n    char distinct_letters[MAXIMUM_DISTINCT_LETTERS], current_char;\r\n    short i, j, distinct_count = 0, already_counted;\r\n\r\n    for(i = 0; username[i] != '\\0';i++)\r\n    {\r\n        current_char = username[i];\r\n        already_counted = false;\r\n        for(j = 0; j < distinct_count; j++)\r\n        {\r\n            if(current_char == distinct_letters[j])\r\n            {\r\n                already_counted = true;\r\n            }\r\n        }\r\n\r\n        if(already_counted == false)\r\n        {\r\n            distinct_letters[distinct_count++] = current_char;\r\n        }\r\n    }\r\n    if(distinct_count %2 == 0)\r\n    {\r\n        return true; //It is a girl\r\n    }\r\n    else\r\n    {\r\n        return false; //It is a boy\r\n    }\r\n}\r\nvoid prepare_advisory_message(char message_of_advice[], short is_a_girl)\r\n{\r\n    if(is_a_girl == true)\r\n    {\r\n        strcpy(message_of_advice, \"CHAT WITH HER!\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(message_of_advice, \"IGNORE HIM!\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Complicated_GCD.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define SIZE_LIMIT 102 //100 + 2 extra characters\r\n\r\nint main()\r\n{\r\n    char first_number[SIZE_LIMIT], last_number[SIZE_LIMIT], gcd[SIZE_LIMIT];\r\n\r\n    scanf(\"%s %s\",first_number, last_number);\r\n\r\n    if(strcmp(first_number, last_number) == 0)//Stcmp return 0 if both strings are equal\r\n    {\r\n        strcpy(gcd,first_number); //gcd(n,n) = n\r\n    }\r\n    else\r\n    {\r\n        strcpy(gcd, \"1\"); //Answer is always 1 if there are atleast two numbers. Since any consecutive numbers are coprime. gcd(n, n+1) = 1\r\n    }\r\n\r\n    printf(\"%s\\n\", gcd);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Compote.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned int min(unsigned int, unsigned int, unsigned int);\r\nint main()\r\n{\r\n    unsigned int lemons,  apples, pears, answer;\r\n\r\n    scanf(\"%u %u %u\", &lemons, &apples, &pears);\r\n\r\n    /*Lemons, apples and pears have to be in the ratio 1:2:4.\r\n    There will be k lemons, 2k apples and 4k pears.\r\n    k = min(lemons, apples/2, pears/4)\r\n    k is assigned the least of those quantities to ensure we are able to pick k, 2k and 4k from the boxes.\r\n    Otherwise, the class may not have k, 2k or 4k elements to get chosen for the wrong choice of k.\r\n    answer = k + 2k + 4k = 7k */\r\n    answer = 7*min(lemons, apples>>1, pears>>2);\r\n    printf(\"%u\\n\" ,answer);\r\n    return 0;\r\n}\r\n\r\nunsigned int min(unsigned int a, unsigned int b, unsigned int c)\r\n{\r\n    if(a < b)\r\n    {\r\n        if(a < c)\r\n        {\r\n            return a;\r\n        }\r\n        else\r\n        {\r\n            return c;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        if(b < c)\r\n        {\r\n            return b;\r\n        }\r\n        else\r\n        {\r\n            return c;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Dasha_and_Stairs.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define ANSWER_SIZE 4\r\nint main()\r\n{\r\n    char answer[ANSWER_SIZE];\r\n    short no_of_odd_steps, no_of_even_steps;\r\n\r\n    scanf(\"%hu %hu\",&no_of_even_steps, &no_of_odd_steps);\r\n\r\n    if( (no_of_odd_steps - no_of_even_steps <= 1) && (no_of_odd_steps - no_of_even_steps >= -1) )\r\n    {\r\n        if( (no_of_odd_steps == 0) && (no_of_even_steps == 0)) //If both are zero, then the answer is no\r\n        {\r\n            strcpy(answer, \"NO\");\r\n        }\r\n        else\r\n        {\r\n            strcpy(answer, \"YES\");\r\n        }\r\n    }\r\n    else\r\n    {\r\n        strcpy(answer, \"NO\");\r\n    }\r\n\r\n    printf(\"%s\\n\",answer);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Elephant.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long distance, no_of_steps;\r\n\r\n    scanf(\"%lu\", &distance);\r\n    if(distance%5 == 0)\r\n    {\r\n        no_of_steps = distance/5;\r\n    }\r\n    else\r\n    {\r\n        no_of_steps = (distance/5 + 1);\r\n    }\r\n    printf(\"%lu\\n\",no_of_steps);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Even_Odds.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long no_of_numbers, position_of_last_odd_number, desired_position, number_at_desired_position;\r\n\r\n    scanf(\"%I64d %I64d\",&no_of_numbers, &desired_position);\r\n\r\n    //The first ceil(n/2) positions are filled with odd numbers and the remaining spots by even numbers\r\n    if(no_of_numbers%2 == 0)\r\n    {\r\n        position_of_last_odd_number = no_of_numbers >> 1; //n/2\r\n    }\r\n    else\r\n    {\r\n        position_of_last_odd_number = (no_of_numbers >> 1) + 1;//n/2 + 1\r\n    }\r\n\r\n    if(desired_position <= position_of_last_odd_number) //kth position has kth odd number = 2k - 1\r\n    {\r\n        number_at_desired_position = 2*desired_position - 1;\r\n    }\r\n    else //kth position has k - ceil(n/2) th even number\r\n    {\r\n        number_at_desired_position = 2*(desired_position - position_of_last_odd_number );\r\n    }\r\n    printf(\"%I64d\\n\",number_at_desired_position);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Fancy_Fence.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n#define ANSWER_SIZE 4\r\n\r\nvoid check_if_regular_polygon_exists(int, char [][ANSWER_SIZE], int);\r\nint main()\r\n{\r\n    int no_of_test_cases, i, angle;\r\n    char answers[180][ANSWER_SIZE];\r\n\r\n    scanf(\"%d\",&no_of_test_cases);\r\n\r\n    for(i = 0; i < no_of_test_cases; i++)\r\n    {\r\n        scanf(\"%d\",&angle);\r\n        check_if_regular_polygon_exists(angle, answers, i);\r\n    }\r\n\r\n    for(i = 0; i < no_of_test_cases; i++)\r\n    {\r\n        printf(\"%s\\n\",answers[i]);\r\n    }\r\n    return 0;\r\n}\r\n\r\n/* theta = {1 - 2/n}*180, then if n = 360/{180-n} is an integer, a regular polygon exists*/\r\nvoid check_if_regular_polygon_exists(int angle, char answers[][ANSWER_SIZE], int answer_no)\r\n{\r\n    if(360%(180 - angle) == 0)\r\n    {\r\n        strcpy(answers[answer_no], \"YES\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(answers[answer_no], \"NO\");\r\n    }\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Holiday_of_Equality.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nunsigned int find_maximum_wealth(unsigned int *, short);\r\nunsigned int sum_of_amount_given_to_everyone(unsigned int *, unsigned int, short);\r\n\r\nint main()\r\n{\r\n   short no_of_citizens, i;\r\n   unsigned int *wealth_of_citizen, maximum_wealth, amount_distributed;\r\n   scanf(\"%hu\",&no_of_citizens);\r\n\r\n   wealth_of_citizen = malloc(no_of_citizens*sizeof(unsigned int));\r\n   for(i = 0; i < no_of_citizens; i++)\r\n    {\r\n            scanf(\"%u\",(wealth_of_citizen + i));\r\n    }\r\n\r\n    maximum_wealth = find_maximum_wealth(wealth_of_citizen, no_of_citizens);\r\n    amount_distributed = sum_of_amount_given_to_everyone(wealth_of_citizen,maximum_wealth, no_of_citizens);\r\n\r\n    printf(\"%u\\n\",amount_distributed);\r\n    free(wealth_of_citizen);\r\n    return 0;\r\n}\r\n\r\nunsigned int find_maximum_wealth(unsigned int *wealth_of_citizen, short no_of_citizens)\r\n{\r\n    short i;\r\n    unsigned int max = *(wealth_of_citizen + 0); //First element\r\n\r\n    for(i = 1; i < no_of_citizens; i++)\r\n    {\r\n        if(max < *(wealth_of_citizen + i))\r\n        {\r\n            max = *(wealth_of_citizen + i);\r\n        }\r\n    }\r\n\r\n    return max;\r\n}\r\n\r\nunsigned int sum_of_amount_given_to_everyone(unsigned int *wealth_of_citizen, unsigned int max, short no_of_citizens)\r\n{\r\n    unsigned int money_given_away = 0;\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_citizens; i++)\r\n    {\r\n        money_given_away += (max - *(wealth_of_citizen + i));\r\n    }\r\n    return money_given_away;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/I_Love_Username.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nshort find_no_of_amazing_performances(unsigned int *,short);\r\nint main()\r\n{\r\n    short no_of_coding_competitions, i, no_of_amazing_performances;\r\n    scanf(\"%hu\",&no_of_coding_competitions);\r\n\r\n    unsigned int *coder_score_list = malloc(no_of_coding_competitions*sizeof(unsigned int));\r\n    for(i = 0; i < no_of_coding_competitions; i++)\r\n    {\r\n        scanf(\"%u\",(coder_score_list + i));\r\n    }\r\n\r\n    no_of_amazing_performances = find_no_of_amazing_performances(coder_score_list, no_of_coding_competitions);\r\n\r\n    printf(\"%u\\n\", no_of_amazing_performances);\r\n\r\n    free(coder_score_list);\r\n    return 0;\r\n}\r\n\r\n//Go through the array linearly and count the number of times there is a new maxima or minima\r\nshort find_no_of_amazing_performances(unsigned int *coder_score_list,short no_of_coding_competitions)\r\n{\r\n    unsigned int minimum = *(coder_score_list + 0);\r\n    unsigned int maximum = *(coder_score_list + 0);\r\n    short i, no_time_best_or_worst_record_broken = 0;\r\n\r\n    for(i = 0; i < no_of_coding_competitions; i++)\r\n    {\r\n        if( *(coder_score_list + i) < minimum)\r\n        {\r\n            minimum = *(coder_score_list + i);\r\n            no_time_best_or_worst_record_broken++;\r\n        }\r\n        else if( *(coder_score_list + i) > maximum)\r\n        {\r\n            maximum = *(coder_score_list + i);\r\n            no_time_best_or_worst_record_broken++;\r\n        }\r\n    }\r\n    return no_time_best_or_worst_record_broken ;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Ilya_Bank_Account.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define MAXIMUM_NUMBER_SIZE 12 //9 digit number + a sign and then two extra characters just in case\r\n\r\nvoid copy_part_of_string(char[], char[], int, int);\r\n\r\nint main()\r\n{\r\n    char bank_balance[MAXIMUM_NUMBER_SIZE], final_bank_balance[MAXIMUM_NUMBER_SIZE];\r\n    short length;\r\n\r\n    scanf(\"%s\",bank_balance);\r\n\r\n    //Checking if balance is positive\r\n    if(bank_balance[0] != '-')\r\n    {\r\n        strcpy(final_bank_balance, bank_balance);\r\n    }\r\n    else //Bank balance is negative\r\n    {\r\n        length = strlen(bank_balance);\r\n\r\n        //Checking which character is greater among the last and second last and deleting the greater one and keeping the smaller one.\r\n        if(bank_balance[length - 1] < bank_balance[length - 2]) //Deleting the second last digit\r\n        {\r\n            copy_part_of_string(final_bank_balance, bank_balance, 0, length - 3);\r\n            final_bank_balance[length - 2] = bank_balance[length - 1];\r\n            final_bank_balance[length - 1] = '\\0';\r\n        }\r\n        else //Deleting the last digit\r\n        {\r\n            copy_part_of_string(final_bank_balance, bank_balance, 0, length - 2);\r\n            final_bank_balance[length - 1] = '\\0';\r\n        }\r\n\r\n        //Incase, the bank balance becomes zero after deletion. For example, -10 becomes -0. We want it to be just zero.\r\n        if((strlen(final_bank_balance) == 2) && (final_bank_balance[1] == '0'))\r\n        {\r\n            final_bank_balance[0] = '0';\r\n            final_bank_balance[1] = '\\0';\r\n        }\r\n    }\r\n\r\n    printf(\"%s\\n\",final_bank_balance);\r\n    return 0;\r\n}\r\n\r\n//Copies source{start_index .... end_index] to destination[0 .... end_index-start_index]\r\nvoid copy_part_of_string(char destination[], char source[], int start_index, int end_index)\r\n{\r\n    int i;\r\n\r\n    for(i = 0; i <= (end_index - start_index); i++)\r\n    {\r\n        destination[i] = source[start_index + i];\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Little_Elephant_Rozdil.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read_time_taken_to_each_city(unsigned int,unsigned long *);\r\nvoid find_which_city_elephant_goes_to(unsigned int,unsigned long *, unsigned int *,unsigned int *);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_cities, no_of_minima, city_with_minimum_time;\r\n    scanf(\"%u\",&no_of_cities);\r\n\r\n    unsigned long *time_taken_to_city = malloc(no_of_cities*(sizeof(unsigned long)));\r\n\r\n    read_time_taken_to_each_city(no_of_cities, time_taken_to_city);\r\n    find_which_city_elephant_goes_to(no_of_cities, time_taken_to_city, &city_with_minimum_time, &no_of_minima); //Pass by reference\r\n\r\n    if(no_of_minima > 1) //If there is more than one city with the same minimum time, stay in Rozdil\r\n    {\r\n        printf(\"Still Rozdil\\n\");\r\n    }\r\n    else //Otherwise, tell the number of the city\r\n    {\r\n        printf(\"%u\\n\", city_with_minimum_time);\r\n    }\r\n\r\n    free(time_taken_to_city);\r\n    return 0;\r\n}\r\n\r\nvoid read_time_taken_to_each_city(unsigned int no_of_cities,unsigned long *time_taken_to_city)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_cities; i++)\r\n    {\r\n            scanf(\"%lu\",(time_taken_to_city + i));\r\n    }\r\n}\r\n\r\nvoid find_which_city_elephant_goes_to(unsigned int no_of_cities,unsigned long *time_taken_to_city, unsigned int *city_with_minimum_time,unsigned int *no_of_minima)\r\n{\r\n    unsigned int i;\r\n\r\n    //First element is marked as minima initially\r\n    *city_with_minimum_time = 0;\r\n    *no_of_minima = 1;\r\n\r\n    for(i = 1; i < no_of_cities; i++)\r\n    {\r\n        if( *(time_taken_to_city + i) < *(time_taken_to_city + *(city_with_minimum_time)))//If it is less than minima, change the minima\r\n        {\r\n            *city_with_minimum_time = i;\r\n            *no_of_minima = 1; //Reseting the count of minima\r\n        }\r\n        else if( *(time_taken_to_city + i) == *(time_taken_to_city + *(city_with_minimum_time)))\r\n        {\r\n            *no_of_minima = *no_of_minima + 1;\r\n        }\r\n    }\r\n\r\n    if(*no_of_minima == 1)//If there is only one minima, increment the value of city because we have started counting from 0 rather than 1\r\n    {\r\n        *(city_with_minimum_time) = *(city_with_minimum_time) + 1;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Lucky_Division.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define true 1\r\n#define false 0\r\n#define base 10\r\n\r\nshort check_if_num_is_lucky(unsigned int);\r\nshort check_if_num_is_almost_lucky(unsigned int);\r\nint main()\r\n{\r\n    unsigned int num;\r\n    short is_almost_lucky;\r\n    char answer[4];\r\n\r\n    scanf(\"%u\",&num);\r\n    is_almost_lucky = check_if_num_is_almost_lucky(num);\r\n    if(is_almost_lucky == true)\r\n    {\r\n        strcpy(answer, \"YES\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(answer, \"NO\");\r\n    }\r\n    printf(\"%s\\n\",answer);\r\n    return 0;\r\n}\r\n\r\nshort check_if_num_is_lucky(unsigned int num)\r\n{\r\n    short last_digit;\r\n\r\n    for( ;num != 0; num = num/base) //Running through all the digits of num, one by one\r\n    {\r\n        last_digit = num%base;\r\n        if((last_digit != 4) && (last_digit != 7))\r\n        {\r\n                return false;\r\n        }\r\n    }\r\n    return true;\r\n}\r\n\r\nshort check_if_num_is_almost_lucky(unsigned int num)\r\n{\r\n    unsigned int i;\r\n\r\n    //Checking if i is a lucky number and if i divides num.\r\n    for(i = 4; (i <= num); i++)\r\n    {\r\n        if(check_if_num_is_lucky(i))\r\n        {\r\n            if(num%i == 0)\r\n            {\r\n                return true;\r\n            }\r\n        }\r\n    }\r\n    return false;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Memory_and_Crow.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid get_crow_answer(long *, long);\r\nvoid get_original_series(long *, long *, long);\r\nvoid display_original_series(long *,long);\r\nint main()\r\n{\r\n    long no_of_numbers;\r\n\r\n    scanf(\"%ld\",&no_of_numbers);\r\n\r\n    long *crow_answer = malloc(no_of_numbers*sizeof(long));\r\n    long *original_series = malloc(no_of_numbers*sizeof(long));\r\n\r\n    get_crow_answer(crow_answer, no_of_numbers);\r\n    get_original_series(crow_answer, original_series, no_of_numbers);\r\n    display_original_series(original_series, no_of_numbers);\r\n\r\n    free(crow_answer);\r\n    free(original_series);\r\n    return 0;\r\n}\r\n\r\nvoid get_crow_answer(long *crow_answer, long no_of_numbers)\r\n{\r\n    long i;\r\n\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        scanf(\"%lu\",(crow_answer + i));\r\n    }\r\n}\r\n\r\nvoid get_original_series(long *crow_answer, long *original_series, long no_of_numbers)\r\n{\r\n    long i;\r\n\r\n    //B(n) = A(n) For all other i != n, B[i] = A[i] + A[i+1]\r\n    *(original_series + no_of_numbers - 1) = *(crow_answer + no_of_numbers - 1);\r\n    for(i = no_of_numbers - 2; i >= 0; i--)\r\n    {\r\n            *(original_series + i) = *(crow_answer + i) + *(crow_answer + i + 1);\r\n    }\r\n}\r\n\r\nvoid display_original_series(long *original_series, long no_of_numbers)\r\n{\r\n    long i;\r\n\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        printf(\"%ld\\t\",*(original_series + i));\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Nearly_Lucky_Number.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort check_if_nearly_lucky(char[]);\r\nint main()\r\n{\r\n    char number[19];\r\n    short is_nearly_lucky;\r\n\r\n    scanf(\"%s\",number);\r\n\r\n    is_nearly_lucky = check_if_nearly_lucky(number);\r\n\r\n    if(is_nearly_lucky == true)\r\n    {\r\n        printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\nshort check_if_nearly_lucky(char number[])\r\n{\r\n    short i, count_of_lucky_digits = 0;\r\n\r\n    for(i = 0; number[i] != '\\0'; i++)\r\n    {\r\n        if( (number[i] == '4') || (number[i] == '7') )\r\n        {\r\n            count_of_lucky_digits++;\r\n        }\r\n    }\r\n\r\n    if( (count_of_lucky_digits == 4) || (count_of_lucky_digits == 7) )//Less than 18 digits are there so these are the only possibilities\r\n    {\r\n\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Opponents.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n#define MAXIMUM_NO_OF_DAYS 100\r\n#define MAXIIMUM_NO_OF_OPPONENTS 100\r\n\r\nvoid make_list_of_aryan_wins(char[][100],short *, short, short);\r\nshort check_if_aryan_wins_on_a_day(char[], short);\r\nvoid count_no_of_wins_after_last_defeat(short *, short *, short);\r\nshort find_maximum_consecutive_wins(short *, short);\r\n\r\nint main()\r\n{\r\n    char opponent_schedule[MAXIMUM_NO_OF_DAYS][MAXIIMUM_NO_OF_OPPONENTS];\r\n    short no_of_opponents, no_of_days, maximum_consecutive_wins, i;\r\n    short *aryan_wins = NULL, *consecutive_wins_after_last_defeat = NULL;\r\n\r\n    //Reading input\r\n    scanf(\"%hu  %hu \",&no_of_opponents, &no_of_days);\r\n    aryan_wins = malloc(no_of_days*sizeof(short));\r\n    consecutive_wins_after_last_defeat = malloc(no_of_days*sizeof(short));\r\n    for(i = 0; i < no_of_days; i++)\r\n    {\r\n        scanf(\"%s\",opponent_schedule[i]);\r\n    }\r\n\r\n    make_list_of_aryan_wins(opponent_schedule, aryan_wins,no_of_days,no_of_opponents);\r\n    count_no_of_wins_after_last_defeat(consecutive_wins_after_last_defeat,aryan_wins, no_of_days);\r\n    maximum_consecutive_wins = find_maximum_consecutive_wins(consecutive_wins_after_last_defeat,no_of_days);\r\n\r\n    printf(\"%hu\\n\",maximum_consecutive_wins);\r\n\r\n    free(aryan_wins);\r\n    free(consecutive_wins_after_last_defeat);\r\n    return 0;\r\n}\r\n\r\n//Aryan wins is a vector such that Win[i] = true if Aryan wins on day i and false otherwise\r\nvoid make_list_of_aryan_wins(char opponent_schedule[][100],short *aryan_wins, short no_of_days, short no_of_opponents)\r\n{\r\n    short i, does_aryan_win;\r\n\r\n    for(i = 0; i < no_of_days; i++)\r\n    {\r\n        does_aryan_win = check_if_aryan_wins_on_a_day(opponent_schedule[i], no_of_opponents);\r\n        if(does_aryan_win == true)\r\n        {\r\n            *(aryan_wins + i) = true;\r\n        }\r\n        else\r\n        {\r\n            *(aryan_wins + i) = false;\r\n        }\r\n    }\r\n}\r\n\r\n//Takes the day number, looks at the opponent schedule and predicts if Aryan wins or loses,depending on how many opponents were absent\r\nshort check_if_aryan_wins_on_a_day(char one_day_opponent_list[], short no_of_opponents)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_opponents; i++)\r\n    {\r\n        if(one_day_opponent_list[i] == '0') //If even one of them is absent, Aryan wins\r\n        {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n/*A vector where C[i] = k, if on day i, Aryan has k consecutive wins after his most recent defeat. In other words C[i] is his winning\r\nStreak on day i*/\r\nvoid count_no_of_wins_after_last_defeat(short *consecutive_wins_after_last_defeat, short *aryan_wins, short no_of_days)\r\n{\r\n    short i;\r\n\r\n    *(consecutive_wins_after_last_defeat + 0) = *(aryan_wins + 0);\r\n    for(i = 1; i < no_of_days; i++)\r\n    {\r\n        if( *(aryan_wins + i) == true) //If he wins, add it to his winning streak\r\n        {\r\n            *(consecutive_wins_after_last_defeat + i) = *(consecutive_wins_after_last_defeat + i - 1) + 1;\r\n        }\r\n        else //If he loses, reset his winning streak\r\n        {\r\n            *(consecutive_wins_after_last_defeat + i) = 0;\r\n        }\r\n    }\r\n}\r\n\r\nshort find_maximum_consecutive_wins(short *consecutive_wins_after_last_defeat, short no_of_days)\r\n{\r\n    short i, maximum_consecutive_wins = *(consecutive_wins_after_last_defeat + 0);\r\n\r\n    for(i = 1; i < no_of_days; i++)\r\n    {\r\n        if(*(consecutive_wins_after_last_defeat + i) > maximum_consecutive_wins)\r\n        {\r\n            maximum_consecutive_wins = *(consecutive_wins_after_last_defeat + i);\r\n        }\r\n    }\r\n\r\n    return maximum_consecutive_wins;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Petr_and_Calendar.c",
    "content": "#include <stdio.h>\r\n\r\nshort find_no_of_calendar_columns(short, short);\r\nshort find_no_of_days_in(short);\r\n\r\nint main()\r\n{\r\n    short starting_day, month_no, no_of_days_in_month, answer;\r\n\r\n    scanf(\"%hu %hu\", &month_no, &starting_day);\r\n\r\n    no_of_days_in_month = find_no_of_days_in(month_no);\r\n\r\n    answer = find_no_of_calendar_columns(starting_day, no_of_days_in_month);\r\n    printf(\"%u\\n\",answer);\r\n    return 0;\r\n}\r\n\r\nshort find_no_of_calendar_columns(short starting_day, short no_of_days_in_month)\r\n{\r\n    short answer;\r\n\r\n    /*answer = ceil(no_of_days + starting_day - 1). Since, integer division is performed, there will never be any value\r\n    after the decimal point to round off. So, the standard function can't be used and 1 has to be added if it's not a multiple of 7.*/\r\n    if( (no_of_days_in_month + starting_day - 1) % 7 == 0)\r\n    {\r\n        answer = (no_of_days_in_month + starting_day - 1)/7;\r\n    }\r\n    else\r\n    {\r\n        answer = (no_of_days_in_month + starting_day - 1)/7 + 1;\r\n    }\r\n    return answer;\r\n}\r\n\r\nshort find_no_of_days_in(short month_no)\r\n{\r\n    short no_of_days;\r\n    switch(month_no)\r\n    {\r\n        case 1:\r\n        case 3:\r\n        case 5:\r\n        case 7:\r\n        case 8:\r\n        case 10:\r\n        case 12: no_of_days = 31;\r\n                  break;\r\n        case 4:\r\n        case 6:\r\n        case 9:\r\n        case 11: no_of_days = 30;\r\n                 break;\r\n        case 2 : no_of_days = 28;\r\n    }\r\n    return no_of_days;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Shell_Game.c",
    "content": "#include <stdio.h>\r\n\r\nshort find_initial_position(short, short);\r\nint main()\r\n{\r\n    unsigned long no_of_turns;\r\n    short effective_no_of_turns, current_ball_position, initial_ball_position;\r\n\r\n    scanf(\"%lu %hu\",&no_of_turns, &current_ball_position);\r\n\r\n    effective_no_of_turns = no_of_turns%6; //The same permutation repeats after every six permutations\r\n\r\n    initial_ball_position = find_initial_position(current_ball_position, effective_no_of_turns);\r\n    printf(\"%hu\\n\",initial_ball_position);\r\n    return 0;\r\n}\r\n\r\n/*Recursive function to find the initial position. Notice the following\r\nabc\r\nbac\r\nbca\r\ncba\r\ncab\r\nacb\r\nabc\r\nThe same permutation repeats after every six operations. After reducing it to this, we simply move one step back at a time\r\ntill we reach the zeroeth permutation.*/\r\nshort find_initial_position(short current_ball_position, short turn_no)\r\n{\r\n    if(turn_no == 0)//First permutation. It is the base case\r\n    {\r\n        return current_ball_position;\r\n    }\r\n    else\r\n    {\r\n        if(turn_no%2 == 0) //Even turn - middle and right interchanged. Left stays invariant\r\n        {\r\n            switch(current_ball_position)//A different operation must happen to each ball. We trace the path of the ball up to the original permutation\r\n            {\r\n                case 0: return find_initial_position(current_ball_position, turn_no - 1);\r\n                        break;\r\n                case 1: return find_initial_position(current_ball_position+1, turn_no - 1);\r\n                        break;\r\n                case 2: return find_initial_position(current_ball_position-1, turn_no - 1);\r\n                        break;\r\n            }\r\n        }\r\n        else //It was an odd turn - middle and left interchange. Right stays invariant\r\n        {\r\n            switch(current_ball_position)\r\n            {\r\n                case 0: return find_initial_position(current_ball_position + 1, turn_no - 1);\r\n                        break;\r\n                case 1: return find_initial_position(current_ball_position - 1, turn_no - 1);\r\n                        break;\r\n                case 2: return find_initial_position(current_ball_position, turn_no - 1);\r\n                        break;\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Sherlock_New_Girlfriend.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define limit 100000\r\n\r\nvoid sunduram_sieve(unsigned int, short []);\r\nvoid make_prime_list(unsigned int, short [],short []);\r\nvoid initial_marking(unsigned int, short [], short);\r\n\r\nint main()\r\n{\r\n    unsigned int n, i;\r\n    short is_prime[limit], no_of_colours = 2;\r\n\r\n    scanf(\"%d\",&n);\r\n\r\n    initial_marking( (n+1), is_prime, 2); //Initialising the array is_prime to 2.\r\n    sunduram_sieve((n+1), is_prime);\r\n\r\n    //If there are only 2 or 1 piece, the numbers are 2 and 3. One colour is sufficient to paint them.\r\n    if(n <= 2)\r\n    {\r\n        no_of_colours = 1;\r\n    }\r\n\r\n    printf(\"%hu\\n\",no_of_colours);\r\n    for(i = 2; i <= n + 1; i++)\r\n    {\r\n        if(is_prime[i] == 1)\r\n        {\r\n            printf(\"%u \",is_prime[i]); //Primes are painted with one colour - 1\r\n        }\r\n        else\r\n        {\r\n            printf(\"%u \",is_prime[i]); //Composites are painted with another colour - 2\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n\r\n//Initially, everything is marked 1\r\nvoid initial_marking(unsigned int size, short array[], short initial_value)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 1; i <= size; i++)\r\n    {\r\n        array[i] = initial_value;\r\n    }\r\n}\r\n\r\n//Crossing out numbers of the form i + j + 2ij\r\nvoid sunduram_sieve(unsigned int target, short is_prime[])\r\n{\r\n    unsigned i, crossed_out_num, cross_limit, increment; //To avoid overflow\r\n    short auxiliary_list[target/2];\r\n    initial_marking(target/2, auxiliary_list, 1);\r\n\r\n    /*f(i,j) = i + j + 2ij\r\n    For a given value of i, the minimum is when j = 1. Minimum is f(i,1) = 3i + 1\r\n    f(i, j + 1) = f(i,j) + 2i + 1 so we only need to increase the value of the crossed number by 2i + 1, instead of updating by one.\r\n    i goes from 1 to target/2. But, f(i,j) starts from 3i + 1. If i is greater than target/6, then f(i,j) is out of range.\r\n    So, the minimum\r\n    Maximum occurs when j = i. f(i,j) = 2i(i+1).\r\n    The last number to be crossed out for a given i is either 2i(i + 1) or the last f(i,j) before target/2, whichever comes first.*/\r\n\r\n\t//All numbers of the form i + j + 2ij need to be marked out\r\n\r\n    for(i = 1; i <= target/6; i++)\r\n    {\r\n        increment = 2*i + 1;\r\n        cross_limit = 2*i*(i + 1);\r\n\r\n        if(cross_limit > target/2)\r\n        {\r\n            cross_limit = target/2;\r\n        }\r\n\r\n        for(crossed_out_num = 3*i + 1;crossed_out_num <= cross_limit ; crossed_out_num += increment)\r\n        {\r\n            auxiliary_list[crossed_out_num] = 0;\r\n        }\r\n    }\r\n\r\n    make_prime_list(target, is_prime, auxiliary_list);\r\n}\r\n\r\n//Making the list of primes\r\nvoid make_prime_list(unsigned int target, short is_prime[],short auxiliary_list[])\r\n{\r\n    int i = 0;;\r\n\r\n    //We need to put 2 in ourselves because the algorithm 'only' generates all the odd primes\r\n    is_prime[2] = 1;\r\n    for(i = 1; i <= target/2; i++)\r\n    {\r\n        //Checking if the number is not crossed out and adding 2i + 1 to the list if it is unmarked.\r\n        if(auxiliary_list[i] == 1)\r\n        {\r\n            is_prime[2*i + 1] = 1;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Taymr_is_Calling_You.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned int gcd(unsigned int,unsigned int);\r\nint main()\r\n{\r\n    unsigned int time_at_which_calls_come, time_at_which_visits_come, total_minutes, no_of_clashes;\r\n    unsigned int lcm;\r\n\r\n    scanf(\"%u %u %u\",&time_at_which_calls_come, &time_at_which_visits_come, &total_minutes);\r\n\r\n    //gcd(a,b)*lcm(a,b) = a*b\r\n    lcm = (time_at_which_calls_come*time_at_which_visits_come)/ gcd(time_at_which_calls_come,time_at_which_visits_come);\r\n    no_of_clashes = total_minutes/lcm;\r\n\r\n    printf(\"%u\\n\",no_of_clashes);\r\n    return 0;\r\n}\r\n\r\n/*We use bitwise operations instead of multiply and divide simply because it is faster at the hardware level.*/\r\nunsigned int gcd(unsigned int u,unsigned int v)\r\n{\r\n    //Base Cases\r\n    if(u == v)\r\n    {\r\n        return u; //Both are GCD\r\n    }\r\n    if(u == 0)\r\n    {\r\n        return v;\r\n    }\r\n    if(v == 0)\r\n    {\r\n        return u;\r\n    }\r\n\r\n    //If both are even, their GCD will also have a factor of 2 in it\r\n    if(~u & 1) //If it is even, the last bit will be 0. Taking complement will make it 1. AND it with 1 and you get 1 if is even and 0 otherwise\r\n    {\r\n        if(v & 1)//v is odd. Removing the factor of 2 from u\r\n        {\r\n            return gcd(u >> 1, v);\r\n        }\r\n        else //Checking if both u and v are even gcd(u,v) = 2*gcd(u/2,v/2)\r\n        {\r\n            return 2*gcd(u >> 1 , v >> 1);//Dividing u and v by 2\r\n        }\r\n    }\r\n\r\n    if(~v & 1) //u is odd and v is even\r\n    {\r\n        return gcd(u,v>>1);\r\n    }\r\n\r\n    //Both are odd. gcd(u,v) = ( (u-v)/2, v) This is just one step ahead of the Euclidean algorithm\r\n    //Any number that divides both u and v must also divide their difference. Here, the difference is even so we just remove\r\n    //the fact of 2\r\n    //Determining the larger number\r\n    if(u > v)\r\n    {\r\n        return gcd( (u - v) >> 1, v);\r\n    }\r\n    else\r\n    {\r\n        return gcd( (v - u) >> 1, u);\r\n    }\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/The_Wall.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned int gcd(unsigned int,unsigned int);\r\nint main()\r\n{\r\n    unsigned int lahub_bricks, floyd_bricks;\r\n    unsigned long lahub_lucky_number, floyd_lucky_number, lcm, answer;\r\n\r\n    scanf(\"%u %u %lu %lu\",&lahub_bricks, &floyd_bricks, &lahub_lucky_number, &floyd_lucky_number);\r\n\r\n    lcm = (lahub_bricks*floyd_bricks)/gcd(lahub_bricks,floyd_bricks);\r\n    answer = floyd_lucky_number/lcm - (lahub_lucky_number-1)/lcm; //Not inclusive of Lahub's lucky number\r\n\r\n    printf(\"%lu\\n\",answer);\r\n    return 0;\r\n}\r\n\r\n/*We use bitwise operations instead of multiply and divide simply because it is faster at the hardware level.*/\r\nunsigned int gcd(unsigned int u,unsigned int v)\r\n{\r\n    //Base Cases\r\n    if(u == v)\r\n    {\r\n        return u; //Both are GCD\r\n    }\r\n    if(u == 0)\r\n    {\r\n        return v;\r\n    }\r\n    if(v == 0)\r\n    {\r\n        return u;\r\n    }\r\n\r\n    //If both are even, their GCD will also have a factor of 2 in it\r\n    if(~u & 1) //If it is even, the last bit will be 0. Taking complement will make it 1. AND it with 1 and you get 1 if is even and 0 otherwise\r\n    {\r\n        if(v & 1)//v is odd. Removing the factor of 2 from u\r\n        {\r\n            return gcd(u >> 1, v);\r\n        }\r\n        else //Checking if both u and v are even gcd(u,v) = 2*gcd(u/2,v/2)\r\n        {\r\n            return 2*gcd(u >> 1 , v >> 1);//Dividing u and v by 2\r\n        }\r\n    }\r\n\r\n    if(~v & 1) //u is odd and v is even\r\n    {\r\n        return gcd(u,v>>1);\r\n    }\r\n\r\n    //Both are odd. gcd(u,v) = ( (u-v)/2, v) This is just one step ahead of the Euclidean algorithm\r\n    //Any number that divides both u and v must also divide their difference. Here, the difference is even so we just remove\r\n    //the fact of 2\r\n    //Determining the larger number\r\n    if(u > v)\r\n    {\r\n        return gcd( (u - v) >> 1, v);\r\n    }\r\n    else\r\n    {\r\n        return gcd( (v - u) >> 1, u);\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Translation.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define true 1\r\n#define false 0\r\n#define ANSWER_SIZE 4 //Yes or No\r\n#define WORD_SIZE_LIMIT 102\r\n\r\nint main()\r\n{\r\n    char word[WORD_SIZE_LIMIT], reversed_word[WORD_SIZE_LIMIT], answer[ANSWER_SIZE];\r\n    short correct_translation = true, i, length;\r\n\r\n    scanf(\"%s %s\",word, reversed_word);\r\n    length = strlen(word);\r\n\r\n    if(strlen(word) != strlen(reversed_word))\r\n    {\r\n        correct_translation = false;\r\n    }\r\n\r\n    for(i = 0; i < length; i++)\r\n    {\r\n        if(word[i] != reversed_word[length - i - 1])\r\n        {\r\n            correct_translation = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(correct_translation)\r\n    {\r\n        strcpy(answer, \"YES\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(answer, \"NO\");\r\n    }\r\n\r\n    printf(\"%s\\n\",answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Vitya_in_the_Countryside.c",
    "content": "#include <stdio.h>\r\n#include<stdlib.h>\r\n#include <string.h>\r\n\r\nint main()\r\n{\r\n    short no_of_observed_days, *size_of_moon, i;\r\n    char answer[4];\r\n\r\n    scanf(\"%hu\",&no_of_observed_days);\r\n\r\n    //Allocating memory for and recording the observations\r\n    size_of_moon = malloc(no_of_observed_days*sizeof(short));\r\n    for(i = 0; i < no_of_observed_days; i++)\r\n    {\r\n        scanf(\"%hu\", (size_of_moon + i));\r\n    }\r\n\r\n    if(*(size_of_moon + no_of_observed_days - 1) == 15) //Last observation is 15. Can only go down\r\n    {\r\n        strcpy(answer,  \"DOWN\");\r\n    }\r\n    else if(*(size_of_moon + no_of_observed_days - 1) == 0)//Last observation is 0. Can only go up\r\n    {\r\n        strcpy(answer,  \"UP\");\r\n    }\r\n\r\n    else if(no_of_observed_days == 1) //Unless the last observation is 0 or 15, 1 observation is insufficient\r\n    {\r\n            strcpy(answer,  \"-1\");\r\n    }\r\n\r\n    else\r\n    {\r\n        if(*(size_of_moon + no_of_observed_days - 1) > *(size_of_moon + no_of_observed_days - 2))//If a_n > a_{n-1}, moon goes up since a_n != 15\r\n        {\r\n            strcpy(answer,  \"UP\");\r\n        }\r\n        else //a_n < a_{n-1}, moon goes down since a_n != 0\r\n        {\r\n           strcpy(answer,  \"DOWN\");\r\n        }\r\n    }\r\n\r\n    free(size_of_moon);\r\n\r\n    printf(\"%s\\n\",answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 1/Vladik_and_Flights.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint main()\r\n{\r\n    short cost;\r\n    unsigned long no_of_airports, start_airport, destination_airport;\r\n    scanf(\"%lu %lu %lu\",&no_of_airports, &start_airport, &destination_airport);\r\n\r\n    char *company_of_airport = malloc((no_of_airports+1)*sizeof(char)); //Allocating an extra character\r\n\r\n    scanf(\"%s\",company_of_airport);\r\n\r\n    //If the airports are of the same company, cost is 0. Else it is 1.\r\n    if( *(company_of_airport + start_airport - 1) == *(company_of_airport + destination_airport- 1) )//1 is subtracted because counting starts from 0 in the array\r\n    {\r\n        cost = 0;\r\n    }\r\n    else\r\n    {\r\n        cost = 1;\r\n    }\r\n\r\n    printf(\"%hu\\n\",cost);\r\n    free(company_of_airport);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/A_and_B_Chess.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define NO_OF_ROWS 8\r\n\r\nvoid determine_stronger_colour(short, short, char[]);\r\nvoid read_chessboard(char [][NO_OF_ROWS  + 1]);\r\nvoid find_strength_of_colour(short *, short *, char[][NO_OF_ROWS + 1]);\r\nshort find_the_weight(char);\r\nint main()\r\n{\r\n    char answer[6];//5 + 1. 5 is the maximum size of answer - White\r\n    short white_strength, black_strength;\r\n    char chessboard[NO_OF_ROWS][NO_OF_ROWS + 1]; //It is an array of strings. Each row of board is one string. So, we add 1.\r\n\r\n    read_chessboard(chessboard);\r\n    find_strength_of_colour(&white_strength, &black_strength, chessboard);//Pass by reference\r\n    determine_stronger_colour(white_strength, black_strength, answer);\r\n\r\n    printf(\"%s\\n\",answer);\r\n    return 0;\r\n}\r\n\r\nvoid read_chessboard(char chessboard[][NO_OF_ROWS  + 1])\r\n{\r\n    short i;\r\n\r\n    //Chessboard is stored as 8 strings\r\n    for(i = 0; i < NO_OF_ROWS; i++)\r\n    {\r\n        scanf(\"%s\",chessboard[i]);\r\n    }\r\n}\r\n\r\nvoid find_strength_of_colour(short *white_strength, short *black_strength, char chessboard[][NO_OF_ROWS + 1])\r\n{\r\n    short i, j;\r\n    *(white_strength) = 0, *(black_strength) = 0;\r\n\r\n    for(i = 0; i < NO_OF_ROWS; i++)\r\n    {\r\n        for(j = 0; j < NO_OF_ROWS; j++)\r\n        {\r\n            if(chessboard[i][j] == '.')\r\n            {\r\n                continue;\r\n            }\r\n            else if( ('A' <= chessboard[i][j]) && (chessboard[i][j] <= 'Z') )\r\n            {\r\n                *(white_strength) = *(white_strength) + find_the_weight(chessboard[i][j]);\r\n            }\r\n            else\r\n            {\r\n                *(black_strength) = *(black_strength) + find_the_weight(chessboard[i][j]);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nshort find_the_weight(char chess_piece)\r\n{\r\n    short weight = 0;\r\n    switch(chess_piece)\r\n    {\r\n        case 'p':\r\n        case 'P': weight = 1;\r\n                break;\r\n\r\n        case 'N':\r\n        case 'n':\r\n        case 'B':\r\n        case 'b': weight = 3;\r\n                  break;\r\n\r\n        case 'R':\r\n        case 'r': weight = 5;\r\n                break;\r\n        case 'Q':\r\n        case 'q': weight = 9;\r\n                  break;\r\n        default : weight = 0;\r\n    }\r\n    return weight;\r\n}\r\n\r\nvoid determine_stronger_colour(short white_strength, short black_strength, char answer[])\r\n{\r\n    //0 represents white and 1 represents black\r\n    if(white_strength > black_strength)\r\n    {\r\n        strcpy(answer, \"White\");\r\n    }\r\n    else if(white_strength < black_strength)\r\n    {\r\n        strcpy(answer,\"Black\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(answer, \"Draw\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Again_Twenty_Five.c",
    "content": "#include <stdio.h>\r\n#define MAX_NUMBER_SIZE 20\r\n\r\nint main()\r\n{\r\n    char power[MAX_NUMBER_SIZE];\r\n    short final_two_digits = 25; //From n > 2  (5^n mod 100 = 25)\r\n\r\n    scanf(\"%s\",power);\r\n\r\n    printf(\"%hu\\n\",final_two_digits);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Anton_and_Danik.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nshort find_who_won_more(char *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_games;\r\n    short winner;\r\n    scanf(\"%u\",&no_of_games);\r\n    char *results = malloc( (no_of_games + 1)*sizeof(char));\r\n\r\n    scanf(\"%s\",results);\r\n    winner = find_who_won_more(results, no_of_games);//Returns 1 if Anton is the winner and 2 if Danik wins and 0 for draw\r\n\r\n    if(winner == 1)\r\n    {\r\n        printf(\"Anton\\n\");\r\n    }\r\n    else if(winner == 2)\r\n    {\r\n        printf(\"Danik\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"Friendship\\n\");\r\n    }\r\n\r\n    free(results);\r\n    return 0;\r\n}\r\n\r\nshort find_who_won_more(char *results, unsigned int no_of_games)\r\n{\r\n    unsigned int i, anton_win = 0, danik_win = 0;\r\n\r\n    for(i = 0; i < no_of_games; i++)\r\n    {\r\n        if(*(results + i) == 'A')\r\n        {\r\n            anton_win++;\r\n        }\r\n        else if(*(results + i) == 'D')\r\n        {\r\n            danik_win++;\r\n        }\r\n    }\r\n\r\n    if(anton_win > danik_win)\r\n    {\r\n        return 1;\r\n    }\r\n    else if(danik_win > anton_win)\r\n    {\r\n        return 2;\r\n    }\r\n    else //Both are equal\r\n    {\r\n        return 0;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Bachgold_Problem.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid get_prime_series_sum_to_n(short *, unsigned int);\r\nvoid fill_with_2(short *, short, unsigned int);\r\nvoid display_prime_series_that_sums_to_n(short *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int num, no_of_terms;\r\n\r\n    scanf(\"%u\",&num);\r\n    //If n is even, there are n/2 terms. If n is odd, there are (n-3)/2 + 1 = (n/2 - 1) + 1\r\n    no_of_terms = num >> 1;\r\n    short *prime_series_sum_n = malloc(no_of_terms*sizeof(short));\r\n\r\n    get_prime_series_sum_to_n(prime_series_sum_n, num);\r\n\r\n    printf(\"%u\\n\", no_of_terms);\r\n    display_prime_series_that_sums_to_n(prime_series_sum_n, no_of_terms);\r\n\r\n    free(prime_series_sum_n);\r\n    return 0;\r\n}\r\n\r\nvoid get_prime_series_sum_to_n(short *prime_series_sum_n, unsigned int n)\r\n{\r\n    if(n%2 == 0)\r\n    {\r\n         //If a number is even, then the maximum number of prime terms that sum to it is n = 2 + 2 + 2 + ...\r\n        fill_with_2(prime_series_sum_n,0, n >> 1);\r\n    }\r\n    else\r\n    {\r\n        //If a number is odd, then the maximum number of prime terms that sum to it is n = 3 + 2 + 2 + 2 + ...\r\n        *(prime_series_sum_n) = 3;\r\n        fill_with_2(prime_series_sum_n,1, (n - 3)>>1 );\r\n    }\r\n}\r\n\r\nvoid display_prime_series_that_sums_to_n(short *prime_series_sum_n, unsigned int no_of_terms)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_terms; i++)\r\n    {\r\n        printf(\"%hu\\t\",*(prime_series_sum_n + i));\r\n    }\r\n}\r\n\r\nvoid fill_with_2(short *prime_series_sum_n, short start, unsigned int no_of_terms)\r\n{\r\n    unsigned int i = start;\r\n\r\n    for(i = start; i < no_of_terms + start; i++)\r\n    {\r\n        *(prime_series_sum_n + i) = 2;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Bit++.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\nint read_and_execute_program(unsigned int);\r\nint main()\r\n{\r\n    unsigned int lines_of_code;\r\n    int final_value_of_x;\r\n    scanf(\"%u\",&lines_of_code);\r\n\r\n    final_value_of_x = read_and_execute_program(lines_of_code);\r\n    printf(\"%d\",final_value_of_x);\r\n    return 0;\r\n}\r\n\r\nint read_and_execute_program(unsigned int lines_of_code)\r\n{\r\n    char current_line_of_code[4]; //Each line of code has three characters\r\n    unsigned int no_of_increments = 0, no_of_decrements = 0, i;\r\n    int final_value;\r\n\r\n    //Count the number of increment and decrement statements\r\n    for(i = 0; i < lines_of_code; i++)\r\n    {\r\n        scanf(\"%s\", current_line_of_code);\r\n\r\n        if( (strcmp(current_line_of_code, \"++X\") == 0) || (strcmp(current_line_of_code, \"X++\") == 0) )\r\n        {\r\n            no_of_increments++;\r\n        }\r\n        else if( (strcmp(current_line_of_code, \"--X\") == 0) || (strcmp(current_line_of_code, \"X--\") == 0) )\r\n        {\r\n            no_of_decrements++;\r\n        }\r\n    }\r\n\r\n    final_value = no_of_increments - no_of_decrements; //This is the final answer.\r\n    return final_value;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Buy_a_Shovel.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned int price_of_a_shovel, total_money_spent;\r\n    short change_available, no_of_shovels;;\r\n\r\n    scanf(\"%u %hu\",&price_of_a_shovel, &change_available);\r\n\r\n    total_money_spent = price_of_a_shovel;\r\n    for(no_of_shovels = 1; (total_money_spent)%10 != change_available && (total_money_spent % 10 != 0); no_of_shovels++)\r\n    {\r\n        total_money_spent = no_of_shovels*price_of_a_shovel;\r\n        //printf(\"%u\\n\",total_money_spent);\r\n    }\r\n\r\n    //The number of shovels is incremented one time after the condition is broken. However, if the condition fails the first time, it is not incremented\r\n    if(no_of_shovels != 1)\r\n    {\r\n        no_of_shovels--;\r\n    }\r\n    printf(\"%hu\\n\",no_of_shovels);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Chat_Room.c",
    "content": "#include <stdio.h>\r\n\r\n#define true 1\r\n#define false 0\r\n#define MAX_MESSAGE_LENGTH 101\r\n\r\nshort is_hello_there(char[]);\r\nint main()\r\n{\r\n    short if_hello_found;\r\n    char message[MAX_MESSAGE_LENGTH];\r\n\r\n    scanf(\"%s\",message);\r\n\r\n    if_hello_found = is_hello_there(message);\r\n    if(if_hello_found)\r\n    {\r\n        printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\nshort is_hello_there(char message[])\r\n{\r\n    char string_to_search[5] = \"hello\";\r\n    short string_to_search_index = 0, i, hello_found = false;\r\n\r\n    for(i = 0; message[i] != '\\0'; i++)\r\n    {\r\n        if(string_to_search[string_to_search_index] == message[i])\r\n        {\r\n            string_to_search_index++;\r\n            if(string_to_search_index == 5)\r\n            {\r\n                hello_found = true;\r\n                return hello_found;\r\n            }\r\n        }\r\n    }\r\n    return hello_found;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Chips.c",
    "content": "#include <stdio.h>\r\n\r\nshort find_no_of_chips_at_end(short, unsigned int);\r\n\r\nint main()\r\n{\r\n    short no_of_walruses, no_of_chips_left;\r\n    unsigned int no_of_chips;\r\n\r\n    scanf(\"%hu %u\",&no_of_walruses, &no_of_chips);\r\n    no_of_chips_left = find_no_of_chips_at_end(no_of_walruses, no_of_chips);\r\n\r\n    printf(\"%hu\\n\",no_of_chips_left);\r\n    return 0;\r\n}\r\n\r\nshort find_no_of_chips_at_end(short no_of_walruses, unsigned int no_of_chips)\r\n{\r\n    short i, no_of_chips_left = no_of_chips;\r\n\r\n    for(i = 1; no_of_chips_left >= i; i = (i%no_of_walruses)+1) //The number of people goes from 1 to n. The residue class of n goes from 0 - n-1. So, we add 1\r\n    {\r\n        no_of_chips_left = no_of_chips_left - i; //Giving i chips to person i\r\n        //printf(\"%hu\\t%hu\\n\",i, no_of_chips_left);\r\n    }\r\n    return no_of_chips_left;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Cinema_Line.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort check_if_clerk_always_has_change(unsigned int,unsigned int *);\r\nvoid read_money_with_each_person(unsigned int,unsigned int *);\r\n\r\nint main()\r\n{\r\n    short does_clerk_always_have_change;\r\n    unsigned int no_of_people;\r\n    scanf(\"%u\",&no_of_people);\r\n\r\n    unsigned int *price_paid_by_people = malloc(no_of_people*sizeof(unsigned int));\r\n\r\n    read_money_with_each_person(no_of_people, price_paid_by_people);\r\n    does_clerk_always_have_change = check_if_clerk_always_has_change(no_of_people, price_paid_by_people);\r\n\r\n    if(does_clerk_always_have_change)\r\n    {\r\n       printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n\r\n    free(price_paid_by_people);\r\n    return 0;\r\n}\r\n\r\nvoid read_money_with_each_person(unsigned int no_of_people, unsigned int *price_paid_by_people)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_people; i++)\r\n    {\r\n            scanf(\"%u\",(price_paid_by_people + i));\r\n    }\r\n}\r\n\r\nshort check_if_clerk_always_has_change(unsigned int no_of_people, unsigned int *price_paid_by_people)\r\n{\r\n    short does_clerk_always_have_change = true;\r\n    int no_of_25_bills = 0, no_of_50_bills = 0, i; //No need of keeping track of 100 because they can't they can't be used for change\r\n\r\n    for(i = 0; i < no_of_people; i++)\r\n    {\r\n        if(*(price_paid_by_people + i) == 25)\r\n        {\r\n            no_of_25_bills++;\r\n        }\r\n        else if(*(price_paid_by_people + i) == 50)\r\n        {\r\n            //Check if he has change\r\n            if(no_of_25_bills < 1)\r\n            {\r\n                does_clerk_always_have_change = false;\r\n                break;\r\n            }\r\n            no_of_50_bills++;\r\n            no_of_25_bills --;\r\n        }\r\n        else if(*(price_paid_by_people + i) == 100)\r\n        {\r\n            if((no_of_25_bills >= 1) && (no_of_50_bills >= 1))\r\n            {\r\n                no_of_50_bills--;\r\n                no_of_25_bills --;\r\n            }\r\n            else if(no_of_25_bills >= 3)\r\n            {\r\n                no_of_25_bills = no_of_25_bills - 3;\r\n            }\r\n            else //Change couldn't be paid\r\n            {\r\n                does_clerk_always_have_change = false;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    return does_clerk_always_have_change;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Domino_Piling.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short no_of_rows, no_of_columns;\r\n    short no_of_dominos;\r\n\r\n    scanf(\"%hu %hu\", &no_of_rows, &no_of_columns);\r\n\r\n    /*If there are m*n squares, and m*n is an even number, all the squares can be tiled. 2 squares for a domino, so m*n/2\r\n    If m*n is an odd number, then m*n-1 squares can be tiled. So, (m*n-1)/2. But, since m*n is an odd number - floor(m*n/2)\r\n    In other words, simple integer division by 2.*/\r\n    no_of_dominos = (no_of_rows*no_of_columns) >> 1;\r\n\r\n    printf(\"%hu\\n\",no_of_dominos);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Drazil_and_Date.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#define true 1\r\n#define false 0\r\n\r\nshort  check_if_possible(long,long,unsigned long);\r\nint main()\r\n{\r\n    short is_possible;\r\n    long x_coordinate, y_coordinate;\r\n    unsigned long distance_travelled;\r\n\r\n    scanf(\"%ld %ld %lu\",&x_coordinate, &y_coordinate, &distance_travelled);\r\n\r\n    is_possible = check_if_possible(x_coordinate, y_coordinate, distance_travelled);\r\n\r\n    if(is_possible)\r\n    {\r\n        printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\n/*1. In a given move, either x or y changes by 1. To go from (0,0) to (a,b) it will take a minimum of (|a|+|b|) moves.\r\n2. From a point (x,y), it is possible to return to (x,y) in an even number of moves only.\r\n\tIf an odd number of moves have been made, it means that one of the coordinates has been changed more times than the other. So, it isn't possible to return to (x,y).\r\n\tA simple example is (x,y) - (x+1, y) - (x,y) and variations of this. It is possible to return only after an even number of moves.*/\r\n\r\nshort  check_if_possible(long x_coordinate,long y_coordinate,unsigned long distance_travelled)\r\n{\r\n    unsigned long minimum_distance_required = abs(x_coordinate) + abs(y_coordinate);\r\n\r\n    if(distance_travelled < minimum_distance_required)//If the distance_travelled is less than the number of moves, then it is not possible\r\n    {\r\n        return false;\r\n    }\r\n    /*the same point can be returned to only in an even number of moves. In an odd number of moves, one coordinate gets changed more times than the other.\r\n    So, it isn't possible*/\r\n    else if((distance_travelled - minimum_distance_required)%2 == 0)\r\n    {\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        return false;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/George_and_Accomodation.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid get_room_details(short *, short *, short);\r\nshort find_no_of_accomodating_rooms(short *, short *, short);\r\n\r\nint main()\r\n{\r\n    short no_of_rooms, no_of_accomodating_rooms;\r\n\r\n    scanf(\"%hu\", &no_of_rooms);\r\n\r\n    short *no_of_room_occupants = malloc(no_of_rooms*sizeof(short));\r\n    short *capacity_room = malloc(no_of_rooms*sizeof(short));\r\n\r\n    get_room_details(no_of_room_occupants,capacity_room,no_of_rooms);\r\n    no_of_accomodating_rooms = find_no_of_accomodating_rooms(no_of_room_occupants,capacity_room,no_of_rooms);\r\n\r\n    printf(\"%hu\\n\",no_of_accomodating_rooms);\r\n\r\n    free(no_of_room_occupants);\r\n    free(capacity_room);\r\n    return 0;\r\n}\r\n\r\nvoid get_room_details(short *no_of_room_occupants, short *capacity_room, short no_of_rooms)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_rooms ; i++)\r\n    {\r\n        scanf(\"%hu %hu\",(no_of_room_occupants + i), (capacity_room + i));\r\n    }\r\n}\r\n\r\nshort find_no_of_accomodating_rooms(short *no_of_room_occupants, short *capacity_room, short no_of_rooms)\r\n{\r\n    short i, no_of_accomodating_rooms = 0;\r\n\r\n    for(i = 0; i < no_of_rooms ; i++)\r\n    {\r\n        if( *(capacity_room + i) - *(no_of_room_occupants + i) >= 2) //Accomodate both George and his friend\r\n        {\r\n            no_of_accomodating_rooms++;\r\n        }\r\n    }\r\n    return no_of_accomodating_rooms;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Gravity_Flip.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(short *, short);\r\nvoid selection_sort(short *, short);\r\nvoid display(short *, short);\r\n\r\nint main()\r\n{\r\n    short no_of_columns;\r\n\r\n    scanf(\"%hu\",&no_of_columns);\r\n\r\n    short *blocks = malloc(no_of_columns*sizeof(short));\r\n\r\n    read(blocks, no_of_columns);\r\n    selection_sort(blocks, no_of_columns);\r\n    display(blocks, no_of_columns);\r\n\r\n    free(blocks);\r\n    return 0;\r\n}\r\n\r\nvoid read(short *blocks, short no_of_columns)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_columns; i++)\r\n    {\r\n        scanf(\"%hu\",(blocks + i));\r\n    }\r\n}\r\n\r\nvoid display(short *blocks, short no_of_columns)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_columns; i++)\r\n    {\r\n        printf(\"%hu\\t\",*(blocks + i));\r\n    }\r\n}\r\n\r\nvoid selection_sort(short *blocks, short no_of_columns)\r\n{\r\n    short i, j, smallest, smallest_index;\r\n\r\n    //Every iteration finds the i-th minima. So, for n elements, we only need to sort n-1 elements. The last element is forced to be in it's correct position.\r\n    for(i = 0; i < no_of_columns - 1; i++)\r\n    {\r\n        smallest = *(blocks + i);\r\n        smallest_index = i;\r\n\r\n        for(j = i + 1; j  < no_of_columns; j++)//Go through the list from i to the end to search for a minima\r\n        {\r\n            if(*(blocks + j) < smallest)\r\n            {\r\n                smallest = *(blocks + j);\r\n                smallest_index = j;\r\n            }\r\n        }\r\n\r\n        //Place the i-th minima in the i-th position, and the element at the i-th position where the minima was\r\n        *(blocks + smallest_index) = *(blocks + i);\r\n        *(blocks + i) = smallest;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Infinite_Sequence.c",
    "content": "#include <stdio.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort check_if_term_falls_in_sequence(long,long,long);\r\n\r\nint main()\r\n{\r\n    short does_term_fall_in_sequence;\r\n    long first_term, term_to_be_checked, common_difference;\r\n\r\n    scanf(\"%ld %ld %ld\",&first_term, &term_to_be_checked, &common_difference);\r\n    does_term_fall_in_sequence = check_if_term_falls_in_sequence(first_term, term_to_be_checked, common_difference);\r\n\r\n    if(does_term_fall_in_sequence)\r\n    {\r\n       printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\nshort check_if_term_falls_in_sequence(long first_term,long term_to_be_checked,long common_difference)\r\n{\r\n    //Prevent division by zero. If difference  = 0, then the sequence consists of one term only, term lies in the sequence iff it is the start term\r\n    if(common_difference == 0)\r\n    {\r\n        if(first_term == term_to_be_checked)\r\n        {\r\n            return true;\r\n        }\r\n        else\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n    /*If b falls in the progression, then a + nc = b, where n is a non-negative integer.\r\n    We have to check that (b-a) mod c = 0, and then that (b-a)/c >= 0,\r\n    The second condition is to prevent n from being negative. For example, the series given by (1, 5) should not accept -4. -4 is the '-1'th term.*/\r\n    if( ( (term_to_be_checked - first_term)%common_difference == 0) && ((term_to_be_checked - first_term)/common_difference >= 0) )\r\n    {\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        return false;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Interview_with_Oleg.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define PRIMARY_FILLER_LENGTH 4\r\n#define ADDITIONAL_FILLER_LENGTH 3\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nvoid remove_filler_from_interview(char *, char *);\r\nshort find_filler_length_from_here(char *, short);\r\nshort search_for_additional_filler(char *, short);\r\nint main()\r\n{\r\n    short size_of_string;\r\n\r\n    scanf(\"%hu\",&size_of_string);\r\n\r\n    char *interview = malloc( (size_of_string + 1)*sizeof(char) );\r\n    char *interview_without_filler = malloc( (size_of_string + 1)*sizeof(char) );\r\n\r\n    scanf(\"%s\",interview);\r\n\r\n    remove_filler_from_interview(interview, interview_without_filler);\r\n\r\n    printf(\"%s\",interview_without_filler);\r\n\r\n    free(interview);\r\n    free(interview_without_filler);\r\n    return 0;\r\n}\r\n\r\nvoid remove_filler_from_interview(char *interview, char *interview_without_filler)\r\n{\r\n    short i = 0, length_of_filler_from_i, final_interview_index = 0, count;\r\n\r\n    while( *(interview + i) != '\\0')\r\n    {\r\n        length_of_filler_from_i = find_filler_length_from_here(interview, i);\r\n\r\n        //If there is no filler here, then just put in the same character as the normal interview and proceed to the next character\r\n        if(length_of_filler_from_i == 0)\r\n        {\r\n            *(interview_without_filler + final_interview_index) = *(interview + i);\r\n            final_interview_index++;\r\n            i++;\r\n        }\r\n        else\r\n        {\r\n            for(count = 0; count < 3; count++, final_interview_index++)//Filling three asterisks\r\n            {\r\n                *(interview_without_filler + final_interview_index) = '*';\r\n            }\r\n            i = i + length_of_filler_from_i; //Start checking the interview from where the current filler ended\r\n        }\r\n    }\r\n    *(interview_without_filler + final_interview_index) = '\\0';//Terminating the string\r\n}\r\n\r\nshort find_filler_length_from_here(char *interview, short i)\r\n{\r\n    short filler_length = 0, primary_filler_index = 0, primary_filler_found = true, additional_filler_found = false;\r\n    char primary_filler[PRIMARY_FILLER_LENGTH] = \"ogo\";\r\n\r\n    for(primary_filler_index = 0; primary_filler[primary_filler_index] !=  '\\0'; primary_filler_index++)\r\n    {\r\n        if(*(primary_filler + primary_filler_index) != *(interview + i + primary_filler_index) )\r\n        {\r\n            primary_filler_found = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(primary_filler_found == false)//If not found, then return filler length is 0\r\n    {\r\n        filler_length = 0;\r\n    }\r\n    else //If a primary filler is found, then search for the secondary filler and update the filler length accordingly\r\n    {\r\n        filler_length = filler_length + 3;\r\n        additional_filler_found = search_for_additional_filler(interview, i+filler_length);\r\n\r\n        while(additional_filler_found)\r\n        {\r\n            filler_length = filler_length + 2;\r\n            additional_filler_found = search_for_additional_filler(interview, i+filler_length);\r\n        }\r\n\r\n    }\r\n\r\n    return filler_length;\r\n}\r\n\r\nshort search_for_additional_filler(char *interview, short here)\r\n{\r\n    short additional_filler_found = true, additional_filler_index;\r\n    char additional_filler[ADDITIONAL_FILLER_LENGTH] = \"go\";\r\n\r\n    for(additional_filler_index = 0; additional_filler[additional_filler_index] != '\\0'; additional_filler_index++)\r\n    {\r\n        if(*(interview + here + additional_filler_index) != additional_filler[additional_filler_index])\r\n        {\r\n            additional_filler_found = false;\r\n            break;\r\n        }\r\n    }\r\n    return additional_filler_found;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Pasha_and_Stick.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long length_of_stick, no_of_rectangular_cuts;\r\n\r\n    scanf(\"%lu\",&length_of_stick);\r\n\r\n    /*If x is not an even number, then the number of rectangles is 0.\r\n    Let x, be an even number. We must find the number of unordered pairs (a, b) such that (a + b) = x/2, where a is not equal to b.\r\n    It is sufficient to count the number of times we can find (a + b) = x/2. We just replicate the same division on the other other x/2 stick.\r\n    This is the number of integers upto (x/2)/2 = x/4 [ (1, x/2-1), (2, x/2 - 2) .... (x/4 - 1, x/4 + 1), (x/4, x/4)]\r\n    If x is a multiple of 4, then the last pair is (x/4, x/4) which has to be discounted.\r\n    Otherwise, it is (x/4 - 1, x/4 + 1)*/\r\n    if(length_of_stick%2 == 1)\r\n    {\r\n        no_of_rectangular_cuts = 0;\r\n    }\r\n    else\r\n    {\r\n        if(length_of_stick%4 == 0)\r\n        {\r\n            no_of_rectangular_cuts = length_of_stick/4 - 1;\r\n        }\r\n        else\r\n        {\r\n            no_of_rectangular_cuts = length_of_stick/4;\r\n        }\r\n    }\r\n\r\n    printf(\"%lu\\n\",no_of_rectangular_cuts);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Pineapple_Incident.c",
    "content": "#include <stdio.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort check_if_pineapple_barks(unsigned long,unsigned long,unsigned long);\r\n\r\nint main()\r\n{\r\n    short does_pineapple_bark;\r\n    unsigned long first_bark_time, barking_interval, desired_time;\r\n\r\n    scanf(\"%lu %lu %lu\",&first_bark_time, &barking_interval, &desired_time);\r\n    does_pineapple_bark = check_if_pineapple_barks(first_bark_time, barking_interval, desired_time);\r\n\r\n    if(does_pineapple_bark)\r\n    {\r\n       printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\nshort check_if_pineapple_barks(unsigned long first_bark_time,unsigned long barking_interval,unsigned long desired_time)\r\n{\r\n    /*First bark time = t, barking interval = s, desired time = x\r\n    If x = t + ms or x = t + ms + 1, then it is a YES, it barks\r\n    If x = t + ms, then x - t is a multiple of s.\r\n    If x = t + ms + 1, then x - t = ms + 1, (x - t) has to leave a remainder of 1 with s.\r\n    However, it doesn't bark at time t + 1\r\n    If x < t, then no other checks are necessary. The pineapple doesn't bark. Avoid subtraction in that case because these are unsigned numbers.*/\r\n    if(desired_time < first_bark_time)\r\n    {\r\n        return false;\r\n    }\r\n    if( (desired_time - first_bark_time) < barking_interval ) //This block ensures t+1 doesn't get counted as a barking time.\r\n    {\r\n        if(desired_time == first_bark_time)//If x-t <s, then it is a barking interval only if x = t + 0s. Not x = t + 0s +1\r\n        {\r\n            return true;\r\n        }\r\n        else\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n    if( ( (desired_time - first_bark_time)%barking_interval == 0) || ( (desired_time - first_bark_time)%barking_interval == 1) )\r\n    {\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        return false;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Serial_Killer.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n#define MAX_NAME_SIZE 11\r\n\r\nint main()\r\n{\r\n    char murdered[MAX_NAME_SIZE], replacement[MAX_NAME_SIZE], person_1[MAX_NAME_SIZE], person_2[MAX_NAME_SIZE], survivor[MAX_NAME_SIZE];\r\n    unsigned int no_of_days, i;\r\n\r\n    scanf(\"%s %s\",person_1, person_2);\r\n    printf(\"%s %s\\n\", person_1, person_2);\r\n    scanf(\"%u\",&no_of_days);\r\n\r\n    for(i = 0; i < no_of_days; i++)\r\n    {\r\n        scanf(\"%s %s\",murdered, replacement);\r\n        if(strcmp(murdered, person_1) == 0)\r\n        {\r\n            strcpy(survivor, person_2);\r\n        }\r\n        else\r\n        {\r\n            strcpy(survivor, person_1);\r\n        }\r\n        printf(\"%s %s\\n\", survivor, replacement);\r\n\r\n        strcpy(person_1, survivor);\r\n        strcpy(person_2, replacement);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Soldier_and_Bananas.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_bananas, price_of_one_banana;\r\n    unsigned long money_with_soldier, amount_to_be_borrowed;\r\n\r\n    scanf(\"%u %lu %u\", &price_of_one_banana, &money_with_soldier, &no_of_bananas);\r\n\r\n    //Sum of bananans = k + 2k + ... wk = w(w+1)/2 * k, where k is the price and w is the number of bananas\r\n    if( (no_of_bananas*(no_of_bananas + 1)/2 )*(price_of_one_banana) < money_with_soldier)\r\n    {\r\n        amount_to_be_borrowed = 0;\r\n    }\r\n    else\r\n    {\r\n        amount_to_be_borrowed = (no_of_bananas*(no_of_bananas + 1)/2 )*(price_of_one_banana) - money_with_soldier;\r\n    }\r\n\r\n    printf(\"%lu\\n\",amount_to_be_borrowed);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Spider_Man.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(unsigned int *, unsigned int);\r\nvoid display(short *, unsigned int);\r\nvoid  make_winner_list(short *, unsigned int *,unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_tests;\r\n    scanf(\"%u\",&no_of_tests);\r\n\r\n    unsigned int *no_of_vertices = malloc(no_of_tests*sizeof(unsigned int));\r\n    short *winner = malloc(no_of_tests*sizeof(short));\r\n\r\n    read(no_of_vertices, no_of_tests);\r\n    make_winner_list(winner, no_of_vertices, no_of_tests);\r\n    display(winner, no_of_tests);\r\n\r\n    free(winner);\r\n    free(no_of_vertices);\r\n    return 0;\r\n}\r\n\r\n/*A move in the game is equivalent to deleting an edge from a graph with n vertices where there's an edge between consecutive numbers.\r\n1-2-3...-n. There is no edge in between n and 1 because deleting it creates no new graphs.\r\nThe number of edges id v - 1, where v is the number of vertices.\r\nThe number of edges reduces by 1 in every move. If the number of edges is even (0 included), Player 2 wins.\r\nIf the number of edges is odd, Player 1 wins.*/\r\nvoid  make_winner_list(short *winner, unsigned int *no_of_vertices,unsigned int no_of_tests)\r\n{\r\n    unsigned int i, sum_of_edges = 0;\r\n\r\n    for(i = 0; i < no_of_tests; i++)\r\n    {\r\n        sum_of_edges = sum_of_edges + *(no_of_vertices + i) - 1;\r\n\r\n        if(sum_of_edges%2 == 0)//Player 2 wins if there are an even number of edges\r\n        {\r\n            *(winner + i) = 2;\r\n        }\r\n        else//Player 1 wins if there are an odd number of edges\r\n        {\r\n            *(winner + i) = 1;\r\n        }\r\n    }\r\n}\r\nvoid read(unsigned int *no_of_vertices, unsigned int no_of_tests)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_tests; i++)\r\n    {\r\n            scanf(\"%u\",(no_of_vertices + i));\r\n    }\r\n}\r\n\r\nvoid display(short *winner, unsigned int no_of_tests)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_tests; i++)\r\n    {\r\n            printf(\"%hu\\n\",*(winner + i));\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Stones_on_a_Table.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nshort find_minimum_stones_to_be_removed(char *);\r\nint main()\r\n{\r\n    short no_of_stones, minimum_stones_to_be_removed;\r\n    scanf(\"%hu\",&no_of_stones);\r\n\r\n    char *colour_of_stones = malloc((no_of_stones+1)*sizeof(char));\r\n    scanf(\"%s\",colour_of_stones);\r\n\r\n    minimum_stones_to_be_removed = find_minimum_stones_to_be_removed(colour_of_stones);\r\n    printf(\"%hu\\n\",minimum_stones_to_be_removed);\r\n\r\n    free(colour_of_stones);\r\n    return 0;\r\n}\r\n\r\nshort find_minimum_stones_to_be_removed(char *colour_of_stones)\r\n{\r\n    short i, j, stones_to_remove = 0;\r\n    char current_colour;\r\n\r\n    for(i = 0; *(colour_of_stones + i) != '\\0'; )\r\n    {\r\n        current_colour = *(colour_of_stones + i);\r\n\r\n        //Counts the number of stones of the same colour as stone i, after stone i\r\n        for(j = i + 1; *(colour_of_stones + j) == current_colour ; j++)\r\n        {\r\n            stones_to_remove++;\r\n        }\r\n\r\n        //All the stones that j ran through has been removed. i needs to resume counting from where j ended.\r\n        i = j;\r\n    }\r\n\r\n    return stones_to_remove;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Transform_A_to_B.c",
    "content": "#include <stdio.h>\r\n#define MAX_INTERMEDIATE_NUMBERS 40\r\n\r\nvoid find_path(unsigned long, unsigned long,short *, unsigned long[]);\r\nvoid display_path_of_numbers(unsigned long[], short);\r\n\r\nint main()\r\n{\r\n    short no_of_intermediate_numbers = 0;\r\n    unsigned long start_number, end_number, path_of_numbers[MAX_INTERMEDIATE_NUMBERS];\r\n\r\n    scanf(\"%lu %lu\",&start_number, &end_number);\r\n\r\n    find_path(start_number, end_number, &no_of_intermediate_numbers, path_of_numbers);//No of intermediate answers is passed by reference\r\n\r\n    //Displaying The Answer. If the path ends in the start number, a path exists.\r\n    if(path_of_numbers[no_of_intermediate_numbers] == start_number)\r\n    {\r\n        printf(\"YES\\n\");\r\n        printf(\"%lu\\n\",no_of_intermediate_numbers+1); //Right now, no_of_intermediate_numbers is the length of the path from b to a, starting from 0.\r\n        display_path_of_numbers(path_of_numbers, no_of_intermediate_numbers);\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\n//Determines the path from a to b\r\nvoid find_path(unsigned long start_number,unsigned long end_number,short *no_of_intermediate_numbers,unsigned long path_of_numbers[])\r\n{\r\n    path_of_numbers[0] = end_number;\r\n    for(*no_of_intermediate_numbers = 0; path_of_numbers[*no_of_intermediate_numbers] > start_number; *no_of_intermediate_numbers = *no_of_intermediate_numbers+1)\r\n    {\r\n        if(path_of_numbers[*no_of_intermediate_numbers]%2 == 0)\r\n        {\r\n            path_of_numbers[*no_of_intermediate_numbers + 1] = path_of_numbers[*no_of_intermediate_numbers]/2;\r\n        }\r\n        else\r\n        {\r\n            //Checking if the given number can be attained by 10x + 1. For example, there is no integer x, for which 10x + 1 = 15\r\n            if( (path_of_numbers[*no_of_intermediate_numbers] - 1) %10 == 0)\r\n            {\r\n                path_of_numbers[*no_of_intermediate_numbers + 1] = (path_of_numbers[*no_of_intermediate_numbers] - 1)/10;\r\n            }\r\n            else //There is no integer x, for which 10x + 1 is the current number\r\n            {\r\n                path_of_numbers[*no_of_intermediate_numbers + 1] = 0; //This will exit the loop because start number has to be atleast 1.\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n//Displays the path from start to end number i.e. in reverse order of how it was built\r\nvoid display_path_of_numbers(unsigned long path_of_numbers[], short no_of_intermediate_numbers)\r\n{\r\n    short i;\r\n\r\n    for(i = no_of_intermediate_numbers; i >= 0; i--)\r\n    {\r\n        printf(\"%lu\\t\",path_of_numbers[i]);\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Triangular_Numbers.c",
    "content": "#include <stdio.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort check_if_triangular(unsigned int);\r\nint main()\r\n{\r\n    short is_triangular;\r\n    unsigned int num;\r\n    scanf(\"%u\",&num);\r\n\r\n    is_triangular = check_if_triangular(num);\r\n\r\n    if(is_triangular)\r\n    {\r\n        printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\nshort check_if_triangular(unsigned int num)\r\n{\r\n    unsigned int i;\r\n\r\n    //Searching for the first triangular number that is not smaller than num\r\n    for(i = 1; i*(i+1)/2 < num; i++);\r\n\r\n    //Checking if the first triangular number greater than or equal to num is equal\r\n    if(i*(i+1)/2 == num)\r\n    {\r\n        return true;\r\n    }\r\n    else\r\n    {\r\n        return false;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Watermelon.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short weight_of_watermelon;\r\n\r\n    scanf(\"%hu\",&weight_of_watermelon);\r\n\r\n    //An odd number can't be divided into two even numbers because two even numbers always sum up to an even number\r\n    //2 can't be divided into two even numbers smaller than it. (A division of size 0 is not allowed.)\r\n    if( (weight_of_watermelon == 2) || (weight_of_watermelon%2 == 1))\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    else //If Weight = 4n + 2, then the weights are 2n and 2n+2, if weight is 4n, then it is 2n and 2n\r\n    {\r\n        printf(\"YES\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 2/Word_Capitalisation.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#define MAX_WORD_SIZE 1001\r\nint main()\r\n{\r\n    char *word = malloc(MAX_WORD_SIZE*sizeof(char));\r\n    scanf(\"%s\",word);\r\n\r\n    if( ('a' <= *(word + 0) ) && ('z' >= *(word + 0)) )\r\n    {\r\n        *(word + 0) = *(word + 0) - ('a' - 'A'); //The ASCII capitals come before the smaller letters. Subtracting the first letter to make it small\r\n    }\r\n\r\n    printf(\"%s\\n\",word);\r\n    free(word);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Anton_and_Polyhedron.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n\r\nvoid read_faces_of_polyhedara(short *, unsigned int);\r\nunsigned int get_total_number_of_faces(short *, unsigned int);\r\nint main()\r\n{\r\n    unsigned int no_of_polyhedra, no_of_faces;\r\n    scanf(\"%u\",&no_of_polyhedra);\r\n\r\n    short *polyhedra_face = malloc(no_of_polyhedra*sizeof(short));\r\n    read_faces_of_polyhedara(polyhedra_face, no_of_polyhedra);\r\n    no_of_faces = get_total_number_of_faces(polyhedra_face, no_of_polyhedra);\r\n\r\n    printf(\"%u\\n\",no_of_faces);\r\n    free(polyhedra_face);\r\n    return 0;\r\n}\r\n\r\nvoid read_faces_of_polyhedara(short *polyhedra_face, unsigned int no_of_polyhedra)\r\n{\r\n    char current_polyhedra[15];\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_polyhedra; i++)\r\n    {\r\n        scanf(\"%s\",current_polyhedra);\r\n\r\n        if(strcmp(current_polyhedra, \"Tetrahedron\") == 0)\r\n        {\r\n            *(polyhedra_face + i) = 4;\r\n        }\r\n        else if(strcmp(current_polyhedra, \"Cube\") == 0)\r\n        {\r\n            *(polyhedra_face + i) = 6;\r\n        }\r\n        else if(strcmp(current_polyhedra, \"Octahedron\") == 0)\r\n        {\r\n            *(polyhedra_face + i) = 8;\r\n        }\r\n        else if(strcmp(current_polyhedra, \"Dodecahedron\") == 0)\r\n        {\r\n            *(polyhedra_face + i) = 12;\r\n        }\r\n        else if(strcmp(current_polyhedra, \"Icosahedron\") == 0)\r\n        {\r\n            *(polyhedra_face + i) = 20;\r\n        }\r\n    }\r\n}\r\n\r\nunsigned int get_total_number_of_faces(short *polyhedra_face, unsigned int no_of_polyhedra)\r\n{\r\n    unsigned int i, total_faces = 0;\r\n\r\n    for(i = 0; i < no_of_polyhedra; i++)\r\n    {\r\n        total_faces = total_faces + *(polyhedra_face + i);\r\n    }\r\n    return total_faces;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Calculating_Function.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    long long number, answer;\r\n    scanf(\"%I64d\",&number);\r\n\r\n    if(number%2 == 0)\r\n    {\r\n        answer = number >> 1; //For even n, the answer is n/2 because f(n) is (1) + (1) + ... +(1)\r\n    }\r\n    else\r\n    {\r\n        answer = (number >> 1) - number;\r\n    }\r\n    printf(\"%I64d\\n\",answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Cheap_Travel.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned int find_minimum_cost(unsigned int, unsigned int,unsigned int,unsigned int);\r\nint main()\r\n{\r\n    unsigned int no_of_rides, price_of_one_ride, special_no_of_rides, price_of_special_rides;\r\n    unsigned int minimum_money_spent;\r\n    scanf(\"%u %u %u %u\", &no_of_rides, &special_no_of_rides, &price_of_one_ride, &price_of_special_rides);\r\n\r\n    minimum_money_spent = find_minimum_cost(no_of_rides, special_no_of_rides, price_of_one_ride, price_of_special_rides);\r\n\r\n    printf(\"%u\",minimum_money_spent);\r\n    return 0;\r\n}\r\n\r\nunsigned int find_minimum_cost(unsigned int no_of_rides, unsigned int special_no_of_rides,unsigned int price_of_one_ride,unsigned int price_of_special_rides)\r\n{\r\n    unsigned int minimum_cost, no_of_special_tickets, no_of_normal_tickets;\r\n\r\n    //If it is cheaper to use the special ticket than normal ticket for b rides\r\n    if(price_of_special_rides <= price_of_one_ride*special_no_of_rides)\r\n    {\r\n        no_of_special_tickets = no_of_rides/special_no_of_rides;\r\n\r\n        //Checking if it is cheaper to use the special ticket for the remaining rides\r\n        if(price_of_special_rides <= price_of_one_ride*(no_of_rides%special_no_of_rides))\r\n        {\r\n            no_of_special_tickets++;\r\n            no_of_normal_tickets = 0;\r\n        }\r\n        else\r\n        {\r\n            no_of_normal_tickets = no_of_rides%special_no_of_rides;\r\n        }\r\n    }\r\n    else //Otherwise only buy normal tickets\r\n    {\r\n        no_of_special_tickets = 0;\r\n        no_of_normal_tickets = no_of_rides;\r\n    }\r\n\r\n    minimum_cost = no_of_special_tickets*price_of_special_rides + no_of_normal_tickets*price_of_one_ride;\r\n    return minimum_cost;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Checking_the_Calendar.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define true 1\r\n#define false 0\r\n#define MAX_DAY_SIZE 10\r\n#define NO_OF_DAYS_IN_WEEK 7\r\n\r\nshort check_if_consecutive_months_start_with(char[], char[]);\r\nshort get_day_no(char[]);\r\nint main()\r\n{\r\n    short is_possible;\r\n    char day_1[MAX_DAY_SIZE], day_2[MAX_DAY_SIZE];\r\n\r\n    scanf(\"%s %s\",day_1, day_2);\r\n    is_possible = check_if_consecutive_months_start_with(day_1, day_2);\r\n\r\n    if(is_possible)\r\n    {\r\n        printf(\"YES\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n\r\nshort check_if_consecutive_months_start_with(char day_1[], char day_2[])\r\n{\r\n    short is_possible = false, no_day_1, no_day_2, difference;\r\n    no_day_1 = get_day_no(day_1);\r\n    no_day_2 = get_day_no(day_2);\r\n\r\n    // 7 is added inside to ensure we always get a positive number. (a-b) mod m = (a-b + m) mod m\r\n    difference = (no_day_2 - no_day_1 + NO_OF_DAYS_IN_WEEK)%NO_OF_DAYS_IN_WEEK;\r\n\r\n    //Let a month begin on day 1 and have x days. x = 7q + r, r is a number less than 7. The day 7q + 1 will have the same day of the week as the first day\r\n    //The next month begins at day r + 1. The difference in between 1(mod 7) and the allowable values of (r + 1) give us the answer.\r\n    //If the month has 31 days, then 31 = 4(7) + 3. The first day is on 1(mod 7). The next month's first day is on 4(mod 7). So, difference of 3 is allowed\r\n    //IF the month has 30 = 4(7) + 2. A difference of 2 is allowed\r\n    //If the month has 28 = 7(4) days. Both the first days are on 1(mod 7) so a difference of 0 is allowed.\r\n    if( (difference == 3) || (difference == 2) || (difference == 0) )\r\n    {\r\n        is_possible = true;\r\n    }\r\n    return is_possible;\r\n}\r\n\r\nshort get_day_no(char day[])\r\n{\r\n\r\n    if(strcmp (day, \"monday\") == 0)\r\n    {\r\n        return 1;\r\n    }\r\n    else if(strcmp (day, \"tuesday\") == 0)\r\n    {\r\n        return 2;\r\n    }\r\n    else if(strcmp (day, \"wednesday\") == 0)\r\n    {\r\n        return 3;\r\n    }\r\n    else if(strcmp (day, \"thursday\") == 0)\r\n    {\r\n        return 4;\r\n    }\r\n    else if(strcmp (day, \"friday\") == 0)\r\n    {\r\n        return 5;\r\n    }\r\n    else if(strcmp (day, \"saturday\") == 0)\r\n    {\r\n        return 6;\r\n    }\r\n    else if(strcmp (day, \"sunday\") == 0)\r\n    {\r\n        return 7;\r\n    }\r\n\r\n    return -1;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Currency_System_in_Geraldion.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nvoid read(unsigned int *, unsigned int);\r\nshort search_for_1(unsigned int *, unsigned int);\r\n\r\nint main()\r\n{\r\n    short is_there_a_1;\r\n    unsigned int no_of_denominations;\r\n\r\n    scanf(\"%u\",&no_of_denominations);\r\n\r\n    unsigned int *currency_notes = malloc(no_of_denominations*sizeof(unsigned int));\r\n\r\n    read(currency_notes, no_of_denominations);\r\n    is_there_a_1 = search_for_1(currency_notes, no_of_denominations);\r\n\r\n    if(is_there_a_1)\r\n    {\r\n        printf(\"-1\\n\"); //All currencies are reachable\r\n    }\r\n    else\r\n    {\r\n        printf(\"1\"); //There is no 1 so that is the smallest unreachable currency\r\n    }\r\n\r\n    free(currency_notes);\r\n    return 0;\r\n}\r\n\r\nvoid read(unsigned int *currency_notes, unsigned int no_of_denominations)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_denominations; i++)\r\n    {\r\n        scanf(\"%u\",(currency_notes + i));\r\n    }\r\n}\r\n\r\nshort search_for_1(unsigned int *currency_notes, unsigned int no_of_denominations)\r\n{\r\n    short one_found = false;\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_denominations; i++)\r\n    {\r\n        if(*(currency_notes + i) == 1)\r\n        {\r\n            one_found = true;\r\n            break;\r\n        }\r\n    }\r\n    return one_found;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Die_Roll.c",
    "content": "#include <stdio.h>\r\n\r\nshort maximum(short, short);\r\nint main()\r\n{\r\n    short roll_1, roll_2, dot_wins, total_rolls = 6;\r\n\r\n    scanf(\"%hu %hu\",&roll_1, &roll_2);\r\n    dot_wins =total_rolls - maximum(roll_1, roll_2) + 1;//+1 because the other two allow Dot to win if she equalises. the maximum is also inclusive of when Dot wins\r\n\r\n    //Reducing dot wins and total rolls to it's simplest form. Since we know it's 6, we just check divisibility by 2 and 3 instead of calling a gcd function\r\n    if(dot_wins%3 == 0)\r\n    {\r\n        dot_wins = dot_wins/3;\r\n        total_rolls = total_rolls/3;\r\n    }\r\n    if(dot_wins%2 == 0)\r\n    {\r\n        dot_wins = dot_wins/2;\r\n        total_rolls = total_rolls/2;\r\n    }\r\n\r\n    printf(\"%hu/%hu\\n\",dot_wins, total_rolls);\r\n    return 0;\r\n}\r\n\r\nshort maximum(short a, short b)\r\n{\r\n    if(a > b)\r\n    {\r\n        return a;\r\n    }\r\n    else\r\n    {\r\n        return b;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Domino_Effect.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint find_no_of_standing_dominos(char *);\r\nint main()\r\n{\r\n    int no_of_dominos, no_of_standing_dominos;\r\n    scanf(\"%d\",&no_of_dominos);\r\n\r\n    char *domino_line = malloc((no_of_dominos + 1)*sizeof(char));\r\n    scanf(\"%s\",domino_line);\r\n\r\n    no_of_standing_dominos = find_no_of_standing_dominos(domino_line);\r\n    printf(\"%d\\n\",no_of_standing_dominos);\r\n    free(domino_line);\r\n    return 0;\r\n}\r\n\r\n/*\r\n1. As we go through the domino line from the first domino, every '.' is counted as a standing domino.\r\n2. If the character in front of a '.' is L, then every domino before it falls. So, the number of standing dominos is reset to 0.\r\n\r\n3. If we find a 'R' at D(i), then we keep going ahead till we find either a 'L' at D(j) or the end of the string at j.\r\n\t\t\tIf there are an odd number of dominos in between position i and j, then one domino stands.\r\n\t\t\tIf there are an even number of dominos in between position i and j, they all fall.\r\n\r\n\t\t\tSo, if {D(j) = 'R' and (j-i-1) is odd}, no_of_dominos++.\r\n\t\t\t{-1 because we are counting the number of dominos in between i and j, exclusive. j not counted}\r\n\r\n\t\t\ti is then updated to j,\r\n\r\n4.If we find a 'L', at D(i) then we keep going ahead till we find either a 'R' at D(j) or the end of the string at position j.\r\n\t\t\tIn either case, all the dominos from i+1 to j-1 stand.\r\n\t\t\tno_of_standing_dominos = no_of_standing_dominos + (j - i - 1) {-1 because the j-th domino doesn't stand}\r\n\r\n\t\t\ti is then updated to j.\r\n\r\nAfter the dots at the beginning i.e. after the first time D(i) is an alphabet,\r\n i will always be either an alphabet or the end of the string.\r\nThis is why we can afford to increment the no of standing dominos every time D(i) is a '.' */\r\n\r\nint find_no_of_standing_dominos(char *domino_line)\r\n{\r\n    int no_of_standing_dominos = 0, i, j;\r\n\r\n    for(i = 0; *(domino_line + i) != '\\0';)\r\n    {\r\n        if(*(domino_line + i) == '.')//These are only for the dots at the beginning\r\n        {\r\n            no_of_standing_dominos++;//These dominos occur at the front.\r\n            i++;\r\n            if(*(domino_line + i) == 'L')\r\n            {\r\n                no_of_standing_dominos = 0;\r\n            }\r\n            continue;\r\n        }\r\n        else if(*(domino_line + i) == 'R')\r\n        {\r\n            //Searching for the next 'L' or the end of the string\r\n            for(j = i + 1; (*(domino_line + j) != '\\0') && (*(domino_line + j) != 'L'); j++);\r\n\r\n            if( (*(domino_line + j) == 'L') && ((j-i - 1)%2 == 1) ) //-1 because the j-th domino isn't counted. No of dominos in between i and j, exclusive\r\n            {\r\n                no_of_standing_dominos++; // Only one domino stands if the number of dominos in between them is odd\r\n            }\r\n            i = j; //i continues where j ends\r\n        }\r\n        else if(*(domino_line + i) == 'L')\r\n        {\r\n            for(j = i + 1; (*(domino_line + j) != '\\0') && (*(domino_line + j) != 'R'); j++);\r\n\r\n            no_of_standing_dominos = no_of_standing_dominos + (j - i - 1);//After a left pushed domino, all the dominos in between i and j stand\r\n            i = j;\r\n        }\r\n    }\r\n\r\n    return no_of_standing_dominos;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Expression.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned int find_maximum_value(short, short, short);\r\nunsigned int maximum(unsigned int, unsigned int);\r\n\r\nint main()\r\n{\r\n    short a, b, c;\r\n    unsigned int maximum_value;\r\n    scanf(\"%hu %hu %hu\", &a, &b, &c);\r\n\r\n    maximum_value = find_maximum_value(a, b, c);\r\n\r\n    printf(\"%u\\n\", maximum_value);\r\n    return 0;\r\n}\r\n\r\nunsigned int find_maximum_value(short a, short b, short c)\r\n{\r\n    unsigned int maximum_value = a + b + c;\r\n\r\n    maximum_value = maximum(maximum_value, (a+b)*c);\r\n    maximum_value = maximum(maximum_value, a+(b*c));\r\n    maximum_value = maximum(maximum_value, a*(b+c));\r\n    maximum_value = maximum(maximum_value, (a*b)+c);\r\n    maximum_value = maximum(maximum_value, a*b*c);\r\n\r\n    return maximum_value;\r\n}\r\n\r\nunsigned int maximum(unsigned int a, unsigned int b)\r\n{\r\n    if(a > b)\r\n    {\r\n        return a;\r\n    }\r\n    else\r\n    {\r\n        return b;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Fedya_and_Maths.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n#define SIZE_LIMIT 100000\r\n\r\nshort get_answer(short, short);\r\nint main()\r\n{\r\n    char number[SIZE_LIMIT];\r\n    short answer, last_digit, second_last_digit;\r\n\r\n    scanf(\"%s\",number);\r\n\r\n    last_digit = number[strlen(number) - 1] - '0'; //Getting the last digit\r\n    second_last_digit = number[strlen(number) - 2] - '0';//Getting the second last digit\r\n\r\n    answer = get_answer(second_last_digit, last_digit);\r\n\r\n    printf(\"%hu\\n\",answer);\r\n    return 0;\r\n}\r\n\r\nshort get_answer(short second_last_digit, short last_digit)\r\n{\r\n    //Notice that 4^n = (5 - 1)^n = (-1)^n (mod 5), Similarly, 3 = (-2)^n (mod 5)\r\n    if(last_digit%2 == 1)// If the number is odd, answer will always be 0.\r\n    {\r\n        return 0; //(1 + 2^n -2^n -1) (mod 5)\r\n    }\r\n    else //Powers of two mod 5 are {2, 4, 3, 1}. We are concerned with the even indices.\r\n    {\r\n          //(1 + 2.2^n + 1) (mod 5) = (2^{n+1} + 2) (mod 5). If n = 2 (mod 4), then the answer is 0, otherwise it is 4 from the observations above\r\n          if( (second_last_digit*10 + last_digit)%4 == 0)\r\n          {\r\n              return 4;\r\n          }\r\n          else //n = 2(mod 4)\r\n          {\r\n              return 0;\r\n          }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Filya_and_Homework.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort count_no_of_distinct_elements(unsigned long *,unsigned long, unsigned long[]);\r\nshort check_if_set_is_in_AP(unsigned long[], short);\r\nvoid get_answer(char[], short);\r\n\r\nint main()\r\n{\r\n    short is_possible = false, distinct_count;\r\n    unsigned long no_of_elements, i, distinct_element[3];\r\n    unsigned long *list_of_numbers = NULL;\r\n    char answer[4];\r\n\r\n    scanf(\"%lu\",&no_of_elements);\r\n    list_of_numbers = malloc(no_of_elements*sizeof(unsigned long));\r\n    for(i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%lu\",(list_of_numbers + i));\r\n    }\r\n\r\n\r\n    distinct_count = count_no_of_distinct_elements(list_of_numbers, no_of_elements, distinct_element);\r\n\r\n    if(distinct_count > 3)\r\n    {\r\n        is_possible = false;\r\n    }\r\n    else\r\n    {\r\n        is_possible = check_if_set_is_in_AP(distinct_element, distinct_count);\r\n    }\r\n    get_answer(answer, is_possible);\r\n\r\n    printf(\"%s\\n\",answer);\r\n    free(list_of_numbers);\r\n    return 0;\r\n}\r\n\r\nshort count_no_of_distinct_elements(unsigned long *list_of_numbers,unsigned long no_of_elements, unsigned long distinct_element[])\r\n{\r\n    short distinct_count = 0, already_counted;\r\n    int i, j;\r\n\r\n    for(i = 0; i < no_of_elements; i++)\r\n    {\r\n        already_counted = false; //For the i=th element,\r\n        for(j = 0; j < distinct_count ; j++)\r\n        {\r\n            if(*(list_of_numbers + i) == distinct_element[j])\r\n            {\r\n                already_counted = true;\r\n                break;\r\n            }\r\n        }\r\n        if(already_counted == false)\r\n        {\r\n            distinct_element[distinct_count] = *(list_of_numbers + i);\r\n            distinct_count++;\r\n            if(distinct_count > 3) //If it exceeds three, just stop. Because it isn't possible for more than three distinct elements.\r\n            {\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    return distinct_count ;\r\n}\r\n\r\nshort check_if_set_is_in_AP(unsigned long distinct_element[], short distinct_count)\r\n{\r\n    short set_is_in_AP = false;\r\n\r\n    if(distinct_count < 3) //Set of 2 or 1 element will always be in AP\r\n    {\r\n        set_is_in_AP = true;\r\n        return set_is_in_AP;\r\n    }\r\n\r\n    unsigned long a = distinct_element[0], b = distinct_element[1], c = distinct_element[2];\r\n\r\n    if( (a + c == 2*b) || (b + c == 2*a) || (b + a == 2*c) )\r\n    {\r\n        set_is_in_AP = true;\r\n    }\r\n    return set_is_in_AP;\r\n}\r\n\r\nvoid get_answer(char answer[], short is_possible)\r\n{\r\n    if(is_possible == true)\r\n    {\r\n        strcpy(answer, \"YES\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(answer, \"NO\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Game.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short no_of_balls_in_box_1, no_of_balls_in_box_2;\r\n    short max_balls_1_can_throw, max_balls_2_can_throw;\r\n\r\n    scanf(\"%hu %hu %hu %hu\",&no_of_balls_in_box_1, &no_of_balls_in_box_2, &max_balls_1_can_throw,&max_balls_2_can_throw);\r\n\r\n    if(no_of_balls_in_box_1 > no_of_balls_in_box_2)\r\n    {\r\n        printf(\"First\\n\");\r\n    }\r\n    else //In case of equality, the second player wins\r\n    {\r\n        printf(\"Second\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Initial_Bet.c",
    "content": "#include <stdio.h>\r\n\r\n#define NO_OF_PEOPLE 5\r\nint main()\r\n{\r\n    int final_coins[NO_OF_PEOPLE], i, start_coins;\r\n    int total_coins = 0;\r\n\r\n    for(i = 0; i < NO_OF_PEOPLE; i++)\r\n    {\r\n        scanf(\"%d\",&final_coins[i]);\r\n    }\r\n\r\n    for(i = 0; i < NO_OF_PEOPLE; i++)\r\n    {\r\n        total_coins = total_coins + final_coins[i];\r\n    }\r\n\r\n    /*No coins leave the system and no new coins enter the system. The total number of coins remain invariant.\r\n    If in the beginning, everyone had b coins, the total number of coins will always be (NO_OF_PEOPLE*b). If the total number of coins are not a multiple\r\n    of NO_OF_PEOPLE, then there can be no b which can be given to everyone leading to the current conversation.\r\n    Conversely, if the total number of coins is NO_OF_PEOPLE*b, where b is some integer\r\n    we can always trace the steps back to when everyone had b coins in the following way -\r\n    Pick the maximum and minimum number of coins. Donate coins of maximum to minimum till the person with maximum is left with only b coins.\r\n    Now, repeat this procedure for the rest of the people till everyone has b coins. We know this process converges because the total number of coins is\r\n    NO_OF_PEOPLE*b,\r\n    According to the question, 0 is not a legitimate answer so that case must be checked.*/\r\n    if( (total_coins%NO_OF_PEOPLE == 0) && (total_coins != 0) )\r\n    {\r\n        start_coins = total_coins/NO_OF_PEOPLE;\r\n    }\r\n    else\r\n    {\r\n        start_coins = -1;\r\n    }\r\n\r\n    printf(\"%d\\n\", start_coins);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/LCM_Challenge.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long n;\r\n    unsigned long long answer;\r\n\r\n    scanf(\"%I64u\",&n);\r\n\r\n    if(n < 3)\r\n    {\r\n        printf(\"%I64u\",n);\r\n        return 0;\r\n    }\r\n\r\n    if(n%2 == 1)\r\n    {\r\n        answer = (n)*(n-1)*(n-2);\r\n    }\r\n    else if(n%3 != 0)//Even number not a multiple of 3. n and (n-2) are not coprime and n(n-1)(n-3) > (n-1)(n-2)(n-3)\r\n    {\r\n        answer = n*(n-1)*(n-3);\r\n    }\r\n    else //Multiples of 6\r\n    {\r\n        answer = (n-1)*(n-2)*(n-3);\r\n    }\r\n\r\n    printf(\"%I64u\\n\",answer);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Maximum_Increase.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(unsigned long *, unsigned int);\r\nunsigned int find_length_max_increasing_subsequence(unsigned long *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_numbers, maximum_subsequence_length;\r\n    scanf(\"%u\",&no_of_numbers);\r\n\r\n    unsigned long *number_sequence = malloc(no_of_numbers*sizeof(unsigned long));\r\n    read(number_sequence, no_of_numbers);\r\n\r\n    maximum_subsequence_length = find_length_max_increasing_subsequence(number_sequence, no_of_numbers);\r\n    printf(\"%u\\n\",maximum_subsequence_length);\r\n\r\n    free(number_sequence);\r\n    return 0;\r\n}\r\n\r\nvoid read(unsigned long *number_sequence, unsigned int no_of_numbers)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0 ; i < no_of_numbers; i++)\r\n    {\r\n        scanf(\"%lu\",(number_sequence + i));\r\n    }\r\n}\r\n\r\nunsigned int find_length_max_increasing_subsequence(unsigned long *number_sequence, unsigned int no_of_numbers)\r\n{\r\n    unsigned int i, j, length_of_increasing_subsequence = 0, maximum_increasing_subsequence = 1;\r\n\r\n    for(i = 0; i < no_of_numbers; )\r\n    {\r\n        length_of_increasing_subsequence = 1;\r\n\r\n        //Finds the length of the increasing subsequence starting at i\r\n        for(j = i + 1; (*(number_sequence + j) > *(number_sequence + j - 1) ) && (j < no_of_numbers); j++)\r\n        {\r\n            length_of_increasing_subsequence++;\r\n        }\r\n        i = j; //i resumes where j ends i.e. It starts from the next subsequence/**< /**< /**< /**< /**<  */ */ */ */ */\r\n\r\n        if(length_of_increasing_subsequence > maximum_increasing_subsequence)\r\n        {\r\n            maximum_increasing_subsequence = length_of_increasing_subsequence;\r\n        }\r\n    }\r\n\r\n    return maximum_increasing_subsequence;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Mishka_and_Game.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nshort find_who_won_more(short *, short *, short);\r\nvoid read_results(short *, short *, short);\r\nint main()\r\n{\r\n    short no_of_games;\r\n    short winner;\r\n    scanf(\"%hu\",&no_of_games);\r\n    short *mishka_results = malloc(no_of_games*sizeof(short));\r\n    short *chris_results = malloc(no_of_games*sizeof(short));\r\n\r\n\r\n    read_results(mishka_results, chris_results, no_of_games);\r\n    winner = find_who_won_more(mishka_results, chris_results, no_of_games);//Returns 1 if Mishka is the winner and 2 if Chris wins and 0 for draw\r\n\r\n    if(winner == 1)\r\n    {\r\n        printf(\"Mishka\\n\");\r\n    }\r\n    else if(winner == 2)\r\n    {\r\n        printf(\"Chris\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"Friendship is magic!^^\\n\");\r\n    }\r\n\r\n    free(mishka_results);\r\n    free(chris_results);\r\n    return 0;\r\n}\r\n\r\nvoid read_results(short *mishka_results, short *chris_results, short no_of_games)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_games; i++)\r\n    {\r\n        scanf(\"%hu %hu\",(mishka_results + i), (chris_results + i));\r\n    }\r\n}\r\nshort find_who_won_more(short *mishka_results, short *chris_results, short no_of_games)\r\n{\r\n    short i, mishka_win = 0, chris_win = 0;\r\n\r\n    for(i = 0; i < no_of_games; i++)\r\n    {\r\n        if(*(mishka_results + i) >  *(chris_results + i))\r\n        {\r\n            mishka_win++;\r\n        }\r\n        else if(*(mishka_results + i) <  *(chris_results + i))\r\n        {\r\n            chris_win++;\r\n        }\r\n    }\r\n\r\n    if(mishka_win > chris_win)\r\n    {\r\n        return 1;\r\n    }\r\n    else if(chris_win > mishka_win)\r\n    {\r\n        return 2;\r\n    }\r\n    else //Both are equal\r\n    {\r\n        return 0;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Multiplication_Table.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_rows, no_of_boxes_containing_num = 0, i;\r\n    unsigned long number;\r\n\r\n    scanf(\"%u %lu\",&no_of_rows, &number);\r\n\r\n    //The question of finding the number of boxes that contain n, is equivalent to counting the number of ordered pairs(i, j) such that i*j = n\r\n    for(i = 1;( (i*i < number) && (i <= no_of_rows) ); i++)\r\n    {\r\n        if( (number%i == 0) && (number/i <=no_of_rows) ) //Checking if the spot[i, x/i] exists on the square\r\n        {\r\n            no_of_boxes_containing_num = no_of_boxes_containing_num + 2; //Two boxes [i, x/i] and [x/i, i]\r\n        }\r\n    }\r\n\r\n    if( (i*i == number)  && (i <=no_of_rows) )\r\n    {\r\n        no_of_boxes_containing_num++; //Perfect square [i, i]\r\n    }\r\n\r\n    printf(\"%u\\n\",no_of_boxes_containing_num);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Next_Round.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(short *, short);\r\nshort find_no_of_winners(short *, short, short );\r\n\r\nint main()\r\n{\r\n    short no_of_players, threshold_winner, no_of_winners;\r\n\r\n    scanf(\"%hu %hu\",&no_of_players, &threshold_winner);\r\n\r\n    short *score = malloc(no_of_players*sizeof(short));\r\n\r\n    read(score, no_of_players);\r\n    no_of_winners = find_no_of_winners(score, no_of_players, threshold_winner - 1);//1 is subtracted because we start counting from 0\r\n    printf(\"%hu\\n\",no_of_winners);\r\n    free(score);\r\n    return 0;\r\n}\r\n\r\nvoid read(short *score, short no_of_players)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_players; i++)\r\n    {\r\n        scanf(\"%hu\",(score + i));\r\n    }\r\n}\r\n\r\nshort find_no_of_winners(short *score, short no_of_players, short winning_threshold)\r\n{\r\n    short no_of_winners;\r\n\r\n    if(*(score + winning_threshold) > 0)\r\n    {\r\n        //If the winning threshold is positive, then check how many players after the winning threshold position, have scored the same number of points\r\n        for(no_of_winners = winning_threshold; no_of_winners < no_of_players; no_of_winners++)\r\n        {\r\n            if(*(score + no_of_winners) != *(score + winning_threshold))\r\n            {\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    else //If the winning threshold is negative, search for the first person ahead of the winning threshold with a positive score\r\n    {\r\n        for(no_of_winners = winning_threshold; no_of_winners >= 0; no_of_winners--)\r\n        {\r\n            if(*(score + no_of_winners) > 0)\r\n            {\r\n                break;\r\n            }\r\n        }\r\n        no_of_winners++;//We have found the first index i, such that Score[i] is positive, increment so that we can count from 1 again.\r\n    }\r\n\r\n    return no_of_winners;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Party.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nvoid read(int *, unsigned int);\r\nunsigned int find_no_of_groups(int *, unsigned int);\r\nunsigned int find_depth_of_employee(int, int *);\r\nvoid find_depths_of_all_employees(int *, int *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_people, no_of_groups;\r\n\r\n    scanf(\"%u\",&no_of_people);\r\n\r\n    int *immediate_manager = malloc(no_of_people*sizeof(int));\r\n    int *depth_of_employee = malloc(no_of_people*sizeof(int));\r\n\r\n    read(immediate_manager, no_of_people);\r\n    find_depths_of_all_employees(depth_of_employee, immediate_manager, no_of_people);\r\n    no_of_groups = find_no_of_groups(depth_of_employee, no_of_people);\r\n\r\n    printf(\"%u\\n\",no_of_groups);\r\n\r\n    free(depth_of_employee);\r\n    free(immediate_manager);\r\n    return 0;\r\n}\r\n\r\nvoid read(int *immediate_manager, unsigned int no_of_people)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_people; i++)\r\n    {\r\n        scanf(\"%d\",(immediate_manager + i));\r\n    }\r\n}\r\n\r\n/*First assign a depth to every node. The rule for depth is -\r\n1. The root node has a depth of 0.\r\n2. For every other node, Depth[i] = 1 + Depth[Immediate_manager(i)]*/\r\n\r\nunsigned int find_depth_of_employee(int current_person, int *immediate_manager)\r\n{\r\n    int next_immediate_manager;\r\n\r\n    if(*(immediate_manager + current_person) == -1)\r\n    {\r\n        return 0;\r\n    }\r\n    else\r\n    {\r\n        next_immediate_manager = *(immediate_manager + current_person) - 1; //-1 because the input counts from 1 and we count from 0 in the array\r\n        return 1 + find_depth_of_employee(next_immediate_manager, immediate_manager);\r\n    }\r\n}\r\n\r\nvoid find_depths_of_all_employees(int *depth_of_employee, int *immediate_manager, unsigned int no_of_people)\r\n{\r\n    int i;\r\n\r\n    for(i = 0; i < no_of_people; i++)\r\n    {\r\n        *(depth_of_employee + i) = find_depth_of_employee(i, immediate_manager);\r\n    }\r\n}\r\n\r\n/*\r\nHere is a simple strategy that achieves the following -\r\n1. Assign a depth to every node.\r\n2. Place all nodes of the same depth in the same set.\r\n\r\nWe have to prove this arrangement ensure two nodes which share an edge aren't in the same set and that this happens in the minimum number of sets.\r\n\r\nThe first part is obvious. This arrangements ensures that a given set only has elements of the same depth. No two nodes (either from the same or different tree)\r\nshare an edge.\r\n\r\nTo prove it's minimum, let us assume that such an arrangement exists with the number of sets l, where l < max{depth}\r\nConsider the tree with the nodes of maximum depth. By the pigeonhole principle there will exist one set which has nodes of this tree of two different depths.\r\nBut, They can't belong to the same tree because it would violate the condition of the partition.\r\nThis contradicts our assumption that an arrangement exists with less than max{depth} sets.\r\n\r\nThe arrangements described takes max{depth} number of nodes. So, it is the minimum number.\r\n*/\r\n\r\nunsigned int find_no_of_groups(int *depth_of_employee, unsigned int no_of_people)\r\n{\r\n    short already_counted;\r\n    int i, j, distinct_depth_count = 0;\r\n\r\n    int *distinct_depth = malloc(no_of_people*sizeof(int));\r\n\r\n    for(i = 0; i < no_of_people; i++)\r\n    {\r\n        already_counted = false; //For the i=th element,\r\n        for(j = 0; j < distinct_depth_count ; j++)\r\n        {\r\n            if(*(depth_of_employee + i) == *(distinct_depth + j) )\r\n            {\r\n                already_counted = true;\r\n                break;\r\n            }\r\n        }\r\n\r\n        if(already_counted == false)\r\n        {\r\n            *(distinct_depth + distinct_depth_count) = *(depth_of_employee + i);\r\n            distinct_depth_count++;\r\n        }\r\n    }\r\n\r\n    free(distinct_depth);\r\n    return distinct_depth_count ; //The number of distinct depths is the answer\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Police_Recruits.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(short *, int);\r\nint find_no_untreated_crimes(short *, int);\r\n\r\nint main()\r\n{\r\n    int no_of_events, untreated_crimes;\r\n\r\n    scanf(\"%u\",&no_of_events);\r\n\r\n    short *events = malloc(no_of_events*sizeof(short));\r\n\r\n    read(events, no_of_events);\r\n    untreated_crimes = find_no_untreated_crimes(events, no_of_events);\r\n    printf(\"%u\\n\",untreated_crimes);\r\n\r\n    free(events);\r\n    return 0;\r\n}\r\n\r\nvoid read(short *events, int no_of_events)\r\n{\r\n    int i;\r\n\r\n    for(i = 0; i < no_of_events; i++)\r\n    {\r\n        scanf(\"%hu\",(events + i));\r\n    }\r\n}\r\n\r\nint find_no_untreated_crimes(short *events, int no_of_events)\r\n{\r\n    int untreated_crimes = 0, i, available_police_officers = 0;\r\n\r\n    for(i = 0; i < no_of_events; i++)\r\n    {\r\n        if(*(events + i) == -1)\r\n        {\r\n            if(available_police_officers > 0)\r\n            {\r\n                available_police_officers--;\r\n            }\r\n            else if(available_police_officers == 0)\r\n            {\r\n                untreated_crimes++;\r\n            }\r\n        }\r\n        else//Officers are recruited\r\n        {\r\n            available_police_officers = available_police_officers + *(events + i);\r\n        }\r\n    }\r\n\r\n    return untreated_crimes;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Raising_Bacteria.c",
    "content": "#include <stdio.h>\r\n#define MASK_1 0x5555555555555555\r\n#define MASK_2 0x3333333333333333\r\n#define MASK_3 0x0F0F0F0F0F0F0F0F\r\n#define MASK_4 0x00FF00FF00FF00FF\r\n#define MASK_5 0x0000FFFF0000FFFF\r\n#define MASK_6 0x00000000FFFFFFFF\r\n\r\nunsigned long long find_no_of_1_in_binary(unsigned long long);\r\nint main()\r\n{\r\n    unsigned long long target_bacteria, no_of_bacteria;\r\n\r\n    scanf(\"%I64u\",&target_bacteria);\r\n\r\n    no_of_bacteria = find_no_of_1_in_binary(target_bacteria);\r\n\r\n    printf(\"%I64u\",no_of_bacteria);\r\n    return 0;\r\n}\r\n\r\nunsigned long long find_no_of_1_in_binary(unsigned long long target_bacteria)\r\n{\r\n    unsigned long long population_count;\r\n\r\n    population_count = target_bacteria;\r\n    population_count = (population_count & MASK_1) + (population_count >> 1 & MASK_1);//After this step, every pair b[i, i+1] = b[i] + b[i+1], for even i\r\n    //After this step, every quartet b[i ..  i+3] = b[i .. i+1] + b[i+2 ... i+3] from previous step, for multiples of 4 - i\r\n    population_count = (population_count & MASK_2) + (population_count >> 2 & MASK_2);\r\n    //After this step, every b[i ..  i+7] = b[i .. i+3] + b[i+4 ... i+7] from previous step, for multiples of 8 - i\r\n    population_count = (population_count & MASK_3) + (population_count >> 4 & MASK_3);\r\n    //After this step, every b[i ..  i+15] = b[i .. i+7] + b[i+8 ... i+15] from previous step, for multiples of 16 - i\r\n    population_count = (population_count & MASK_4) + (population_count >> 8 & MASK_4);\r\n    //After this step, every b[i ..  i+31] = b[i .. i+15] + b[i+16 ... i+31] from previous step, for multiples of 32 - i\r\n    population_count = (population_count & MASK_5) + (population_count >> 16 & MASK_5);\r\n    //After this step, every b[i ..  i+63] = b[i .. i+31] + b[i+32 ... i+63] from previous step, for multiples of 64 - i\r\n    population_count = (population_count & MASK_6) + (population_count >> 32 & MASK_6);\r\n    //After this last step, what's left is the number of 1s in the binary representation of a number\r\n\r\n    return population_count;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Save_Luke.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    float velocity_left, velocity_right, length_of_corridor, width_of_luke;\r\n    float relative_velocity, effective_distance, max_survival_time;\r\n\r\n    scanf(\"%f %f %f %f\", &width_of_luke, &length_of_corridor, &velocity_left, &velocity_right);\r\n\r\n    relative_velocity = velocity_left + velocity_right;\r\n    effective_distance = length_of_corridor - width_of_luke;\r\n    max_survival_time = effective_distance/relative_velocity;\r\n\r\n    printf(\"%f\",max_survival_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Taxes.c",
    "content": "#include <stdio.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort is_prime(unsigned long);\r\nshort find_minimum_tax(unsigned long);\r\n\r\nint main()\r\n{\r\n    short minimum_taxes;\r\n    unsigned long total_taxes;\r\n    scanf(\"%lu\",&total_taxes);\r\n    minimum_taxes = find_minimum_tax(total_taxes);\r\n    printf(\"%hu\\n\",minimum_taxes);\r\n    return 0;\r\n}\r\n\r\n//Happens in O(root(n)) time\r\nshort is_prime(unsigned long n)\r\n{\r\n    short prime = true;\r\n    unsigned long i;\r\n\r\n    for(i = 2; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            prime = false;\r\n            break;\r\n        }\r\n    }\r\n    return prime;\r\n}\r\n\r\n/*If the number is prime, then only 1 has to be paid. That is the minimum possible.\r\nThe next minimum is 2.\r\nSince the Goldbach conjecture has been verified upto the limit, we can use it. Any even number is the sum of two primes.\r\nWe don't need to actually find the pair of primes, we just know it exists.\r\nIf a number is odd and composite , n = (n-2) + 2, is the only way it can be written as the sum of two primes. 2 is the only even prime number.\r\nThe sum of two odd numbers is another odd number. So, an even number has to be involved. If (n-2) is prime, then the minimum tax = 1+1 = 2\r\n\r\nn = n-3 + 3, and then n-3 is an even number and has minimum return 2. 3 is prime. 2+1 = 3. This is the maximum possible tax that will ever be given\r\nfollowing the scheme.\r\n\r\nNote - Although logically the first thing to do is check if a number is prime and return 1 if it is and then go for the other test,\r\nI have included it second because checking parity of number is a very quick and easy process Even numbers don't need to be subjected to primality tests.*/\r\nshort find_minimum_tax(unsigned long tax)\r\n{\r\n    //According to Goldbach conjecture, every even number can be written as the sum of two odd primes, It has been numerically verified upto the limit given\r\n    if( (tax%2 == 0) && (tax != 2) )\r\n    {\r\n        return 2;\r\n    }\r\n    else if(is_prime(tax))\r\n    {\r\n        return 1;\r\n    }\r\n    else\r\n    {\r\n        //If n-2 is prime, then n = (n - 2) + 2 is the sum of two primes. This is the only way since one summand has to be even to get an odd number\r\n        if(is_prime(tax - 2))\r\n        {\r\n            return 2;\r\n        }\r\n        else //Then, n = (n-3) + 3. n-3 is an even number and can be written as the sum of two odd primes\r\n        {\r\n            return 3;\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Tennis_Tournament.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_bottles_for_one_player, no_of_participants, no_of_towels_for_one_player;\r\n    unsigned int total_no_of_bottles, total_no_of_towels, no_of_matches;\r\n\r\n    scanf(\"%u %u %u\",&no_of_participants, &no_of_bottles_for_one_player, &no_of_towels_for_one_player);\r\n\r\n    //If there are n people, then there have to be n-1 matches. Each match eliminates one player and one player only. We need n-1 eliminations to end\r\n    no_of_matches = no_of_participants - 1;\r\n    //Each player takes two bottles and one for the judge\r\n    total_no_of_bottles = no_of_matches*(2*no_of_bottles_for_one_player + 1);//One judge for every match\r\n    total_no_of_towels = no_of_participants*no_of_towels_for_one_player ;\r\n\r\n    printf(\"%u %u\\n\", total_no_of_bottles, total_no_of_towels);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/The_Number_of_Positions.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned int minimum(unsigned int, unsigned int);\r\nint main()\r\n{\r\n    short no_of_people, minimum_people_in_front, maximum_people_at_back, no_of_possible_positions;\r\n\r\n    scanf(\"%hu %hu %hu\", &no_of_people, &minimum_people_in_front, &maximum_people_at_back);\r\n\r\n    //The number of possible positions is the overlap in between (n-a) and (b + 1).\r\n    //one is added because if someone is standing at the (b+1)th position from the back, there are exactly b people behind him and he can stand in any position\r\n    //after this\r\n    no_of_possible_positions = minimum(no_of_people - minimum_people_in_front, maximum_people_at_back + 1);\r\n    printf(\"%hu\\n\",no_of_possible_positions);\r\n    return 0;\r\n}\r\n\r\nunsigned int minimum(unsigned int a, unsigned int b)\r\n{\r\n    if(a < b)\r\n    {\r\n        return a;\r\n    }\r\n    else\r\n    {\r\n        return b;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 3/Theatre_Square.c",
    "content": "#include <stdio.h>\r\n#include <math.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long rectangular_length, rectangular_breadth, square_side, answer;\r\n    scanf(\"%I64u %I64u %I64u\",&rectangular_length, &rectangular_breadth, &square_side);\r\n\r\n    if(rectangular_length%square_side != 0)\r\n    {\r\n        if(rectangular_breadth%square_side != 0)\r\n        {\r\n            answer = (rectangular_length/square_side + 1)*(rectangular_breadth/square_side + 1);\r\n        }\r\n        else\r\n        {\r\n            answer = (rectangular_length/square_side + 1)*(rectangular_breadth/square_side);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        if(rectangular_breadth%square_side != 0)\r\n        {\r\n            answer = (rectangular_length/square_side)*(rectangular_breadth/square_side + 1);\r\n        }\r\n        else\r\n        {\r\n            answer = (rectangular_length/square_side)*(rectangular_breadth/square_side);\r\n        }\r\n    }\r\n    printf(\"%I64u\\n\",answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Aloyna_Numbers.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned long long count_pairs_multiple_5(unsigned long long, unsigned long long);\r\nint main()\r\n{\r\n    unsigned long long m, n, answer;\r\n    scanf(\"%I64u %I64u\",&m, &n);\r\n    answer = count_pairs_multiple_5(m,n);\r\n    printf(\"%I64u\\n\",answer);\r\n    return 0;\r\n}\r\n\r\nunsigned long long count_pairs_multiple_5(unsigned long long m, unsigned long long n)\r\n{\r\n    short i;\r\n    unsigned long long answer = 0, current_mod_x, current_mod_y;\r\n\r\n    answer = (n/5)*(m/5);//doing the case of i = 0 (mod 5) separately because (m - (5 - i)) will actually lose 1 possible value of y.\r\n    for(i = 1; i <5; i++)\r\n    {\r\n        current_mod_x = n/5;\r\n        current_mod_y = m/5;\r\n        if(n%5 >= i)\r\n        {\r\n            current_mod_x++;\r\n        }\r\n        if(m%5 >= 5 - i)\r\n        {\r\n            current_mod_y++;\r\n        }\r\n        answer = answer + current_mod_x*current_mod_y;\r\n    }\r\n    return answer;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Arpa_Hard_Problem_Mehrad_Naive_Cheat.c",
    "content": "#include <stdio.h>\r\n\r\nshort get_last_digit(unsigned long);\r\nint main()\r\n{\r\n    short answer;\r\n    unsigned long power;\r\n    scanf(\"%lu\",&power);\r\n\r\n    answer = get_last_digit(power);\r\n    printf(\"%hu\\n\",answer);\r\n    return 0;\r\n}\r\n\r\nshort get_last_digit(unsigned long power)\r\n{\r\n    short i, answer = 1;\r\n\r\n    if(power == 0)//n^0 = 1\r\n    {\r\n        return answer;\r\n    }\r\n\r\n    /*(10x + a)^{n} = a^n (mod 10) because every other term in (10x + a)^n binomial expansion is a multiple of 10.\r\n    1378^n = 8^n (mod 10). Powers of 8 are cyclic with period 4.*/\r\n    power = power%4;\r\n\r\n    if(power == 0)//This means it is a multiple of 4 not equal to zero. We set it to 4 so that we multiply 8 four times (mod 10) instead of 0 times.\r\n    {\r\n        power = 4;\r\n    }\r\n\r\n    for(i = 1; i <= power; i++)\r\n    {\r\n        answer = (answer*8)%10;\r\n    }\r\n\r\n    return answer;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Benches.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long no_of_paths;\r\n    unsigned long long no_of_arrangements;\r\n    scanf(\"%I64u\",&no_of_paths);\r\n    //nC5 nP5\r\n    no_of_arrangements = (no_of_paths)*(no_of_paths -1)/2* (no_of_paths -2)/3* (no_of_paths-3)/4*(no_of_paths-4)/5;\r\n    no_of_arrangements *= (no_of_paths)*(no_of_paths -1)* (no_of_paths -2)* (no_of_paths-3)*(no_of_paths-4);\r\n    printf(\"%I64u\\n\",no_of_arrangements);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Challenge_Pendants.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long no_of_tables, no_of_ways;\r\n    scanf(\"%I64u\",&no_of_tables);\r\n\r\n    //(n + 5 -1) C (5) x (n + 3 - 1) C (3) - The two kinds of pendants' distribution is independent. Stars and bars for both of them.\r\n    //Among any n consecutive integers, one of them is a multiple of n. That is why we divide by 2 after the first two numbers, 3 after first 3, etc.\r\n    //Dividing at each step reduces the chance of overflow that might happen if the entire number is multiplied and then divided.\r\n    no_of_ways = (no_of_tables + 4) * (no_of_tables + 3)/2 * (no_of_tables + 2)/3 * (no_of_tables + 1)/4 * (no_of_tables)/5;\r\n    no_of_ways *= (no_of_tables + 2)*(no_of_tables + 1)/2 *(no_of_tables)/3;\r\n    printf(\"%I64u\\n\",no_of_ways);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Chewbacca_and_Number.c",
    "content": "#include <stdio.h>\r\n#define NO_OF_DIGITS 20\r\n\r\nvoid transform_n_to_minimum(char[]);\r\nint main()\r\n{\r\n    char number[NO_OF_DIGITS];\r\n    scanf(\"%s\",number);\r\n    transform_n_to_minimum(number);\r\n    printf(\"%s\",number);\r\n    return 0;\r\n}\r\n\r\nvoid transform_n_to_minimum(char number[])\r\n{\r\n    short i;\r\n\r\n    for(i = 0; number[i] != '\\0'; i++)\r\n    {\r\n        //Digits greater than 5 are replaced by their compliment\r\n        if(('5' <= number[i]) && (number[i] <= '9'))\r\n        {\r\n            number[i] = '9' - number[i] + '0';\r\n        }\r\n    }\r\n\r\n    if(number[0] == '0')//If first digit is zero, then it means it was a 9. We leave it untouched.\r\n    {\r\n        number[0] = '9';\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Chocolate.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nvoid read(short *, short);\r\nshort check_if_divison_exists(short *, short);\r\nlong long find_no_of_divisions(short *, short);\r\n\r\nint main()\r\n{\r\n    short no_of_pieces;\r\n    long long no_of_divisions;\r\n\r\n    scanf(\"%hu\",&no_of_pieces);\r\n\r\n    short *chocolate = malloc(no_of_pieces*sizeof(short));\r\n\r\n    read(chocolate, no_of_pieces);\r\n    no_of_divisions = find_no_of_divisions(chocolate, no_of_pieces);\r\n\r\n    printf(\"%I64d\\n\",no_of_divisions);\r\n    free(chocolate);\r\n    return 0;\r\n}\r\n\r\nvoid read(short *chocolate, short no_of_pieces)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_pieces; i++)\r\n    {\r\n        scanf(\"%hu\",(chocolate + i));\r\n    }\r\n}\r\n\r\nshort check_if_divison_exists(short *chocolate, short no_of_pieces)\r\n{\r\n    short i, division_exists = false;\r\n\r\n    for(i = 0; i < no_of_pieces; i++)\r\n    {\r\n        if(*(chocolate + i) == 1)\r\n        {\r\n            division_exists = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    return division_exists;\r\n}\r\nlong long find_no_of_divisions(short *chocolate, short no_of_pieces)\r\n{\r\n    short does_division_exist;\r\n    long long no_of_divsions = 1;\r\n    short i, zero_count;\r\n\r\n    //Checking if a division exists\r\n    does_division_exist = check_if_divison_exists(chocolate, no_of_pieces);\r\n    if(does_division_exist == false)\r\n    {\r\n        no_of_divsions = 0;\r\n        return no_of_divsions;\r\n    }\r\n\r\n    //If there is a run of p 0s in between 2 1s, then a cut can be made in (p + 1) places. We multiply all the (p+1)\r\n    for(i = 0; i < no_of_pieces;)\r\n    {\r\n        if( *(chocolate + i) == 0)\r\n        {\r\n            i++;\r\n            continue;\r\n        }\r\n        else\r\n        {\r\n            //Count the number of zeros in between two consecutive 1s i.e. the current run of 0s.\r\n            for(zero_count = 0; (i + zero_count) < no_of_pieces ; zero_count++)\r\n            {\r\n                if( *(chocolate + i + zero_count + 1) == 1)\r\n                {\r\n                    no_of_divsions = no_of_divsions*(zero_count + 1);\r\n                    break;\r\n                }\r\n            }\r\n\r\n            i = i + zero_count + 1; //i resumes from where the run of 0s ends, i.e. the next 1 or the end of the string.\r\n        }\r\n    }\r\n    return no_of_divsions;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Design_Tutorial_Learn_From_Math.c",
    "content": "#include <stdio.h>\r\n\r\nvoid get_composite_summands(unsigned long, unsigned long *, unsigned long *);\r\nint main()\r\n{\r\n    unsigned long number, composite_summand_1, composite_summand_2;\r\n    scanf(\"%lu\",&number);\r\n\r\n    get_composite_summands(number, &composite_summand_1, &composite_summand_2); //Pass by Reference\r\n    printf(\"%lu %lu\\n\", composite_summand_1, composite_summand_2);\r\n    return 0;\r\n}\r\n\r\nvoid get_composite_summands(unsigned long number, unsigned long *composite_summand_1, unsigned long *composite_summand_2)\r\n{\r\n    if(number%2 == 0)\r\n    {\r\n        //2n = n + n, If n is an even number, we are done\r\n        if(number%4 == 0)\r\n        {\r\n            *composite_summand_1 = number/2;\r\n            *composite_summand_2 = number/2;\r\n            return;\r\n        }\r\n        else //2n = n - 1 + n + 1, here (n-1) and (n+1) are even numbers because n is odd\r\n        {\r\n            *composite_summand_1 = number/2 - 1;\r\n            *composite_summand_2 = number/2 + 1;\r\n            return;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        //n = 9 + (n -9). 9 is composite and (n-9) is even. Since, n >= 12, n-9 >=4 when n is odd in the given range. We will always get an even number\r\n        *composite_summand_1 = 9;\r\n        *composite_summand_2 = number - 9;\r\n        return;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Divisibility.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long sales, no_of_bonuses;\r\n    scanf(\"%I64u\",&sales);\r\n\r\n    //To be divisible by every number from 1-10, it has to be divisible by 2^3, 3^2, 5, 7 i.e. 2520 - Any number divisible by 2520 can be divided by\r\n    //every number from 1-10 because each i in between 1-10, has all it's prime factors in such a number.\r\n    //Any number not divisible by 2520, will have atleast one number such that all it's prime factors aren't in that number. So, the condition is necessary\r\n    //and sufficient\r\n    no_of_bonuses = sales/2520LL;\r\n    printf(\"%I64u\\n\",no_of_bonuses);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Fedor_and_New_Game.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define MASK1 0x55555555\r\n#define MASK2 0x33333333\r\n#define MASK3 0x0F0F0F0F\r\n#define MASK4 0x00FF00FF\r\n#define MASK5 0x0000FFFF\r\n\r\nvoid read(int *, int);\r\nint find_maximum_number_of_friends(int *, int,int, int);\r\nint population_count(int);\r\nint main()\r\n{\r\n    short n, maximum_allowed_differences;\r\n    int fedor_army, no_of_soldiers, maximum_no_of_friends;\r\n\r\n    scanf(\"%hu %d %hu\", &n, &no_of_soldiers, &maximum_allowed_differences);\r\n    int *army = malloc(no_of_soldiers*sizeof(int));\r\n\r\n    read(army, no_of_soldiers);\r\n    scanf(\"%d\",&fedor_army);\r\n\r\n    maximum_no_of_friends = find_maximum_number_of_friends(army, no_of_soldiers, maximum_allowed_differences, fedor_army);\r\n    printf(\"%d\\n\",maximum_no_of_friends);\r\n    free(army);\r\n    return 0;\r\n}\r\n\r\nvoid read(int *army, int no_of_soldiers)\r\n{\r\n    int i;\r\n\r\n    for(i = 0; i < no_of_soldiers; i++)\r\n    {\r\n        scanf(\"%d\",(army + i));\r\n    }\r\n}\r\n\r\nint find_maximum_number_of_friends(int *army, int no_of_soldiers,int maximum_allowed_differences, int fedor_army)\r\n{\r\n    int i, no_of_possible_friends = 0;\r\n\r\n    for(i = 0; i < no_of_soldiers; i++)\r\n    {   //printf(\"%d\\t%d\\tXOR = %d\\n\",fedor_army, *(army + i), fedor_army^ (*(army + i)) );\r\n        //bitwise XOR on fedor army and every other army. Population count is the number of 1s i.e. the number of differences.\r\n        if( (population_count(fedor_army^ *(army + i))) <= maximum_allowed_differences)\r\n        {\r\n            no_of_possible_friends++;\r\n        }\r\n    }\r\n    return no_of_possible_friends;\r\n}\r\n\r\nint population_count(int x)\r\n{\r\n    int no_of_1s = x;\r\n\r\n    //x is always 32 bits\r\n    no_of_1s = (no_of_1s &MASK1) + ((no_of_1s >> 1) &MASK1);\r\n    no_of_1s = (no_of_1s &MASK2) + ((no_of_1s >> 2) &MASK2);\r\n    no_of_1s = (no_of_1s &MASK3) + ((no_of_1s >> 4) &MASK3);\r\n    no_of_1s = (no_of_1s &MASK4) + ((no_of_1s >> 8) &MASK4);\r\n    no_of_1s = (no_of_1s &MASK5) + ((no_of_1s >> 16) &MASK5);\r\n    //printf(\"Population Count = %d\\n\",no_of_1s);\r\n    return no_of_1s;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Game_test.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short winner;\r\n    unsigned long long order_of_square;\r\n    scanf(\"%I64u\",&order_of_square);\r\n    /*If n is an even number, then the square can be divided into four smaller squares. Whatever move, player 1 makes, player 2 makes the same move on the\r\n    diagonally opposite square. In other words, the square rotated by 180 degrees is painted. Player 2 always has a move and wins.\r\n    If n is an odd number, then the first player paints the central square (m+1, m+1), where n = 2m+1,  After that player 1 paints the diagonally opposite\r\n    square that any square that player 2 paints. Player 1 always wins.*/\r\n    if(order_of_square%2 == 1)\r\n    {\r\n        winner = 1;\r\n    }\r\n    else\r\n    {\r\n        winner = 2;\r\n    }\r\n    printf(\"%hu\\n\",winner);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Hexagons.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long n, answer;\r\n    scanf(\"%I64u\",&n);\r\n\r\n    //Each layer adds 6 new hexagons.Including itself, 1 + 6( 1 + 2 + ... + n) = 1 + 6n(n+1)/2\r\n    answer = 1LL + 3LL*n*(n+1);\r\n    printf(\"%I64u\\n\",answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Hulk.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n#define MAX_SIZE 1200\r\nvoid get_final_emotions(char[], short);\r\nint main()\r\n{\r\n    short no_of_layers;\r\n    char emotions[MAX_SIZE];\r\n    scanf(\"%hu\",&no_of_layers);\r\n\r\n    get_final_emotions(emotions, no_of_layers);\r\n    printf(\"%s\\n\",emotions);\r\n    return 0;\r\n}\r\n\r\nvoid get_final_emotions(char emotions[], short no_of_layers)\r\n{\r\n    short i;\r\n    char odd_emotion[8] = \"I hate \", even_emotion[8] = \"I love \";\r\n    strcpy(emotions, \"\");\r\n\r\n    for(i = 1; i <= no_of_layers; i++)\r\n    {\r\n        if(i%2 == 1)\r\n        {\r\n            strcat(emotions, odd_emotion);\r\n        }\r\n        else\r\n        {\r\n            strcat(emotions, even_emotion);\r\n        }\r\n\r\n        if(i != no_of_layers)\r\n        {\r\n            strcat(emotions, \"that \");\r\n        }\r\n        else\r\n        {\r\n            strcat(emotions, \"it\");\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Indivisibility.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long sales, bonuses, anti_bonuses;\r\n    scanf(\"%I64u\",&sales);\r\n\r\n    //Sufficient to check which numbers are not multiples of any of the primes below 10\r\n    //Principle of inclusion and exclusion counts anti-bonus - the number of numbers divisible by one of the primes - 2, 3,,5, 7\r\n    anti_bonuses = (sales/2LL + sales/3LL + sales/5LL + sales/7LL);\r\n    anti_bonuses -= (sales/6LL + sales/10LL + sales/14LL + sales/15LL + sales/21LL + sales/35LL);\r\n    anti_bonuses += (sales/30LL + sales/42LL + sales/70LL + sales/105LL);\r\n    anti_bonuses -= (sales/210LL);\r\n    bonuses = sales - anti_bonuses;\r\n\r\n    printf(\"%I64u\\n\",bonuses);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Interview.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(unsigned long *, unsigned long *, unsigned int);\r\nunsigned long get_maximum(unsigned long *, unsigned long *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_numbers;\r\n    unsigned long maximum;\r\n\r\n    scanf(\"%u\",&no_of_numbers);\r\n\r\n    unsigned long *list_1 = malloc(no_of_numbers*sizeof(unsigned long));\r\n    unsigned long *list_2 = malloc(no_of_numbers*sizeof(unsigned long));\r\n\r\n    read(list_1, list_2, no_of_numbers);\r\n    maximum = get_maximum(list_1, list_2, no_of_numbers);\r\n\r\n    printf(\"%lu\\n\",maximum);\r\n\r\n    free(list_1);\r\n    free(list_2);\r\n    return 0;\r\n}\r\n\r\nvoid read(unsigned long *list_1, unsigned long *list_2, unsigned int no_of_numbers)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        scanf(\"%lu\",(list_1 + i));\r\n    }\r\n\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        scanf(\"%lu\",(list_2 + i));\r\n    }\r\n}\r\n\r\nunsigned long get_maximum(unsigned long *list_1, unsigned long *list_2, unsigned int no_of_numbers)\r\n{\r\n    unsigned int i;\r\n    unsigned long function_list_1 = *list_1, function_list_2 = *list_2;\r\n\r\n    //Finding f(a, 1, n) and f(b, 1, n) i.e. - the bitwise OR of the entire array\r\n    for(i = 1; i < no_of_numbers; i++)\r\n    {\r\n        function_list_1 = function_list_1 | *(list_1 + i);\r\n        function_list_2 = function_list_2 | *(list_2 + i);\r\n    }\r\n    return (function_list_1 + function_list_2);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/King_Moves.c",
    "content": "#include <stdio.h>\r\n\r\nshort count_no_of_legal_king_moves(char[]);\r\nint main()\r\n{\r\n    char king_position[3];\r\n    short no_of_legal_moves;\r\n\r\n    scanf(\"%s\", king_position);\r\n    no_of_legal_moves = count_no_of_legal_king_moves(king_position);\r\n\r\n    printf(\"%hu\\n\",no_of_legal_moves);\r\n    return 0;\r\n}\r\n\r\nshort count_no_of_legal_king_moves(char king_position[])\r\n{\r\n    if( ( (king_position[0] == 'a') || (king_position[0] == 'h') )  && (  (king_position[1] == '1') || (king_position[1] == '8') ) )//Corner piece\r\n    {\r\n        return 3;\r\n    }\r\n    else if( ( (king_position[0] == 'a') || (king_position[0] == 'h') )  || (  (king_position[1] == '1') || (king_position[1] == '8') ) )//Border row or column but not corner piece\r\n    {\r\n            return 5;\r\n    }\r\n    else\r\n    {\r\n        return 8;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Lineland_Mail.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(long *, unsigned int);\r\nvoid get_minimum(long *, long *, unsigned int);\r\nlong min(long a, long b);\r\nlong max(long a, long b);\r\nvoid get_maximum(long *, long *, unsigned int);\r\nvoid display(long *, long *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_cities;\r\n\r\n    scanf(\"%u\",&no_of_cities);\r\n\r\n    long *city = malloc(no_of_cities*sizeof(long));\r\n    long *minimum = malloc(no_of_cities*sizeof(long));\r\n    long *maximum = malloc(no_of_cities*sizeof(long));\r\n\r\n    read(city, no_of_cities);\r\n    get_minimum(minimum, city, no_of_cities);\r\n    get_maximum(maximum, city, no_of_cities);\r\n    display(minimum, maximum, no_of_cities);\r\n\r\n    free(city);\r\n    free(minimum);\r\n    free(maximum);\r\n    return 0;\r\n}\r\n\r\nvoid read(long *city, unsigned int no_of_cities)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_cities; i++)\r\n    {\r\n        scanf(\"%ld\",(city + i));\r\n    }\r\n}\r\n\r\nvoid display(long *minimum, long *maximum, unsigned int no_of_cities)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_cities; i++)\r\n    {\r\n        printf(\"%ld\\t%ld\\n\",*(minimum + i), *(maximum + i));\r\n    }\r\n}\r\n\r\nvoid get_minimum(long *minimum, long *city, unsigned int no_of_cities)\r\n{\r\n    unsigned int i;\r\n    //The minimum distance is one of the adjacent cities. The first and last city have only one adjacent city so we solve it separately.\r\n    *(minimum + 0) = *(city + 1) - *(city + 0); //For First city, it has to be the next city\r\n    *(minimum + no_of_cities - 1) = *(city + no_of_cities - 1)-*(city + no_of_cities - 2); //For last city, it has to be the previous city\r\n\r\n    for(i = 1; i < no_of_cities - 1; i++)\r\n    {\r\n        *(minimum + i) = min( abs(*(city + i) - *(city + i -1)), abs(*(city + i) - *(city + i +1))); //The closer distance among the next and previous city\r\n    }\r\n}\r\n\r\nlong min(long a, long b)\r\n{\r\n    if(a < b)\r\n        return a;\r\n    else\r\n        return b;\r\n}\r\n\r\nlong max(long a, long b)\r\n{\r\n    if(a > b)\r\n        return a;\r\n    else\r\n        return b;\r\n}\r\n\r\nvoid get_maximum(long *maximum, long *city, unsigned int no_of_cities)\r\n{\r\n    unsigned int i;\r\n\r\n    //The cities are given in ascending order. Clearly, the city at the maximum distance is either the first city or the last city.\r\n    for(i = 0; i < no_of_cities; i++)\r\n    {\r\n        *(maximum + i) = max(*(city + i) - *(city + 0), *(city + no_of_cities - 1) - *(city + i));\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Lucky_Numbers.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long max_door_plate_length, no_of_unique_numbers;\r\n    scanf(\"%I64u\",&max_door_plate_length);\r\n\r\n    //Answer = 2 + 2^2 + 2^3 + ... + 2^n = 2^{n + 1} - 2. When 2 is right shifted n times, the 1 is in position n+1, which is 2^{n+1}\r\n    no_of_unique_numbers = (2LL << max_door_plate_length) - 2;\r\n    printf(\"%I64u\",no_of_unique_numbers);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/PolandBall_and_Hypothesis.c",
    "content": "#include <stdio.h>\r\nint find_counterexample(int);\r\n\r\nint main()\r\n{\r\n    int n, counterexample;\r\n    scanf(\"%d\",&n);\r\n    counterexample = find_counterexample(n);\r\n    printf(\"%d\\n\",counterexample);\r\n    return 0;\r\n}\r\n//Return m such that m.n + 1 is guaranteed to be composite\r\nint find_counterexample(int n)\r\n{\r\n    if(n <= 2)\r\n    {\r\n        return 7; //7 works for both 1 and 2\r\n    }\r\n    else\r\n    {\r\n        //n(n-2) + 1 = n^2 -1, m = n - 2 always works for n > 2\r\n        return (n-2);\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Professor_Gukiz_Robot.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nlong maximum(long, long);\r\n\r\nint main()\r\n{\r\n    long start_x, start_y, final_x, final_y, minimum_moves;\r\n    scanf(\"%ld %ld %ld %ld\",&start_x, &start_y, &final_x, &final_y);\r\n    \r\n    /*First take as many diagonal steps as possible. This is min{|x-x1|, |y - y1|}\r\n    Then take the required number of line moves. This is max{|x-x1|, |y - y1|} - min{|x-x1|, |y - y1|}\r\n    The total sum is max{|x-x1|, |y - y1|}*/\r\n    minimum_moves = maximum(abs(start_x-final_x),abs(start_y-final_y));\r\n    \r\n    printf(\"%ld\\n\",minimum_moves);\r\n    return 0;\r\n}\r\n\r\nlong maximum(long a, long b)\r\n{\r\n    if(a > b)\r\n        return a;\r\n    else\r\n        return b;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Random_Teams.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned long long find_minimum(unsigned long long,unsigned long long);\r\nunsigned long long find_maximum(unsigned long long,unsigned long long);\r\nint main()\r\n{\r\n    unsigned long long no_of_people, no_of_teams, minimum_friends, maximum_friends;\r\n    scanf(\"%I64u %I64u\",&no_of_people, &no_of_teams);\r\n\r\n    minimum_friends = find_minimum(no_of_people, no_of_teams);\r\n    maximum_friends = find_maximum(no_of_people, no_of_teams);\r\n    printf(\"%I64u %I64u\\n\",minimum_friends, maximum_friends);\r\n    return 0;\r\n}\r\n\r\n/*The minimum is obtained when every team has at most one more than the minimum number of people.\r\nIf there is a team for which the difference between the number of people and the minimum number of people is more than 1, we can reduce the friendships\r\nby transfering a person from that team to the minimum team.\r\nIn this arrangement, the friendships can't be reduced. Transfering from two piles with the same amount of people increases the friendships,\r\nAnd transfering from (p + 1) to p people conserver the number of friendships.\r\nThis can be obtained in the following way - Place n/m people in each team. Place the remaining n%m people in different teams.\r\nn = 13, m = 5\r\n.   .   .\r\n.   .   .   .   .\r\n.   .   .   .   .\r\nThe number is given by n/m * (n/m C 2) + (n%m)*(n/m)\r\nWe first count the number of friendships in all m teams when they have n/m people.\r\nThen when the remaining n%m people are placed into their teams, new n/m friendships are formed in each team. */\r\nunsigned long long find_minimum(unsigned long long no_of_people,unsigned long long no_of_teams)\r\n{\r\n    unsigned long long minimum;\r\n\r\n    minimum = no_of_teams*(no_of_people/no_of_teams) * ((no_of_people/no_of_teams) - 1) /2; //n/m * (n/m C 2)\r\n    minimum += (no_of_people%no_of_teams)*( (no_of_people/no_of_teams)); //n%m * (n/m)\r\n\r\n    return minimum;\r\n}\r\n\r\n/*This is obtained when we place one person in m-1 teams each and place all the remaining people in the last team.\r\nIn any other arrangement, the number of friends can be increased by transfering a person from a given team to the team with the maximum number of people.\r\nIn this arrangement, no such transfer can take place. This yields the maximum number of friendships. Detailed proofs given in the 'Explanation' part.*/\r\nunsigned long long find_maximum(unsigned long long no_of_people,unsigned long long no_of_teams)\r\n{\r\n    unsigned long long maximum;\r\n\r\n    maximum = (no_of_people - no_of_teams + 1)*(no_of_people - no_of_teams + 1 - 1)/2;//(n - (m-1) ) C 2\r\n    return maximum;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Reconnaissance_2.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid get_difference_of_consecutive_soldiers(unsigned int *, unsigned int *,short);\r\nshort get_position_of_first_reconnaisance_soldier(unsigned int *,short);\r\nint main()\r\n{\r\n    short no_of_soldiers, i, position_of_first_reconnaissance_soldier, position_of_second_reconnaissance_soldier;\r\n    scanf(\"%hu\",&no_of_soldiers);\r\n\r\n    unsigned int *heights_of_soldier =  malloc(no_of_soldiers*sizeof(unsigned int));\r\n    unsigned int *consecutive_height_difference = malloc(no_of_soldiers*sizeof(unsigned int));\r\n    for(i = 0; i < no_of_soldiers; i++)\r\n    {\r\n        scanf(\"%u\",(heights_of_soldier + i));\r\n    }\r\n\r\n    get_difference_of_consecutive_soldiers(heights_of_soldier, consecutive_height_difference, no_of_soldiers);\r\n    position_of_first_reconnaissance_soldier = get_position_of_first_reconnaisance_soldier(consecutive_height_difference, no_of_soldiers);\r\n\r\n    //IF a soldier is standing at position x, then his neighbour is standing at position (x+1)mod n, where n is the number of people in the circle.\r\n    //The position returned is from 1 to n. We perform mod only on the second number, since we may get (n+1) if the first position is n.\r\n    if(position_of_first_reconnaissance_soldier == no_of_soldiers)\r\n    {\r\n        position_of_second_reconnaissance_soldier = 1;\r\n    }\r\n    else\r\n    {\r\n        position_of_second_reconnaissance_soldier = position_of_first_reconnaissance_soldier + 1;\r\n    }\r\n    printf(\"%u %u\\n\",position_of_first_reconnaissance_soldier, position_of_second_reconnaissance_soldier );\r\n\r\n    free(heights_of_soldier);\r\n    free(consecutive_height_difference);\r\n    return 0;\r\n}\r\n\r\nvoid get_difference_of_consecutive_soldiers(unsigned int *heights_of_soldier, unsigned int *consecutive_height_difference,short no_of_soldiers)\r\n{\r\n    //C[i] = H[i] - H[(i+1)mod n]\r\n    short i;\r\n    for(i = 0; i < no_of_soldiers; i++)\r\n    {\r\n        *(consecutive_height_difference + i) = abs(*(heights_of_soldier + i) - *(heights_of_soldier + (i + 1)%no_of_soldiers));\r\n    }\r\n}\r\n\r\n//Returns position of minimum element of consecutive height difference\r\nshort get_position_of_first_reconnaisance_soldier(unsigned int *consecutive_height_difference,short no_of_soldiers)\r\n{\r\n    unsigned int minimum = *(consecutive_height_difference + 0);\r\n    short i, first_soldier_position = 0;\r\n\r\n    for(i = 0; i < no_of_soldiers; i++)\r\n    {\r\n        if( *(consecutive_height_difference + i) < minimum)\r\n        {\r\n            minimum = *(consecutive_height_difference + i);\r\n            first_soldier_position = i;\r\n        }\r\n    }\r\n    return first_soldier_position + 1 ;//Pointer arithmetic is performed starting from 0. But, the soldiers are counted starting from 1. So we add 1.\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Selection_of_Personnel.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long no_of_applications, no_of_teams, no_of_applications_choose_5, no_of_applications_choose_6, no_of_applications_choose_7;\r\n    scanf(\"%I64u\",&no_of_applications);\r\n\r\n    no_of_applications_choose_5 = (no_of_applications)*(no_of_applications-1)/2*(no_of_applications-2)/3*(no_of_applications-3)/4*(no_of_applications-4)/5;\r\n\r\n    //nC6 = nC5 *(n - 5)/6 and nC7 = nC6* (n - 5)/6\r\n    no_of_applications_choose_6 =  no_of_applications_choose_5*(no_of_applications - 5)/6;\r\n    no_of_applications_choose_7 =  no_of_applications_choose_6*(no_of_applications - 6)/7;\r\n    no_of_teams = no_of_applications_choose_5 + no_of_applications_choose_6 + no_of_applications_choose_7;\r\n\r\n    printf(\"%I64u\\n\",no_of_teams);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Tetrahedron.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nunsigned long long find_no_of_cycles(unsigned long long);\r\nconst long long mod = 1000000007;\r\nint main()\r\n{\r\n    unsigned long long no_of_moves, no_of_cyclic_paths;\r\n    scanf(\"%I64u\",&no_of_moves);\r\n    no_of_cyclic_paths = find_no_of_cycles(no_of_moves);\r\n    printf(\"%I64u\\n\",no_of_cyclic_paths);\r\n    return 0;\r\n}\r\n\r\nunsigned long long find_no_of_cycles(unsigned long long no_of_moves)\r\n{\r\n    unsigned long long paths_from_D_i, path_D_i_minus_1;\r\n    unsigned long long paths_from_ABC_i, path_ABC_i_minus_1;\r\n    unsigned long long i, no_of_cycles;\r\n\r\n    //f(X, n) is the number of ways to reach D in n moves when ant is on vertex X\r\n    paths_from_D_i = 1; //f(D, 0) = 1\r\n    paths_from_ABC_i = 0; //f(ABC, 0) = 1\r\n\r\n    for(i = 1; i <= no_of_moves; i++)\r\n    {\r\n        path_D_i_minus_1 = paths_from_D_i ;\r\n        path_ABC_i_minus_1 = paths_from_ABC_i;\r\n\r\n        paths_from_D_i = (3LL* path_ABC_i_minus_1)%mod; //f(D,i) = 3f(ABC, i-1) - From D ant can go to either A, B or C having spent one move.\r\n        paths_from_ABC_i = (path_D_i_minus_1 + 2LL*path_ABC_i_minus_1)%mod; //f(ABC, i) = f(D,i-1) + 2f(ABC, i-1) - From A, B, C ant can go to either D or two other vertices\r\n    }\r\n\r\n    no_of_cycles = paths_from_D_i;//f(D, n) is the required number and this is the last value stored in f(D, i)\r\n\r\n    return no_of_cycles;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Vasya_and_Petya_Game.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid display(unsigned int *, unsigned int);\r\nvoid sundaram_sieve(unsigned int *, unsigned int, unsigned int *);\r\nvoid get_question_sequence(unsigned int *, unsigned int *, unsigned int);\r\n\r\nint main()\r\n{\r\n    unsigned int number, no_of_questions = 0;\r\n    scanf(\"%u\",&number);\r\n\r\n    unsigned int *question_sequence = malloc(number*sizeof(question_sequence));\r\n\r\n    get_question_sequence(question_sequence, &no_of_questions, number);\r\n    display(question_sequence, no_of_questions);\r\n\r\n    free(question_sequence);\r\n    return 0;\r\n}\r\n\r\nvoid display(unsigned int *question_sequence, unsigned int no_of_questions)\r\n{\r\n    unsigned int i;\r\n    printf(\"%u\\n\", no_of_questions);\r\n    for(i = 0; i < no_of_questions; i++)\r\n    {\r\n        printf(\"%u\\t\",*(question_sequence + i));\r\n    }\r\n}\r\n\r\n/*Question sequence consists of all primes p less than n, raised to every power i, such that p^i <= n*/\r\nvoid get_question_sequence(unsigned int *question_sequence, unsigned int *no_of_questions, unsigned int number)\r\n{\r\n    unsigned int current_prime, current_prime_power, current_prime_index, primeCount;\r\n    //Looking at the primes mod 6, except 2 and 3, all primes are 6m + 1 or 6m - 1\r\n    unsigned int *primes = malloc((number/3 + 2)*sizeof(unsigned int));\r\n\r\n    sundaram_sieve(primes, number, &primeCount); //All primes upto the target number\r\n\r\n    for(current_prime_index = 0; current_prime_index < primeCount ; current_prime_index++)\r\n    {\r\n        current_prime = *(primes + current_prime_index); //p = p initially\r\n        current_prime_power = current_prime;\r\n        //printf(\"Current prime index = %u\\tCurrent prime = %u\\n\",current_prime_index, *(primes + current_prime_index));\r\n        while(current_prime_power <= number)\r\n        {\r\n            *(question_sequence + *no_of_questions) = current_prime_power; //printf(\"Q%u\\t\",*(question_sequence + *no_of_questions));\r\n            *(no_of_questions) = *(no_of_questions) + 1;\r\n\r\n            current_prime_power *= current_prime; //p^{i+1} = p^i * p\r\n        }\r\n    }\r\n    free(primes);\r\n}\r\n\r\n//Crossing out numbers of the form i + j + 2ij\r\nvoid sundaram_sieve(unsigned int *primes, unsigned int target, unsigned int *primeCount)\r\n{\r\n    unsigned i, crossed_out_num, cross_limit, increment;\r\n    short *auxiliary_list = malloc(target*sizeof(short));\r\n\r\n    /*f(i,j) = i + j + 2ij\r\n    For a given value of i, the minimum is when j = 1. Minimum is f(i,1) = 3i + 1\r\n    f(i, j + 1) = f(i,j) + 2i + 1 so we only need to increase the value of the crossed number by 2i + 1, instead of updating by one.\r\n    i goes from 1 to target/2. But, f(i,j) starts from 3i + 1. If i is greater than target/6, then f(i,j) is out of range.\r\n    So, the minimum\r\n    Maximum occurs when j = i. f(i,j) = 2i(i+1).\r\n    The last number to be crossed out for a given i is either 2i(i + 1) or the last f(i,j) before target/2, whichever comes first.*/\r\n\r\n\t//All numbers of the form i + j + 2ij need to be marked out\r\n    for(i = 0; i < target; i ++)\r\n    {\r\n        *(auxiliary_list + i) = 1;\r\n    }\r\n\r\n    for(i = 1; i <= target/6; i++)\r\n    {\r\n        increment = 2*i + 1;\r\n        cross_limit = 2*i*(i + 1);\r\n\r\n        if(cross_limit > target/2)\r\n        {\r\n            cross_limit = target/2;\r\n        }\r\n\r\n        for(crossed_out_num = 3*i + 1;crossed_out_num <= cross_limit ; crossed_out_num += increment)\r\n        {\r\n            *(auxiliary_list + crossed_out_num) = 0;\r\n        }\r\n    }\r\n\r\n    //We need to put 2 in ourselves because the algorithm 'only' generates all the odd primes\r\n    *primeCount = 0;\r\n    *(primes + *primeCount) = 2;\r\n    *primeCount = *primeCount + 1;\r\n\r\n    for(i = 1; i <= target/2; i++)\r\n    {\r\n        //Checking if the number is not crossed out and adding 2i + 1 to the list if it is unmarked.\r\n        if(*(auxiliary_list + i) == 1)\r\n        {\r\n            *(primes + *primeCount) = (2*i + 1); //printf(\"%u\\t\", *(primes + *primeCount));\r\n            *primeCount = *primeCount + 1;\r\n        }\r\n    }\r\n\r\n    free(auxiliary_list);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 4/Way_Too_Long_Words.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\nint main()\r\n{\r\n    short no_of_words, i;\r\n    char current_word[101];\r\n    scanf(\"%hu\",&no_of_words);\r\n    for(i = 0; i < no_of_words; i++)\r\n    {\r\n        scanf(\"%s\",current_word);\r\n        if(strlen(current_word) > 10)\r\n        {\r\n            printf(\"%c%d%c\\n\",current_word[0],strlen(current_word)-2, current_word[strlen(current_word)-1]);\r\n        }\r\n        else\r\n        {\r\n            printf(\"%s\\n\",current_word);\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Bear_and_Poker.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nvoid read(int *, int);\r\nvoid reduce_bid(int *, int);\r\nshort is_possible(int *, int);\r\n\r\nint main()\r\n{\r\n    int no_of_players;\r\n    scanf(\"%d\",&no_of_players);\r\n    int *bid = malloc(no_of_players*sizeof(int));\r\n    read(bid, no_of_players);\r\n    reduce_bid(bid, no_of_players);//dividing the bids till they are coprime to 2 and 3\r\n\r\n    printf(is_possible(bid, no_of_players) ? \"Yes\\n\" : \"No\\n\");\r\n    free(bid);\r\n    return 0;\r\n}\r\n\r\n//true if all elements are equal\r\nshort is_possible(int *bid, int no_of_players)\r\n{\r\n    int i;\r\n    for(i = 1; i < no_of_players; i++)\r\n    {\r\n        if(*(bid + i) != *(bid + 0))\r\n            return false;\r\n    }\r\n    return true;\r\n}\r\n//Every bid is divided till it is coprime to 2 and 3\r\nvoid reduce_bid(int *bid, int no_of_players)\r\n{\r\n    int i;\r\n    for(i = 0; i < no_of_players; i++)\r\n    {\r\n        while(*(bid + i) %2 == 0)\r\n        {\r\n            *(bid + i) = *(bid + i)/2;\r\n        }\r\n        while(*(bid + i) %3 == 0)\r\n        {\r\n            *(bid + i) = *(bid + i)/3;\r\n        }\r\n    }\r\n}\r\n\r\nvoid read(int *bid, int no_of_players)\r\n{\r\n    int i;\r\n    for(i = 0; i < no_of_players; i++)\r\n    {\r\n        scanf(\"%d\",(bid + i));\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Boredom.c",
    "content": "#include <stdio.h>\r\n\r\n#define MAX_LENGTH 100000 + 1\r\n\r\nvoid read_frequency(int [], int, int *);\r\nlong long max(long long ,long long);\r\nlong long find_maximum_score(int [], int);\r\n\r\nint main()\r\n{\r\n    int frequency[MAX_LENGTH]= {0}, no_of_numbers, max_in_array = 0;\r\n    long long maximum_score;\r\n    scanf(\"%d\",&no_of_numbers);\r\n\r\n    read_frequency(frequency, no_of_numbers, &max_in_array);\r\n    maximum_score = find_maximum_score(frequency, max_in_array);\r\n    printf(\"%I64d\\n\",maximum_score);\r\n    return 0;\r\n}\r\n\r\nlong long find_maximum_score(int frequency[],int max_in_array)\r\n{\r\n    int i;\r\n    long long maximum_score_i_minus_2 = 0, maximum_score_i_minus_1 = frequency[1], maximum_score_i  = frequency[1];\r\n\r\n    /*Let f(i) be the greatest score possible where all numbers upto i are deleted.\r\n      There are two options - Either we delete i by selecting it - f(i-2) + frequency[i]*i.\r\n\t  Or we delete it by selecting i-1 - f(i-1)\r\n        i = 2 to 10^5\r\n       f(i) = max{f(i-1), f(i-2) + i*frequency[i]}*/\r\n    for(i = 2; i <= 1e5; i++)\r\n    {\r\n        maximum_score_i = max(maximum_score_i_minus_1, maximum_score_i_minus_2 + frequency[i]*1LL*i);\r\n\r\n        maximum_score_i_minus_2 = maximum_score_i_minus_1;\r\n        maximum_score_i_minus_1 = maximum_score_i;\r\n    }\r\n\r\n    return maximum_score_i;\r\n}\r\n\r\nvoid read_frequency(int frequency[], int no_of_numbers, int *max_in_array)\r\n{\r\n    int i, current_number;\r\n\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        scanf(\"%d\",&current_number);\r\n        frequency[current_number]++;\r\n        *max_in_array = max(*max_in_array, current_number);\r\n    }\r\n}\r\n\r\nlong long max(long long a, long long b)\r\n{\r\n    return (a > b ? a : b);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Cut_Ribbon.c",
    "content": "#include <stdio.h>\r\n#define MAX_LENGTH 4001\r\n#define NEGATIVE_INFINITY -4000\r\n\r\nint max(int, int);\r\nint find_maximum_number_of_pieces(int, int , int , int );\r\nint main()\r\n{\r\n    int a, b, c, total_length, maximum_number_of_pieces;\r\n\r\n    scanf(\"%d %d %d %d\",&total_length, &a, &b, &c);\r\n\r\n    maximum_number_of_pieces = find_maximum_number_of_pieces(total_length, a, b, c);\r\n    printf(\"%d\\n\",maximum_number_of_pieces);\r\n    return 0;\r\n}\r\n\r\nint find_maximum_number_of_pieces(int total_length, int a, int b, int c)\r\n{\r\n    int i, max_number_of_pieces[MAX_LENGTH];\r\n\r\n    for(i = 1; i <= total_length; i++)\r\n    {\r\n        max_number_of_pieces[i] = NEGATIVE_INFINITY;\r\n    }\r\n\r\n    max_number_of_pieces[0] = 0;\r\n    for(i =a; i <= total_length; i++)\r\n    {\r\n        max_number_of_pieces[i] = max(max_number_of_pieces[i],max_number_of_pieces[i-a] + 1);\r\n    }\r\n\r\n    for(i =b; i <= total_length; i++)\r\n    {\r\n        max_number_of_pieces[i] = max(max_number_of_pieces[i],max_number_of_pieces[i-b] + 1);\r\n    }\r\n\r\n    for(i =c; i <= total_length; i++)\r\n    {\r\n        max_number_of_pieces[i] = max(max_number_of_pieces[i],max_number_of_pieces[i-c] + 1);\r\n    }\r\n\r\n    return max_number_of_pieces[total_length];\r\n}\r\n\r\nint max(int a, int b)\r\n{\r\n    if(a > b)\r\n    {\r\n        return a;\r\n    }\r\n    else\r\n    {\r\n        return b;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Display_Size.c",
    "content": "#include <stdio.h>\r\n#include <math.h>\r\n\r\nint main()\r\n{\r\n    int no_of_pixels, no_of_rows, no_of_columns;\r\n    scanf(\"%d\",&no_of_pixels);\r\n\r\n    for(no_of_rows = (int) sqrt(no_of_pixels) ;no_of_rows > 0; no_of_rows--)\r\n    {\r\n        if(no_of_pixels%no_of_rows == 0)\r\n        {\r\n            break;\r\n        }\r\n    }\r\n    no_of_columns = no_of_pixels/no_of_rows;\r\n    printf(\"%d %d\\n\",no_of_rows, no_of_columns);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Duff_in_Love.c",
    "content": "#include <stdio.h>\r\nunsigned long long find_product_all_prime_factors(unsigned long long);\r\nint main()\r\n{\r\n    unsigned long long n, largest_lovely_number;\r\n    scanf(\"%I64u\",&n);\r\n    largest_lovely_number = find_product_all_prime_factors(n);\r\n    printf(\"%I64u\\n\",largest_lovely_number);\r\n    return 0;\r\n}\r\n\r\nunsigned long long find_product_all_prime_factors(unsigned long long n)\r\n{\r\n    unsigned long long prime_product = 1, reduced_n = n, i;\r\n\r\n    //n = p1^{a1} p2^{a2} ... pk^ {ak}.\r\n    //Answer is product of n's prime factors a = p_1 p_2 ... p_k\r\n    //This number is squarefree. And since all numbers from 1 till n are divisible by some combination of these numbers,\r\n    //the largest squarefree number <= p_1 p_2 ... p_k. since no p^2 divides it.\r\n    for(i = 2; i*i <= n; i++)\r\n    {\r\n        if(reduced_n%i == 0)\r\n        {\r\n            prime_product = prime_product*i;\r\n\r\n            //Reducing n from p1^{a1} p2^{a2} ... .pn^ {an} to p2^{a2} ... .pn^ {an}\r\n            //So that none of the multiples of i divide reduced_n. This ensures only prime factors are multiplies in product.\r\n            while(reduced_n%i == 0)\r\n            {\r\n                reduced_n = reduced_n/i;\r\n            }\r\n        }\r\n    }\r\n\r\n    //N has been reduced to either 1 or a single number greater than root(n) since the composite factors of n are cancelled out, this number must be prime.\r\n    prime_product = prime_product*reduced_n;\r\n\r\n    return prime_product;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Flipping_Game.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(short *, short);\r\nshort find_maximum_number_of_ones_after_move(short *, short);\r\nshort greatest_continuous_sum(short *, short);\r\nint max(int, int);\r\n\r\nint main()\r\n{\r\n    short no_of_numbers, maximum_number_of_ones;\r\n\r\n    scanf(\"%hu\",&no_of_numbers);\r\n\r\n    short *gain = malloc(no_of_numbers*sizeof(short));\r\n\r\n    read(gain, no_of_numbers);\r\n    maximum_number_of_ones = find_maximum_number_of_ones_after_move(gain, no_of_numbers);\r\n\r\n    printf(\"%hu\\n\",maximum_number_of_ones);\r\n\r\n    free(gain);\r\n    return 0;\r\n}\r\n\r\nvoid read(short *gain, short no_of_numbers)\r\n{\r\n    short i, current;\r\n\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        scanf(\"%hu\",&current);\r\n        /*If there is a 0, the number of 1s increases by 1 after flipping. If it is a 1, the number of 1s increases by -1 after flipping\r\n        G[i] = -1, if A[i] = 1 and\r\n        G[i] = 0, if A[i] = 0*/\r\n        *(gain + i) = ( (current == 0) ? 1 : -1 );\r\n    }\r\n}\r\n\r\nshort find_maximum_number_of_ones_after_move(short *gain, short no_of_numbers)\r\n{\r\n    short i, number_of_1s_before_move = 0, number_of_1s_after_move;\r\n\r\n    //This is the number of 1s in the original array. Corresponds to G[i] = -1\r\n    for(i = 0; i < no_of_numbers; i++)\r\n    {\r\n        if(*(gain + i) == -1)\r\n        {\r\n            number_of_1s_before_move++;\r\n        }\r\n    }\r\n\r\n    number_of_1s_after_move = greatest_continuous_sum(gain, no_of_numbers);\r\n\r\n    return (number_of_1s_before_move + number_of_1s_after_move);\r\n}\r\n\r\nshort greatest_continuous_sum(short *gain, short no_of_numbers)\r\n{\r\n    short i, greatest_sum = *(gain + 0), current_sum = *(gain + 0);\r\n\r\n    for(i = 1; i < no_of_numbers; i++)\r\n    {\r\n        current_sum = max(current_sum + *(gain + i), *(gain + i));\r\n        greatest_sum = max(greatest_sum, current_sum);\r\n    }\r\n\r\n    return greatest_sum;\r\n}\r\n\r\nint max(int a, int b)\r\n{\r\n    return (a > b ? a: b);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Flowers.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\nusing namespace std;\r\n\r\nvoid count(vector <int> &no_of_ways, int group, int LIMIT)\r\n{\r\n\tconst int MOD = 1e9 + 7;\r\n\tno_of_ways[0] = 1;\r\n\r\n\tfor(int i = 1; i < LIMIT; i++)\r\n\t{\r\n\t\tif(i < group)\r\n\t\t\tno_of_ways[i] = 1;\r\n\t\telse\r\n\t\t\tno_of_ways[i] = (no_of_ways[i - 1] + no_of_ways[i - group])%MOD;\r\n\t}\r\n}\r\n\r\nint main()\r\n{\r\n\tint no_of_queries, group;\r\n\tscanf(\"%d %d\", &no_of_queries, &group);\r\n\r\n\tconst int LIMIT = 1e5 + 1, MOD = 1e9 + 7;\r\n\tvector <int> no_of_ways(LIMIT, 0);\r\n\r\n\tcount(no_of_ways, group, LIMIT);\r\n\r\n\tvector <int> no_of_ways_till(LIMIT, 0);\r\n\tfor(int i = 1; i < LIMIT; i++)\r\n\t\tno_of_ways_till[i] = (no_of_ways_till[i - 1] + no_of_ways[i])%MOD;\r\n\r\n\twhile(no_of_queries--)\r\n\t{\r\n\t\tint a, b;\r\n\t\tscanf(\"%d %d\", &a, &b);\r\n\r\n\t\tprintf(\"%d\\n\", (no_of_ways_till[b] - no_of_ways_till[a - 1] + MOD)%MOD);\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Fox_and_Dividing_Cheese.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint find_common_power(int *, int *, int);\r\nint main()\r\n{\r\n    int piece_1, piece_2;\r\n    int answer;\r\n    scanf(\"%u %u\",&piece_1, &piece_2);\r\n\r\n    answer = find_common_power(&piece_1, &piece_2, 2);\r\n    answer = answer + find_common_power(&piece_1, &piece_2, 3);\r\n    answer = answer + find_common_power(&piece_1, &piece_2, 5);\r\n\r\n    printf(\"%d\\n\", (piece_1 == piece_2 ? answer : -1) );//Checking if the numbers are equal after 2, 3, 5 have been cancelled out completely.\r\n    return 0;\r\n}\r\n\r\n//Returns the greatest power of prime which divides both the numbers and reduces both numbers to numbers without the prime.\r\nint find_common_power(int *piece_1, int *piece_2, int prime)\r\n{\r\n    int power_1 = 0, power_2 = 0;\r\n    while(*piece_1 % prime == 0)\r\n    {\r\n        *piece_1 = *piece_1/prime;\r\n        power_1++;\r\n    }\r\n    while(*piece_2 % prime == 0)\r\n    {\r\n        *piece_2 = *piece_2/prime;\r\n        power_2++;\r\n    }\r\n\r\n    return abs(power_1 - power_2);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Hungry_Sequence.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int i, no_of_terms;\r\n    scanf(\"%d\",&no_of_terms);\r\n\r\n    /*The sequence of consecutive numbers - 2n + 1, 2n + 2, .... , 2n + n - satisfies this property.\r\n    For any number x, it's largest proper divisor is at most x/2. 2*(x/2) = x\r\n    If x had a divisor greater than x/2, than it would have to be multiplied by a number less than 2. But there is only one option - 1,\r\n    The largest proper divisor of any number is this series is smaller than the smallest term of this sequence of consecutive numbers.\r\n    The greatest divisor of 2n + n, is n + n/2, which is less than 2n + 1 for all positive n.\r\n    This means that the divisors of any number from this list are smaller than the smallest number in this sequence.\r\n    So, this is a hungry sequence.\r\n    There is nothing special about the number 2. Any positive integer value m can be multiplied - nm + 1, nm + 2, ... , mn + n to get a Hungry sequence.\r\n    Conversely, choose any number from this sequence, x. The smallest multiple of x is 2x. If x = 2n + 1, then 2x = 4n + 2.\r\n    Now, 4n + 2 > 2n + n, for all positive integers n. \r\n    Since, the smallest multiple of the smallest element is greater than the largest element of the list, it is a Hungry sequence.*/\r\n    for(i = 1; i <= no_of_terms; i++)\r\n    {\r\n        printf(\"%d \", (2*no_of_terms+ i));\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/K_Interesting_Pair_of_Integers.c",
    "content": "#include <stdio.h>\r\n\r\n#define RANGE 10000\r\n\r\nvoid build_population_count(unsigned int[]);\r\nvoid read_and_find_frequency(int[], unsigned int);\r\nunsigned long long count_k_interesting_pairs(int[],int, unsigned int[]);\r\n\r\nint main()\r\n{\r\n    int count[RANGE + 1] = {0}, k;\r\n    unsigned int population_count[2*RANGE], no_of_elements;\r\n    unsigned long long no_of_k_interesting_pairs;\r\n\r\n    scanf(\"%u %d\", &no_of_elements, &k);\r\n\r\n    build_population_count(population_count);\r\n    read_and_find_frequency(count, no_of_elements);\r\n    no_of_k_interesting_pairs = count_k_interesting_pairs(count, k, population_count);\r\n    printf(\"%I64u\\n\",no_of_k_interesting_pairs);\r\n    return 0;\r\n}\r\n\r\n//Builds a vector PC - Population Count, where PC[x] has the number of 1s in the binary representation of x\r\nvoid build_population_count(unsigned int population_count[])\r\n{\r\n    unsigned int i;\r\n    population_count[0] = 0;\r\n\r\n    /*Let us suppose there is a binary number x - 10001, then we can XOR with 01110 to get 11111.\r\n    We can XOR to numbers to get a number greater than either of the numbers. What is the greatest number we can get ?\r\n    If x and y are binary numbers, and x > y, and the first 1 in the binary form of x is at position p (from the right),\r\n    the greatest value of x XOR y is a number with all 1s from position p.\r\n    So, x XOR y is always less than a 1 at position (p+1) and all 0s afterwards. So, 2*x is a loose upper bound.\r\n    That is why we build a population count table till 2* RANGE instead of just RANGE*/\r\n\r\n    for(i = 1; i <= 2*RANGE; i++)\r\n    {\r\n        /*for even x, f(x) = f(x/2) ,the string is left shifted once\r\n          for odd x, f(x) = f(x/2) + 1 , x/2 is left shifted and then 1 is added\r\n          We can write this elegantly in one case. */\r\n\r\n        population_count[i] = population_count[i >> 1] + (i % 2);\r\n    }\r\n}\r\n\r\nunsigned long long count_k_interesting_pairs(int count[],int k, unsigned int population_count[])\r\n{\r\n    unsigned int i, j;\r\n    unsigned long long k_interesting_count = 0;\r\n\r\n    if(k == 0) //k = 0 is a special case. Then if the count of x is n, no of pairs is nC2.\r\n    {\r\n        for(i = 0; i <= RANGE; i++)\r\n        {\r\n            if(count[i] > 0)\r\n            {\r\n                k_interesting_count += (long long)count[i]*(count[i] - 1)/2; //Preventing overflow by typecasting\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(i = 0; i <= RANGE; i++)\r\n        {\r\n            for(j = i + 1; j <= RANGE; j++)\r\n            {\r\n                if( (count[j] > 0) && (population_count[i^j] == k) )\r\n                {\r\n                    //Explicit typecasting done to prevent overflow\r\n                    k_interesting_count += (long long) count[i]*count[j];//i occurs count[i] times and j count[j]. No of pairs (i,j) s their product\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    return k_interesting_count;\r\n}\r\n\r\nvoid read_and_find_frequency(int count[], unsigned int no_of_elements)\r\n{\r\n    unsigned int num, i;\r\n\r\n    for(i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%u\", &num);\r\n        count[num]++;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Kefa_and_First_Step.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(unsigned long *, unsigned int);\r\nunsigned int find_length_longest_non_decreasing_streak(unsigned long *, unsigned int);\r\nunsigned long max(unsigned long, unsigned long);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_days, longest_non_decreasing_streak;\r\n\r\n    scanf(\"%u\",&no_of_days);\r\n\r\n    unsigned long *money_made = malloc(no_of_days*sizeof(unsigned long));\r\n    read(money_made, no_of_days);\r\n\r\n    longest_non_decreasing_streak = find_length_longest_non_decreasing_streak(money_made, no_of_days);\r\n    printf(\"%u\\n\",longest_non_decreasing_streak);\r\n    free(money_made);\r\n    return 0;\r\n}\r\n\r\nunsigned int find_length_longest_non_decreasing_streak(unsigned long *money_made, unsigned int no_of_days)\r\n{\r\n    unsigned int i, longest_non_decreasing_streak = 1, current_non_decreasing_streak = 1 ;\r\n\r\n    for(i = 1; i < no_of_days; i++)\r\n    {\r\n        //If A[i] >= A[i-1], current streak increases, else a new streak begins.\r\n        current_non_decreasing_streak = (  ( *(money_made + i) >= *(money_made + i -1) ) ? current_non_decreasing_streak+1 : 1 );\r\n\r\n        longest_non_decreasing_streak = max(longest_non_decreasing_streak, current_non_decreasing_streak);\r\n    }\r\n\r\n    return longest_non_decreasing_streak;\r\n}\r\n\r\nvoid read(unsigned long *money_made, unsigned int no_of_days)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_days; i++)\r\n    {\r\n        scanf(\"%lu\",(money_made + i));\r\n    }\r\n}\r\n\r\nunsigned long max(unsigned long a, unsigned long b)\r\n{\r\n    return ( (a > b) ? a : b);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Making_a_String.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(long long*, short);\r\nvoid selection_sort_descending(long long*, short);\r\nlong long min(long long, long long);\r\nlong long find_longest_string(long long*, short);\r\n\r\nint main()\r\n{\r\n    short no_of_letters;\r\n\r\n    scanf(\"%hu\",&no_of_letters);\r\n\r\n    long long longest_length, *occurence_of_letter = malloc(no_of_letters*sizeof(long long));\r\n\r\n    read(occurence_of_letter, no_of_letters);\r\n    selection_sort_descending(occurence_of_letter, no_of_letters);\r\n    longest_length = find_longest_string(occurence_of_letter, no_of_letters);\r\n\r\n    printf(\"%I64d\\n\",longest_length);\r\n    free(occurence_of_letter);\r\n    return 0;\r\n}\r\n\r\nlong long find_longest_string(long long*occurence_of_letter, short no_of_letters)\r\n{\r\n    short i;\r\n    long long longest_length = 0, maximum_frequency_current = *(occurence_of_letter + 0);\r\n\r\n    for(i = 0; (i < no_of_letters) && (maximum_frequency_current > 0); i++)\r\n    {\r\n        longest_length += min(maximum_frequency_current, *(occurence_of_letter + i));\r\n        maximum_frequency_current = min(maximum_frequency_current, *(occurence_of_letter + i));\r\n        maximum_frequency_current--;\r\n    }\r\n\r\n    return longest_length;\r\n}\r\n\r\nlong long min(long long a, long long b)\r\n{\r\n    if(a < b)\r\n        return a;\r\n    else\r\n        return b;\r\n}\r\n\r\nvoid read(long long*occurence_of_letter, short no_of_letters)\r\n{\r\n    short i;\r\n\r\n    for(i = 0; i < no_of_letters; i++)\r\n    {\r\n        scanf(\"%I64d\",(occurence_of_letter + i));\r\n    }\r\n}\r\n\r\nvoid selection_sort_descending(long long*occurence_of_letter, short no_of_letters)\r\n{\r\n    short i, j, largest_index;\r\n    long long largest;\r\n\r\n    //Every iteration finds the i-th maxima. So, for n elements, we only need to sort n-1 elements. The last element is forced to be in it's correct position.\r\n    for(i = 0; i < no_of_letters - 1; i++)\r\n    {\r\n        largest = *(occurence_of_letter + i);\r\n        largest_index = i;\r\n\r\n        for(j = i + 1; j  < no_of_letters; j++)//Go through the list from i to the end to search for a maxima\r\n        {\r\n            if(*(occurence_of_letter + j) > largest)\r\n            {\r\n                largest = *(occurence_of_letter + j);\r\n                largest_index = j;\r\n            }\r\n        }\r\n\r\n        //Place the i-th minima in the i-th position, and the element at the i-th position where the maxima was\r\n        *(occurence_of_letter + largest_index) = *(occurence_of_letter + i);\r\n        *(occurence_of_letter + i) = largest;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Non_Square_Equation.c",
    "content": "#include <stdio.h>\r\n#include <math.h>\r\n\r\nlong long find_solution(long long);\r\nint sum_of_digits(long long);\r\n\r\nint main()\r\n{\r\n    long long n, solution;\r\n    scanf(\"%I64d\",&n);\r\n\r\n    solution = find_solution(n);\r\n    printf(\"%I64d\\n\",solution);\r\n    return 0;\r\n}\r\n\r\n//Find smallest x, such that x^2 + s(x)*x = n, where s(x) is the sum of digits of x\r\nlong long find_solution(long long n)\r\n{\r\n    long long x;\r\n    long long solution = -1;\r\n    const int MAX_DIGIT_SUM = 81; //x^2 can be 10^18 at most, x can be 10^9 at most. s(x) can be s(10^9 -1) = 9*9 = 81 at most.\r\n\r\n    x = (int)sqrt(n);\r\n    while(x*x + MAX_DIGIT_SUM*x >= n)\r\n    {\r\n        if(x*x + sum_of_digits(x)*x == n)\r\n        {\r\n            solution = x;\r\n            break;\r\n        }\r\n        x--;\r\n    }\r\n\r\n    return solution;\r\n}\r\n\r\nint sum_of_digits(long long num)\r\n{\r\n    long long temp;\r\n    int sum = 0;\r\n    for(temp = num; temp > 0; temp = temp/10)\r\n    {\r\n        sum = sum + temp%10;\r\n    }\r\n    return sum;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Odd_Sum.c",
    "content": "#include <stdio.h>\r\n\r\n#define INFINITY 1e5 + 1\r\nint abs(int);\r\nint find_longest_subsequence_odd_sum(int);\r\n\r\nint main()\r\n{\r\n    int no_of_elements, longest_odd_subsequence_sum;\r\n    scanf(\"%d\",&no_of_elements);\r\n\r\n    longest_odd_subsequence_sum = find_longest_subsequence_odd_sum(no_of_elements);\r\n    printf(\"%d\\n\",longest_odd_subsequence_sum);\r\n    return 0;\r\n}\r\n\r\nint find_longest_subsequence_odd_sum(int no_of_elements)\r\n{\r\n    int number, sum = 0, odd_min = INFINITY, i;\r\n\r\n    /*Find the sum of all positive numbers. Keep track of the minimum |x| such that x is odd.\r\n      If the sum we get is odd, return the sum.\r\n      Else - the minimum absolute odd number may be odd or even.\r\n      If it is positive, we delete it from the chosen subsequence. Sum becomes sum - x\r\n      If it is negative, we add it to the subsequence, Sum becomes sum + x = sum - abs(x)\r\n      In one line, we can write, sum = sum - abs(x)*/\r\n    for(i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\",&number);\r\n        if(number > 0)\r\n        {\r\n            //Only adding positive numbers\r\n            sum = sum + number;\r\n        }\r\n\r\n        if(abs(number) % 2 == 1)\r\n        {\r\n            //We want the smallest odd number. If it is positive, we remove it from the sum. If it is negative we add it to the sum, in case sum is even\r\n            odd_min = (abs(number) < odd_min ? abs(number) : odd_min);\r\n        }\r\n    }\r\n\r\n    //Returning sum if it is odd. Else, if sum is even, we subtract the smallest odd number so that it's sum is still odd\r\n    return (sum%2 == 1 ? sum : (sum - abs(odd_min)) );\r\n}\r\n\r\nint abs(int a)\r\n{\r\n    return (a > 0 ? a : -a);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Parking_Lot.c",
    "content": "#include <stdio.h>\r\nunsigned long long power(unsigned long long, unsigned long long);\r\nint main()\r\n{\r\n    unsigned long long no_of_parking_positions, no_of_arrangements, four_power_n_minus_3;\r\n    scanf(\"%I64u\",&no_of_parking_positions);\r\n\r\n    four_power_n_minus_3 = power(4, no_of_parking_positions - 3);\r\n\r\n    no_of_arrangements = 6*(four_power_n_minus_3 * 4) + (no_of_parking_positions - 3)*9*(four_power_n_minus_3);\r\n    printf(\"%I64u\",no_of_arrangements);\r\n    return 0;\r\n}\r\n\r\nunsigned long long power(unsigned long long base, unsigned long long exponent)\r\n{\r\n    unsigned long long answer = 1;\r\n\r\n    if(exponent == 0)\r\n    {\r\n        return answer;\r\n    }\r\n\r\n    //Binary exponentiation algorithm. Number is squared as many times as the number of 0s in binary representation. x^5 = (x^2)^2*x\r\n    while(exponent > 0)\r\n    {\r\n        if(exponent%2 == 1)\r\n        {\r\n            answer = answer*base;\r\n        }\r\n        base = base*base;\r\n        exponent = exponent >> 1;\r\n    }\r\n    return answer;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Perfect_Permutation.c",
    "content": "#include <stdio.h>\r\nvoid display_perfect_permutation(unsigned int);\r\nint main()\r\n{\r\n    unsigned int no_of_elements;\r\n    scanf(\"%u\",&no_of_elements);\r\n    display_perfect_permutation(no_of_elements);\r\n    return 0;\r\n}\r\n\r\n/*If p(i) = i, then it is clearly a perfect permutation.\r\n\r\nSince, this is not allowed, we swap adjacent values p(2k) = 2k+ 1 and p(2k + 1) = 2k\r\nSo, an answer is available for all even n.\r\n\r\nSince, p(p(i)) = i, every time we change the value of p(i), we must also change the p(i) accordingly. Values have to get changed in pairs. Swapping adjacent values\r\ndoes the trick.\r\n\r\nHowever, if there are an odd number of elements, the last element will not have any number to get swapped with and will satisfy p(i) = i.\r\nSo, there is no perfect permutation for odd i.*/\r\n\r\nvoid display_perfect_permutation(unsigned int no_of_elements)\r\n{\r\n    unsigned int i;\r\n    if(no_of_elements%2 == 1)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else\r\n    {\r\n        for(i = 1; i < no_of_elements; i = i + 2)\r\n        {\r\n            printf(\"%u %u \",(i + 1), i);\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Preparing_for_Olympiad.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\nvoid read(long *, int);\r\nlong min(long, long);\r\nlong max(long, long);\r\nlong count_no_of_problem_sets(long *, int,long, long,long);\r\n\r\nint main()\r\n{\r\n    int no_of_problems;\r\n    long min_difficulty, max_difficulty,least_difficulty_range, no_of_problem_sets;\r\n    scanf(\"%d %ld %ld %ld\",&no_of_problems, &min_difficulty, &max_difficulty, &least_difficulty_range);\r\n\r\n    long *problem_difficulty = malloc(no_of_problems*sizeof(long));\r\n    read(problem_difficulty, no_of_problems);\r\n\r\n    no_of_problem_sets = count_no_of_problem_sets(problem_difficulty, no_of_problems, min_difficulty, max_difficulty, least_difficulty_range);\r\n    printf(\"%ld\\n\",no_of_problem_sets);\r\n\r\n    free(problem_difficulty);\r\n    return 0;\r\n}\r\n\r\nlong count_no_of_problem_sets(long *problem_difficulty, int no_of_problems,long min_difficulty, long max_difficulty,long least_difficulty_range)\r\n{\r\n    /*We construct a binary string in bijection to the problems chosen. If the i-th bit is 1, then it means that the i-th problem is chosen\r\n    If i-th bit is 0, then it isn't chosen. This bitmask is n digits long. We know n is always less than 15\r\n    The binary string is helpful in visiting every set that can be chosen from these n elements.*/\r\n    int current_problem_no, bitmask, total_no_of_problem_sets = 1 << no_of_problems; //No of binary strings of length n is 2^n. 1 right shifted n times is 2^n\r\n    long total_legitimate_arrangements = 0, current_min_difficulty, current_max_difficulty, problems_in_set;\r\n    long total_difficulty;\r\n\r\n    //Now, we iterate through all the bitmasks\r\n    for(bitmask = 1; bitmask < total_no_of_problem_sets; bitmask++)\r\n    {\r\n        total_difficulty = 0;\r\n        problems_in_set = 0;\r\n        /*The values of minimum and maximum are so set that the first problem selected becomes both min and max and from there it's just the\r\n        standard way of finding min and max in an array.\r\n        The min and max can't be set to the first element like usual because the first element may not be part of the chosen set.*/\r\n        current_min_difficulty = 1e6 + 1;\r\n        current_max_difficulty = -1;\r\n\r\n        for(current_problem_no = 0; current_problem_no < no_of_problems; current_problem_no++)\r\n        {\r\n            //The number 2^j corresponds with only the j-th problem chosen. We AND this with the current bitmask. If it's non-zero, then j-problem\r\n            //is chosen in this arrangement\r\n            if(bitmask & (1 << current_problem_no))\r\n            {\r\n                current_min_difficulty = min(current_min_difficulty, *(problem_difficulty + current_problem_no));\r\n                current_max_difficulty = max(current_max_difficulty, *(problem_difficulty + current_problem_no));\r\n                total_difficulty = total_difficulty + *(problem_difficulty + current_problem_no);\r\n                problems_in_set++;\r\n            }\r\n        }\r\n\r\n        if( (problems_in_set >= 2) && (total_difficulty >= min_difficulty) && (total_difficulty <= max_difficulty) &&\r\n           (current_max_difficulty-current_min_difficulty >=least_difficulty_range) )\r\n        {\r\n            total_legitimate_arrangements++;\r\n        }\r\n    }\r\n\r\n    return total_legitimate_arrangements;\r\n}\r\n\r\nvoid read(long *problem_difficulty, int no_of_problems)\r\n{\r\n    int i;\r\n    for(i = 0; i < no_of_problems; i++)\r\n    {\r\n        scanf(\"%ld\",(problem_difficulty + i));\r\n    }\r\n}\r\n\r\nlong min(long a, long b)\r\n{\r\n    if(a < b)\r\n        return a;\r\n    else\r\n        return b;\r\n}\r\nlong max(long a, long b)\r\n{\r\n    if(a > b)\r\n        return a;\r\n    else\r\n        return b;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Star.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned long long n, star_n;\r\n    scanf(\"%I64u\",&n);\r\n    //A star number consists of a central number and 12 copies of the (n-1)th triangular number\r\n    star_n = 6LL*n*(n-1) + 1;\r\n    printf(\"%I64u\",star_n);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Table_Tennis_Game_2.c",
    "content": "#include <stdio.h>\r\n\r\nlong find_no_of_sets(unsigned long,unsigned long ,unsigned long);\r\n\r\nint main()\r\n{\r\n    unsigned long no_of_points_in_a_set, misha_points, vanya_points;\r\n    long no_of_sets;\r\n    scanf(\"%lu %lu %lu\",&no_of_points_in_a_set, &misha_points, &vanya_points);\r\n    no_of_sets = find_no_of_sets(no_of_points_in_a_set, misha_points, vanya_points);\r\n    printf(\"%ld\\n\",no_of_sets);\r\n    return 0;\r\n}\r\n\r\nlong find_no_of_sets(unsigned long no_of_points_in_a_set,unsigned long misha_points,unsigned long vanya_points)\r\n{\r\n    long no_of_sets, misha_sets, vanya_sets;\r\n\r\n    //(a +b) might cause overflow. So doing (a%k + b%k) %k\r\n    misha_sets = misha_points/no_of_points_in_a_set;\r\n    vanya_sets = vanya_points/no_of_points_in_a_set;\r\n\r\n    no_of_sets = (misha_sets + vanya_sets);\r\n\r\n    if( (no_of_sets == 0) ||(misha_sets == 0 && vanya_points%no_of_points_in_a_set != 0) ||(vanya_sets == 0 && misha_points%no_of_points_in_a_set != 0) )\r\n    {\r\n        no_of_sets = -1;\r\n    }\r\n\r\n    return no_of_sets;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Tavas_and_Saddas.c",
    "content": "#include <stdio.h>\r\n\r\n#define MAX_NO_DIGITS 11\r\nunsigned int get_index(char[]);\r\nint main()\r\n{\r\n    char lucky_number[MAX_NO_DIGITS];\r\n    unsigned int index;\r\n\r\n    scanf(\"%s\",lucky_number);\r\n\r\n    index = get_index(lucky_number);\r\n\r\n    printf(\"%u\\n\",index);\r\n    return 0;\r\n}\r\n\r\nunsigned int get_index(char lucky_number[])\r\n{\r\n    short i;\r\n    unsigned int index = 1; //index can be atmost 2^{11} - 1 - A binary string with 11 ones. Int is sufficient\r\n\r\n    /*Construct a binary string in correspondence to the lucky number,\r\n    b[0] = 0,\r\n    b[i + 1] = 0, if d[i] = 4 and\r\n    b[i + 1] = 1, if d[i] = 7\r\n    4 corresponds with 01, 7 with 11, 44 with 001, 47 with 011 and so on.\r\n    Where b[i] is the i-th letter of the binary string, and d[i] is the i-th letter of the decimal string.\r\n    The binary string must be read from right to left.\r\n    The binary number we get is (reversed) always one more than the lexicographic number of the digit we have gotten since the first string is 2 and not 1.\r\n    So, we subtract 1 at the end, after constructing a binary number from the given decimal string.\r\n    We read the decimal string from right to left and then keep shifting each character to the left so that the rightmost character is at the left.\r\n    This way we already get the reversed binary string, as required. */\r\n    for(i = 0; lucky_number[i] != '\\0'; i++)\r\n    {\r\n        if(lucky_number[i] == '4')\r\n        {\r\n            index = (index << 1);\r\n        }\r\n        else if(lucky_number[i] == '7')\r\n        {\r\n            index = (index << 1) + 1;\r\n        }\r\n    }\r\n\r\n    index = index - 1;\r\n    return index;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Team.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short no_of_problems, vasya, petya, tonya, i, total_problems_solved = 0;\r\n    scanf(\"%hu\",&no_of_problems);\r\n    for(i = 1; i <= no_of_problems; i++)\r\n    {\r\n        scanf(\"%hu %hu %hu\",&vasya, &petya, &tonya);\r\n        total_problems_solved = total_problems_solved + (vasya + petya + tonya >= 2 ? 1 : 0);\r\n    }\r\n    printf(\"%hu\\n\",total_problems_solved);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Tetrahedron_Efficiently.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned long long find_no_of_cycles(int);\r\nvoid raise_matrix_power(unsigned long long[][2], int);\r\nvoid multiply(unsigned long long [][2], unsigned long long [][2]);\r\nvoid copy(unsigned long long [][2], unsigned long long [][2]);\r\n\r\nconst long long mod = 1e9 + 7;\r\nint main()\r\n{\r\n    int no_of_moves;\r\n    unsigned long long no_of_cyclic_paths;\r\n    scanf(\"%d\",&no_of_moves);\r\n    no_of_cyclic_paths = find_no_of_cycles(no_of_moves);\r\n    printf(\"%I64u\\n\",no_of_cyclic_paths);\r\n    return 0;\r\n}\r\n\r\nunsigned long long find_no_of_cycles(int no_of_moves)\r\n{\r\n    unsigned long long matrix[2][2];\r\n\r\n    if(no_of_moves == 0)\r\n    {\r\n        return 1;\r\n    }\r\n    /*\r\n    | f^n(D)    | = | 0    3 | | f^{n-1}(D)   |\r\n    | f^n(ABC)  | = | 1    2 | | f^{n-1}(ABC) |\r\n    Also, f^0(D) = 1 and f^0(ABC) = 0. */\r\n    matrix[0][0] = 0;\r\n    matrix[0][1] = 3;\r\n    matrix[1][0] = 1;\r\n    matrix[1][1] = 2;\r\n    raise_matrix_power(matrix, no_of_moves);\r\n\r\n    return (matrix[0][0]*1 + matrix[0][1]*0);//f^n(D) = first_row(A^n) * (1, 0)\r\n}\r\n\r\n//Binary exponentiation\r\nvoid raise_matrix_power(unsigned long long matrix[][2], int exponent)\r\n{\r\n    unsigned long long answer[2][2];\r\n\r\n    /*Initialise it to identity Answer = I_2*/\r\n    answer[0][0] = answer[1][1] = 1;\r\n    answer[0][1] = answer[1][0] = 0;\r\n\r\n    while(exponent > 0)\r\n    {\r\n        if(exponent%2 == 1)\r\n        {\r\n            multiply(answer, matrix);//Answer = Answer*A\r\n        }\r\n        multiply(matrix, matrix); //A = A*A\r\n        exponent = exponent >> 1;\r\n    }\r\n\r\n    copy(matrix, answer);\r\n}\r\n\r\nvoid multiply(unsigned long long matrix_1[][2], unsigned long long matrix_2[][2])\r\n{\r\n    short i, j, k;\r\n    unsigned long long product[2][2];\r\n\r\n    for(i = 0; i < 2; i++)\r\n    {\r\n        for(j = 0; j < 2; j++)\r\n        {\r\n            product[i][j] = 0;\r\n            for(k = 0; k < 2; k++)\r\n            {\r\n                product[i][j] += matrix_1[i][k]*matrix_2[k][j];\r\n                product[i][j] = (product[i][j]% mod);\r\n            }\r\n        }\r\n    }\r\n\r\n    copy(matrix_1, product);\r\n}\r\n\r\nvoid copy(unsigned long long matrix_1[][2], unsigned long long matrix_2[][2])\r\n{\r\n    short i, j;\r\n\r\n    for(i = 0; i < 2; i++)\r\n    {\r\n        for(j = 0; j < 2; j++)\r\n        {\r\n            matrix_1[i][j] = matrix_2[i][j];\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Tricky_Sum.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short no_of_test_cases, i;\r\n    long long answer, n, power_of_2_to_be_subtracted = 0;\r\n\r\n    scanf(\"%hu\",&no_of_test_cases);\r\n\r\n    for(i = 0; i < no_of_test_cases; i++)\r\n    {\r\n        scanf(\"%I64d\",&n);\r\n        power_of_2_to_be_subtracted = 0;\r\n        answer = n*(n+1)/2;\r\n\r\n        //The greatest power of 2 less than n is 2^{i-1}, where i is the position of it's most siginificant byte in binary.\r\n        //The sum of all powers of 2 upto 2^i corresponds to a string of i 1s, which is what we construct here.\r\n        while(n > 0)\r\n        {\r\n            power_of_2_to_be_subtracted = (power_of_2_to_be_subtracted << 1) + 1;\r\n            n = n >> 1;\r\n        }\r\n\r\n        //Answer = sum(n) - 2(sum (powers of 2) ) because they are also counted once in sum(n).\r\n        answer = answer - (power_of_2_to_be_subtracted << 1);\r\n        printf(\"%I64d\\n\",answer);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Vacations.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    short no_of_days, i, current_activity, previous_activity = 0, rest_days = 0;\r\n    scanf(\"%hu\",&no_of_days);\r\n    for(i = 1; i <= no_of_days; i++)\r\n    {\r\n        scanf(\"%hu\",&current_activity);\r\n\r\n        /*If the gym is closed and there is no contest, he takes rest.\r\n        Else, if gym is open today and he went to the gym the previous day, he is forced to take rest.\r\n        Same reasoning for the contest. If only contest is available today and he went to contest yesterday, he is forced to rest.*/\r\n        if( (current_activity == 0) || (current_activity == 1 && previous_activity == 1) || (current_activity == 2 && previous_activity == 2) )\r\n        {\r\n            rest_days++;\r\n            previous_activity = 0; //Previous activity for the next day.\r\n        }\r\n        else\r\n        {\r\n            //If he went to contest the previous day, go to gym. If he went to gym the previous day go to contest. If it was rest, do either.\r\n            if(current_activity == 3)\r\n            {\r\n                //If previous = 1, do 2 on the current day.\r\n                //If previous = 2, do 1 on the current day\r\n                //If previous = 0, do 3 on the current day\r\n                //If previous = 3, do 3 on the current day as well.\r\n                //What is done on the current day is the previous activity for the next day.\r\n                previous_activity = ( (previous_activity < 3) ? (3 - previous_activity) : previous_activity);\r\n            }\r\n            else //If it isn't 3, then record the exact event.\r\n            {\r\n                previous_activity = current_activity;\r\n            }\r\n        }\r\n    }\r\n    printf(\"%hu\\n\",rest_days);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 5/Vanya_and_Table.c",
    "content": "#include <stdio.h>\r\nunsigned int count_cells_covered(unsigned int);\r\nint main()\r\n{\r\n    unsigned int no_of_rectangles, total_cells_counted;\r\n    scanf(\"%u\",&no_of_rectangles);\r\n    total_cells_counted = count_cells_covered(no_of_rectangles);\r\n    printf(\"%u\\n\",total_cells_counted);\r\n    return 0;\r\n}\r\n\r\nunsigned int count_cells_covered(unsigned int no_of_rectangles)\r\n{\r\n    unsigned int i, x1, x2, y1, y2, no_of_cells_counted = 0;\r\n\r\n    for(i = 0; i < no_of_rectangles; i++)\r\n    {\r\n        scanf(\"%u %u %u %u\", &x1, &y1, &x2, &y2);\r\n        no_of_cells_counted = no_of_cells_counted + (x2 - x1 + 1)*(y2 - y1 + 1); //This is the number of cells in the current rectangle. The last\r\n        //cell has a point (x2 + 1, y2 + 1). We want to count it as well.\r\n    }\r\n    return no_of_cells_counted;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/A_Shell_Game.c",
    "content": "#include <stdio.h>\r\n#define NO_OF_SHUFFLES 3\r\n\r\nint main()\r\n{\r\n    int ball_shell, shell_1, shell_2, i;\r\n\r\n    FILE *input = fopen(\"input.txt\", \"r\");\r\n    FILE *output = fopen(\"output.txt\", \"w\");\r\n\r\n    fscanf(input, \"%d\", &ball_shell);\r\n\r\n    for(i = 1; i <= NO_OF_SHUFFLES; i++)\r\n    {\r\n        fscanf(input,\"%d %d\",&shell_1, &shell_2);\r\n        if(ball_shell == shell_1)\r\n        {\r\n            ball_shell =  shell_2;\r\n        }\r\n        else if(ball_shell == shell_2)\r\n        {\r\n            ball_shell = shell_1;\r\n        }\r\n    }\r\n    fprintf(output,\"%d\\n\",ball_shell);\r\n\r\n    fclose(input);\r\n    fclose(output);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Accounting.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#define NOT_POSSIBLE -10\r\nint find_coefficient_of_income(int,int ,short);\r\nint power(int, int);\r\n\r\nint main()\r\n{\r\n    int money_at_beginning, money_at_end, coefficient_of_income_growth;\r\n    short no_of_years;\r\n    scanf(\"%d %d %hu\",&money_at_beginning, &money_at_end, &no_of_years);\r\n    coefficient_of_income_growth = find_coefficient_of_income(money_at_beginning, money_at_end, no_of_years);\r\n    if(coefficient_of_income_growth == NOT_POSSIBLE)\r\n    {\r\n        printf(\"No solution\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"%d\\n\",coefficient_of_income_growth);\r\n    }\r\n    return 0;\r\n}\r\n\r\nint find_coefficient_of_income(int money_at_beginning,int money_at_end, short no_of_years)\r\n{\r\n    int assumed_coefficient, expected_answer ;\r\n\r\n    if(money_at_beginning == 0)//No solution then\r\n    {\r\n        /*If both a = b= 0, then any value of x satisfies the equation\r\n         If a is 0 and b is non zero, there is no solution*/\r\n        assumed_coefficient = (money_at_end == 0 ? 1 : NOT_POSSIBLE);\r\n\r\n        return assumed_coefficient;\r\n    }\r\n    else\r\n    {\r\n        if(abs(money_at_end)% abs(money_at_beginning) != 0)\r\n        {\r\n            return NOT_POSSIBLE;\r\n        }\r\n        expected_answer =   money_at_end/money_at_beginning; //X^n = b/a\r\n    }\r\n\r\n    if(expected_answer > 0)\r\n    {\r\n        for(assumed_coefficient = 0; power(assumed_coefficient, no_of_years) < expected_answer; assumed_coefficient++);\r\n    }\r\n    else\r\n    {\r\n        for(assumed_coefficient = 0; power(assumed_coefficient, no_of_years) > expected_answer; assumed_coefficient--);\r\n    }\r\n    //printf(\"%d\\t%d\\t=%d\\n\",assumed_coefficient,power(assumed_coefficient, 1),expected_answer);\r\n    if(power(assumed_coefficient, no_of_years) != expected_answer)\r\n    {\r\n        assumed_coefficient = NOT_POSSIBLE;\r\n    }\r\n\r\n    return assumed_coefficient;\r\n}\r\n\r\nint power(int x,int n)\r\n{\r\n    return (n == 0 ? 1 : x*power(x, n-1));\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Anton_and_Digits.c",
    "content": "#include <stdio.h>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define min_of_3(a,b,c) min(a, min(b,c))\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_2, no_of_3, no_of_5, no_of_6, no_of_256, no_of_32, sum = 0;\r\n    scanf(\"%u %u %u %u\",&no_of_2, &no_of_3, &no_of_5, &no_of_6);\r\n\r\n    no_of_256 = min_of_3(no_of_2, no_of_5, no_of_6); //Make as many 256s as possible\r\n    no_of_32 = min(no_of_2 - no_of_256, no_of_3); //Some of the 2s have been used in 256s.\r\n\r\n    sum = 256*no_of_256 + 32*no_of_32;\r\n    printf(\"%u\\n\",sum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Black_Square.c",
    "content": "#include <stdio.h>\r\n\r\n#define MAX_LENGTH 100001\r\nint main()\r\n{\r\n    int calories[5],total_calories = 0, i;\r\n    char game[MAX_LENGTH];\r\n\r\n    for(i = 1; i <= 4; i++) //For convenience start the array index from 1-4, because the string also contains elements from 1-4\r\n    {\r\n        scanf(\"%d\", &calories[i]);\r\n    }\r\n    scanf(\"%s\",game);\r\n\r\n    for(i = 0; game[i] != '\\0'; i++)\r\n    {\r\n        total_calories += calories[game[i] - '0'];\r\n    }\r\n\r\n    printf(\"%d\\n\",total_calories);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Dinner_with_Emma.c",
    "content": "#include <stdio.h>\r\n\r\n#define INFINITY 1e9 + 1\r\n#define min(a, b) (a < b ? a : b)\r\n#define max(a, b) (a > b ? a : b)\r\nint main()\r\n{\r\n    short no_of_streets, no_of_avenues, i, j;\r\n    unsigned int current_cost, minimum_street_cost, maximum_street_minimum_cost = 0;\r\n    scanf(\"%hu %hu\",&no_of_streets, &no_of_avenues);\r\n\r\n    for(i = 0; i < no_of_streets; i++)\r\n    {\r\n        //Find the minimum cost on the current street\r\n        minimum_street_cost = INFINITY;\r\n        for(j = 0; j < no_of_avenues; j++)\r\n        {\r\n            scanf(\"%u\",&current_cost);\r\n            minimum_street_cost = min(minimum_street_cost, current_cost);\r\n        }\r\n        //Among the set of minimum costs on each street, choose the maximum element\r\n        maximum_street_minimum_cost = max(maximum_street_minimum_cost, minimum_street_cost);\r\n    }\r\n\r\n    printf(\"%u\\n\",maximum_street_minimum_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Ebony_and_Ivory.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nint main()\r\n{\r\n    int ebony, ivory, shield, i;\r\n    scanf(\"%d %d %d\", &ebony, &ivory, &shield);\r\n    short *is_possible = malloc( (shield + 100)*sizeof(short));\r\n    *(is_possible + 0) = true;\r\n\r\n    for(i = 0; i <= shield; i++)\r\n    {\r\n        if(*(is_possible + i) == true) //If c is possible, then c + a, and c + b are possible as well.\r\n        {\r\n            *(is_possible + i + ebony) = true;\r\n            *(is_possible + i + ivory) = true;\r\n        }\r\n    }\r\n\r\n    printf(*(is_possible + shield) == true ? \"Yes\\n\" : \"No\\n\");\r\n    free(is_possible);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Find Amir.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_schools, minimum_cost;\r\n    scanf(\"%d\",&no_of_schools);\r\n\r\n    /*Firstly, make as many pairs of 0 cost as possible.\r\n\r\n    {1 + n}, {2, n-1}, {3, n-2} ... {n/2, n/2 + 1} if n is even. If n is odd, then n/2 + 1 is unpaired.\r\n\r\n    These pairs have 0 cost.\r\n\r\n    Since a ticket can be used multiple times, it is sufficient to connect these pairs. The minimum way to do this is to pay a cost of 1\r\n\r\n    n/2 + (n/2 + 2) = n + 2 = 1 (mod n+1)\r\n    n/2-1 + (n/2 + 3) = n + 2\r\n    n/2-2 + (n/2 + 4) = n + 2\r\n\r\n    If n is even, then there are n/2 pairs. These n/2 pairs can be connected in (n/2 - 1) tickets of price 1.\r\n    For example, if there are 10 pairs, there are 5 pairs, and 4 tickets can connect them.\r\n    So, cost is (n/2 - 1).\r\n\r\n    If n is odd, then there are n/2 pairs (which can be connected in (n/2 - 1) tickets). Also, n/2 + 1 is isolated. n/2 + 1 should be connected to n/2 + 2.\r\n    So, there are (n/2 - 1 + 1) = n/2 tickets of cost 1.*/\r\n\r\n    minimum_cost = (no_of_schools%2 == 0 ? no_of_schools/2 - 1 : no_of_schools/2);\r\n    printf(\"%d\\n\", minimum_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Game_with_Sticks.c",
    "content": "#include <stdio.h>\r\n#define min(a, b) (a < b ? a : b)\r\nint main()\r\n{\r\n    int horizontal, vertical;\r\n    scanf(\"%d %d\", &horizontal, &vertical);\r\n\r\n    //It doesn't matter which stick is taken. After it is taken, the grid is reduced to (m-1, n-1)\r\n    //Whoever gets the configuration (1, x) or (x, 1) wins.\r\n    //If min(m, n) is even, the minimum becomes odd on Malvika's turn so Malvika gets the configuration (1, x)\r\n    //If min(m, n) is odd, then the minimum is odd on the first player's turns. So, the first player wins.\r\n    printf( min(horizontal, vertical)%2 == 0 ? \"Malvika\\n\" : \"Akshat\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Increasing_Sequence.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_elements, i, current_number, previous_number = 0,step_length, no_of_steps_to_be_added, no_of_operations_performed = 0;\r\n    scanf(\"%d %d\",&no_of_elements, &step_length);\r\n\r\n    for(i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\",&current_number);\r\n        if(previous_number >= current_number)\r\n        {\r\n            //We need to add enough steps to make current number atleast previous number + 1.\r\n            //This is at least (previous number - current number + 1)/step length\r\n            //If it is not a perfect multiple of step length, then we need to add one more step because integer division finds the floor.\r\n            no_of_steps_to_be_added = (previous_number - current_number + 1)/step_length;\r\n            no_of_steps_to_be_added += (previous_number - current_number + 1)%step_length == 0 ? 0 : 1;\r\n\r\n            current_number = current_number + no_of_steps_to_be_added*step_length;\r\n            no_of_operations_performed += no_of_steps_to_be_added;\r\n        }\r\n        previous_number = current_number;\r\n    }\r\n\r\n    printf(\"%d\\n\",no_of_operations_performed);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Insomnia_Cure.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int punched, trapped, trampled, mothered, total_dragons, i, harmed_dragons = 0;\r\n    scanf(\"%d %d %d %d %d\", &punched, &trapped, &trampled, &mothered, &total_dragons);\r\n\r\n    for(i = 1; i <= total_dragons; i++)\r\n    {\r\n        if(i%punched == 0 || i%trapped == 0 || i%trampled == 0 || i%mothered == 0)\r\n        {\r\n            harmed_dragons++;\r\n        }\r\n    }\r\n    printf(\"%d\\n\",harmed_dragons);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Jumping_Ball.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint find_eventually_falling_bumpers(char *, int);\r\nint main()\r\n{\r\n    int no_of_bumpers, no_of_bumpers_leading_to_fall;\r\n\r\n    scanf(\"%d\",&no_of_bumpers);\r\n\r\n    char *bumpers = malloc((no_of_bumpers+1)*sizeof(char));\r\n    scanf(\"%s\",bumpers);\r\n\r\n    no_of_bumpers_leading_to_fall = find_eventually_falling_bumpers(bumpers, no_of_bumpers);\r\n    printf(\"%d\\n\",no_of_bumpers_leading_to_fall);\r\n    free(bumpers);\r\n    return 0;\r\n}\r\n\r\nint find_eventually_falling_bumpers(char *bumpers, int no_of_bumpers)\r\n{\r\n    int i, fall_count = 0;\r\n\r\n    for(i = 0; (*(bumpers + i) == '<') && (*(bumpers + i) != '\\0'); i++,fall_count++);//No of < in the beginning before the first > or end of string\r\n\r\n    for(i = no_of_bumpers - 1; (*(bumpers + i) == '>') && ( i >= 0); i--, fall_count++);//No of > in the end before the last < or beginning of string\r\n    return fall_count;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/K_Tree.c",
    "content": "#include <stdio.h>\r\n\r\nunsigned long calculate_no_of_paths(short, short, short);\r\n\r\nint main()\r\n{\r\n    short sum, no_of_children, d;\r\n    unsigned long no_of_paths;\r\n    scanf(\"%hu %hu %hu\",&sum, &no_of_children, &d);\r\n    no_of_paths = calculate_no_of_paths(sum, no_of_children, d);\r\n    printf(\"%lu\\n\",no_of_paths);\r\n    return 0;\r\n}\r\n\r\nunsigned long calculate_no_of_paths(short sum, short no_of_children, short d)\r\n{\r\n    unsigned long no_of_paths[101][2];\r\n    short i, j;\r\n    const unsigned long mod = (1e9 + 7);\r\n\r\n    no_of_paths[0][0] = 1;\r\n    no_of_paths[0][1] = 0;\r\n    /*Here, f(n, i) represents the number of paths which sum up to n. i is a boolean value which is 1 if the path contains an edge atleast d and 0 otherwise\r\n    We make a recurrence based on selecting each child separately.\r\n    f(n, 0) = f(n-1, 0) + f(n-2, 0) + ... + f(n - min{n, d-1}, 0)\r\n    Other case -\r\n    f(n, 1) = f(n-1, 1) + f(n-2, 1) + ... + f(n - min{n, d-1}, 1) + {f(n - d, 0) + f(n - d, 1} + ... + {f(n - k, 0) + f(n - k, 1)}*/\r\n    for(i = 1; i <= sum; i++)\r\n    {\r\n        no_of_paths[i][0] = no_of_paths[i][1] = 0;\r\n\r\n        for(j = 1; ((j <= no_of_children) && (i-j >= 0)); j++)\r\n        {\r\n            if(j < d)\r\n            {\r\n                no_of_paths[i][0] =(no_of_paths[i][0]+ no_of_paths[i-j][0])%mod;\r\n                no_of_paths[i][1] = (no_of_paths[i][1] + no_of_paths[i-j][1])%mod;\r\n            }\r\n            else\r\n            {\r\n                no_of_paths[i][1] = (no_of_paths[i][1] + no_of_paths[i-j][0])%mod;\r\n                no_of_paths[i][1] = (no_of_paths[i][1] + no_of_paths[i-j][1])%mod;\r\n            }\r\n        }\r\n    }\r\n    return no_of_paths[sum][1];\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Lovely_Palindromes.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define MAX_LENGTH 100002\r\n\r\nint main()\r\n{\r\n    char string[MAX_LENGTH], reverse[MAX_LENGTH];\r\n    int length, i;\r\n    scanf(\"%s\",string);\r\n\r\n    length = strlen(string);\r\n    for(i = 0; i < length; i++)\r\n    {\r\n        reverse[i] = string[length - i - 1];\r\n    }\r\n    reverse[length] = '\\0';\r\n\r\n    printf(\"%s%s\\n\",string,reverse);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Luxurious_Buildings.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define maximum(a, b) (a > b ? a : b)\r\n\r\nvoid read(int *, int);\r\nvoid display(int *, int);\r\nvoid make_every_building_luxurious(int *, int *, int);\r\n\r\nint main()\r\n{\r\n    int no_of_buildings;\r\n    scanf(\"%d\",&no_of_buildings);\r\n    int *no_of_floors = malloc(no_of_buildings*sizeof(int));\r\n    int *no_of_floors_to_be_added = malloc(no_of_buildings*sizeof(int));\r\n\r\n    read(no_of_floors, no_of_buildings);\r\n    make_every_building_luxurious(no_of_floors, no_of_floors_to_be_added, no_of_buildings);\r\n    display(no_of_floors_to_be_added, no_of_buildings);\r\n\r\n    free(no_of_floors);\r\n    free(no_of_floors_to_be_added);\r\n    return 0;\r\n}\r\n\r\nvoid make_every_building_luxurious(int *no_of_floors, int *no_of_floors_to_be_added, int no_of_buildings)\r\n{\r\n    int i, max = *(no_of_floors + no_of_buildings - 1);\r\n    *(no_of_floors_to_be_added + no_of_buildings - 1) = 0;\r\n\r\n    for(i = no_of_buildings - 2; i >= 0; i--)\r\n    {\r\n        *(no_of_floors_to_be_added + i) = (max >= *(no_of_floors + i) ) ? (max - *(no_of_floors + i) + 1) : 0 ;\r\n        max = maximum(max, *(no_of_floors + i) ) ;\r\n    }\r\n}\r\n\r\nvoid read(int *no_of_floors, int no_of_buildings)\r\n{\r\n    int i;\r\n    for(i = 0; i < no_of_buildings; i++)\r\n    {\r\n        scanf(\"%d\",(no_of_floors + i));\r\n    }\r\n}\r\n\r\nvoid display(int *no_of_floors_to_be_added, int no_of_buildings)\r\n{\r\n    int i;\r\n    for(i = 0; i < no_of_buildings; i++)\r\n    {\r\n        printf(\"%d \",*(no_of_floors_to_be_added + i));\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Meeting_of_Old_Friends.c",
    "content": "#include <stdio.h>\r\n\r\n#define max(a,b) (a > b ? a : b)\r\n#define min(a,b) (a < b ? a : b)\r\nint main()\r\n{\r\n    long long sonya_start, sonya_end, filya_start, filya_end, no_of_minutes, prinking_minute, meeting_start, meeting_end;\r\n    scanf(\"%I64d %I64d %I64d %I64d %I64d\",&sonya_start, &sonya_end, &filya_start, &filya_end, &prinking_minute);\r\n\r\n    meeting_start = max(sonya_start, filya_start);\r\n    meeting_end = min(sonya_end, filya_end);\r\n\r\n    no_of_minutes = (meeting_end >= meeting_start) ? (meeting_end - meeting_start + 1) : 0; //Inclusive of starting and ending time\r\n    no_of_minutes -= (prinking_minute >= meeting_start) && (prinking_minute <= meeting_end)? 1 : 0; //Decrement 1 if k is in the meeting time\r\n    printf(\"%I64d\\n\",no_of_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Oleg_and_Shares.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define min(a,b) (a < b ? a : b)\r\n#define INFINITY 1e9 + 1\r\n\r\nint read_and_find_minimum(int *, int);\r\nlong long find_no_of_days_equalise_shares(int *, int, int, int);\r\n\r\nint main()\r\n{\r\n    int no_of_shares, decreasing_amount, minimum_share;\r\n    long long no_of_days;\r\n    scanf(\"%d %d\", &no_of_shares, &decreasing_amount);\r\n    int *share = malloc(no_of_shares*sizeof(int));\r\n\r\n    minimum_share = read_and_find_minimum(share, no_of_shares);\r\n    no_of_days = find_no_of_days_equalise_shares(share, no_of_shares, decreasing_amount, minimum_share);\r\n\r\n    printf(\"%I64d\\n\",no_of_days);\r\n    free(share);\r\n    return 0;\r\n}\r\n\r\nlong long find_no_of_days_equalise_shares(int *share, int no_of_shares,int decreasing_amount,int minimum_share)\r\n{\r\n    int i;\r\n    long long no_of_days = 0;\r\n\r\n    for(i = 0; i < no_of_shares; i++)\r\n    {\r\n        if( ( *(share + i) - minimum_share) % decreasing_amount != 0)\r\n        {\r\n            no_of_days = -1;\r\n            break;\r\n        }\r\n        else\r\n        {\r\n            no_of_days = no_of_days + (( *(share + i) - minimum_share) / decreasing_amount);\r\n        }\r\n    }\r\n    return no_of_days;\r\n}\r\n\r\nint read_and_find_minimum(int *share, int no_of_shares)\r\n{\r\n    int i, minimum = INFINITY;\r\n\r\n    for(i = 0; i < no_of_shares; i++)\r\n    {\r\n        scanf(\"%d\",(share + i));\r\n        minimum = min(minimum, *(share + i));\r\n    }\r\n    return minimum;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Patrick_and_Shopping.c",
    "content": "#include <stdio.h>\r\n#define min(a,b) (a < b ? a : b)\r\nint main()\r\n{\r\n    int distance_1, distance_2, distance_between_shops, minimum_distance;\r\n    scanf(\"%d %d %d\",&distance_1, &distance_2, &distance_between_shops);\r\n\r\n    minimum_distance = min(distance_1 + distance_between_shops + distance_2, 2*(distance_1 + distance_2));\r\n    minimum_distance = min(minimum_distance, 2*(distance_1 + distance_between_shops));\r\n    minimum_distance = min(minimum_distance, 2*(distance_2 + distance_between_shops));\r\n    printf(\"%d\\n\",minimum_distance);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Plate_Game.c",
    "content": "#include <stdio.h>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\nint main()\r\n{\r\n    int side_a, side_b, radius;\r\n    scanf(\"%d %d %d\",&side_a, &side_b, &radius);\r\n\r\n    //If the first player can't place a plate, the second player wins. Else, the first player always wins. He places a plate in the center of the table.\r\n    //And then places a table diagonally opposite to wherever the second player places a table\r\n    printf(min(side_a, side_b) < (2*radius) ? \"Second\\n\" : \"First\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Rewards.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int gold_trophy, silver_trophy, bronze_trophy, gold_medal, silver_medal, bronze_medal, total_trophies, total_medals, no_of_shelves;\r\n    int trophy_shelves, medal_shelves;\r\n\r\n    scanf(\"%d %d %d\",&gold_trophy, &silver_trophy, &bronze_trophy);\r\n    scanf(\"%d %d %d\",&gold_medal, &silver_medal, &bronze_medal);\r\n    scanf(\"%d\",&no_of_shelves);\r\n\r\n    total_trophies = gold_trophy + silver_trophy + bronze_trophy;\r\n    total_medals = gold_medal + silver_medal + bronze_medal;\r\n\r\n    trophy_shelves = (total_trophies%5 == 0 ? total_trophies/5 : total_trophies/5 + 1);\r\n    medal_shelves = (total_medals%10 == 0 ? total_medals/10 : total_medals/10 + 1);\r\n\r\n    printf(trophy_shelves + medal_shelves <= no_of_shelves ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Round_House.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_houses, starting_house, no_of_houses_travelled, ending_house;\r\n    scanf(\"%d %d %d\", &no_of_houses, &starting_house, &no_of_houses_travelled);\r\n\r\n    /*Simple modular arithmetic -\r\n    (a + b) mod n\r\n    However, the house numbers start from 1. And the modular class start from 0. So,\r\n    {(a - 1 + b) mod n } + 1\r\n    -1 is added to a so that the house starts from 0 and then 1 is added at the end to balance the answer out.\r\n\r\n    To ensure the number is positive, if (a - 1 + b)mod n, is negative, then n is added to it to keep it positive.*/\r\n    ending_house = (starting_house - 1 + no_of_houses_travelled)%no_of_houses + 1;\r\n    ending_house = ending_house + (ending_house <= 0 ? no_of_houses : 0);\r\n\r\n    printf(\"%d\\n\",ending_house);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/System_of_Equations.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int n, m, no_of_solutions = 0, i, j;\r\n    scanf(\"%d %d\", &n, &m);\r\n\r\n    for(i = 0; i <= m; i++)\r\n    {\r\n        for(j = 0; j <= n; j++)\r\n        {\r\n            if( (i*i + j == n) && (i + j*j == m))\r\n            {\r\n                no_of_solutions++;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\",no_of_solutions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Vanya_and_Fence.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_people, i, height_fence, current_height, total_width = 0;\r\n    scanf(\"%d %d \",&no_of_people,&height_fence);\r\n\r\n    for(i = 1; i <= no_of_people; i++)\r\n    {\r\n        scanf(\"%d\",&current_height);\r\n        total_width += (current_height > height_fence ? 2 : 1); //bent person has width 2\r\n    }\r\n    printf(\"%d\\n\",total_width);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Vanya_and_Lanterns.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\n#define max(a,b) (a > b ? a : b)\r\n\r\nvoid read(int *, int);\r\nvoid selection_sort(int *, int);\r\nfloat find_maximum_radius(int *, int, int);\r\n\r\nint main()\r\n{\r\n    int no_of_lanterns, street_length;\r\n    float maximum_radius;\r\n    scanf(\"%d %d\", &no_of_lanterns, &street_length);\r\n    int *lantern_position = malloc(no_of_lanterns*sizeof(int));\r\n\r\n    read(lantern_position, no_of_lanterns);\r\n    selection_sort(lantern_position, no_of_lanterns);\r\n    maximum_radius = find_maximum_radius(lantern_position, no_of_lanterns, street_length);\r\n\r\n    printf(\"%.6f\",maximum_radius);\r\n\r\n    free(lantern_position);\r\n    return 0;\r\n}\r\n\r\nfloat find_maximum_radius(int *lantern_position, int no_of_lanterns, int street_length)\r\n{\r\n    float maximum_radius = 0;\r\n    int i;\r\n\r\n    for(i = 1; i < no_of_lanterns; i++)\r\n    {\r\n        maximum_radius = max(maximum_radius, (*(lantern_position + i) - *(lantern_position + i - 1)) );\r\n    }\r\n    //Finding the maximum of distance between first lantern and beginning and last lantern and ending.\r\n    maximum_radius = maximum_radius/2; //We have only compared adjacent lamps so divide by 2.\r\n    maximum_radius = max(maximum_radius, *(lantern_position + 0));\r\n    maximum_radius = max(maximum_radius, street_length - *(lantern_position + no_of_lanterns - 1));\r\n    return maximum_radius;\r\n}\r\n\r\nvoid read(int *lantern_position, int no_of_lanterns)\r\n{\r\n    int i;\r\n\r\n    for(i = 0; i < no_of_lanterns; i++)\r\n    {\r\n        scanf(\"%d\",(lantern_position + i));\r\n    }\r\n}\r\n\r\nvoid selection_sort(int *lantern_position, int no_of_lanterns)\r\n{\r\n    int i, j, smallest, smallest_index;\r\n\r\n    //Every iteration finds the i-th minima. So, for n elements, we only need to sort n-1 elements. The last element is forced to be in it's correct position.\r\n    for(i = 0; i < no_of_lanterns - 1; i++)\r\n    {\r\n        smallest = *(lantern_position + i);\r\n        smallest_index = i;\r\n\r\n        for(j = i + 1; j  < no_of_lanterns; j++)//Go through the list from i to the end to search for a minima\r\n        {\r\n            if(*(lantern_position + j) < smallest)\r\n            {\r\n                smallest = *(lantern_position + j);\r\n                smallest_index = j;\r\n            }\r\n        }\r\n\r\n        //Place the i-th minima in the i-th position, and the element at the i-th position where the minima was\r\n        *(lantern_position + smallest_index) = *(lantern_position + i);\r\n        *(lantern_position + i) = smallest;\r\n    }\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Vasya_and_Hipster.c",
    "content": "#include <stdio.h>\r\n\r\n#define min(a,b) (a < b ? a : b)\r\n#define max(a,b) (a > b ? a : b)\r\nint main()\r\n{\r\n    int red_socks, blue_socks, no_of_days_different_socks, no_of_days_same_socks;\r\n    scanf(\"%d %d\", &red_socks, &blue_socks);\r\n\r\n    no_of_days_different_socks = min(red_socks, blue_socks);\r\n    no_of_days_same_socks = (max(red_socks, blue_socks) - min(red_socks, blue_socks))/ 2;\r\n    printf(\"%d %d\\n\",no_of_days_different_socks, no_of_days_same_socks);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 6/Wizard_Duel.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int length_of_corridor, speed_of_Harry_spell, speed_of_voldemort_spell;\r\n    float time_taken, distance_from_Harry;\r\n    scanf(\"%d %d %d\",&length_of_corridor, &speed_of_Harry_spell, &speed_of_voldemort_spell);\r\n\r\n    //L-x = tq, x = tp therefore L = t(p + q)\r\n    //The speed is constant. So, the spells reach their casters with the same time with which they reached their meeting point.\r\n    //From here, the situation is exactly the same as the first spell. That means all the collisions happen at the same point.\r\n    time_taken = length_of_corridor/(float)(speed_of_Harry_spell + speed_of_voldemort_spell);\r\n    distance_from_Harry = time_taken*speed_of_Harry_spell;\r\n\r\n    printf(\"%f\\n\",distance_from_Harry);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/3_Palindrome.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int number_of_letters, i;\r\n    scanf(\"%d\", &number_of_letters);\r\n\r\n    //No letter must have the same neighbour on both the left and the right. aabbaabbaabb.... satisfies this condition\r\n    for(i = 1; i <= number_of_letters; i = i+2)\r\n    {\r\n        //If n is odd, then only one letter should be printed at the end.\r\n        if(i%4 == 1)\r\n        {\r\n            printf(i == number_of_letters ? \"a\\n\" : \"aa\");\r\n        }\r\n        else\r\n        {\r\n            printf(i == number_of_letters ? \"b\\n\" : \"bb\");\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Alena_Schedule.c",
    "content": "#include <stdio.h>\r\n\r\n#define YES 1\r\n#define NO 0\r\n\r\nint main()\r\n{\r\n    int no_of_classes, i, continuous_breaks = 0, first_class, total_breaks = 0, current_class;\r\n    scanf(\"%d\", &no_of_classes);\r\n\r\n\r\n    //Adding all the leading zeroes\r\n    for(first_class = 1; first_class <= no_of_classes; first_class++)\r\n    {\r\n        scanf(\"%d\", &current_class);\r\n\r\n        if(current_class == 1)\r\n            break;\r\n        else\r\n            total_breaks++;\r\n    }\r\n\r\n    for(i = first_class + 1; i <= no_of_classes; i++)\r\n    {\r\n        scanf(\"%d\", &current_class);\r\n\r\n        if(current_class == 1 && continuous_breaks >= 2)\r\n            total_breaks += continuous_breaks;\r\n\r\n        continuous_breaks = (current_class == 0 ? continuous_breaks + 1 : 0);\r\n    }\r\n    total_breaks += continuous_breaks;//Adding up all the breaks after the last class i.e. - the trailing zeroes\r\n\r\n    printf(\"%d\\n\",(no_of_classes - total_breaks) );\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Alice_and_Bob.c",
    "content": "#include <stdio.h>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint find_gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n\r\n    if(a == b)\r\n        return a;\r\n\r\n    if(a%2 == 0)\r\n        if(b%2 == 0)\r\n            return 2*find_gcd(a >> 1, b >> 1);\r\n        else\r\n            return find_gcd(a >> 1, b);\r\n    else\r\n        if(b%2 == 0)\r\n            return find_gcd(a, b >> 1);\r\n        else\r\n            return find_gcd(min(a, b), (max(a, b) - min(a, b) ) >> 1);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, maximum = 0, number, no_of_numbers_at_end, i, no_of_turns, gcd;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    for(i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        scanf(\"%d\", &number);\r\n        maximum = max(maximum, number);\r\n        gcd = (i == 1 ? number : find_gcd(gcd, number) );\r\n    }\r\n    no_of_numbers_at_end = maximum/gcd;\r\n    no_of_turns = no_of_numbers_at_end - no_of_numbers;\r\n\r\n    printf(no_of_turns%2 == 1 ? \"Alice\\n\" : \"Bob\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/An_Abandoned_Sentiment_From_Past.c",
    "content": "#include <stdio.h>\r\n\r\n#define MAX_LENGTH 100 + 1\r\n#define true 1\r\n#define false 0\r\n\r\nint main()\r\n{\r\n    int a[MAX_LENGTH], missing_number, zero_index = -1, no_of_zeroes, entire_length,i, is_possible = false;\r\n    scanf(\"%d %d\",&entire_length, &no_of_zeroes);\r\n\r\n    for(i = 0; i < entire_length; i++)\r\n    {\r\n        scanf(\"%d\", &a[i]);\r\n\r\n        if(a[i] == 0)\r\n            zero_index = i;\r\n        else if(i > 0 && a[i] <= a[i - 1])\r\n            is_possible = true;\r\n\r\n    }\r\n    for(i = 0; i < no_of_zeroes; i++)\r\n        scanf(\"%d\",&missing_number);\r\n\r\n    //If there is more than one zero, it is always possible to make the sequence non-increasing.\r\n    if(no_of_zeroes > 1)\r\n    {\r\n        is_possible = true;\r\n    }\r\n    else\r\n    {\r\n        if(zero_index == 0)\r\n        {\r\n            if(missing_number >= a[zero_index + 1])\r\n                is_possible = true;\r\n        }\r\n        else if(zero_index == entire_length - 1)\r\n        {\r\n            if(missing_number <= a[zero_index - 1])\r\n                is_possible = true;\r\n        }\r\n        else if(missing_number >= a[zero_index + 1] || missing_number <= a[zero_index - 1])\r\n        {\r\n            is_possible = true;\r\n        }\r\n    }\r\n\r\n\r\n    printf(is_possible ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Andrushya_and_Socks.c",
    "content": "#include <stdio.h>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define MAX_SIZE 100000 + 1\r\n\r\nint no_of_socks[MAX_SIZE] = {0};\r\nint main()\r\n{\r\n    int current_sock_type, i, no_of_sock_types, no_of_socks_on_table = 0, max_no_of_socks_on_table = 0;\r\n    scanf(\"%d\", &no_of_sock_types);\r\n\r\n    for(i = 1; i < 2*no_of_sock_types; i++)\r\n    {\r\n        scanf(\"%d\", &current_sock_type);\r\n        no_of_socks[current_sock_type]++;\r\n\r\n        if(no_of_socks[current_sock_type] == 1)\r\n            no_of_socks_on_table++;\r\n        else if(no_of_socks[current_sock_type] == 2)\r\n            no_of_socks_on_table--;\r\n\r\n        max_no_of_socks_on_table = max(max_no_of_socks_on_table, no_of_socks_on_table);\r\n    }\r\n\r\n    printf(\"%d\\n\",max_no_of_socks_on_table);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Combination Lock.cpp",
    "content": "#include <stdio.h>\r\n#include <algorithm>\r\n#define MAX_LENGTH 1000 + 1\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    char current_state[MAX_LENGTH], final_state[MAX_LENGTH];\r\n    int number_of_moves = 0, number_of_locks;\r\n    scanf(\"%d %s %s\", &number_of_locks, current_state, final_state);\r\n\r\n    for(int i = 0; i < number_of_locks; i++)\r\n    {\r\n        int start, ending;\r\n        start = min(current_state[i], final_state[i]) - '0';\r\n        ending = max(current_state[i], final_state[i]) - '0';\r\n\r\n        number_of_moves += min(ending - start,  10 + start - ending); //Optimal to go forwards or backwards\r\n    }\r\n\r\n    printf(\"%d\\n\", number_of_moves);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Devu_Singer_Charu_Joker.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_songs, total_time_for_songs = 0, minutes_current_song, i, total_time_available, minimum_performance_time, maximum_jokes = -1;\r\n    const int minutes_for_charu_joke = 5;\r\n\r\n    scanf(\"%d %d\", &no_of_songs, &total_time_available);\r\n    for(i = 1; i <= no_of_songs; i++)\r\n    {\r\n        scanf(\"%d\", &minutes_current_song);\r\n        total_time_for_songs += minutes_current_song;\r\n    }\r\n\r\n    minimum_performance_time = total_time_for_songs + (no_of_songs - 1)*2*minutes_for_charu_joke;\r\n\r\n    if(minimum_performance_time <= total_time_available)\r\n    {\r\n        maximum_jokes = (no_of_songs - 1)*2 + (total_time_available - minimum_performance_time)/(minutes_for_charu_joke);\r\n    }\r\n\r\n    printf(\"%d\\n\",maximum_jokes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Fake_NP.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    unsigned int left_limit, right_limit;\r\n    scanf(\"%u %u\",&left_limit, &right_limit);\r\n\r\n    printf(left_limit != right_limit ? \"2\\n\" : \"%u\\n\",left_limit);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Fence.c",
    "content": "#include <stdio.h>\r\n\r\n#define MAX_LENGTH 150000 + 1\r\nint heights[MAX_LENGTH];\r\n\r\nint main()\r\n{\r\n    int i, no_of_planks, k, k_consecutive_sum = 0, minimum_k_consecutive_sum = 1e9, start_of_minimum_sum;\r\n    scanf(\"%d %d\", &no_of_planks, &k);\r\n\r\n    for(i = 1; i <= no_of_planks; i++)\r\n    {\r\n        scanf(\"%d\", &heights[i]);\r\n\r\n        k_consecutive_sum += (i <= k ? heights[i] : heights[i] - heights[i - k]);\r\n\r\n        if(i >= k && k_consecutive_sum <= minimum_k_consecutive_sum)\r\n        {\r\n            minimum_k_consecutive_sum = k_consecutive_sum;\r\n            start_of_minimum_sum = (i - k + 1);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\",start_of_minimum_sum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Find_Marble.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nint main()\r\n{\r\n    int no_of_glasses, initial_position, final_position, minimum_shuffles = 0, i;\r\n    scanf(\"%d %d %d\", &no_of_glasses, &initial_position, &final_position);\r\n\r\n    int *shuffled_result = malloc((no_of_glasses + 1)*sizeof(int));\r\n    for(i = 1; i <= no_of_glasses;  i++)\r\n        scanf(\"%d\", (shuffled_result + i) );\r\n\r\n     for(i = initial_position; ; i = *(shuffled_result + i), minimum_shuffles++)\r\n        if( (i == initial_position && minimum_shuffles!= 0) || (i == final_position) )\r\n            break;\r\n\r\n\r\n    printf(\"%d\\n\", (i == final_position ?  minimum_shuffles : -1) );//\r\n\r\n    free(shuffled_result);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Free Ice Cream.cpp",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_people, distressed_kids = 0;\r\n    long long ice_cream;\r\n    scanf(\"%d %I64d\", &no_of_people, &ice_cream);\r\n\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        char action;\r\n        int amount;\r\n        scanf(\" %c %d\", &action, &amount);\r\n\r\n        if(action == '+')\r\n            ice_cream += amount;\r\n        else\r\n            if(amount > ice_cream)\r\n                distressed_kids++;\r\n            else\r\n                ice_cream -= amount;\r\n    }\r\n    printf(\"%I64d %d\\n\", ice_cream, distressed_kids);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Hexadecimal's Theorem Alternate Solution.cpp",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    printf(\"0 0 %d\\n\", n);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Hexadecimal's Theorem.cpp",
    "content": "#include <stdio.h>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvector <int> fibonacci;\r\n\r\nvoid precompute_fibonacci()\r\n{\r\n    const int MAX = 1e9;\r\n\r\n    fibonacci.push_back(0);\r\n    fibonacci.push_back(1);\r\n\r\n    for(int i = 2; fibonacci[i - 1] + fibonacci[i - 2] <= MAX; i++)\r\n        fibonacci.push_back(fibonacci[i - 1] + fibonacci[i - 2]);\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_fibonacci();\r\n\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    if(n == 0) //F(0)\r\n        printf(\"0 0 0\\n\");\r\n    else if(n == 1)//F(1) and F(2)\r\n        printf(\"1 0 0\\n\");\r\n    else if(n == 2) //F(3)\r\n        printf(\"1 1 0\\n\");\r\n    else\r\n    {\r\n        int index = 4;\r\n\r\n        while(fibonacci[index] != n)\r\n         index++;\r\n\r\n        printf(\"%d %d %d\\n\",fibonacci[index - 1], fibonacci[index - 3], fibonacci[index - 4]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/IQ_Test.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, number, no_of_even_numbers = 0, no_of_odd_numbers = 0, last_even_index, last_odd_index, i;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    for(i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        scanf(\"%d\", &number);\r\n\r\n        if(number%2 == 0)\r\n            no_of_even_numbers++, last_even_index = i;\r\n        else\r\n            no_of_odd_numbers++, last_odd_index = i;\r\n    }\r\n\r\n    printf(\"%d\\n\", (no_of_even_numbers == 1 ? last_even_index : last_odd_index) );\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Magnets.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_magnets, i, no_of_magnet_groups = 0;\r\n    char previous_orientation = 'X', current_orientation, current_magnet[3];\r\n    scanf(\"%d\", &no_of_magnets);\r\n\r\n    for(i = 1; i <= no_of_magnets; previous_orientation = current_orientation, i++)\r\n    {\r\n        scanf(\"%s\",current_magnet);\r\n        current_orientation = current_magnet[0];\r\n\r\n        if(previous_orientation != current_orientation)\r\n            no_of_magnet_groups++;\r\n    }\r\n\r\n    printf(\"%d\\n\",no_of_magnet_groups);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Mahmod_Longest_Uncommon_Subsequence.c",
    "content": "#include <stdio.h>\r\n#include <string.h>\r\n\r\n#define max(a, b) (a > b  ? a : b)\r\n#define MAX_LENGTH 100000\r\nint main()\r\n{\r\n    char string_1[MAX_LENGTH + 1], string_2[MAX_LENGTH + 1];\r\n    scanf(\"%s %s\",string_1, string_2);\r\n\r\n    printf(\"%d\\n\", (strcmp(string_1, string_2) != 0 ? max( strlen(string_1),strlen(string_2) ) : -1) );\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Monster_and_Squirrel.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int number_of_vertices;\r\n    long long number_of_regions;\r\n    scanf(\"%d\",&number_of_vertices);\r\n\r\n    //Each vertex had (n - 3) lines drawn from it. Since, there are no intersections, each line increases the number of regions by 1.\r\n    number_of_regions = (number_of_vertices - 2)*1LL*(number_of_vertices - 2);\r\n    printf(\"%I64d\\n\",number_of_regions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/New Year Transportation.cpp",
    "content": "#include <stdio.h>\r\n#include <vector>\r\n#define INFINITY 1e9\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_cells, destination;\r\n    scanf(\"%d %d\", &number_of_cells, &destination);\r\n\r\n    vector <int> number_of_jumps(number_of_cells);\r\n    vector <int> visited(number_of_cells + 1, false);\r\n\r\n    for(int i = 1; i <= number_of_cells - 1; i++)\r\n        scanf(\"%d\", &number_of_jumps[i]);\r\n\r\n    number_of_jumps[number_of_cells] = INFINITY;\r\n\r\n    for(int next_cell = 1; next_cell <= number_of_cells; next_cell += number_of_jumps[next_cell])\r\n        visited[next_cell] = true;\r\n\r\n    printf(visited[destination] ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Optimal_Point_on_a_Line.cpp",
    "content": "#include <stdio.h>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\n#define MAX_POINTS 300000 + 1\r\nint points[MAX_POINTS];\r\n\r\nint main()\r\n{\r\n    int no_of_points, median, i;\r\n    scanf(\"%d\",&no_of_points);\r\n\r\n    for(i = 0; i < no_of_points; i++)\r\n        scanf(\"%d\", &points[i]);\r\n\r\n    sort(points, points + no_of_points);\r\n    median = points[(no_of_points - 1)/2];\r\n\r\n    printf(\"%d\\n\",median);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Pashmak_and_Flowers.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_minima = 0, no_of_maxima = 0, most_beautiful = 0, least_beautiful = 1e9 + 1, no_of_flowers, current_beauty, i;\r\n    long long no_of_choices;\r\n    scanf(\"%d\", &no_of_flowers);\r\n\r\n    for(i = 1; i <= no_of_flowers; i++)\r\n    {\r\n        scanf(\"%d\",&current_beauty);\r\n\r\n        if(current_beauty == most_beautiful)\r\n            no_of_maxima++;\r\n\r\n        if(current_beauty == least_beautiful)\r\n            no_of_minima++;\r\n\r\n        if(current_beauty < least_beautiful)\r\n            least_beautiful = current_beauty, no_of_minima = 1;\r\n\r\n        if(current_beauty > most_beautiful)\r\n            most_beautiful = current_beauty, no_of_maxima = 1;\r\n    }\r\n\r\n    //If all flowers are equally beautiful, then choices = n(n-1)/2\r\n    no_of_choices = ( most_beautiful == least_beautiful ? (no_of_flowers*1LL*(no_of_flowers - 1) )/2 : no_of_minima*1LL*no_of_maxima );\r\n\r\n    printf(\"%d %I64d\\n\",(most_beautiful - least_beautiful), no_of_choices);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Potions_Homework.cpp",
    "content": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nlong long laziness[100001];\r\nint main()\r\n{\r\n    const int MOD = 1e4 + 7;\r\n    int no_of_students, i;\r\n    long long minimum_time = 0LL;\r\n    ios::sync_with_stdio(false);\r\n\tcin.tie(0);\r\n    cin >> no_of_students;\r\n\r\n    for(i = 0; i < no_of_students; i++)\r\n        cin >> laziness[i];\r\n\r\n    sort(laziness, laziness + no_of_students);\r\n\r\n    for(i = 0; i < no_of_students; i++)\r\n        minimum_time = (minimum_time + laziness[i]*laziness[no_of_students - i - 1])%MOD;\r\n\r\n    cout << minimum_time;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Pythagorean Triples.cpp",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int side_1;\r\n    long long side_2, side_3, k;\r\n    scanf(\"%d\", &side_1);\r\n\r\n    if(side_1 <= 2)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    /*If n is even, n^2 = 4k, then (2k - 1)^2 + 4k = (2k + 1)^2\r\n    a = root(4k), b = k - 1, c = k + 1\r\n\r\n    If n is odd, n^2 = (2k + 1),\r\n    a = root(2k + 1), b = k, c = k + 1*/\r\n\r\n    if(side_1%2 == 0)\r\n    {\r\n        k = (side_1*1ll*side_1)/4;\r\n\r\n        side_2 = (k - 1);\r\n        side_3 = (k + 1);\r\n    }\r\n    else\r\n    {\r\n        k = ( (side_1*1LL*side_1) - 1)/2;\r\n        side_2 = k;\r\n        side_3 =(k + 1);\r\n    }\r\n\r\n    printf(\"%I64d %I64d\\n\" ,side_2, side_3);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Red_Blue_Balls.c",
    "content": "#include <stdio.h>\r\n#define MAX_SIZE 50\r\n\r\nint main()\r\n{\r\n    long long equivalent_number = 0LL;\r\n    int no_of_balls, i;\r\n    char stack[MAX_SIZE + 1];\r\n\r\n    scanf(\"%d %s\", &no_of_balls, stack);\r\n\r\n    for(i = 0; i < no_of_balls; i++)\r\n        if(stack[i] == 'B')\r\n            equivalent_number = equivalent_number| (1LL << i);\r\n\r\n    printf(\"%I64d\\n\",equivalent_number);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/The_Contest.c",
    "content": "#include <stdio.h>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define max(a, b) (a > b ? a : b)\r\nint main()\r\n{\r\n    int no_of_problems, i, time_i_problem, total_time = 0, no_of_time_periods, minimum_time;\r\n    int start_time[1001], end_time[1001];\r\n    scanf(\"%d\", &no_of_problems);\r\n\r\n    for(i = 1; i <= no_of_problems; i++)\r\n    {\r\n        scanf(\"%d\", &time_i_problem);\r\n        total_time += time_i_problem;\r\n    }\r\n\r\n    scanf(\"%d\", &no_of_time_periods);\r\n    for(i = 0; i < no_of_time_periods; i++)\r\n        scanf(\"%d %d\", &start_time[i], &end_time[i]);\r\n\r\n    for(i = 0; i < no_of_time_periods && total_time > end_time[i]; i++);\r\n\r\n    minimum_time = (i == no_of_time_periods ? -1 : max(start_time[i], total_time) );\r\n\r\n    printf(\"%d\\n\",minimum_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 7/Young_Physicist.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_vectors, total_x = 0, x, total_y = 0, y, total_z = 0, z, i;\r\n    scanf(\"%d\", &no_of_vectors);\r\n\r\n    for(i = 1; i <= no_of_vectors; i++)\r\n    {\r\n        scanf(\"%d %d %d\",&x, &y, &z);\r\n        total_x += x;\r\n        total_y += y;\r\n        total_z += z;\r\n    }\r\n\r\n    printf(total_x == 0 && total_y == 0 && total_z == 0 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/A and B Team Training.cpp",
    "content": "#include <stdio.h>\r\n\r\n#define min(a,b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int experienced_people_no, newbie_no, no_of_available_people;\r\n    int no_of_teams;\r\n    scanf(\"%d %d\", &experienced_people_no, &newbie_no);\r\n\r\n    no_of_teams = min(experienced_people_no, newbie_no);\r\n\r\n    /*No of teams cannot exceed the min(E, N) ... We choose the highest configuration possible.\r\n    To check if a configuration is possible, make I teams of (E, N, _) and then check if the third spot can be filled in all i teams.*/\r\n    while(no_of_teams > 0)\r\n    {\r\n        no_of_available_people = (experienced_people_no + newbie_no) - 2*no_of_teams;\r\n\r\n        if(no_of_available_people >= no_of_teams)\r\n            break;\r\n\r\n        no_of_teams--;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_teams);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Almost Prime.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvector <int> no_of_almost_primes_till(3000 + 1, 0);\r\n\r\nvoid precompute_primes()\r\n{\r\n    vector <int> no_of_prime_factors(3000 + 1, 0);\r\n\r\n    for(int i = 2; i <= 3000; i++)\r\n    {\r\n        if(no_of_prime_factors[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple <= 3000; multiple += i)\r\n            {\r\n                no_of_prime_factors[multiple]++;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= 3000; i++)\r\n    {\r\n        no_of_almost_primes_till[i] = no_of_almost_primes_till[i - 1] + (no_of_prime_factors[i] == 2);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_primes();\r\n\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(\"%d\\n\", no_of_almost_primes_till[n]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Brian's Photos.cpp",
    "content": "#include <stdio.h>\n\nint main()\n{\n    bool is_colourful = false;\n    int no_of_rows, no_of_columns;\n    scanf(\"%d %d\", &no_of_rows, &no_of_columns);\n\n    for(int row = 1; row <= no_of_rows; row++)\n    {\n        for(int column = 1; column <= no_of_columns; column++)\n        {\n            char colour;\n            scanf(\" %c\", &colour);\n\n            if(colour != 'B' && colour != 'G' && colour != 'W')\n                is_colourful = true;\n        }\n    }\n\n    printf(is_colourful ? \"#Color\\n\" : \"#Black&White\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs - 8/Caisa and Pylons.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_plyons;\r\n    scanf(\"%d\", &number_of_plyons);\r\n\r\n    vector <int> height (number_of_plyons + 1);\r\n    for(int i = 1; i <= number_of_plyons; i++)\r\n        scanf(\"%d\", &height[i]);\r\n\r\n    int money_needed = height[1];\r\n    int energy = 0;\r\n    for(int i = 1; i <= number_of_plyons - 1; i++)\r\n    {\r\n        energy += (height[i] - height[i + 1]);\r\n\r\n        if(energy < 0)\r\n        {\r\n            money_needed += abs(energy);\r\n            energy = 0;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", money_needed);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Choosing Teams.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(),(v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_people, number_of_attempts;\r\n    scanf(\"%d %d\", &number_of_people, &number_of_attempts);\r\n\r\n    vector <int> attempts (number_of_people);\r\n    for(int i = 0; i < number_of_people; i++)\r\n        scanf(\"%d\", &attempts[i]);\r\n\r\n    sort(all(attempts));\r\n\r\n    int no_of_teams = 0, i = 0;\r\n    while(i + 2 < number_of_people && (attempts[i +2] + number_of_attempts) <= 5)\r\n    {\r\n        i += 3;\r\n        no_of_teams++;\r\n    }\r\n\r\n    printf(\"%d\\n\",no_of_teams);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Ciel and Flowers.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define min_3(a, b, c) min(a, min(b, c) )\r\n#define max_3(a, b, c) max(a, max(b, c) )\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int green, red, blue;\r\n    scanf(\"%d %d %d\",&red, &green, &blue);\r\n\r\n    int one_mixed_boquet = 0, two_mixed_boquet = 0, no_mixed_boquet;\r\n\r\n    no_mixed_boquet = red/3 + green/3 + blue/3;\r\n\r\n    if(min_3(red,green, blue) >= 1)\r\n        one_mixed_boquet = 1 + (red - 1)/3 + (green - 1)/3 + (blue - 1)/3;\r\n    if(min_3(red, green, blue) >= 2)\r\n        two_mixed_boquet = 2 + (red - 2)/3 + (green - 2)/3 + (blue - 2)/3;\r\n\r\n    printf(\"%d\\n\",max_3(no_mixed_boquet, two_mixed_boquet, one_mixed_boquet));\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Diverse Permutation.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    int current_number, previous_number;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    for(int i = 1; i <= k + 1; i++)\r\n    {\r\n        if(i == 1)\r\n            current_number = 1;\r\n        else\r\n            current_number = (i%2 == 0 ? k + 2 - previous_number : k + 3 - previous_number);\r\n\r\n        printf(\"%d \", current_number);\r\n\r\n        previous_number = current_number;\r\n    }\r\n\r\n    for(int i = k + 2; i <= n; i++)\r\n    {\r\n        printf(\"%d \",i);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/HQ9+.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 100 + 1\r\n\r\nint main()\r\n{\r\n    bool produces_output = false;\r\n    char program[MAX_LENGTH];\r\n    scanf(\"%s\", program);\r\n\r\n    for(int i = 0; program[i] != '\\0'; i++)\r\n    {\r\n        if(program[i] == 'H' || program[i] == 'Q' || program[i] == '9')\r\n        {\r\n            produces_output = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(produces_output ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Hexadecimal's Numbers.cpp",
    "content": "#include <stdio.h>\r\n\r\nint corresponding_decimal(int bitmask)\r\n{\r\n    int decimal = 0;\r\n\r\n    //Get the bitmask in decimal For example, 11 should be eleven .. So, we treat it like a polynomial, multiply decimal by 10 at each step and add\r\n    //it to whatever bit was there ... 11 will be 1*10 + 1.\r\n    for(int i = 31; i >= 0; i--)\r\n    {\r\n        decimal = decimal*10 + ( (bitmask & (1 << i) ) != 0) ;\r\n    }\r\n    return decimal;\r\n}\r\n\r\nint main()\r\n{\r\n    int limit, no_of_saved_numbers = 0;\r\n    scanf(\"%d\", &limit);\r\n\r\n    int max_numbers = (1 << 10) - 1; //At most 2^10 - 1 numbers\r\n    for(int bitmask = 1; bitmask <= max_numbers; bitmask++)\r\n    {\r\n        if(corresponding_decimal(bitmask) > limit)\r\n            break;\r\n\r\n        no_of_saved_numbers++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_saved_numbers);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Infinite Sequence.cpp",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    long long nearest_end, position, i;\r\n    scanf(\"%I64d\", &position);\r\n\r\n    i = 0;\r\n    while(i*(i + 1)/2 < position)\r\n        i++;\r\n\r\n    i--;\r\n    nearest_end = i*(i + 1)/2 ;\r\n\r\n    printf(\"%I64d\\n\",(position - nearest_end));\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Jzzhu and Sequences.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    const int MOD = 1e9 + 7;\r\n    int X, Y, number_of_terms;\r\n    long long answer;\r\n\r\n    scanf(\"%d %d %d\", &X, &Y, &number_of_terms);\r\n\r\n    X = (X + MOD)%MOD;\r\n    Y = (Y + MOD)%MOD;\r\n\r\n    switch(number_of_terms%6)\r\n    {\r\n        case 1: answer = X; break;\r\n\r\n        case 2: answer = Y; break;\r\n\r\n        case 3: answer = Y + MOD - X; break;\r\n\r\n        case 4: answer = 0 + MOD - X; break;\r\n\r\n        case 5: answer = 0 + MOD - Y; break;\r\n\r\n        case 0: answer = X + MOD - Y; break;\r\n    }\r\n\r\n    answer = (answer + MOD)%MOD; //In case it's negative\r\n\r\n    printf(\"%I64d\\n\",answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/K-Factorisation.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    unsigned int n, number_of_factors;\r\n    scanf(\"%d %d\", &n, &number_of_factors);\r\n\r\n    vector <int> factor;\r\n    for(unsigned int i = 2; i <= n ; i++)\r\n    {\r\n        while(n%i == 0)\r\n        {\r\n            if(factor.size() == number_of_factors)\r\n                factor.back() *=i;\r\n            else\r\n                factor.push_back(i);\r\n\r\n            n = n/i;\r\n        }\r\n    }\r\n\r\n    if(factor.size() < number_of_factors)\r\n        printf(\"-1\\n\");\r\n    else\r\n        for(unsigned int i = 0; i < number_of_factors; i++)\r\n            printf(\"%d \",factor[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Noldbach Problem.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvector <int> noldbach_number(1000 + 1, false);\r\nvector <int> primes;\r\n\r\nvoid precompute_noldbach()\r\n{\r\n    vector <int> is_prime(1000 + 1, true);\r\n\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= 1000; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            for(int multiple = 2*i; multiple <= 1000; multiple += i)\r\n            {\r\n                is_prime[multiple] = false;\r\n            }\r\n            primes.push_back(i);\r\n        }\r\n    }\r\n\r\n    for(int i = 0; primes[i] + primes[i + 1] <= 1000 ; i++)\r\n    {\r\n        noldbach_number[primes[i] + primes[i + 1] + 1] = true;\r\n    }\r\n\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_noldbach();\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    int conjecture_count = 0;\r\n    for(int i = 0; primes[i] <= n; i++)\r\n    {\r\n        if(noldbach_number[primes[i]])\r\n            conjecture_count++;\r\n    }\r\n\r\n    printf(conjecture_count >= k ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Olesya and Rodion.cpp",
    "content": "#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_digits, multiple;\r\n    scanf(\"%d %d\", &number_of_digits, &multiple);\r\n\r\n    if(number_of_digits == 1 && multiple == 10)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"%d\", multiple);\r\n\r\n        int no_of_zeroes = (multiple == 10 ? number_of_digits - 2 : number_of_digits - 1);\r\n\r\n        for(int zero_count = 1; zero_count <= no_of_zeroes; zero_count++)\r\n            printf(\"0\");\r\n    }\r\n\r\n    printf(\"\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Petr and Book.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_pages;\r\n    scanf(\"%d\", &no_of_pages);\r\n\r\n    int i;\r\n    vector <int> pages_read_on_day(7);\r\n    for(i = 0; i < 7; i++)\r\n        scanf(\"%d\", &pages_read_on_day[i]);\r\n\r\n\r\n    i = 0;\r\n    while(true)\r\n    {\r\n         no_of_pages -= pages_read_on_day[i];\r\n\r\n        if(no_of_pages <= 0)\r\n            break;\r\n\r\n        i = (i + 1)%7;\r\n    }\r\n\r\n    printf(\"%d\\n\",i + 1);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Petya and Strings.cpp",
    "content": "#include <cstdio>\r\n#include <string.h>\r\n\r\n#define MAX_LENGTH 100 + 1\r\n#define tolower(c) (c < 'a' ? (c + 'a' - 'A') : c)\r\n\r\nint main()\r\n{\r\n    char string_1[MAX_LENGTH], string_2[MAX_LENGTH];\r\n    scanf(\"%s %s\", string_1, string_2);\r\n\r\n    for(int i = 0; string_1[i] != '\\0'; i++)\r\n    {\r\n        if(tolower(string_1[i]) > tolower(string_2[i]) )\r\n        {\r\n            printf(\"1\\n\");\r\n            return 0;\r\n        }\r\n        else if(tolower(string_1[i]) < tolower(string_2[i]) )\r\n        {\r\n            printf(\"-1\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    printf(\"0\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Sum of Digits.cpp",
    "content": "#include <stdio.h>\r\n\r\n#define MAX_LENGTH 100000 + 1\r\n\r\nint find_digit_sum(int n)\r\n{\r\n    int sum = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        sum += n%10;\r\n        n /= 10;\r\n    }\r\n    return sum;\r\n}\r\n\r\nint main()\r\n{\r\n    char number[MAX_LENGTH];\r\n    int i, digit_sum = 0, no_of_spells = 0;\r\n    scanf(\"%s\", number);\r\n\r\n    if(number[1] != '\\0')\r\n    {\r\n        for(i = 0; number[i] != '\\0'; i++)\r\n            digit_sum += (number[i] - '0');\r\n\r\n        no_of_spells = 1;\r\n        while(digit_sum >= 10)\r\n        {\r\n            no_of_spells++;\r\n            digit_sum = find_digit_sum(digit_sum);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_spells);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/T Primes  Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <math.h>\r\n\r\nusing namespace std;\r\n\r\nvector <int> is_prime(1000000 + 1, true);\r\n\r\nvoid precompute_prime_squares()\r\n{\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= 1e6; i++)\r\n        if(is_prime[i])\r\n            for(int multiple = 2*i; multiple <= 1e6; multiple += i)\r\n                is_prime[multiple] = false;\r\n\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    precompute_prime_squares();\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        long long number, root;\r\n        scanf(\"%I64d\", &number);\r\n\r\n        root = (int) sqrt(number);\r\n\r\n        printf(root*root == number && is_prime[root] ? \"YES\\n\" : \"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/T-Primes.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nset <long long> prime_square;\r\n\r\nvoid precompute_prime_squares()\r\n{\r\n    vector <int> is_prime(1000000 + 1, true);\r\n\r\n    for(int i = 2; i <= 1e6; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            prime_square.insert(i*1LL*i);\r\n\r\n            for(int multiple = 2*i; multiple <= 1e6; multiple += i)\r\n                is_prime[multiple] = false;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    precompute_prime_squares();\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        long long number;\r\n        scanf(\"%I64d\", &number);\r\n\r\n        printf(prime_square.count(number) == 1 ? \"YES\\n\" : \"NO\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/The Golden Age.cpp",
    "content": "#include <stdio.h>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(),(v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    unsigned int a, b, i;\r\n    long long x, y, left_limit, right_limit, max_lucky_years = 0, current_lucky_run;\r\n\r\n    scanf(\"%I64d %I64d %I64d %I64d\",&x, &y, &left_limit, &right_limit);\r\n\r\n    vector <long long> powers_of_x;\r\n    vector <long long> powers_of_y;\r\n    vector <long long> sums_of_powers_x_y; //All the unlucky years.\r\n\r\n    powers_of_x.push_back(1);\r\n    while(powers_of_x.back() <= right_limit/x)\r\n    {\r\n        powers_of_x.push_back(x*powers_of_x.back());\r\n    }\r\n\r\n    powers_of_y.push_back(1);\r\n    while(powers_of_y.back() <= right_limit/y)\r\n    {\r\n        powers_of_y.push_back(y*powers_of_y.back());\r\n    }\r\n\r\n    sums_of_powers_x_y.push_back(left_limit - 1);\r\n    sums_of_powers_x_y.push_back(right_limit + 1);\r\n    for(a = 0; a < powers_of_x.size(); a++)\r\n    {\r\n        for(b = 0; b < powers_of_y.size(); b++)\r\n        {\r\n            sums_of_powers_x_y.push_back(powers_of_x[a] + powers_of_y[b]);\r\n        }\r\n    }\r\n\r\n    sort( all(sums_of_powers_x_y) );\r\n\r\n    i = 0;\r\n    while(sums_of_powers_x_y[i] < left_limit - 1)\r\n        i++;\r\n\r\n    i++;\r\n    while(sums_of_powers_x_y[i] <= right_limit + 1 && i < sums_of_powers_x_y.size())\r\n    {\r\n        current_lucky_run = sums_of_powers_x_y[i] - sums_of_powers_x_y[i - 1] - 1;\r\n\r\n        max_lucky_years = max(max_lucky_years, current_lucky_run);\r\n        i++;\r\n    }\r\n\r\n    printf(\"%I64d\\n\",max_lucky_years);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Two Bags of Potatos.cpp",
    "content": "#include <stdio.h>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n   int x, y, limit, k, sum;\r\n   scanf(\"%d %d %d\",&y, &k, &limit);\r\n\r\n   vector <int> possibilities;\r\n   int no_of_possibilities = 0;\r\n\r\n   for(sum = k, x = sum - y; sum <= limit; sum += k, x = sum - y)\r\n   {\r\n       if(x > 0)\r\n       {\r\n           no_of_possibilities++;\r\n           possibilities.push_back(x);\r\n       }\r\n\r\n    }\r\n\r\n   if(no_of_possibilities == 0)\r\n        printf(\"-1\\n\");\r\n   else\r\n        for(int i = 0; i < no_of_possibilities; i++)\r\n            printf(\"%d\\t\",possibilities[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Vanya and Cards.cpp",
    "content": "#include <cstdio>\r\n\r\n#define abs(x) ( (x) > 0 ? (x) : -(x) )\r\n\r\nint main()\r\n{\r\n    int number_of_cards, maximum, card_i;\r\n    scanf(\"%d %d\", &number_of_cards, &maximum);\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= number_of_cards; i++)\r\n    {\r\n        scanf(\"%d\", &card_i);\r\n        sum += card_i;\r\n    }\r\n\r\n    int no_of_cards_required = 0;\r\n    sum = abs(sum);\r\n\r\n    if(sum != 0)\r\n        no_of_cards_required = sum/maximum + (sum%maximum != 0);\r\n\r\n    printf(\"%d\\n\", no_of_cards_required);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Vitaly and Night.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_floors, no_of_flats, open, awake_people = 0;\r\n    scanf(\"%d %d\", &no_of_floors, &no_of_flats);\r\n\r\n    for(int i = 1; i <= no_of_floors; i++)\r\n    {\r\n        for(int j = 1; j <= no_of_flats; j++)\r\n        {\r\n            bool is_awake = false;\r\n            for(int window = 1; window <= 2; window++)\r\n            {\r\n                scanf(\"%d\", &open);\r\n\r\n                if(open == 1)\r\n                    is_awake = true;\r\n            }\r\n\r\n            awake_people += (is_awake == true);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", awake_people);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Wet Shark and Odd and Even.cpp",
    "content": "#include <stdio.h>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int min_odd_number, number_of_elements, number_i;\r\n    long long sum = 0;\r\n    scanf(\"%d\", &number_of_elements);\r\n\r\n    min_odd_number = 1e9 + 1;\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &number_i);\r\n        sum += number_i;\r\n\r\n        if(number_i%2 == 1)\r\n            min_odd_number = min(min_odd_number, number_i);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", sum%2 == 0 ? sum : sum - min_odd_number);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 8/Yaroslav and Permutations.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_elements, element_i;\r\n    scanf(\"%d\", &number_of_elements);\r\n\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        frequency[element_i]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n        max_frequency = max(max_frequency, it->second);\r\n\r\n    int half_size = number_of_elements/2 + number_of_elements%2;\r\n\r\n    printf(max_frequency > half_size ? \"NO\\n\" : \"YES\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Alyona and Copybooks.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define min_3(a, b, c) min(a, min(b, c))\r\n\r\nint main()\r\n{\r\n    int no_of_books, price_1, price_2, price_3;\r\n    scanf(\"%d %d %d %d\", &no_of_books, &price_1, &price_2, &price_3);\r\n\r\n    long long minimum_amount = 0;\r\n\r\n    switch(no_of_books%4)\r\n    {\r\n        case 1: minimum_amount = min_3(price_1*3LL, price_1 + price_2, price_3);\r\n                break;\r\n\r\n        case 2: minimum_amount = min_3(price_1*2LL, price_2, price_3*2LL);\r\n                break;\r\n\r\n        case 3: minimum_amount = min_3(price_1, price_2 + price_3, price_3*3LL);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", minimum_amount);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Appleman and Toastman.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_groups;\r\n    long long answer = 0;\r\n    scanf(\"%d\", &no_of_groups);\r\n\r\n    vector <int> group(no_of_groups + 1, 0);\r\n    for(int i = 1; i <= no_of_groups; i++)\r\n    {\r\n        scanf(\"%d\", &group[i]);\r\n    }\r\n\r\n\r\n    sort(all(group));\r\n    for(unsigned int i = group.size() - 1; i >= 1; i--)\r\n    {\r\n        int no_of_times_i_is_counted = (i == group.size() - 1 ? i : i + 1);\r\n        answer += no_of_times_i_is_counted*1LL*group[i];\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(),(v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    vector <int> zero; vector <int> positive; vector <int> negative;\r\n\r\n    int no_of_elements, zero_start;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n\r\n    sort(all(element));\r\n\r\n    if(element.back() > 0)\r\n    {\r\n        positive.push_back(element.back());\r\n        element.pop_back();\r\n\r\n        negative.push_back(element.front());\r\n\r\n        zero_start = 1;\r\n    }\r\n    else\r\n    {\r\n        positive.push_back(element[0]);\r\n        positive.push_back(element[1]);\r\n\r\n        negative.push_back(element[2]);\r\n\r\n        zero_start = 3;\r\n    }\r\n\r\n    for(unsigned int i = zero_start; i < element.size(); i++)\r\n            zero.push_back(element[i]);\r\n\r\n    printf(\"1 %d\\n\",negative.back());\r\n\r\n    printf(\"%u \", positive.size() );\r\n    for(unsigned int i = 0; i < positive.size(); i++)\r\n        printf(\"%d \",positive[i]);\r\n\r\n    printf(\"\\n%u \", zero.size());\r\n    for(unsigned int i = 0; i < zero.size(); i++)\r\n        printf(\"%d \",zero[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Bear and Five Cards.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    map <int, int> frequency;\r\n    const int no_of_cards = 5;\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= no_of_cards; i++)\r\n    {\r\n        int card_i;\r\n        scanf(\"%d\", &card_i);\r\n\r\n        sum += card_i;\r\n        frequency[card_i]++;\r\n    }\r\n\r\n    int max_subtracted = 0;\r\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        int number_i = it->first;\r\n        int frequency_i = it->second;\r\n        int subtracted_amount = 0;\r\n\r\n        if(frequency_i > 1)\r\n        {\r\n            subtracted_amount = (frequency_i > 2 ? 3*number_i : 2*number_i);\r\n        }\r\n\r\n        max_subtracted = max(max_subtracted, subtracted_amount);\r\n    }\r\n\r\n    printf(\"%d\\n\", sum - max_subtracted);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Bus to Udayland.cpp",
    "content": "#include <cstdio>\r\n\r\n#define ROW_LENGTH 5 + 1\r\n#define MAX_ROWS 1000 + 1\r\n\r\nint main()\r\n{\r\n    char bus_seating[MAX_ROWS][ROW_LENGTH];\r\n    int no_of_rows;\r\n    scanf(\"%d\", &no_of_rows);\r\n\r\n    bool can_sit_together = false;\r\n\r\n    for(int i = 0; i < no_of_rows; i++)\r\n    {\r\n        scanf(\"%s\", bus_seating[i]);\r\n\r\n        if(bus_seating[i][0] == 'O' && bus_seating[i][1] == 'O' && can_sit_together == false)\r\n        {\r\n            bus_seating[i][0] = bus_seating[i][1] = '+';\r\n            can_sit_together = true;\r\n        }\r\n\r\n        if(bus_seating[i][3] == 'O' && bus_seating[i][4] == 'O' && can_sit_together == false)\r\n        {\r\n            bus_seating[i][3] = bus_seating[i][4] = '+';\r\n            can_sit_together = true;\r\n        }\r\n    }\r\n\r\n    if(can_sit_together)\r\n    {\r\n        printf(\"YES\\n\");\r\n        for(int i = 0; i < no_of_rows; i++)\r\n            printf(\"%s\\n\",bus_seating[i]);\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Case of the Zeroes and Ones.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 200000 + 1\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    char sequence[MAX_LENGTH];\r\n    int length, no_of_zeroes = 0, no_of_ones = 0;\r\n    scanf(\"%d %s\", &length, sequence);\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        no_of_zeroes += (sequence[i] == '0');\r\n        no_of_ones += (sequence[i] == '1');\r\n    }\r\n\r\n    int no_of_survivors = length - 2*min(no_of_ones, no_of_zeroes);\r\n\r\n    printf(\"%d\\n\", no_of_survivors);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Circle Line.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_stations, start, destination;\r\n    scanf(\"%d\", &no_of_stations);\r\n\r\n    vector <int> distance(no_of_stations + 1);\r\n    for(int i = 1; i <= no_of_stations; i++)\r\n        scanf(\"%d\", &distance[i]);\r\n\r\n    scanf(\"%d %d\", &start, &destination);\r\n\r\n    int straight_distance = 0;\r\n    for(int i = start; i != destination; i = (i == no_of_stations ? 1 : i + 1))\r\n        straight_distance += distance[i];\r\n\r\n    int round_distance = 0;\r\n    for(int i = destination; i != start; i = (i == no_of_stations ? 1 : i + 1))\r\n        round_distance += distance[i];\r\n\r\n    printf(\"%d\\n\", min(straight_distance, round_distance));\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Crazy Computer.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_words, minute_i, maximum_break;\r\n    scanf(\"%d %d\", &no_of_words, &maximum_break);\r\n\r\n    int previous_minute = 0, no_of_words_on_screen = 0;\r\n    for(int i = 1; i <= no_of_words; i++)\r\n    {\r\n        scanf(\"%d\", &minute_i);\r\n        no_of_words_on_screen = (minute_i - previous_minute <= maximum_break ? no_of_words_on_screen + 1 : 1);\r\n\r\n        previous_minute = minute_i;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_words_on_screen);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Crossword Solving.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define MAX_LENGTH 1000 + 1\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int key_length, text_length;\r\n    char key[MAX_LENGTH], text[MAX_LENGTH];\r\n    scanf(\"%d %d %s %s\", &key_length, &text_length, key, text);\r\n\r\n    vector <int> change(key_length + 1);\r\n    vector <int> current_change;\r\n\r\n    for(int i = 0; i + key_length <= text_length ; i++)\r\n    {\r\n        current_change.clear();\r\n\r\n        for(int j = 0; j < key_length; j++)\r\n        {\r\n            if(key[j] != text[i + j])\r\n            {\r\n                current_change.push_back(j);\r\n            }\r\n        }\r\n\r\n        if(current_change.size() < change.size())\r\n        {\r\n            change = current_change;\r\n        }\r\n    }\r\n\r\n    printf(\"%u\\n\", change.size());\r\n\r\n    if(change.size() > 0)\r\n    {\r\n        for(unsigned int i = 0; i < change.size(); i++)\r\n            printf(\"%d \", change[i] + 1);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Divisibility.cpp",
    "content": "#include <cstdio>\r\n\r\n#define abs(x) ( (x) > 0 ? (x) : -(x) )\r\n#define max(a, b) (a > b ? a : b)\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    long long k, left, right, no_of_multiples = 0;\r\n    scanf(\"%I64d %I64d %I64d\", &k, &left, &right);\r\n\r\n    if(right > 0 && left < 0)\r\n    {\r\n        left = abs(left);\r\n\r\n        no_of_multiples = (right)/k + (left)/k + 1; //Add 0 as a multiple as well.\r\n    }\r\n    else\r\n    {\r\n        long long greater_limit = max(abs(right), abs(left));\r\n        long long lower_limit = min(abs(right), abs(left));\r\n\r\n        if(lower_limit == 0)\r\n        {\r\n            no_of_multiples = (greater_limit)/k + 1; //Count 0 as well\r\n        }\r\n        else\r\n        {\r\n            no_of_multiples = (greater_limit)/k - (lower_limit - 1)/k;\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_multiples);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Fox and Number Game.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, element_i, array_gcd;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        array_gcd = (i == 1 ? element_i : gcd(array_gcd, element_i));\r\n    }\r\n\r\n    printf(\"%d\\n\", array_gcd*no_of_elements);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Haiku.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 100 + 2\r\n\r\nbool is_vowel(char ch)\r\n{\r\n    switch(ch)\r\n    {\r\n        case 'a':\r\n        case 'e':\r\n        case 'i':\r\n        case 'o':\r\n        case 'u':\r\n                    return true;\r\n        default :\r\n                    return false;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    bool is_haiku = true;\r\n    char line[MAX_LENGTH];\r\n    const int no_of_lines = 3;\r\n\r\n    for(int i = 1; i <= no_of_lines; i++)\r\n    {\r\n        int vowel_count = 0;\r\n\r\n        fgets(line, MAX_LENGTH, stdin);\r\n\r\n        for(int letter = 0; line[letter] != '\\n'; letter++)\r\n            vowel_count += is_vowel(line[letter]);\r\n\r\n        if(i == 2)\r\n        {\r\n            if(vowel_count != 7)\r\n                is_haiku = false;\r\n        }\r\n        else\r\n        {\r\n            if(vowel_count != 5)\r\n                is_haiku = false;\r\n        }\r\n    }\r\n\r\n    printf(is_haiku ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/I'm Bored with Life.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint factorial(int n)\r\n{\r\n    int fact = 1;\r\n\r\n    while(n > 0)\r\n    {\r\n        fact *= n;\r\n        n--;\r\n    }\r\n\r\n    return fact;\r\n}\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n\r\n    printf(\"%d\\n\", factorial(min(a, b)));\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Is your Horseshoe on the other hoof.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    map <int, int> frequency;\r\n    int  hoof_i, no_of_hooves = 4;\r\n\r\n    for(int i = 1; i <= no_of_hooves;i++)\r\n    {\r\n        scanf(\"%d\", &hoof_i);\r\n        frequency[hoof_i]++;\r\n    }\r\n\r\n    int no_of_new_hooves = 0;\r\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        int frequency_i = it->second;\r\n\r\n        no_of_new_hooves += frequency_i - 1; //Keep one copy and throw the rest\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_new_hooves);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Kitahara Haruki's Gift.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_apples, weight_i;\r\n    scanf(\"%d\", &no_of_apples);\r\n\r\n    int no_of_100s = 0, no_of_200s = 0;\r\n    for(int i = 1; i <= no_of_apples; i++)\r\n    {\r\n        scanf(\"%d\", &weight_i);\r\n\r\n        no_of_100s += (weight_i == 100);\r\n        no_of_200s += (weight_i == 200);\r\n    }\r\n\r\n    no_of_200s = (no_of_200s%2); //Distribute half of them to either group.\r\n    no_of_100s = no_of_100s - 2*no_of_200s; //Balancing out the 200;\r\n\r\n    printf(no_of_100s%2 == 0 && no_of_100s >= 0 ? \"YES\\n\" : \"NO\\n\"); //check if remaining 100s can be divided in half.\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Little Elephant and Function.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    printf(\"%d \", no_of_elements);\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        printf(\"%d \", i);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Little Elephant and Problem.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> original_array(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &original_array[i]);\r\n\r\n    vector <int> sorted_array = original_array;\r\n\r\n    sort(all(sorted_array));\r\n\r\n    int differences = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        differences += (sorted_array[i] != original_array[i]);\r\n\r\n    printf(differences <= 2 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/New Year and Days.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_TIME_LENGTH 5 + 1\r\n\r\nint main()\r\n{\r\n    int savings = 0, date;\r\n    char of[2 + 1], time_period[MAX_TIME_LENGTH];\r\n    scanf(\"%d %s %s\", &date ,of, time_period); //Scanf reads a string till it encounters a whitespace ... so I used two strings.\r\n\r\n    if(time_period[0] == 'm') //Month\r\n    {\r\n        savings = 12*(date <= 29) + 11*(date == 30) + 7*(date == 31); //Only one of these can be true.\r\n    }\r\n    else if(time_period[0] == 'w') //Week\r\n    {\r\n        savings = 52 + (date == 5 || date == 6); // Days 6 and 7 occur one more time\r\n    }\r\n\r\n    printf(\"%d\\n\", savings);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/One Dimensional Japanese Crossword.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define MAX_LENGTH 100 + 1\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_blocks, segment_length;\r\n    char crossword[MAX_LENGTH];\r\n\r\n    scanf(\"%d %s\", &no_of_blocks, crossword);\r\n\r\n    vector <int> black_segment_length;\r\n    for(int i = 0; i < no_of_blocks; i += segment_length + 1)\r\n    {\r\n        segment_length = 0;\r\n        while(crossword[i + segment_length] == 'B')\r\n        {\r\n             segment_length++;\r\n        }\r\n\r\n        if(segment_length > 0)\r\n            black_segment_length.push_back(segment_length);\r\n    }\r\n\r\n    printf(\"%u\\n\", black_segment_length.size());\r\n    for(unsigned int i = 0; i < black_segment_length.size(); i++)\r\n        printf(\"%d \",black_segment_length[i]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Present from Lena.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    for(int row = 0; row <= n; row++)\r\n    {\r\n        for(int space = 0; space < n - row; space++)\r\n            printf(\"  \");\r\n\r\n        for(int number = 0; number <= row; number++)\r\n            if(row == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        for(int number = row - 1; number >= 0; number--)\r\n            if(number == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    for(int row = n - 1; row >= 0; row--)\r\n    {\r\n        for(int space = 0; space < n - row; space++)\r\n            printf(\"  \");\r\n\r\n        for(int number = 0; number <= row; number++)\r\n            if(row == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        for(int number = row - 1; number >= 0; number--)\r\n            if(number == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Prime Matrix.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\n#define min(a, b) (a < b ? a : b)\n\nusing namespace std;\n\nvector <int> prime_distance(1e5 + 4);\n\nvoid precompute_prime_distance()\n{\n    vector <int> is_prime(1e5 + 10, true);\n\n    is_prime[0] = is_prime[1] = false;\n    for(int i = 2; i <= 1e5 + 3; i++)\n    {\n        if(is_prime[i])\n        {\n            for(int multiple = 2*i; multiple <= 1e5 + 3; multiple += i)\n            {\n                is_prime[multiple] = false;\n            }\n        }\n    }\n\n    int last_prime;\n    for(int i = 1e5 + 3; i >= 0; i--)\n    {\n        if(is_prime[i])\n            last_prime = i;\n\n        prime_distance[i] = last_prime - i;\n    }\n}\n\nint main()\n{\n    const int INFINITY = 1e9 + 1;\n    int no_of_rows, no_of_columns;\n    scanf(\"%d %d\", &no_of_rows, &no_of_columns);\n\n    precompute_prime_distance();\n\n    vector <vector <int> > matrix(no_of_rows, vector<int> (no_of_columns) );\n\n    for(int row = 0; row < no_of_rows; row++)\n    {\n        for(int column = 0; column < no_of_columns; column++)\n        {\n            int element;\n            scanf(\"%d\", &element);\n\n            matrix[row][column] = prime_distance[element];\n        }\n    }\n\n    int min_row_sum = INFINITY;\n    for(int row = 0; row < no_of_rows; row++)\n    {\n        int row_sum = 0;\n        for(int column = 0; column < no_of_columns; column++)\n        {\n            row_sum += matrix[row][column];\n        }\n        min_row_sum = min(min_row_sum, row_sum);\n    }\n\n    int min_column_sum = INFINITY;\n    for(int column = 0; column < no_of_columns; column++)\n    {\n        int column_sum = 0;\n        for(int row = 0; row < no_of_rows; row++)\n        {\n            column_sum += matrix[row][column];\n        }\n        min_column_sum = min(min_column_sum, column_sum);\n    }\n\n    printf(\"%d\\n\",min(min_row_sum, min_column_sum));\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs - 9/String Task.cpp",
    "content": "#include <iostream>\r\n#include <cstdio>\r\n#include <string>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\n#define to_lower(ch) ( ch += (ch >= 'A' && ch <= 'Z' ?  'a' - 'A' : 0) )\r\n#define MAX_LENGTH 100 + 2\r\n\r\nbool is_vowel(char ch)\r\n{\r\n    switch(ch)\r\n    {\r\n        case 'a':\r\n        case 'e':\r\n        case 'i':\r\n        case 'o':\r\n        case 'u':\r\n        case 'y':\r\n                    return true;\r\n        default :\r\n                    return false;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    char initial_string[MAX_LENGTH];\r\n    string answer;\r\n    scanf(\"%s\", initial_string);\r\n\r\n    for(int i = 0; initial_string[i] != '\\0'; i++)\r\n    {\r\n        if(is_vowel(to_lower(initial_string[i])) == false)\r\n        {\r\n            answer += '.';\r\n            answer += to_lower(initial_string[i]);\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Subtractions.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint no_of_steps_in_finding_gcd(int a, int b)\r\n{\r\n    int m = min(a, b);\r\n    int n = max(a, b);\r\n\r\n    if(m == 0)\r\n        return 0;\r\n    else\r\n        return n/m + no_of_steps_in_finding_gcd(m, n%m);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n    printf(\"%d\\n\", no_of_steps_in_finding_gcd(a, b) );\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/Toy Army.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int number_of_soldiers, killed;\r\n    scanf(\"%d\", &number_of_soldiers);\r\n\r\n    killed = 3*((number_of_soldiers + 1)/2);\r\n    printf(\"%d\\n\", killed);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs - 9/k-th_Divisor.cpp",
    "content": "#include <stdio.h>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(),(v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long num, answer;\r\n    unsigned int k, max_number_of_divisors;\r\n    scanf(\"%I64d %d\", &num, &k);\r\n\r\n    vector <int> divisors;\r\n    for(int i = 1; i*1LL*i <= num; i++)\r\n        if(num%i == 0)\r\n            divisors.push_back(i);\r\n\r\n    max_number_of_divisors = 2*divisors.size();\r\n\r\n    if(divisors.back()*1LL*divisors.back() == num)\r\n        max_number_of_divisors--; //Square root gets counted twice\r\n\r\n    if(k > max_number_of_divisors)\r\n    {\r\n        answer = -1;\r\n    }\r\n    else\r\n    {\r\n        if(k <= divisors.size())\r\n            answer = divisors[k - 1];\r\n        else //If k and k' are indices such that f(k)*f(k') = N, k + k' = f - 1, where f is the number of factors, k' =  f - k - 1, in 1-index.\r\n            answer = num/divisors[max_number_of_divisors - k ]; \r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/A and B Compilation Errors.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    int no_of_errors, error_i;\n    scanf(\"%d\", &no_of_errors);\n\n    int sum_1 = 0;\n    for(int i = 1; i <= no_of_errors; i++)\n    {\n        scanf(\"%d\", &error_i);\n        sum_1 += error_i;\n    }\n\n    //Second List\n    int sum_2 = 0;\n    for(int i = 1; i <= no_of_errors - 1; i++)\n    {\n        scanf(\"%d\", &error_i);\n        sum_2 += error_i;\n    }\n\n    int sum_3 = 0;\n    for(int i = 1; i <= no_of_errors - 2; i++)\n    {\n        scanf(\"%d\", &error_i);\n        sum_3 += error_i;\n    }\n\n\n    printf(\"%d \\n%d\\n\", sum_1-sum_2, sum_2 - sum_3);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 10/Amr and Music.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\ntypedef pair <int, int> int_pair;\r\n\r\nint main()\r\n{\r\n    int no_of_instruments, no_of_days, day_i;\r\n    scanf(\"%d %d\", &no_of_instruments, &no_of_days);\r\n\r\n    vector < int_pair > no_of_days_to_learn;\r\n    for(int i = 0; i < no_of_instruments; i++)\r\n    {\r\n        scanf(\"%d\", &day_i);\r\n        no_of_days_to_learn.push_back( make_pair(day_i, i + 1));\r\n    }\r\n\r\n    sort(all(no_of_days_to_learn));\r\n\r\n    vector <int> learnt_instrument;\r\n    for(int i = 0; i < no_of_instruments && no_of_days > 0; i++)\r\n    {\r\n        no_of_days -= no_of_days_to_learn[i].first;\r\n\r\n        if(no_of_days >= 0)\r\n            learnt_instrument.push_back(no_of_days_to_learn[i].second);\r\n    }\r\n\r\n    printf(\"%u\\n\", learnt_instrument.size());\r\n    for(unsigned int i = 0; i < learnt_instrument.size(); i++)\r\n            printf(\"%d \", learnt_instrument[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Arrival of General.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_soldiers;\r\n    scanf(\"%d\", &no_of_soldiers);\r\n\r\n    const int oo = 100 + 1;\r\n    int tallest_soldier = 0, shortest_soldier = oo;\r\n    int leftmost_tallest = -1, rightmost_shortest = -1;\r\n\r\n    for(int i = 1; i <= no_of_soldiers; i++)\r\n    {\r\n        int height_i;\r\n        scanf(\"%d\", &height_i);\r\n\r\n        if(height_i > tallest_soldier)\r\n        {\r\n            tallest_soldier = height_i;\r\n            leftmost_tallest = i;\r\n        }\r\n\r\n        if(height_i <= shortest_soldier)\r\n        {\r\n            shortest_soldier = height_i;\r\n            rightmost_shortest = i;\r\n        }\r\n    }\r\n\r\n    int no_of_swaps = 0;\r\n\r\n    if(leftmost_tallest < rightmost_shortest)\r\n        no_of_swaps = (leftmost_tallest - 1) + (no_of_soldiers - rightmost_shortest);\r\n    else\r\n        no_of_swaps = (leftmost_tallest - 1) + (no_of_soldiers - rightmost_shortest) - 1;\r\n\r\n    printf(\"%d\\n\", no_of_swaps);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Bear and Game.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_interesting_minutes, interesting_minute_i, tv_on_minutes = 0;\r\n    scanf(\"%d\", &no_of_interesting_minutes);\r\n\r\n    bool tv_on = true;\r\n\r\n    vector <int> interesting_minute;\r\n    interesting_minute.push_back(0);\r\n    for(int i = 1; i <= no_of_interesting_minutes; i++)\r\n    {\r\n        scanf(\"%d\", &interesting_minute_i);\r\n        interesting_minute.push_back(interesting_minute_i);\r\n    }\r\n\r\n    if(interesting_minute.back() != 90)\r\n        interesting_minute.push_back(90);\r\n\r\n    for(unsigned int i = 1; i < interesting_minute.size() ; i++)\r\n    {\r\n        if(tv_on)\r\n        {\r\n            int boring_interval = (interesting_minute[i] - 1) - interesting_minute[i - 1];\r\n\r\n            if(boring_interval >= 15)\r\n            {\r\n                tv_on_minutes += 15;\r\n                tv_on = false;\r\n            }\r\n            else\r\n            {\r\n                tv_on_minutes += boring_interval + 1; //Watch the boring interval + the interesting minute\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", tv_on_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Beautiful Year.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_beautiful(int year)\r\n{\r\n    vector <int> digit_frequency(10, 0);\r\n    while(year > 0)\r\n    {\r\n        digit_frequency[year%10]++;\r\n\r\n        year = year/10;\r\n    }\r\n\r\n    for(int i = 0; i < 10; i++)\r\n        if(digit_frequency[i] > 1)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int year;\r\n    scanf(\"%d\", &year);\r\n\r\n    int beautiful_year;\r\n    for(beautiful_year = year + 1; ; beautiful_year++)\r\n        if(is_beautiful(beautiful_year))\r\n            break;\r\n\r\n    printf(\"%d\\n\", beautiful_year);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Black Square.cpp",
    "content": "#include <cstdio>\n#include <algorithm>\n\nusing namespace std;\n\n#define MAX_LENGTH 100 + 5\n\nint main()\n{\n    int no_of_rows, no_of_columns;\n    scanf(\"%d %d\", &no_of_rows, &no_of_columns);\n    char rectangle[MAX_LENGTH][MAX_LENGTH];\n\n    int no_of_black_squares = 0, left_most = no_of_columns + 1, right_most = -1, highest = -1, lowest = no_of_rows + 1;\n\n    for(int i = 0; i < no_of_rows; i++)\n    {\n        scanf(\"%s\", rectangle[i]);\n\n        for(int j = 0; j < no_of_columns; j++)\n        {\n            if(rectangle[i][j] == 'B')\n            {\n                no_of_black_squares ++;\n\n                left_most = min(left_most, j);\n                right_most = max(right_most, j);\n\n                highest = max(highest, i);\n                lowest = min(lowest, i);\n            }\n        }\n    }\n\n    int square_rows = highest - lowest + 1, square_columns = right_most - left_most + 1;\n    int square_side = max(square_columns, square_rows);\n    int repainted = -1;\n\n    if(no_of_black_squares == 0)\n    {\n        repainted = 1;\n    }\n    else if(square_side <= min(no_of_rows, no_of_columns))\n    {\n        repainted = square_side*square_side - no_of_black_squares;\n    }\n\n    printf(\"%d\\n\", repainted);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 10/Counterexample.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    long long range = right - (left - 1);\r\n    if(range < 3 || (left%2 == 1 && range < 4))\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else\r\n    {\r\n        if(left%2 == 0)\r\n            printf(\"%I64d %I64d %I64d\", left, left + 1, left + 2);\r\n        else\r\n            printf(\"%I64d %I64d %I64d\", left + 1, left + 2, left + 3);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Difference Row.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> sequence(no_of_elements);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &sequence[i]);\r\n\r\n    sort(all(sequence));\r\n\r\n    swap(sequence[0], sequence.back());\r\n\r\n    for(unsigned int i = 0; i < sequence.size(); i++)\r\n        printf(\"%d \", sequence[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Eugene and Array.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries, no_of_1 = 0, no_of_minus_1 = 0;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        no_of_1 += (element_i == 1);\r\n        no_of_minus_1 += (element_i == -1);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        int left, right, range;\r\n        scanf(\"%d %d\", &left, &right);\r\n\r\n        range = right - (left - 1);\r\n        printf(range%2 == 0 && no_of_1 >= range/2 && no_of_minus_1 >= range/2 ? \"1\\n\" : \"0\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Interesting Drink.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <iostream>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_shops;\r\n    scanf(\"%d\", &no_of_shops);\r\n\r\n    vector <int> price_in_shop(no_of_shops);\r\n    for(int i = 0; i < no_of_shops; i++)\r\n        scanf(\"%d\", &price_in_shop[i]);\r\n\r\n    sort(all(price_in_shop));\r\n\r\n    int no_of_days, budget_day_i;\r\n    scanf(\"%d\", &no_of_days);\r\n\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        scanf(\"%d\", &budget_day_i);\r\n        int no_of_eligible_shops = upper_bound(all(price_in_shop), budget_day_i) - price_in_shop.begin();\r\n\r\n        printf(\"%d\\n\",no_of_eligible_shops); //0 indexed vector so no need to subtract 1.\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Keyboard Layouts.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\n#define NO_OF_ALPHABETS 26\r\n#define MAX_LENGTH 1000 + 2\r\n#define tolower(ch) (ch >= 'A' && ch <= 'Z' ? ch + 'a' - 'A' : ch)\r\n#define tocapital(ch) (ch >= 'a' && ch <= 'z' ? ch - ('a' - 'A') : ch)\r\n#define isalpha(ch) (tolower(ch) >= 'a' && tolower(ch) <= 'z' ? true : false)\r\n#define is_capital(ch) (ch >= 'A' && ch <= 'Z' ? true : false)\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    char keyboard_1[NO_OF_ALPHABETS], keyboard_2[NO_OF_ALPHABETS];\r\n    scanf(\"%s %s\", keyboard_1, keyboard_2);\r\n\r\n    map <char, char> corresponding_keyboard_2_char;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        corresponding_keyboard_2_char[ keyboard_1[i] ] = keyboard_2[i];\r\n    }\r\n\r\n    char text[MAX_LENGTH];\r\n    scanf(\"%s\", text);\r\n\r\n    for(int i = 0; text[i] != '\\0'; i++)\r\n    {\r\n        if(isalpha(text[i]))\r\n        {\r\n            char input = tolower(text[i]);\r\n            putchar(is_capital(text[i]) ? tocapital(corresponding_keyboard_2_char[input]) : corresponding_keyboard_2_char[input]);\r\n        }\r\n        else\r\n        {\r\n            putchar(text[i]); //Not there in the keyboards\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Life Without Zeroes.cpp",
    "content": "#include <cstdio>\r\n\r\nlong long reverse(long long n)\r\n{\r\n    long long reverse_n = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        reverse_n = reverse_n*10 + n%10;\r\n        n = n/10;\r\n    }\r\n    return reverse_n;\r\n}\r\n\r\nlong long zeroless(long long n)\r\n{\r\n    long long zeroless_n = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        int digit = n%10;\r\n        if(digit != 0)\r\n            zeroless_n = zeroless_n*10 + digit;\r\n\r\n        n = n/10;\r\n    }\r\n    return reverse(zeroless_n);\r\n}\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n\r\n    printf(zeroless(a) + zeroless(b) == zeroless(a + b) ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Modified GCD.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint get_gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return get_gcd(max(a, b)%min(a, b), min(a, b));\r\n}\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n\r\n    int gcd = get_gcd(a, b);\r\n\r\n    vector <int> factors;\r\n    for(int i = 1; i*i <= gcd; i++)\r\n    {\r\n        if(gcd%i == 0)\r\n        {\r\n            if(i*i == gcd)\r\n            {\r\n                factors.push_back(i);\r\n            }\r\n            else\r\n            {\r\n                factors.push_back(i);\r\n                factors.push_back(gcd/i);\r\n            }\r\n        }\r\n    }\r\n\r\n    sort(all(factors));\r\n\r\n    int number_of_queries;\r\n    scanf(\"%d\", &number_of_queries);\r\n\r\n    for(int i = 1; i <= number_of_queries; i++)\r\n    {\r\n        int left, right, answer;\r\n        scanf(\"%d %d\", &left, &right);\r\n\r\n        int index = upper_bound(factors.begin(), factors.end(), right) - factors.begin(); //Returns 1 indexed\r\n        index--;\r\n\r\n        if(factors[index] < left)\r\n            answer = -1;\r\n        else\r\n            answer = factors[index];\r\n\r\n        printf(\"%d\\n\", answer);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Multi Judge Solving.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_problems, max_solved_difficulty;\r\n    scanf(\"%d %d\", &no_of_problems, &max_solved_difficulty);\r\n\r\n    vector <int> difficulty(no_of_problems);\r\n    for(int i = 0; i < no_of_problems; i++)\r\n    {\r\n        scanf(\"%d\", &difficulty[i]);\r\n    }\r\n\r\n    sort(all(difficulty));\r\n\r\n    int no_of_practice_problems_required = 0;\r\n    int range = 2*max_solved_difficulty;\r\n\r\n    for(int i = 0; i < no_of_problems; i++)\r\n    {\r\n        if(difficulty[i] > range)\r\n        {\r\n             while(difficulty[i] > range)\r\n            {\r\n                no_of_practice_problems_required++;\r\n\r\n                range = range*2;\r\n            }\r\n        }\r\n\r\n        range = max(2*difficulty[i], range);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_practice_problems_required);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Next Test.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    vector <int> is_used(3000 + 2, false);\r\n    int no_of_tests, test_i, default_for_next;\r\n    scanf(\"%d\", &no_of_tests);\r\n\r\n    for(int i = 1; i <= no_of_tests; i++)\r\n    {\r\n        scanf(\"%d\", &test_i);\r\n        is_used[test_i] = true;\r\n    }\r\n\r\n    for(int i = 1; i <= 3001; i++)\r\n    {\r\n        if(is_used[i] == false)\r\n        {\r\n            default_for_next = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", default_for_next);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Presents.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_people;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    vector <int> present_giver_of(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int gift_receiver;\r\n        scanf(\"%d\", &gift_receiver);\r\n\r\n        present_giver_of[gift_receiver] = i;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        printf(\"%d \", present_giver_of[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Serega and Coat Rack.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_hooks, fine, no_of_guests;\r\n    scanf(\"%d %d\", &no_of_hooks, &fine);\r\n\r\n    vector <int> hook_prices(no_of_hooks);\r\n    for(int i = 0; i < no_of_hooks; i++)\r\n        scanf(\"%d\", &hook_prices[i]);\r\n\r\n    sort(all(hook_prices));\r\n\r\n    scanf(\"%d\", &no_of_guests);\r\n\r\n    int unhappy_guests = max(no_of_guests - no_of_hooks, 0);\r\n    int total_fine = unhappy_guests*fine;\r\n\r\n    int no_of_satisfied_guests = no_of_guests - unhappy_guests;\r\n    int income = 0;\r\n    for(int i = 0; i < no_of_satisfied_guests; i++)\r\n        income += hook_prices[i];\r\n\r\n    printf(\"%d\\n\", income - total_fine);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Serega and Suffixes.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <unsigned int> no_of_distinct_elements_from_here(no_of_elements + 1, 0);\r\n    set <int> distinct_elements;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        distinct_elements.insert(element[i]);\r\n\r\n        no_of_distinct_elements_from_here[i] = distinct_elements.size();\r\n    }\r\n\r\n    for(int i = 0; i < no_of_queries; i++)\r\n    {\r\n        int start_i;\r\n        scanf(\"%d\", &start_i);\r\n        printf(\"%u\\n\", no_of_distinct_elements_from_here[start_i]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Slightly Decreasing Permutation.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    for(int i = 1; i <= k ; i++)\r\n        printf(\"%d \", n - (i - 1));\r\n\r\n    for(int i = 1; i + k <= n; i++)\r\n        printf(\"%d \", i);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/SwapSort.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    typedef pair <int, int> pair_int;\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <pair_int> swaps;\r\n    //Selection Sort\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        int min_i_index = i;\r\n        for(int j = i + 1; j < no_of_elements; j++)\r\n        {\r\n            if(element[j] < element[min_i_index])\r\n                min_i_index = j;\r\n        }\r\n\r\n        if(min_i_index != i)\r\n        {\r\n            swaps.push_back(make_pair(i, min_i_index));\r\n\r\n            swap(element[min_i_index], element[i]);\r\n        }\r\n    }\r\n\r\n    printf(\"%u\\n\", swaps.size());\r\n    for(unsigned int i = 0; i < swaps.size(); i++)\r\n    {\r\n        printf(\"%d %d\\n\", swaps[i].first, swaps[i].second);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Taxi.cpp",
    "content": "#include <cstdio>\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_groups;\r\n    scanf(\"%d\", &no_of_groups);\r\n\r\n    int no_of_1s = 0, no_of_2s = 0, no_of_3s = 0, no_of_4s = 0;\r\n    int group_i;\r\n    for(int i = 1; i <= no_of_groups; i++)\r\n    {\r\n        scanf(\"%d\", &group_i);\r\n\r\n        no_of_1s += (group_i == 1);\r\n        no_of_2s += (group_i == 2);\r\n        no_of_3s += (group_i == 3);\r\n        no_of_4s += (group_i == 4);\r\n    }\r\n\r\n    int no_of_rides_with_3_and_1 = min(no_of_3s, no_of_1s);\r\n\r\n    int no_of_rides = no_of_4s + no_of_rides_with_3_and_1 + no_of_2s/2;\r\n\r\n    //The remaining groups of 2s 3s and 4s\r\n    no_of_3s -= no_of_rides_with_3_and_1;\r\n    no_of_1s -= no_of_rides_with_3_and_1;\r\n    no_of_2s = no_of_2s%2;\r\n\r\n    no_of_rides += no_of_3s; //Pair up as many 3s with 1s and then the remaining 3s go alone.\r\n\r\n    //Pair of 1s with the remaining 2s\r\n    if(no_of_2s > 0)\r\n    {\r\n        no_of_1s -= 2;\r\n        no_of_rides++;\r\n    }\r\n\r\n    if(no_of_1s > 0)\r\n        no_of_rides += no_of_1s/4 + (no_of_1s%4 != 0);\r\n\r\n    printf(\"%d\\n\", no_of_rides);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Toy Cars.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_cars;\r\n    scanf(\"%d\", &no_of_cars);\r\n\r\n    vector <int> good_cars;\r\n\r\n    for(int i = 1; i <= no_of_cars; i++)\r\n    {\r\n        bool good_car = true;\r\n        for(int j = 1; j <= no_of_cars; j++)\r\n        {\r\n            int collision;\r\n            scanf(\"%d\", &collision);\r\n\r\n            if(collision == 1 || collision == 3)\r\n                good_car = false;\r\n        }\r\n\r\n        if(good_car)\r\n            good_cars.push_back(i);\r\n    }\r\n\r\n    printf(\"%u\\n\",good_cars.size());\r\n    for(unsigned int i = 0; i < good_cars.size(); i++)\r\n        printf(\"%d\\n\", good_cars[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Unimodal Arrays.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    bool is_unimodal = true;\r\n    int no_of_elements, element_i, element_i_minus_1 = 0, phase = 1;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n\r\n        if(phase == 1)\r\n        {\r\n            if(element_i < element_i_minus_1)//Phase 2 has only one element\r\n                phase = 3;\r\n            else if(element_i == element_i_minus_1)\r\n                phase = 2;\r\n        }\r\n        else if(phase == 2)\r\n        {\r\n            if(element_i > element_i_minus_1)\r\n                is_unimodal = false;\r\n            else if(element_i < element_i_minus_1)\r\n                phase = 3;\r\n        }\r\n        else if(phase == 3)\r\n        {\r\n            if(element_i >= element_i_minus_1)\r\n                is_unimodal = false;\r\n        }\r\n\r\n        element_i_minus_1 = element_i;\r\n    }\r\n\r\n    printf(is_unimodal ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Valera and Plates.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_days, no_of_bowls, no_of_plates;\r\n    scanf(\"%d %d %d\", &no_of_days, &no_of_bowls, &no_of_plates);\r\n\r\n    int no_of_cleanings = 0;\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        int dish_type;\r\n        scanf(\"%d\", &dish_type);\r\n\r\n        if(dish_type == 1)\r\n        {\r\n            if(no_of_bowls == 0)\r\n                no_of_cleanings++;\r\n            else\r\n                no_of_bowls--;\r\n        }\r\n\r\n        if(dish_type == 2)\r\n        {\r\n            if(no_of_plates == 0 && no_of_bowls == 0)\r\n                no_of_cleanings++;\r\n            else if(no_of_plates > 0)\r\n                no_of_plates--;\r\n            else\r\n                no_of_bowls--;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_cleanings);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 10/Vanya and Cubes.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n\tint no_of_cubes, height;\r\n\tscanf(\"%d\", &no_of_cubes);\r\n\r\n\tfor(height = 1; ; height++)\r\n\t{\r\n\t\tno_of_cubes -= (height*(height + 1))/2;\r\n\r\n        if(no_of_cubes < 0)\r\n            break;\r\n\t}\r\n\r\n\theight--;\r\n\tprintf(\"%d\\n\", height);\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/BerSU Ball.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\n\nusing namespace std;\n\nint main()\n{\n    int no_of_girls;\n    scanf(\"%d\", &no_of_girls);\n\n    vector <int> girl_skills(no_of_girls);\n    for(int i = 0; i < no_of_girls; i++)\n        scanf(\"%d\", &girl_skills[i]);\n\n    int no_of_boys;\n    scanf(\"%d\", &no_of_boys);\n\n    vector <int> boy_skills(no_of_boys);\n    for(int i = 0; i < no_of_boys; i++)\n        scanf(\"%d\", &boy_skills[i]);\n\n    sort(all(girl_skills));\n    sort(all(boy_skills));\n\n    vector <int> is_available(no_of_boys, true);\n\n    int no_of_pairs = 0;\n    for(int i = 0; i < no_of_girls; i++)\n    {\n        int eligible_boy = lower_bound(all(boy_skills), girl_skills[i] - 1) - boy_skills.begin();\n\n        for( ;abs(boy_skills[eligible_boy] - girl_skills[i]) <= 1 && eligible_boy < no_of_boys; eligible_boy++)\n        {\n            if(is_available[eligible_boy])\n            {\n                no_of_pairs++;\n                is_available[eligible_boy] = false;\n                break;\n            }\n        }\n    }\n\n    printf(\"%d\\n\", no_of_pairs);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 11/Elections.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_candidates, no_of_cities;\r\n    scanf(\"%d %d\", &no_of_candidates, &no_of_cities);\r\n\r\n    vector <int> no_of_wins_for(no_of_candidates + 1, 0);\r\n    for(int city_i = 1; city_i <= no_of_cities; city_i++)\r\n    {\r\n        int round_winner = 1, winner_votes = 0; //If everyone gets 0 votes, the first candidate must win.\r\n\r\n        for(int candidate_i = 1; candidate_i <= no_of_candidates; candidate_i++)\r\n        {\r\n            int votes;\r\n            scanf(\"%d\", &votes);\r\n\r\n            if(votes > winner_votes)\r\n            {\r\n                round_winner = candidate_i;\r\n                winner_votes = votes;\r\n            }\r\n        }\r\n\r\n        no_of_wins_for[round_winner]++;\r\n    }\r\n\r\n    int winner = 0;\r\n    for(int i = 1; i <= no_of_candidates; i++)\r\n        if(no_of_wins_for[i] > no_of_wins_for[winner])\r\n            winner = i;\r\n\r\n    printf(\"%d\\n\", winner);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Five in a Row.cpp",
    "content": "#include <cstdio>\r\n#define NO_OF_ROWS 10\r\n#define NO_OF_COLUMNS 10\r\n\r\nbool horizontal_win(char grid[][NO_OF_COLUMNS + 2], int i, int j)\r\n{\r\n    int no_of_crosses = 0, no_of_dots = 0;\r\n\r\n    for(int counter = 0; counter < 5 && i + counter < NO_OF_ROWS; counter++)\r\n    {\r\n        no_of_crosses += (grid[i + counter][j] == 'X');\r\n        no_of_dots += (grid[i + counter][j] == '.');\r\n    }\r\n\r\n    return (no_of_crosses == 4 && no_of_dots == 1 ? true : false);\r\n}\r\n\r\nbool vertical_win(char grid[][NO_OF_COLUMNS + 2], int i, int j)\r\n{\r\n    int no_of_crosses = 0, no_of_dots = 0;\r\n\r\n    for(int counter = 0; counter < 5 && j + counter < NO_OF_COLUMNS; counter++)\r\n    {\r\n        no_of_crosses += (grid[i][j + counter] == 'X');\r\n        no_of_dots += (grid[i][j + counter] == '.');\r\n    }\r\n\r\n    return (no_of_crosses == 4 && no_of_dots == 1 ? true : false);\r\n}\r\n\r\nbool diagonal_win(char grid[][NO_OF_COLUMNS + 2], int i, int j)\r\n{\r\n    int no_of_crosses = 0, no_of_dots = 0;\r\n\r\n    for(int counter = 0; counter < 5 && i + counter < NO_OF_ROWS && j + counter < NO_OF_COLUMNS; counter++)\r\n    {\r\n        no_of_crosses += (grid[i + counter][j + counter] == 'X');\r\n        no_of_dots += (grid[i + counter][j + counter] == '.');\r\n    }\r\n\r\n    return (no_of_crosses == 4 && no_of_dots == 1 ? true : false);\r\n}\r\n\r\nbool anti_diagonal_win(char grid[][NO_OF_COLUMNS + 2], int i, int j)\r\n{\r\n    int no_of_crosses = 0, no_of_dots = 0;\r\n\r\n    for(int counter = 0; counter < 5 && i + counter <= NO_OF_ROWS && j - counter >= 0; counter++)\r\n    {\r\n        no_of_crosses += (grid[i + counter][j - counter] == 'X');\r\n        no_of_dots += (grid[i + counter][j - counter] == '.');\r\n    }\r\n\r\n    return (no_of_crosses == 4 && no_of_dots == 1 ? true : false);\r\n}\r\n\r\nint main()\r\n{\r\n    bool win_possible = false;\r\n    char grid[NO_OF_ROWS][NO_OF_COLUMNS + 2];\r\n\r\n    for(int i = 0; i < NO_OF_ROWS; i++)\r\n        scanf(\"%s\", grid[i]);\r\n\r\n    for(int i = 0; i < NO_OF_ROWS; i++)\r\n    {\r\n        for(int j = 0; j < NO_OF_COLUMNS; j++)\r\n        {\r\n            if(horizontal_win(grid, i, j) || vertical_win(grid, i, j) || diagonal_win(grid, i, j) || anti_diagonal_win(grid, i, j))\r\n            {\r\n                win_possible = true;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(win_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Football.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define MAX_LENGTH 100 + 2\r\n\r\nint main()\r\n{\r\n    char players[MAX_LENGTH];\r\n    scanf(\"%s\", players);\r\n\r\n    int maximum_dangerous_sequence = 1, current_dangerous_sequence = 1;\r\n    for(int i = 1; players[i] != '\\0'; i++)\r\n    {\r\n        current_dangerous_sequence = (players[i] == players[i - 1] ? current_dangerous_sequence + 1 : 1);\r\n        maximum_dangerous_sequence = max(maximum_dangerous_sequence, current_dangerous_sequence);\r\n    }\r\n\r\n    printf(maximum_dangerous_sequence >= 7 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Fortune Telling.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int odd_oo = 1e9 + 1;\r\n    int no_of_flowers, answer;\r\n    scanf(\"%d\", &no_of_flowers);\r\n\r\n    int sum_of_even_numbers = 0, sum_of_odd_numbers = 0, smallest_odd_number = odd_oo;\r\n    for(int i = 1; i <= no_of_flowers; i++)\r\n    {\r\n        int petals;\r\n        scanf(\"%d\", &petals);\r\n\r\n        if(petals%2 == 0)\r\n            sum_of_even_numbers += petals;\r\n        else\r\n        {\r\n            sum_of_odd_numbers += petals;\r\n            smallest_odd_number = min(smallest_odd_number, petals);\r\n        }\r\n    }\r\n\r\n    if(sum_of_odd_numbers == 0)\r\n        answer = 0;\r\n    else\r\n        if(sum_of_odd_numbers%2 == 0)\r\n            answer = sum_of_even_numbers + sum_of_odd_numbers - smallest_odd_number; //To keep the sum odd\r\n        else if(sum_of_odd_numbers%2 == 1)\r\n            answer = sum_of_even_numbers + sum_of_odd_numbers;\r\n\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Free Cash Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_customers;\r\n    scanf(\"%d \", &no_of_customers);\r\n\r\n    int hour_i, minute_i, previous_hour = 0, previous_minute = 0;\r\n    int no_of_customers_at_this_time = 0, max_customers_arriving_together = 0;\r\n\r\n    for(int i = 1; i <= no_of_customers; i++)\r\n    {\r\n        scanf(\"%d %d\", &hour_i, &minute_i);\r\n\r\n        no_of_customers_at_this_time = (hour_i == previous_hour && minute_i == previous_minute ? no_of_customers_at_this_time + 1 : 1);\r\n\r\n        max_customers_arriving_together = max(max_customers_arriving_together, no_of_customers_at_this_time);\r\n\r\n        previous_hour = hour_i;\r\n        previous_minute = minute_i;\r\n    }\r\n\r\n    printf(\"%d\\n\", max_customers_arriving_together);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Free Cash.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int NO_OF_MINUTES_IN_HOUR = 60;\r\n    int no_of_customers, no_of_minutes, no_of_hours;\r\n    scanf(\"%d \", &no_of_customers);\r\n\r\n    map <int, int> no_of_customers_arriving_at;\r\n    for(int i = 1; i <= no_of_customers; i++)\r\n    {\r\n        scanf(\"%d %d\", &no_of_hours, &no_of_minutes);\r\n\r\n        int arrival_time = no_of_hours*NO_OF_MINUTES_IN_HOUR + no_of_minutes;\r\n        no_of_customers_arriving_at[arrival_time]++;\r\n    }\r\n\r\n    int max_customers_arriving_together = 0;\r\n    for(map <int, int> :: iterator it = no_of_customers_arriving_at.begin(); it != no_of_customers_arriving_at.end(); it++)\r\n    {\r\n        max_customers_arriving_together = max(max_customers_arriving_together, it->second);\r\n    }\r\n\r\n    printf(\"%d\\n\", max_customers_arriving_together);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Games.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_teams;\r\n    scanf(\"%d\", &no_of_teams);\r\n\r\n    vector <int> home_uniform(no_of_teams + 1);\r\n    map <int, int> no_of_guest_uniforms;\r\n    for(int i = 1; i <= no_of_teams; i++)\r\n    {\r\n        int guest_uniform;\r\n        scanf(\"%d %d\", &home_uniform[i], &guest_uniform);\r\n\r\n        no_of_guest_uniforms[guest_uniform]++;\r\n    }\r\n\r\n    int no_of_changes = 0;\r\n    for(int i = 1; i <= no_of_teams; i++)\r\n    {\r\n        no_of_changes += no_of_guest_uniforms[home_uniform[i]];\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_changes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Good Number.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, k;\r\n    scanf(\"%d %d\", &no_of_numbers, &k);\r\n\r\n    int good_numbers = 0;\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number, digit_present[10] = {false}, smallest_missing_digit = 0;\r\n        scanf(\"%d\", &number);\r\n\r\n        if(number == 0)\r\n            digit_present[0] = true;\r\n\r\n        while(number > 0)\r\n        {\r\n            digit_present[number%10] = true;\r\n            number = number/10;\r\n        }\r\n\r\n        while(digit_present[smallest_missing_digit] && smallest_missing_digit < 10)\r\n            smallest_missing_digit++;\r\n\r\n        good_numbers += (smallest_missing_digit > k);\r\n    }\r\n\r\n    printf(\"%d\\n\", good_numbers);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Johnny Likes Numbers.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    int next_multiple = n + (k - n%k);\r\n    printf(\"%d\\n\", next_multiple);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Lever.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 1000000 + 2\r\n\r\nint main()\r\n{\r\n    char lever[MAX_LENGTH];\r\n    scanf(\"%s\", lever);\r\n\r\n    bool left = true, right = false;\r\n    long long left_moment = 0, right_moment = 0, weights_till_here = 0;\r\n    int distance_from_pivot;\r\n\r\n    for(int i = 0; lever[i] != '\\0'; i++)\r\n    {\r\n        if(lever[i] == '^')\r\n        {\r\n            left = false, right = true;\r\n            distance_from_pivot = 0;\r\n        }\r\n        else\r\n        {\r\n            if(left)\r\n            {\r\n                if(lever[i] != '=')\r\n                    weights_till_here += (lever[i] - '0');\r\n\r\n                left_moment += weights_till_here;\r\n            }\r\n            else if(right)\r\n            {\r\n                distance_from_pivot++;\r\n\r\n                if(lever[i] != '=')\r\n                   right_moment += distance_from_pivot*(lever[i] - '0');\r\n            }\r\n        }\r\n    }\r\n\r\n    if(left_moment == right_moment)\r\n        printf(\"balance\\n\");\r\n    else\r\n        printf(left_moment > right_moment ? \"left\\n\" : \"right\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Lunch Rush.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_restaurants, time_limit;\r\n    scanf(\"%d %d\", &no_of_restaurants, &time_limit);\r\n\r\n    const int NEGATIVE_INFINITY = -1e9;\r\n    int maximum_joy = NEGATIVE_INFINITY;\r\n    for(int i = 1; i <= no_of_restaurants; i++)\r\n    {\r\n        int time_i, joy_i;\r\n        scanf(\"%d %d\", &joy_i, &time_i);\r\n\r\n        if(time_i <= time_limit)\r\n        {\r\n            maximum_joy = max(maximum_joy, joy_i);\r\n        }\r\n        else\r\n        {\r\n            maximum_joy = max(maximum_joy, joy_i - (time_i - time_limit));\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", maximum_joy);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Magic Spheres.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int blue, violet, orange;\r\n    scanf(\"%d %d %d\", &blue, &violet, &orange);\r\n\r\n    int required_blue, required_violet, required_orange;\r\n    scanf(\"%d %d %d\", &required_blue, &required_violet, &required_orange);\r\n\r\n    int no_of_new_spheres_possible = 0, no_of_new_spheres_needed = 0;\r\n\r\n    no_of_new_spheres_needed = max(required_blue - blue, 0) + max(required_orange - orange, 0) + max(required_violet - violet, 0);\r\n\r\n    no_of_new_spheres_possible = max( (blue - required_blue)/2, 0) + max( (orange - required_orange)/2, 0) + max( (violet - required_violet)/2, 0);\r\n\r\n    printf(no_of_new_spheres_possible >= no_of_new_spheres_needed ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/New Year and Hurry.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int travel_time, no_of_problems;\r\n    scanf(\"%d %d\", &no_of_problems, &travel_time);\r\n\r\n    const int NO_OF_MINUTES_IN_HOUR = 60;\r\n    int time = 4*NO_OF_MINUTES_IN_HOUR;\r\n\r\n    time = time - travel_time;\r\n\r\n    int solved_problems = 0;\r\n\r\n    for(int problem_i = 1; problem_i <= no_of_problems; problem_i++)\r\n    {\r\n        if(time - 5*problem_i >= 0)\r\n        {\r\n            time = time - 5*problem_i;\r\n            solved_problems++;\r\n        }\r\n        else //Time is insufficient\r\n        {\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", solved_problems);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Nicholas and Permutation.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int index_1, index_n;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n\r\n        if(element == 1)\r\n            index_1 = i;\r\n        else if(element == n)\r\n            index_n = i;\r\n    }\r\n\r\n    int distance = max( max(index_1, index_n) - 1, n - min(index_1, index_n) );\r\n\r\n    printf(\"%d\\n\", distance);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Petya and Staircases.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_steps, no_of_dirty_steps;\r\n    scanf(\"%d %d\", &no_of_steps, &no_of_dirty_steps);\r\n\r\n    vector <int> dirty_steps(no_of_dirty_steps);\r\n    for(int i = 0; i < no_of_dirty_steps; i++)\r\n        scanf(\"%d\", &dirty_steps[i]);\r\n\r\n    sort(all(dirty_steps));\r\n\r\n    bool is_possible = true;\r\n    if(no_of_dirty_steps > 0)\r\n    {\r\n        if(dirty_steps.front() == 1 || dirty_steps.back() == no_of_steps)\r\n        {\r\n            is_possible = false;\r\n        }\r\n        else\r\n        {\r\n            for(int i = 2; i < no_of_dirty_steps; i++)\r\n            {\r\n                if(dirty_steps[i] == dirty_steps[i - 1] + 1 && dirty_steps[i] == dirty_steps[i - 2] + 2) //Three consecutive dirty steps\r\n                {\r\n                    is_possible = false;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    printf(is_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Playing with Dice.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int num_1, num_2;\r\n    scanf(\"%d %d\", &num_1, &num_2);\r\n\r\n    int one_wins = 0, draw = 0, two_wins = 0;\r\n    for(int dice_i = 1; dice_i <= 6; dice_i++)\r\n    {\r\n        one_wins += (abs(num_1 - dice_i) < abs(num_2 - dice_i));\r\n        two_wins += (abs(num_1 - dice_i) > abs(num_2 - dice_i));\r\n        draw     += (abs(num_1 - dice_i) == abs(num_2 - dice_i));\r\n    }\r\n\r\n    printf(\"%d %d %d\", one_wins, draw, two_wins);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Saitama Destroys Hotel.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int  no_of_stops, top_floor;\r\n    scanf(\"%d %d\", &no_of_stops, &top_floor);\r\n\r\n    vector <int> floor_stop(no_of_stops);\r\n    vector <int> passenger_arrival_time(no_of_stops);\r\n    for(int i = 0; i < no_of_stops; i++)\r\n        scanf(\"%d %d\", &floor_stop[i], &passenger_arrival_time[i]);\r\n\r\n    reverse(all(floor_stop));\r\n    reverse(all(passenger_arrival_time));\r\n\r\n    int total_travel_time = 0, current_floor = top_floor;\r\n    for(int i = 0; i < no_of_stops; i++)\r\n    {\r\n        total_travel_time += (current_floor - floor_stop[i]);\r\n\r\n        int wait_time = max(passenger_arrival_time[i] - total_travel_time, 0);\r\n\r\n        total_travel_time += wait_time;\r\n\r\n        current_floor = floor_stop[i];\r\n    }\r\n    total_travel_time += current_floor; //Go to floor 0 from the last floor stop\r\n\r\n    printf(\"%d\\n\", total_travel_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Sasha and Sticks.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    long long no_of_sticks, one_turn_draw;\r\n    scanf(\"%I64d %I64d\", &no_of_sticks, &one_turn_draw);\r\n\r\n    long long no_of_turns = no_of_sticks/one_turn_draw;\r\n    printf(no_of_turns%2 == 1 ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Soft Drinking.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define min_3(a, b, c) min(a, min(b, c))\r\n\r\nint main()\r\n{\r\n    int no_of_friends , no_of_bottles, bottle_volume, no_of_limes, no_of_slices, total_salt, one_round_drink, one_round_salt;\r\n    scanf(\"%d %d %d %d\", &no_of_friends, &no_of_bottles, &bottle_volume, &no_of_limes);\r\n    scanf(\"%d %d %d %d\", &no_of_slices, &total_salt, &one_round_drink, &one_round_salt);\r\n\r\n    int no_of_toasts = min_3( (no_of_bottles*bottle_volume)/one_round_drink, no_of_limes*no_of_slices, total_salt/one_round_salt )/no_of_friends;\r\n    printf(\"%d\\n\", no_of_toasts);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/The Child and The Homework.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n#define MAX_LENGTH 100 + 2\r\n\r\nint main()\r\n{\r\n    typedef pair <int, char> int_char;\r\n\r\n    char option[MAX_LENGTH];\r\n    vector <int_char> option_length;\r\n\r\n    for(int i = 0; i < 4; i++)\r\n    {\r\n        scanf(\"%s\", option);\r\n        option_length.push_back(make_pair(strlen(option) - 2, 'A' + i)); //Excluding the alphabet and the .\r\n    }\r\n\r\n    sort(all(option_length));\r\n\r\n    char answer = 'C';\r\n    if(2*option_length[0].first <= option_length[1].first && option_length[3].first >= 2*option_length[2].first)//Two options\r\n    {\r\n        answer = 'C';\r\n    }\r\n    else if(2*option_length[0].first <= option_length[1].first)\r\n    {\r\n        answer = option_length[0].second;\r\n    }\r\n    else if(option_length[3].first >= 2*option_length[2].first)\r\n    {\r\n        answer = option_length[3].second;\r\n    }\r\n\r\n    printf(\"%c\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/The New Year Meeting Friends Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define min_3(a, b, c) min(a, min(b, c))\r\n#define max_3(a, b, c) max(a, max(b, c))\r\n\r\nint main()\r\n{\r\n    int location_1, location_2, location_3;\r\n    scanf(\"%d %d %d\", &location_1, &location_2, &location_3);\r\n\r\n    int leftmost  = min_3(location_1, location_2, location_3);\r\n    int rightmost = max_3(location_1, location_2, location_3);\r\n\r\n    printf(\"%d\\n\", rightmost - leftmost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/The New Year Meeting Friends.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int no_of_friends = 3;\r\n    vector <int> location(no_of_friends);\r\n    scanf(\"%d %d %d\", &location[0], &location[1], &location[2]);\r\n\r\n    sort(all(location));\r\n\r\n    int minimum_distance = 300;\r\n    for(int meet_point = location[0]; meet_point <= location[2]; meet_point++)\r\n    {\r\n        int distance = abs(meet_point - location[0]) + abs(meet_point - location[1]) + abs(meet_point - location[2]);\r\n\r\n        minimum_distance = min(minimum_distance, distance);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_distance);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/Word.cpp",
    "content": "#include <cstdio>\r\n\r\n#define is_capital(ch) (ch >= 'A' && ch <= 'Z' ? true : false)\r\n#define lower_case(ch) (is_capital(ch) ? ch + 'a' - 'A' : ch)\r\n#define capital(ch) (is_capital(ch) ? ch : ch - ('a' - 'A') )\r\n#define MAX_LENGTH 100 + 2\r\n\r\nint main()\r\n{\r\n    char word[MAX_LENGTH];\r\n    scanf(\"%s\", word);\r\n\r\n    int i, no_of_capitals = 0, no_of_lower_case = 0, length;\r\n    for(i = 0; word[i] != '\\0'; i++)\r\n    {\r\n        no_of_capitals += is_capital(word[i]) ;\r\n    }\r\n    length = i;\r\n    no_of_lower_case = (length - no_of_capitals);\r\n\r\n    if(no_of_lower_case >= no_of_capitals)\r\n    {\r\n        for(i = 0; word[i] != '\\0'; i++)\r\n        {\r\n            putchar(lower_case(word[i]));\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(int i = 0; i < length; i++)\r\n        {\r\n            putchar(capital(word[i]));\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 11/inc ARG.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 100 + 2\r\n\r\nint main()\r\n{\r\n    int no_of_bits;\r\n    char initial_state[MAX_LENGTH];\r\n    scanf(\"%d %s\", &no_of_bits, initial_state);\r\n\r\n    int first_zero_location = no_of_bits; //Assume there is no 0 so it will be outside the register at first\r\n    for(int i = 0; i < no_of_bits; i++)\r\n    {\r\n        if(initial_state[i] == '0')\r\n        {\r\n            first_zero_location = i + 1; //0-indexed\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", first_zero_location);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Anastasia and Pebbles.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_pebble_types, pebble_limit;\r\n    scanf(\"%d %d\", &no_of_pebble_types, &pebble_limit);\r\n\r\n    int days_to_collect_all_pebbles = 0;\r\n    for(int i = 1; i <= no_of_pebble_types; i++)\r\n    {\r\n        int pebble_i;\r\n        scanf(\"%d\", &pebble_i);\r\n\r\n        days_to_collect_all_pebbles += pebble_i/pebble_limit + (pebble_i%pebble_limit != 0); //Ceil\r\n    }\r\n    days_to_collect_all_pebbles = days_to_collect_all_pebbles/2 + days_to_collect_all_pebbles%2;\r\n\r\n    printf(\"%d\\n\", days_to_collect_all_pebbles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Bear and Three Balls.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_balls;\r\n    scanf(\"%d\", &no_of_balls);\r\n\r\n    set <int> ball;\r\n    for(int i = 1; i <= no_of_balls; i++)\r\n    {\r\n        int ball_i;\r\n        scanf(\"%d\", &ball_i);\r\n        ball.insert(ball_i);\r\n    }\r\n\r\n    bool gift_givable = false;\r\n    for(set <int> :: iterator i = ball.begin(); i != ball.end(); i++)\r\n    {\r\n        int ball_i = *i;\r\n\r\n        if(ball.count(ball_i + 1) == 1 && ball.count(ball_i - 1) == 1)\r\n        {\r\n            gift_givable = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(gift_givable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Buggy Sorting.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    if(no_of_elements <= 2)\r\n        printf(\"-1\\n\");\r\n    else\r\n        for(int i = no_of_elements; i >= 1; i--)\r\n            printf(\"%d \", i);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Co Prime Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    vector <int> coprime_array;\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number_i;\r\n        scanf(\"%d\", &number_i);\r\n\r\n        if(i == 1 || gcd(coprime_array.back(), number_i) == 1)\r\n        {\r\n            coprime_array.push_back(number_i);\r\n        }\r\n        else\r\n        {\r\n            coprime_array.push_back(1);\r\n            coprime_array.push_back(number_i);\r\n        }\r\n    }\r\n\r\n    int no_of_operations = coprime_array.size() - no_of_numbers;\r\n\r\n    printf(\"%d\\n\", no_of_operations);\r\n    for(unsigned int i = 0; i < coprime_array.size(); i++)\r\n        printf(\"%d \", coprime_array[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Dima and Friends.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_friends;\r\n    scanf(\"%d\", &no_of_friends);\r\n\r\n    int other_fingers = 0;\r\n    for(int i = 1; i <= no_of_friends; i++)\r\n    {\r\n        int finger_i;\r\n        scanf(\"%d\", &finger_i);\r\n\r\n        other_fingers += finger_i;\r\n    }\r\n\r\n    const int NO_OF_FINGERS = 5;\r\n    int no_of_choices = 0, no_of_people = no_of_friends + 1;\r\n\r\n    for(int dima_fingers = 1; dima_fingers <= NO_OF_FINGERS; dima_fingers++)\r\n    {\r\n        int total_fingers = other_fingers + dima_fingers;\r\n        no_of_choices += (total_fingers%no_of_people != 1); //choice is valid only if total =/= 1 mod no of people\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_choices);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Dima and Sequence.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint population_count(int x)\r\n{\r\n    int no_of_1s = x;\r\n\r\n    const int MASK_1 = 0x55555555;\r\n    const int MASK_2 = 0x33333333;\r\n    const int MASK_3 = 0x0F0F0F0F;\r\n    const int MASK_4 = 0x00FF00FF;\r\n    const int MASK_5 = 0x0000FFFF;\r\n\r\n    no_of_1s = (no_of_1s&MASK_1) + ( (no_of_1s >> 1) & MASK_1);\r\n    no_of_1s = (no_of_1s&MASK_2) + ( (no_of_1s >> 2) & MASK_2);\r\n    no_of_1s = (no_of_1s&MASK_3) + ( (no_of_1s >> 4) & MASK_3);\r\n    no_of_1s = (no_of_1s&MASK_4) + ( (no_of_1s >> 8) & MASK_4);\r\n    no_of_1s = (no_of_1s&MASK_5) + ( (no_of_1s >> 16) & MASK_5);\r\n\r\n    return no_of_1s;\r\n}\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int MAX_BITS = 32;\r\n    vector <int> no_of_elements_with_i_bits_set(MAX_BITS, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        no_of_elements_with_i_bits_set[population_count(element_i)]++;\r\n    }\r\n\r\n    long long no_of_pairs = 0;\r\n    for(int i = 0; i < MAX_BITS; i++)\r\n    {\r\n        int frequency_i_pop_count = no_of_elements_with_i_bits_set[i];\r\n\r\n        no_of_pairs += frequency_i_pop_count*1LL*(frequency_i_pop_count - 1);\r\n    }\r\n    no_of_pairs = no_of_pairs/2; //All pairs are counted up to order\r\n\r\n    printf(\"%I64d\\n\", no_of_pairs);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Dreamoon and Stairs Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_steps, multiple;\r\n    scanf(\"%d %d\", &no_of_steps, &multiple);\r\n\r\n    int lower_limit = no_of_steps/2 + no_of_steps%2;\r\n\r\n    int smallest_multiplier = lower_limit/multiple + (lower_limit%multiple != 0);\r\n\r\n    int minimum_number_of_steps = smallest_multiplier*multiple;\r\n\r\n    printf(\"%d\\n\", (minimum_number_of_steps <= no_of_steps ? minimum_number_of_steps : - 1));\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Dreamoon and Stairs.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_steps, multiple;\r\n    scanf(\"%d %d\", &no_of_steps, &multiple);\r\n\r\n    int minimum_no_of_steps = no_of_steps/2 + no_of_steps%2;\r\n\r\n    while(minimum_no_of_steps <= no_of_steps)\r\n    {\r\n        if(minimum_no_of_steps%multiple == 0)\r\n        {\r\n            break;\r\n        }\r\n        minimum_no_of_steps++; //Replace a 2 with two 1s\r\n    }\r\n\r\n    printf(minimum_no_of_steps > no_of_steps ? \"-1\\n\" : \"%d\\n\", minimum_no_of_steps);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Fashion in Berland.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_buttons;\r\n    scanf(\"%d\", &no_of_buttons);\r\n\r\n    int no_of_open_buttons = 0;\r\n    for(int i = 1; i <= no_of_buttons; i++)\r\n    {\r\n        int button_i;\r\n        scanf(\"%d\", &button_i);\r\n\r\n        no_of_open_buttons += (button_i == 0);\r\n    }\r\n\r\n    bool fashionable = (no_of_buttons > 1 && no_of_open_buttons == 1) || (no_of_buttons == 1 && no_of_open_buttons == 0);\r\n    printf(fashionable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Inbox (100500).cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_letters;\r\n    scanf(\"%d\", &no_of_letters);\r\n\r\n    int previous_letter_status = 0, no_of_unread_letters = 0, no_of_unread_segments = 0;\r\n    for(int i = 1; i <= no_of_letters; i++)\r\n    {\r\n        int unread;\r\n        scanf(\"%d\", &unread);\r\n\r\n        no_of_unread_letters += (unread == 1);\r\n\r\n        if(previous_letter_status == 0 && unread == 1)\r\n            no_of_unread_segments++;\r\n\r\n        previous_letter_status = unread;\r\n    }\r\n\r\n    int no_of_operations = no_of_unread_letters + max(no_of_unread_segments - 1, 0); //Incase there are no unread segments, it should be 0\r\n    printf(\"%d\\n\", no_of_operations);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Key Races.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int length_text, speed_1, speed_2, ping_1, ping_2;\r\n    scanf(\"%d %d %d %d %d\", &length_text, &speed_1, &speed_2, &ping_1, &ping_2);\r\n\r\n    int total_time_1 = speed_1*length_text + 2*ping_1;\r\n    int total_time_2 = speed_2*length_text + 2*ping_2;\r\n\r\n    if(total_time_1 == total_time_2)\r\n        printf(\"Friendship\\n\");\r\n    else\r\n        printf(total_time_1 < total_time_2 ? \"First\\n\" : \"Second\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Ksusha and Arrays.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    sort(all(element));\r\n\r\n    bool first_element_divides_all = true;\r\n    for(int i = 1; i < no_of_elements; i++)\r\n    {\r\n        if(element[i]%element.front() != 0)\r\n        {\r\n            first_element_divides_all = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", first_element_divides_all ? element.front(): -1);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Lecture.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length_of_sentence, no_of_words;\r\n    cin >> length_of_sentence >> no_of_words;\r\n\r\n    map <string, string> translated;\r\n\r\n    for(int i = 1; i <= no_of_words; i++)\r\n    {\r\n        string word, translation;\r\n        cin >> word >> translation;\r\n\r\n        translated[word] = translation;\r\n    }\r\n\r\n    for(int i = 1; i <= length_of_sentence; i++)\r\n    {\r\n        string current_word;\r\n        cin >> current_word;\r\n\r\n        cout << (current_word.length() <= translated[current_word].length() ? current_word : translated[current_word]) << \" \";\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Little Elephant and Chess.cpp",
    "content": "#include <cstdio>\r\n\r\n#define NO_OF_COLUMNS 8\r\n\r\nint main()\r\n{\r\n    const int no_of_rows = 8;\r\n    bool all_rows_have_alternating_colours = true;\r\n\r\n    for(int i = 1; i <= no_of_rows; i++)\r\n    {\r\n        char row[NO_OF_COLUMNS + 2];\r\n        scanf(\"%s\", row);\r\n\r\n        for(int square = 1; row[square] != '\\0'; square++)\r\n        {\r\n            if(row[square] ==row[square - 1])\r\n            {\r\n                all_rows_have_alternating_colours = false;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(all_rows_have_alternating_colours ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Little Girl and Maximum Sum.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, no_of_queries;\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\n\n    vector <int> element(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n        scanf(\"%d\", &element[i]);\n\n    vector <int> no_of_queries_starting_here(no_of_elements + 1, 0);\n    vector <int> no_of_queries_ending_here(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int left_i, right_i;\n        scanf(\"%d %d\", &left_i, &right_i);\n\n        no_of_queries_starting_here[left_i]++;\n\n        if(right_i + 1 <= no_of_elements)\n            no_of_queries_ending_here[right_i + 1]++;\n    }\n\n    int no_of_queries_on_this_index = 0;\n    vector <int> no_of_times_index_queried(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        no_of_queries_on_this_index += (no_of_queries_starting_here[i] - no_of_queries_ending_here[i]);\n\n        no_of_times_index_queried[i] = no_of_queries_on_this_index;\n    }\n\n    sort(all(element));\n    sort(all(no_of_times_index_queried));\n\n    long long maximum_sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n        maximum_sum += no_of_times_index_queried[i]*1LL*element[i];\n\n    printf(\"%I64d\\n\", maximum_sum);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 12/Minimum Difficulty.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_holds;\r\n    scanf(\"%d\", &number_of_holds);\r\n\r\n    vector <int> height(number_of_holds + 1);\r\n    for(int i = 1; i <= number_of_holds; i++)\r\n        scanf(\"%d\", &height[i]);\r\n\r\n    int original_difficulty = 0;\r\n    for(int i = 2; i <= number_of_holds; i++)\r\n        original_difficulty = max(original_difficulty, height[i] - height[i - 1]);\r\n\r\n    const int oo = 1e4;\r\n    int minimum_difficulty = oo;\r\n    for(int i = 2; i <= number_of_holds - 1; i++)\r\n    {\r\n        int current_difficulty = max(original_difficulty, height[i + 1] - height[i - 1]);\r\n\r\n        minimum_difficulty = min(current_difficulty, minimum_difficulty);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_difficulty);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Pasha and Pixels.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_rows, no_of_columns, no_of_moves;\r\n    scanf(\"%d %d %d\", &no_of_rows, &no_of_columns, &no_of_moves);\r\n\r\n    int black_square_formed_on_move = 0;\r\n\r\n    typedef vector <int> v_int;\r\n    vector <v_int> black_pixel(no_of_rows + 2, v_int (no_of_columns + 2, false));\r\n\r\n    for(int move_i = 1; move_i <= no_of_moves; move_i++)\r\n    {\r\n        int row_i, column_i;\r\n        scanf(\"%d %d\", &row_i, &column_i);\r\n\r\n        black_pixel[row_i][column_i] = true;\r\n\r\n        if(black_square_formed_on_move == 0)\r\n        {\r\n            if(black_pixel[row_i - 1][column_i] && black_pixel[row_i - 1][column_i - 1] && black_pixel[row_i][column_i - 1])\r\n            {\r\n                black_square_formed_on_move = move_i;\r\n            }\r\n\r\n            if(black_pixel[row_i - 1][column_i] && black_pixel[row_i - 1][column_i + 1] && black_pixel[row_i][column_i + 1])\r\n            {\r\n                black_square_formed_on_move = move_i;\r\n            }\r\n\r\n            if(black_pixel[row_i][column_i - 1] && black_pixel[row_i + 1][column_i - 1] && black_pixel[row_i + 1][column_i])\r\n            {\r\n                black_square_formed_on_move = move_i;\r\n            }\r\n\r\n            if(black_pixel[row_i][column_i + 1] && black_pixel[row_i + 1][column_i + 1] && black_pixel[row_i + 1][column_i])\r\n            {\r\n                black_square_formed_on_move = move_i;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", black_square_formed_on_move);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Puzzles.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_students, no_of_puzzles;\r\n    scanf(\"%d %d\", &no_of_students, &no_of_puzzles);\r\n\r\n    vector <int> no_of_pieces(no_of_puzzles);\r\n    for(int i = 0; i < no_of_puzzles; i++)\r\n        scanf(\"%d\", &no_of_pieces[i]);\r\n\r\n    sort(all(no_of_pieces));\r\n\r\n    const int oo = 1e9;\r\n    int minimum_difference = oo;\r\n    for(int i = no_of_students - 1; i < no_of_puzzles; i++)\r\n    {\r\n        minimum_difference = min(minimum_difference, no_of_pieces[i] - no_of_pieces[i - (no_of_students - 1)]);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_difference);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Santa Claus and Candies.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_gifts;\r\n    scanf(\"%d\", &no_of_gifts);\r\n\r\n    int no_of_people = 1;\r\n    while(no_of_people*(no_of_people + 1) <= 2*no_of_gifts)\r\n        no_of_people++;\r\n\r\n    no_of_people--;\r\n\r\n    printf(\"%d\\n\", no_of_people);\r\n    for(int i = 1; i < no_of_people; i++)\r\n    {\r\n        printf(\"%d \", i);\r\n        no_of_gifts -= i;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_gifts); //Last person gets all remaining gifts\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Sereja and Dima.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_cards;\r\n    scanf(\"%d\", &no_of_cards);\r\n\r\n    vector <int> card(no_of_cards);\r\n    for(int i = 0; i < no_of_cards; i++)\r\n        scanf(\"%d\", &card[i]);\r\n\r\n    int sergey_sum = 0, dima_sum = 0;\r\n    for(int front_i = 0, back_i = no_of_cards - 1, no_of_turns = 1; no_of_turns <= no_of_cards; no_of_turns++)\r\n    {\r\n        int greater_card = max(card[front_i], card[back_i]);\r\n\r\n        if(card[front_i] >= card[back_i])\r\n            front_i++;\r\n        else\r\n            back_i--;\r\n\r\n        if(no_of_turns%2 == 1)\r\n            sergey_sum += greater_card;\r\n        else\r\n            dima_sum += greater_card;\r\n\r\n    }\r\n\r\n    printf(\"%d %d\\n\", sergey_sum, dima_sum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Shaas and Oskols.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_wires;\r\n    scanf(\"%d\", &no_of_wires);\r\n\r\n    vector <int> no_of_birds_on_wire(no_of_wires + 1);\r\n    for(int i = 1; i <= no_of_wires; i++)\r\n        scanf(\"%d\", &no_of_birds_on_wire[i]);\r\n\r\n    int no_of_shots;\r\n    scanf(\"%d\", &no_of_shots);\r\n\r\n    for(int i = 1; i <= no_of_shots; i++)\r\n    {\r\n        int wire_i, shot_bird;\r\n        scanf(\"%d %d\", &wire_i, &shot_bird);\r\n\r\n        if(wire_i - 1 >= 1)\r\n            no_of_birds_on_wire[wire_i - 1] += (shot_bird - 1);\r\n\r\n        if(wire_i + 1 <= no_of_wires)\r\n            no_of_birds_on_wire[wire_i + 1] += (no_of_birds_on_wire[wire_i] - shot_bird);\r\n\r\n        no_of_birds_on_wire[wire_i] = 0;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_wires; i++)\r\n        printf(\"%d\\n\", no_of_birds_on_wire[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Sleuth.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\n#define MAX_LENGTH 100 + 5\r\n#define to_upper(ch) (ch >= 'a' && ch <= 'z' ?  ch - ('a' - 'A') : ch)\r\n#define is_alpha(ch) (to_upper(ch) >= 'A' && to_upper(ch) <= 'Z' ? true : false)\r\n\r\nbool is_vowel(char ch)\r\n{\r\n    switch(to_upper(ch))\r\n    {\r\n        case 'A':\r\n        case 'E':\r\n        case 'I':\r\n        case 'O':\r\n        case 'U':\r\n        case 'Y': return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    char question[MAX_LENGTH];\r\n    fgets(question, MAX_LENGTH, stdin);\r\n\r\n    bool last_letter_vowel = false;\r\n    for(int i = strlen(question) - 1; i >= 0; i--)\r\n    {\r\n        if(is_alpha(question[i]) )\r\n        {\r\n            if(is_vowel(question[i]) )\r\n               last_letter_vowel = true;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(last_letter_vowel ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/The Festive Evening.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n#include <map>\r\n\r\n#define MAX_LENGTH 1000000 + 2\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_guests, no_of_guards;\r\n    char guests[MAX_LENGTH];\r\n    scanf(\"%d %d %s\", &no_of_guests, &no_of_guards, guests);\r\n\r\n    map <char, int> last_appearance;\r\n    for(int i = 0; i < no_of_guests; i++)\r\n        last_appearance[guests[i]] = i;\r\n\r\n    set <char> entering_guests;\r\n    bool unsafe_situation = false;\r\n    for(int i = 0; i < no_of_guests; i++)\r\n    {\r\n        entering_guests.insert(guests[i]);\r\n        if(entering_guests.size() > no_of_guards)\r\n            unsafe_situation = true;\r\n\r\n        if(last_appearance[guests[i]] == i)\r\n            entering_guests.erase(guests[i]);\r\n    }\r\n\r\n    printf(unsafe_situation ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/The Number on The Board.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n#define MAX_LENGTH 100000 + 2\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int digit_sum;\r\n    char number_on_board[MAX_LENGTH];\r\n    scanf(\"%d %s\", &digit_sum, number_on_board);\r\n\r\n    vector <int> board_number;\r\n    int board_digit_sum = 0;\r\n    for(int i = 0; number_on_board[i] != '\\0'; i++)\r\n    {\r\n        board_digit_sum += number_on_board[i] - '0';\r\n        board_number.push_back(number_on_board[i] - '0');\r\n    }\r\n\r\n    sort(all(board_number));\r\n\r\n    int min_no_of_digit_changes = 0;\r\n    for(unsigned int i = 0; i < board_number.size() && board_digit_sum < digit_sum; i++)\r\n    {\r\n        if(board_number[i] != 9)\r\n        {\r\n            board_digit_sum += 9 - board_number[i];\r\n            min_no_of_digit_changes++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", min_no_of_digit_changes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 12/Watching a Movie.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_interesting_portions, skip_step;\r\n    scanf(\"%d %d\", &no_of_interesting_portions, &skip_step);\r\n\r\n    int current_minute = 1, no_of_watched_minutes = 0;\r\n    for(int i = 1; i <= no_of_interesting_portions; i++)\r\n    {\r\n        int beginning_i, end_i;\r\n        scanf(\"%d %d\", &beginning_i, &end_i);\r\n\r\n        no_of_watched_minutes += (beginning_i - current_minute)%skip_step + (end_i - (beginning_i - 1));\r\n\r\n        current_minute = end_i + 1;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_watched_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/A Good Contest.cpp",
    "content": "#include <cstdio>\r\n#define MAX_SIZE 10 + 2\r\n\r\nint main()\r\n{\r\n    int no_of_users, good_contest = false;\r\n    scanf(\"%d\", &no_of_users);\r\n\r\n    while(no_of_users--)\r\n    {\r\n        char name[MAX_SIZE];\r\n        int before_score, after_score;\r\n        scanf(\"%s %d %d\", name, &before_score, &after_score);\r\n\r\n        if(before_score >= 2400 && after_score > before_score)\r\n            good_contest = true;\r\n    }\r\n\r\n    printf(good_contest ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Arpa's Obvious Problem and Mehrad's Terrible Solution.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, target;\r\n    scanf(\"%d %d\", &no_of_elements, &target);\r\n\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        frequency[element_i]++;\r\n    }\r\n\r\n    long long no_of_good_pairs = 0;\r\n    for(map <int, int>:: iterator i = frequency.begin(); i != frequency.end(); i++)\r\n    {\r\n        int element_i = i->first;\r\n        int frequency_i = i->second;\r\n\r\n        int pair_element = target^element_i;\r\n        int pair_frequency = (element_i == pair_element ? frequency_i - 1 : frequency[pair_element]);\r\n\r\n        no_of_good_pairs += pair_frequency*1LL*frequency_i;\r\n    }\r\n\r\n    no_of_good_pairs = no_of_good_pairs/2;\r\n\r\n    printf(\"%I64d\\n\", no_of_good_pairs);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Arrays.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int size_a, size_b;\r\n    scanf(\"%d %d\", &size_a, &size_b);\r\n\r\n    int last_a, first_b, last_a_position, first_b_position;\r\n    scanf(\"%d %d\", &last_a_position, &first_b_position);\r\n\r\n    int element_i;\r\n    for(int i = 1; i <= size_a; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        if(i == last_a_position)\r\n            last_a = element_i;\r\n    }\r\n\r\n    for(int i = size_b; i >= 1; i--)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        if(i == first_b_position)\r\n            first_b = element_i;\r\n    }\r\n\r\n    printf(last_a < first_b ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Arya and Bran.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_days, target_candies;\r\n    scanf(\"%d %d\", &no_of_days, &target_candies);\r\n\r\n    const int one_day_limit = 8;\r\n    int total_candies = 0, given_candies = 0, required_days = -1;\r\n    for(int day_i = 1; day_i <= no_of_days; day_i++)\r\n    {\r\n        int box_i, given_on_day_i;\r\n        scanf(\"%d\", &box_i);\r\n\r\n        total_candies += box_i;\r\n        given_on_day_i = min(one_day_limit, total_candies);\r\n\r\n        total_candies -= given_on_day_i;\r\n        given_candies += given_on_day_i;\r\n\r\n        if(given_candies >= target_candies)\r\n        {\r\n            required_days = day_i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", required_days);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Bear and Elections.cpp",
    "content": "#include <cstdio>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_candidates;\r\n    scanf(\"%d\", &no_of_candidates);\r\n\r\n    int limak_votes;\r\n    priority_queue <int> votes;\r\n\r\n    scanf(\"%d\", &limak_votes);\r\n    for(int i = 2; i <= no_of_candidates; i++)\r\n    {\r\n        int vote_i;\r\n        scanf(\"%d\", &vote_i);\r\n\r\n        votes.push(vote_i);\r\n    }\r\n\r\n    int limak_bribes = 0;\r\n    while(limak_votes + limak_bribes <= votes.top())\r\n    {\r\n        int current_max = votes.top();\r\n        votes.pop();\r\n\r\n        current_max--;\r\n        limak_bribes++;\r\n        votes.push(current_max);\r\n    }\r\n\r\n\r\n    printf(\"%d\\n\", limak_bribes);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Business Trip.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int minimum_growth;\n    scanf(\"%d\", &minimum_growth);\n\n    const int no_of_months = 12;\n    vector <int> growth(no_of_months);\n    for(int i = 0; i < no_of_months; i++)\n        scanf(\"%d\", &growth[i]);\n\n    sort(all(growth));\n    reverse(all(growth));\n\n    int month_i = 0, plant_growth = 0;\n    while(plant_growth < minimum_growth && month_i < no_of_months)\n    {\n        plant_growth += growth[month_i++];\n    }\n\n    printf(\"%d\\n\", plant_growth < minimum_growth ? -1 : month_i);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 13/Cards.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_people;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    vector < pair <int, int> > cards;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int card_i;\r\n        scanf(\"%d\", &card_i);\r\n        cards.push_back(make_pair(card_i, i));\r\n    }\r\n\r\n    sort(all(cards));\r\n    vector < pair <int, int> > dealt_cards;\r\n    for(int front_i = 0, back_i = no_of_people - 1; front_i < back_i; front_i++, back_i--)\r\n    {\r\n        int front_index = cards[front_i].second;\r\n        int back_index = cards[back_i].second;\r\n\r\n        dealt_cards.push_back(make_pair(front_index, back_index));\r\n    }\r\n\r\n    for(unsigned int i = 0; i < dealt_cards.size(); i++)\r\n        printf(\"%d %d\\n\", dealt_cards[i].first, dealt_cards[i].second);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Code Obfuscation.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n\r\n#define MAX_LENGTH 500 + 2\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    char code[MAX_LENGTH];\r\n    scanf(\"%s\", code);\r\n\r\n    set <char> alphabets_used;\r\n    int code_obfuscation = true;\r\n\r\n    for(int i = 0; code[i] != '\\0'; i++)\r\n    {\r\n        //Before inserting an alphabet, all alphabets smaller than it must already have been used\r\n        if(alphabets_used.count(code[i]) == 0)\r\n        {\r\n            if(alphabets_used.size() < code[i] - 'a')\r\n            {\r\n                code_obfuscation = false;\r\n                break;\r\n            }\r\n        }\r\n        alphabets_used.insert(code[i]);\r\n    }\r\n\r\n\r\n    printf(code_obfuscation ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Drinks.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_drinks;\r\n    scanf(\"%d\", &no_of_drinks);\r\n\r\n    double numerator = 0.0;\r\n    for(int i = 1; i <= no_of_drinks; i++)\r\n    {\r\n        int percent_i;\r\n        scanf(\"%d\", &percent_i);\r\n\r\n        numerator += percent_i;\r\n    }\r\n\r\n    double denominator = no_of_drinks*1.0;\r\n    double fraction = numerator/denominator;\r\n\r\n    printf(\"%lf\\n\", fraction);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Epic Game.cpp",
    "content": "#include <cstdio>\r\n#include <algorithm>\r\nusing namespace std;\r\n\r\nint gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nint main()\r\n{\r\n    int a, b, n;\r\n    scanf(\"%d %d %d\", &a, &b, &n);\r\n\r\n    int winner;\r\n    for(int turn_i = 0; n > 0; turn_i++)\r\n    {\r\n        int current_player = (turn_i%2 == 0 ? a : b) ;\r\n        n -= gcd(current_player, n);\r\n\r\n        if(n == 0)\r\n            winner = turn_i%2;\r\n    }\r\n\r\n    printf(\"%d\\n\", winner);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Functions Again.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    long long maximum_value, maximum_with_last_difference_added, maximum_with_last_difference_removed;\r\n\r\n    maximum_with_last_difference_added = abs(element[2] - element[1]);\r\n    maximum_with_last_difference_removed = 0;\r\n    maximum_value = maximum_with_last_difference_added;\r\n\r\n    for(int i = 3; i <= no_of_elements; i++)\r\n    {\r\n        long long maximum_with_this_difference_added, maximum_with_this_difference_removed, maximum_value_ending_here;\r\n\r\n        maximum_with_this_difference_added = max(0LL, maximum_with_last_difference_removed) + abs(element[i] - element[i - 1]);\r\n        maximum_with_this_difference_removed = maximum_with_last_difference_added - abs(element[i] - element[i - 1]);\r\n\r\n        maximum_value_ending_here = max(maximum_with_this_difference_added, maximum_with_this_difference_removed);\r\n        maximum_value = max(maximum_value, maximum_value_ending_here);\r\n\r\n        maximum_with_last_difference_added = maximum_with_this_difference_added;\r\n        maximum_with_last_difference_removed = maximum_with_this_difference_removed;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", maximum_value);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Generous Kefa.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 100 + 2\r\n#define NO_OF_ALPHABETS 26\r\n\r\nint main()\r\n{\r\n    int no_of_balloons, no_of_people;\r\n    char balloon_colours[MAX_LENGTH];\r\n    scanf(\"%d %d %s\",&no_of_balloons, &no_of_people, balloon_colours);\r\n\r\n    int no_of_balloons_of_colour[NO_OF_ALPHABETS] = {0};\r\n    for(int i = 0; i < no_of_balloons; i++)\r\n    {\r\n        no_of_balloons_of_colour[balloon_colours[i] - 'a']++;\r\n    }\r\n\r\n    int everyone_happy = true;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(no_of_balloons_of_colour[i] > no_of_people)\r\n        {\r\n            everyone_happy = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(everyone_happy ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/George and Job.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, no_of_intervals, max_interval_size;\r\n    scanf(\"%d %d %d\", &no_of_numbers, &max_interval_size, &no_of_intervals);\r\n\r\n    vector <long long> sum_till(no_of_numbers + 1, 0);\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number_i;\r\n        scanf(\"%d\", &number_i);\r\n        sum_till[i] = number_i + sum_till[i - 1];\r\n    }\r\n\r\n    typedef vector <long long> v_long;\r\n    vector <v_long> maximum_sum_till(no_of_numbers + 1, v_long(no_of_intervals + 1, 0));\r\n\r\n    for(int interval_i = 1; interval_i <= no_of_intervals; interval_i++)\r\n    {\r\n        for(int number_i = max_interval_size; number_i <= no_of_numbers; number_i++)\r\n        {\r\n            int right = number_i, left = (number_i - max_interval_size) + 1;\r\n            long long interval_ending_here_sum = sum_till[right] - sum_till[left - 1];\r\n\r\n            long long maximum_sum_with_interval_ending_here = maximum_sum_till[left - 1][interval_i - 1] + interval_ending_here_sum ;\r\n\r\n            long long maximum_sum_with_interval_ending_before_here = maximum_sum_till[number_i - 1][interval_i];\r\n\r\n            maximum_sum_till[number_i][interval_i] = max(maximum_sum_with_interval_ending_here, maximum_sum_with_interval_ending_before_here);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", maximum_sum_till[no_of_numbers][no_of_intervals]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Godsend.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    int only_even_numbers = true;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        if(element_i%2 == 1)\r\n            only_even_numbers = false;\r\n    }\r\n\r\n    printf(only_even_numbers ? \"Second\\n\" : \"First\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Ilya and Queries.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\n#define MAX_LENGTH 100000 + 2\r\n\r\nint main()\r\n{\r\n    char string[MAX_LENGTH];\r\n    scanf(\"%s\", string);\r\n\r\n    int length = strlen(string);\r\n    vector <int> answer_till_here(length + 1, 0);\r\n    for(unsigned int i = 0; string[i] != '\\0'; i++)\r\n    {\r\n        answer_till_here[i] = (i == 0 ? 0 : answer_till_here[i - 1]);\r\n\r\n        if(string[i] != '\\0' && string[i] == string[i + 1])\r\n            answer_till_here[i]++;\r\n    }\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int left_i, right_i;\r\n        scanf(\"%d %d\", &left_i, &right_i);\r\n\r\n        left_i--, right_i--; //1-indexed\r\n\r\n        int answer = (left_i == 0 ? answer_till_here[right_i - 1] : answer_till_here[right_i - 1] - answer_till_here[left_i - 1]);\r\n\r\n        printf(\"%d\\n\", answer);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Kuriyama Mirai's Stones.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 1, 0);\r\n    vector <long long> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element[i]);\r\n        sum_till[i] = element[i] + sum_till[i - 1];\r\n    }\r\n\r\n    sort(all(element));\r\n    vector <long long> sorted_sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sorted_sum_till[i] = element[i] + sorted_sum_till[i - 1];\r\n    }\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int query_type, left, right;\r\n        scanf(\"%d %d %d\", &query_type, &left, &right);\r\n\r\n        long long answer = (query_type == 1 ? sum_till[right] - sum_till[left - 1] : sorted_sum_till[right] - sorted_sum_till[left - 1]);\r\n        printf(\"%I64d\\n\", answer);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Lights Out.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\nusing namespace std;\r\n\r\n#define toggle(x) (x = !x)\r\n\r\nint main()\r\n{\r\n    typedef vector <int> v_int;\r\n    vector <v_int> light_on(3 + 2, v_int(3 + 2, true));\r\n\r\n    for(int row = 1; row <= 3; row++)\r\n    {\r\n        for(int column = 1; column <= 3; column++)\r\n        {\r\n            int no_of_toggles;\r\n            scanf(\"%d\", &no_of_toggles);\r\n\r\n            if(no_of_toggles%2 == 1)\r\n            {\r\n                toggle(light_on[row][column]);\r\n\r\n                toggle(light_on[row][column - 1]);\r\n                toggle(light_on[row][column + 1]);\r\n                toggle(light_on[row + 1][column]);\r\n                toggle(light_on[row - 1][column]);\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int row = 1; row <= 3; row++)\r\n    {\r\n        for(int column = 1; column <= 3; column++)\r\n        {\r\n            if(light_on[row][column])\r\n                printf(\"1\");\r\n            else\r\n                printf(\"0\");\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Little Dima and Equation.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long int_power(int x, int n)\r\n{\r\n    long long power = 1;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        power *= x;\r\n    }\r\n    return power;\r\n}\r\n\r\nint sum_of_digits(int x)\r\n{\r\n    const int base = 10;\r\n    int digit_sum = 0;\r\n\r\n    while(x > 0)\r\n    {\r\n        digit_sum += x%base;\r\n        x = x/base;\r\n    }\r\n    return digit_sum;\r\n}\r\n\r\nint main()\r\n{\r\n    int a, b, c;\r\n    scanf(\"%d %d %d\", &a, &b, &c);\r\n\r\n    vector <int> solutions;\r\n\r\n    for(int digit_sum = 1; digit_sum <= 81; digit_sum++)\r\n    {\r\n        long long x = b*int_power(digit_sum, a) + c;\r\n        if(sum_of_digits(x) == digit_sum && x > 0 && x < 1e9)\r\n            solutions.push_back(x);\r\n    }\r\n\r\n    printf(\"%d\\n\", solutions.size());\r\n    for(unsigned int i = 0; i < solutions.size(); i++)\r\n        printf(\"%d \", solutions[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Little Elephant and Bits.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_SIZE 100000 + 2\r\n\r\nint main()\r\n{\r\n    char number[MAX_SIZE];\r\n    scanf(\"%s\", number);\r\n\r\n    char new_number[MAX_SIZE];\r\n    int first_zero = -1, new_number_i = 0;\r\n\r\n    for(int i = 0; number[i] != '\\0'; i++)\r\n    {\r\n        if(number[i] == '0' && first_zero == -1)//Delete leftmost 0.\r\n        {\r\n            first_zero = i;\r\n        }\r\n        else\r\n        {\r\n            new_number[new_number_i++] = number[i];\r\n        }\r\n    }\r\n\r\n    int last_digit_position = new_number_i;\r\n    if(first_zero == -1) //If no 0, delete any 1.\r\n        last_digit_position--;\r\n\r\n    new_number[last_digit_position] = '\\0';\r\n\r\n    printf(\"%s\\n\", new_number);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/New Skateboard.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_LENGTH 300000 + 2\r\n\r\nint main()\r\n{\r\n    char calculator[MAX_LENGTH];\r\n    scanf(\"%s\", calculator);\r\n\r\n    long long no_of_multiples_of_4 = ( (calculator[0] - '0')%4 == 0);\r\n\r\n    for(int i = 0; calculator[i + 1] != '\\0'; i++)\r\n    {\r\n        int current_suffix = (calculator[i] - '0')*10 + (calculator[i + 1] - '0');\r\n        int no_of_strings_ending_with_this_suffix = i + 1;\r\n\r\n        if(current_suffix%4 == 0)\r\n            no_of_multiples_of_4 += no_of_strings_ending_with_this_suffix;\r\n\r\n        no_of_multiples_of_4 += ( (calculator[i + 1] - '0')%4 == 0);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_multiples_of_4);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Oath of the Night's Watch.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define min(a, b) (a < b ? a : b)\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int oo = 1e9 + 1;\r\n    int no_of_people, min_strength = oo, max_strength = 0;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    map <int, int> strength_frequency;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int strength_i;\r\n        scanf(\"%d\", &strength_i);\r\n\r\n        strength_frequency[strength_i]++;\r\n        min_strength = min(strength_i, min_strength);\r\n        max_strength = max(strength_i, max_strength);\r\n    }\r\n\r\n    int number_of_people_supported = max(0, no_of_people - strength_frequency[max_strength] - strength_frequency[min_strength]);\r\n    printf(\"%d\\n\", number_of_people_supported);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Sort the Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_elements;\r\n    scanf(\"%d\", &number_of_elements);\r\n\r\n    vector <int> element(number_of_elements + 1);\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    int descending_segments = 0, in_descending_segment = false, reversed_segment_fits = false;\r\n    int segment_start = 1, segment_end = number_of_elements;\r\n\r\n    for(int i = 2; i <= number_of_elements && descending_segments <= 1; i++)\r\n    {\r\n        if(in_descending_segment)\r\n        {\r\n            if(element[i] > element[i - 1])\r\n            {\r\n                segment_end = i - 1;\r\n                in_descending_segment = false;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            if(element[i] < element[i - 1])\r\n            {\r\n                in_descending_segment = true;\r\n                segment_start = i - 1;\r\n\r\n                descending_segments++;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(descending_segments == 0)\r\n        segment_end = segment_start;\r\n\r\n    if( (segment_end == number_of_elements || element[segment_start] <= element[segment_end + 1] ) &&\r\n        (segment_start == 1 || element[segment_end] >= element[segment_start - 1]) )\r\n    {\r\n        reversed_segment_fits = true;\r\n    }\r\n\r\n    if(descending_segments <= 1 && reversed_segment_fits)\r\n        printf(\"yes\\n%d %d\\n\", segment_start, segment_end);\r\n    else\r\n        printf(\"no\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Star Sky.cpp",
    "content": "#include <cstdio>\r\n\r\n#define MAX_BRIGHTNESS 10\r\n#define MAX_LENGTH 100\r\n\r\nint main()\r\n{\r\n    int no_of_stars, no_of_views, maximum_brightness;\r\n    scanf(\"%d %d %d\", &no_of_stars, &no_of_views, &maximum_brightness);\r\n\r\n    int no_of_stars_of_initial_brightness_in[MAX_BRIGHTNESS + 1][MAX_LENGTH + 1][MAX_LENGTH + 1] = {{{0}}};\r\n\r\n    for(int star_i = 1; star_i <= no_of_stars; star_i++)\r\n    {\r\n        int brightness_i, x_i, y_i;\r\n        scanf(\"%d %d %d\", &x_i, &y_i, &brightness_i);\r\n\r\n        no_of_stars_of_initial_brightness_in[brightness_i][x_i][y_i]++;\r\n    }\r\n\r\n    for(int brightness_i = 0; brightness_i <= maximum_brightness; brightness_i++)\r\n    {\r\n        for(int x_i = 1; x_i <= MAX_LENGTH; x_i++)\r\n        {\r\n            for(int y_i = 1; y_i <= MAX_LENGTH; y_i++)\r\n            {\r\n                no_of_stars_of_initial_brightness_in[brightness_i][x_i][y_i] += no_of_stars_of_initial_brightness_in[brightness_i][x_i][y_i - 1]\r\n                                                                              + no_of_stars_of_initial_brightness_in[brightness_i][x_i - 1][y_i]\r\n                                                                              - no_of_stars_of_initial_brightness_in[brightness_i][x_i - 1][y_i - 1];\r\n            }\r\n        }\r\n    }\r\n\r\n    while(no_of_views--)\r\n    {\r\n        int time, x_1,y_1, x_2, y_2;\r\n        scanf(\"%d %d %d %d %d\", &time, &x_1, &y_1, &x_2, &y_2);\r\n\r\n        int sum_of_brightness = 0;\r\n\r\n        for(int brightness_i = 0; brightness_i <= maximum_brightness; brightness_i++)\r\n        {\r\n            int no_of_stars_of_this_brightness = no_of_stars_of_initial_brightness_in[brightness_i][x_2][y_2]\r\n                                               - no_of_stars_of_initial_brightness_in[brightness_i][x_2][y_1 - 1]\r\n                                               - no_of_stars_of_initial_brightness_in[brightness_i][x_1 - 1][y_2]\r\n                                               + no_of_stars_of_initial_brightness_in[brightness_i][x_1 - 1][y_1 - 1];\r\n\r\n            int final_brightness = (brightness_i + time)%(maximum_brightness + 1);\r\n\r\n\r\n            sum_of_brightness += no_of_stars_of_this_brightness*final_brightness;\r\n        }\r\n\r\n        printf(\"%d\\n\", sum_of_brightness);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Vanya and Books.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_pages;\r\n    scanf(\"%d\", &no_of_pages);\r\n\r\n    long long no_of_digits_used = 0;\r\n    long long power_of_10 = 1;\r\n\r\n    while(power_of_10 <= no_of_pages)\r\n    {\r\n        no_of_digits_used += no_of_pages - (power_of_10 - 1);\r\n        power_of_10 *= 10;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_digits_used);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 13/Vasya and Digital Root.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int digital_root, no_of_digits;\r\n    scanf(\"%d %d\", &no_of_digits, &digital_root);\r\n\r\n    if(digital_root == 0 && no_of_digits > 1)\r\n        printf(\"No solution\\n\");\r\n    else\r\n    {\r\n        for(int i =no_of_digits; i >= 2; i--)\r\n            printf(\"9\");\r\n        printf(\"%d\\n\", digital_root);\r\n    }\r\n\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Asphalting Roads.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_roads;\r\n    scanf(\"%d\", &no_of_roads);\r\n\r\n    const int MAX_ROADS = 50 + 1;\r\n    vector <int> horizontal_is_asphalted(MAX_ROADS, false);\r\n    vector <int> vertical_is_asphalted(MAX_ROADS, false);\r\n\r\n    vector <int> new_asphalt_applied_on_day;\r\n\r\n    for(int day_i = 1; day_i <= no_of_roads*no_of_roads; day_i++)\r\n    {\r\n        int road_1, road_2;\r\n        scanf(\"%d %d\", &road_1, &road_2);\r\n\r\n        if(!horizontal_is_asphalted[road_1] && !vertical_is_asphalted[road_2])\r\n        {\r\n            horizontal_is_asphalted[road_1] = vertical_is_asphalted[road_2] = true;\r\n            new_asphalt_applied_on_day.push_back(day_i);\r\n        }\r\n    }\r\n\r\n    for(unsigned int i = 0; i < new_asphalt_applied_on_day.size(); i++)\r\n        printf(\"%d \", new_asphalt_applied_on_day[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Bicycle Chain.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_pedal_stars;\r\n    scanf(\"%d\", &no_of_pedal_stars);\r\n\r\n    vector <int> pedal_star(no_of_pedal_stars);\r\n    for(int i = 0; i < no_of_pedal_stars; i++)\r\n        scanf(\"%d\", &pedal_star[i]);\r\n\r\n    int no_of_wheel_stars;\r\n    scanf(\"%d\",&no_of_wheel_stars);\r\n\r\n    vector <int> wheel_star(no_of_wheel_stars);\r\n    for(int i = 0; i < no_of_wheel_stars; i++)\r\n        scanf(\"%d\", &wheel_star[i]);\r\n\r\n    int maximum_ratio = 0, no_of_maxima = 0;\r\n    for(int i = 0; i < no_of_pedal_stars; i++)\r\n    {\r\n        for(int j = 0; j < no_of_wheel_stars; j++)\r\n        {\r\n            if(wheel_star[j]%pedal_star[i] == 0)\r\n            {\r\n                int this_ratio = wheel_star[j]/pedal_star[i];\r\n\r\n                if(this_ratio == maximum_ratio)\r\n                {\r\n                    no_of_maxima++;\r\n                }\r\n                else if(this_ratio > maximum_ratio)\r\n                {\r\n                    maximum_ratio = this_ratio, no_of_maxima = 1;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_maxima);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Borze.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string borze_code, translation;\r\n    cin >> borze_code;\r\n\r\n    for(unsigned int i = 0; i < borze_code.size(); i++)\r\n    {\r\n        if(borze_code[i] == '.')\r\n            translation += '0';\r\n        else if(borze_code[i] == '-')\r\n        {\r\n            if(borze_code[i + 1] == '.')\r\n                translation += '1';\r\n            else if(borze_code[i + 1] == '-')\r\n                translation += '2';\r\n\r\n            i++;\r\n        }\r\n    }\r\n\r\n    cout << translation;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Building Permutation.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    sort(all(element));\r\n\r\n    long long no_of_moves = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        no_of_moves += abs(element[i] - (i+1) );\r\n\r\n    printf(\"%I64d\\n\", no_of_moves);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Chess Tourney.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_pairs;\r\n    scanf(\"%d\", &no_of_pairs);\r\n\r\n    vector <int> player_rating(2*no_of_pairs + 1, 0);\r\n    for(int i = 1; i <= 2*no_of_pairs; i++)\r\n        scanf(\"%d\", &player_rating[i]);\r\n\r\n    sort(all(player_rating));\r\n\r\n    printf(player_rating[no_of_pairs] < player_rating[no_of_pairs + 1] ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Cormen - The Best Friend of Man.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_days, minimum_walks_in_two_days;\r\n    scanf(\"%d %d\", &no_of_days, &minimum_walks_in_two_days);\r\n\r\n    vector <int> no_of_walks_on_day(no_of_days + 1);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        scanf(\"%d\", &no_of_walks_on_day[i]);\r\n\r\n    int no_of_additional_walks = 0;\r\n    for(int i = 2; i <= no_of_days; i++)\r\n    {\r\n        int walks_in_last_two_days = no_of_walks_on_day[i] + no_of_walks_on_day[i - 1];\r\n        if(walks_in_last_two_days < minimum_walks_in_two_days)\r\n        {\r\n            int no_of_additional_walks_on_day_i = minimum_walks_in_two_days - walks_in_last_two_days;\r\n            no_of_walks_on_day[i] += no_of_additional_walks_on_day_i;\r\n\r\n            no_of_additional_walks += no_of_additional_walks_on_day_i;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_additional_walks);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        printf(\"%d \", no_of_walks_on_day[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/DZY Loves Sequences.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 2);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <int> longest_increasing_to_left(no_of_elements + 2, 1);\r\n    longest_increasing_to_left[1] = 0;\r\n\r\n    for(int i = 3; i <= no_of_elements; i++)\r\n    {\r\n        if(element[i - 1] > element[i - 2])\r\n            longest_increasing_to_left[i] = longest_increasing_to_left[i - 1] + 1;\r\n    }\r\n\r\n    vector <int> longest_increasing_to_right(no_of_elements + 2, 1);\r\n    longest_increasing_to_right[no_of_elements] = 0;\r\n\r\n    for(int i = no_of_elements - 2; i >= 0; i--)\r\n    {\r\n        if(element[i + 1] < element[i + 2])\r\n            longest_increasing_to_right[i] = longest_increasing_to_right[i + 1] + 1;\r\n    }\r\n\r\n    int longest_increasing_subsequence = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int length_by_changing_current_element = max(longest_increasing_to_left[i], longest_increasing_to_right[i]) + 1;\r\n\r\n        if(i > 1 && i < no_of_elements)\r\n        {\r\n            if(element[i + 1] - element[i - 1] >= 2)\r\n            {\r\n                length_by_changing_current_element = longest_increasing_to_left[i] + longest_increasing_to_right[i] + 1;\r\n            }\r\n        }\r\n\r\n        longest_increasing_subsequence = max(longest_increasing_subsequence, length_by_changing_current_element);\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_increasing_subsequence);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Dragons.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int strength, no_of_dragons;\r\n    scanf(\"%d %d\", &strength, &no_of_dragons);\r\n\r\n    vector < pair <int, int> > dragon(no_of_dragons);\r\n    for(int i = 0; i < no_of_dragons; i++)\r\n        scanf(\"%d %d\", &dragon[i].first, &dragon[i].second);\r\n\r\n    sort(all(dragon));\r\n\r\n    int can_defeat_all_dragons = true;\r\n    for(int i = 0; i < no_of_dragons; i++)\r\n    {\r\n        int strength_of_dragon = dragon[i].first;\r\n        int bonus = dragon[i].second;\r\n\r\n        if(strength <= strength_of_dragon)\r\n        {\r\n            can_defeat_all_dragons = false;\r\n            break;\r\n        }\r\n        else\r\n        {\r\n            strength += bonus;\r\n        }\r\n    }\r\n\r\n    printf(can_defeat_all_dragons ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Drazil and Factorial.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_digits;\r\n    scanf(\"%d\", &no_of_digits);\r\n\r\n    vector <int> number;\r\n    for(int i = 1; i <= no_of_digits; i++)\r\n    {\r\n        int digit_i;\r\n        scanf(\"%1d\", &digit_i);\r\n\r\n        switch(digit_i)\r\n        {\r\n            case 2:\r\n            case 3:\r\n            case 5:\r\n            case 7: number.push_back(digit_i);\r\n                    break;\r\n\r\n            case 4: number.push_back(2); number.push_back(2); number.push_back(3);\r\n                    break;\r\n\r\n            case 6: number.push_back(3); number.push_back(5);\r\n                    break;\r\n\r\n            case 8: number.push_back(2); number.push_back(2); number.push_back(2); number.push_back(7);\r\n                    break;\r\n\r\n            case 9: number.push_back(2); number.push_back(3); number.push_back(3); number.push_back(7);\r\n                    break;\r\n        }\r\n    }\r\n\r\n    sort(all(number));\r\n\r\n    for(int i = number.size() - 1; i >= 0; i--)\r\n        printf(\"%d\", number[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Football.cpp",
    "content": "#include <string>\r\n#include <iostream>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_lines;\r\n    cin >> no_of_lines;\r\n\r\n    map <string, int> no_of_goals;\r\n\r\n    while(no_of_lines--)\r\n    {\r\n        string team;\r\n        cin >> team;\r\n\r\n        no_of_goals[team]++;\r\n    }\r\n\r\n    string winner;\r\n    int max_goals = 0;\r\n    for(map <string, int> :: iterator i = no_of_goals.begin(); i != no_of_goals.end(); i++)\r\n    {\r\n        int no_of_goals = i->second;\r\n        if(no_of_goals > max_goals)\r\n        {\r\n            max_goals = no_of_goals;\r\n            winner = i->first;\r\n        }\r\n    }\r\n\r\n    cout << winner;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Helpful Maths.cpp",
    "content": "#include <cstdio>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string expression;\r\n    cin >> expression;\r\n\r\n    typedef unsigned int u_int;\r\n    vector <char> number;\r\n    for(u_int i = 0; i < expression.size(); i++)\r\n    {\r\n        if(expression[i] != '+')\r\n            number.push_back(expression[i]);\r\n    }\r\n\r\n    sort(all(number));\r\n\r\n    for(u_int i = 0; i < number.size() - 1; i++)\r\n    {\r\n        printf(\"%c+\", number[i]);\r\n    }\r\n    printf(\"%c\\n\", number.back());\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Increase and Decrease.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        sum += element_i;\r\n    }\r\n\r\n    printf(\"%d\\n\", sum%no_of_elements == 0 ? no_of_elements : no_of_elements - 1);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Jeff and Digits.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_digits;\r\n    scanf(\"%d\", &no_of_digits);\r\n\r\n    int no_of_5s = 0, no_of_0s = 0;\r\n    for(int i = 1; i <= no_of_digits; i++)\r\n    {\r\n        int digit;\r\n        scanf(\"%d\", &digit);\r\n\r\n        no_of_5s += (digit == 5);\r\n        no_of_0s += (digit == 0);\r\n    }\r\n\r\n    if(no_of_0s == 0)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else if(no_of_5s < 9)\r\n    {\r\n        printf(\"0\\n\");\r\n    }\r\n    else\r\n    {\r\n        int no_of_5s_in_number = (no_of_5s/9)*9;\r\n        for(int i = 1; i <= no_of_5s_in_number; i++)\r\n            printf(\"5\");\r\n\r\n        for(int i = 1; i <= no_of_0s; i++)\r\n            printf(\"0\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Jzzhu and Children.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_children, no_of_candies_given;\r\n    scanf(\"%d %d\", &no_of_children, &no_of_candies_given);\r\n\r\n    int maximum_turns = 0, last_child = 0;\r\n    for(int i = 1; i <= no_of_children; i++)\r\n    {\r\n        int candy_i;\r\n        scanf(\"%d\", &candy_i);\r\n\r\n        int no_of_turns = candy_i/no_of_candies_given + (candy_i%no_of_candies_given != 0);\r\n\r\n        if(no_of_turns >=  maximum_turns)\r\n        {\r\n            maximum_turns = no_of_turns;\r\n            last_child = i;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", last_child);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Modulo Sum.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, modulo;\r\n    scanf(\"%d %d\", &no_of_elements, &modulo);\r\n\r\n    typedef vector <int> v_int;\r\n    vector <v_int> remainder_possible(modulo + 1, v_int(modulo, false));\r\n\r\n    int last_element = min(no_of_elements, modulo);\r\n    for(int i = 1; i <= last_element; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        for(int remainder = 0; remainder < modulo; remainder++)\r\n        {\r\n            if(remainder_possible[i - 1][remainder])\r\n            {\r\n                int remainder_after_adding = (remainder + element_i)%modulo;\r\n                remainder_possible[i][remainder_after_adding] = true;\r\n\r\n                remainder_possible[i][remainder] = true;\r\n            }\r\n        }\r\n\r\n        remainder_possible[i][element_i%modulo] = true;\r\n    }\r\n\r\n    printf(no_of_elements > modulo || remainder_possible[last_element][0] ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Odds and Ends.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    int first_or_last_element_even = false;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        if(i == 1 || i == no_of_elements)\r\n            if(element_i%2 == 0)\r\n                first_or_last_element_even = true;\r\n    }\r\n\r\n    printf(no_of_elements%2 == 0 || first_or_last_element_even ? \"No\\n\" : \"Yes\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Panoramix's Prediction.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_prime(int n)\r\n{\r\n    for(int i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int x, y;\r\n    scanf(\"%d %d\", &x, &y);\r\n\r\n    int prime_in_middle = false;\r\n    for(int i = x + 1; i < y; i++)\r\n    {\r\n        if(is_prime(i))\r\n        {\r\n            prime_in_middle = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(!prime_in_middle && is_prime(y) ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Permutation.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int limit = 5000;\r\n    vector <int> is_present(limit + 1, false);\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        is_present[element_i] = true;\r\n    }\r\n\r\n    int no_of_changes = 0;\r\n    for(int i = 1; i <= n; i++)\r\n        no_of_changes += (!is_present[i]);\r\n\r\n    printf(\"%d\\n\", no_of_changes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Powers of Two.cpp",
    "content": "#include <cstdio>\n#include <map>\n#include <set>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    set <int> original_array;\n    map <int, int> frequency;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        int element_i;\n        scanf(\"%d\", &element_i);\n\n        frequency[element_i]++;\n        original_array.insert(element_i);\n    }\n\n    long long no_of_pairs = 0;\n    for(map <int, int> :: iterator i = frequency.begin(); i != frequency.end(); i++)\n    {\n        int element_i = i->first;\n        int frequency_i = i->second;\n\n        for(int power = 0; power <= 31; power++)\n        {\n            int power_of_2 = (1 << power);\n\n            int pair_element = power_of_2 - element_i;\n            int pair_frequency = 0;\n\n            if(pair_element > 0 && original_array.count(pair_element) == 1)\n                pair_frequency = (element_i == pair_element ? frequency_i - 1 : frequency[pair_element]);\n\n            no_of_pairs += frequency_i*1LL*pair_frequency;\n\n        }\n    }\n\n    no_of_pairs = no_of_pairs/2;\n\n    printf(\"%I64d\\n\", no_of_pairs);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 14/Queue at the School.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_people, time;\r\n    string school_queue;\r\n    cin >> no_of_people >> time >> school_queue;\r\n\r\n    for(int i = 1; i <= time; i++)\r\n    {\r\n        for(int person = 0; person < no_of_people; person++)\r\n        {\r\n            if(school_queue[person] == 'B' && school_queue[person + 1] == 'G')\r\n            {\r\n                swap(school_queue[person], school_queue[person + 1]);\r\n                person++;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << school_queue;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Rectangles.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_rows, no_of_columns;\r\n    scanf(\"%d %d\", &no_of_rows, &no_of_columns);\r\n\r\n    typedef vector <int> v_int;\r\n    vector <v_int> rectangle(no_of_rows + 1, v_int(no_of_columns + 1));\r\n    long long no_of_sets = 0;\r\n\r\n    for(int row = 1; row <= no_of_rows; row++)\r\n    {\r\n        int no_of_blacks_in_row = 0, no_of_whites_in_row = 0;\r\n        for(int column = 1; column <= no_of_columns; column++)\r\n        {\r\n            scanf(\"%d\", &rectangle[row][column]);\r\n            no_of_blacks_in_row += (rectangle[row][column] == 1);\r\n        }\r\n\r\n        no_of_whites_in_row = no_of_columns - no_of_blacks_in_row;\r\n\r\n        long long black_sets = (1LL << no_of_blacks_in_row) - 1;\r\n        long long white_sets = (1LL << no_of_whites_in_row) - 1;\r\n\r\n        no_of_sets += black_sets + white_sets;\r\n    }\r\n\r\n    for(int column = 1; column <= no_of_columns; column++)\r\n    {\r\n        int no_of_blacks_in_column = 0, no_of_whites_in_column = 0;\r\n        for(int row = 1; row <= no_of_rows; row++)\r\n        {\r\n            no_of_blacks_in_column += (rectangle[row][column] == 1);\r\n        }\r\n        no_of_whites_in_column = no_of_rows - no_of_blacks_in_column;\r\n\r\n        long long black_sets = (1LL << no_of_blacks_in_column) - 1;\r\n        long long white_sets = (1LL << no_of_whites_in_column) - 1;\r\n\r\n        no_of_sets += black_sets + white_sets;\r\n    }\r\n\r\n    no_of_sets -= (no_of_columns*no_of_rows); //Singleton sets counted twice\r\n\r\n    printf(\"%I64d\\n\", no_of_sets);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Supercentral Point.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nstruct Point\r\n{\r\n    int x, y;\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <Point> vertex(no_of_points + 1);\r\n    for(int i = 1; i <= no_of_points; i++)\r\n        scanf(\"%d %d\", &vertex[i].x, &vertex[i].y);\r\n\r\n    int no_of_supercentral_points = 0;\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        int upper = false, lower = false, right = false, left = false;\r\n\r\n        for(int j = 1; j <= no_of_points; j++)\r\n        {\r\n            if(j != i)\r\n            {\r\n                if( (vertex[j].x == vertex[i].x) && (vertex[i].y > vertex[j].y) ) upper = true;\r\n                if( (vertex[j].x == vertex[i].x) && (vertex[i].y < vertex[j].y) ) lower = true;\r\n                if( (vertex[j].y == vertex[i].y) && (vertex[i].x > vertex[j].x) ) left = true;\r\n                if( (vertex[j].y == vertex[i].y) && (vertex[i].x < vertex[j].x) ) right = true;\r\n            }\r\n\r\n\r\n        }//printf(\"Point %d\\nUpper = %d, Lower = %d, left = %d, Right = %d\\n\", i, upper, lower, left, right);\r\n        no_of_supercentral_points += (upper && lower && right && left);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_supercentral_points);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Tram.cpp",
    "content": "#include <cstdio>\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_stops;\r\n    scanf(\"%d\", &no_of_stops);\r\n\r\n    int minimum_capacity = 0, no_of_people_on_train = 0;\r\n    for(int i = 1; i <= no_of_stops; i++)\r\n    {\r\n        int no_of_entries, no_of_exits;\r\n        scanf(\"%d %d\",&no_of_exits, &no_of_entries);\r\n\r\n        no_of_people_on_train += (no_of_entries - no_of_exits);\r\n        minimum_capacity = max(minimum_capacity, no_of_people_on_train);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_capacity);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Ultra Fast Mathematician.cpp",
    "content": "#include <cstring>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string num_1, num_2, answer;\r\n    cin >> num_1 >> num_2;\r\n\r\n    typedef unsigned int u_int;\r\n    for(u_int i = 0; i < num_1.size(); i++)\r\n    {\r\n        answer += (num_1[i] == num_2[i] ? '0' : '1');\r\n    }\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 14/Vasya and String.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define MAX_LENGTH 100000 + 2\r\n\r\nint get_max_window_length(char string[], char changed_char, int max_changes)\r\n{\r\n    int max_window_length = 0, window_length = 0, no_of_changes = 0;\r\n\r\n    for(int window_end = 0, window_start = 0; string[window_end] != '\\0'; window_end++)\r\n    {\r\n        no_of_changes += (string[window_end] == changed_char);\r\n\r\n        while(no_of_changes > max_changes)\r\n        {\r\n            no_of_changes -= (string[window_start++] == changed_char);\r\n        }\r\n\r\n        window_length = window_end - (window_start - 1);\r\n        max_window_length = max(max_window_length, window_length);\r\n    }\r\n\r\n    return max_window_length;\r\n}\r\n\r\nint main()\r\n{\r\n    int length, max_changes;\r\n    char string[MAX_LENGTH];\r\n    scanf(\"%d %d %s\", &length, &max_changes, string);\r\n\r\n    int beauty = max(get_max_window_length(string, 'a', max_changes), get_max_window_length(string, 'b', max_changes));\r\n\r\n    printf(\"%d\\n\", beauty);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Army.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_ranks;\r\n    scanf(\"%d\", &no_of_ranks);\r\n\r\n    vector <int> no_of_days_to_reach(no_of_ranks + 1, 0);\r\n    for(int rank_i = 2; rank_i <= no_of_ranks; rank_i++)\r\n    {\r\n        int day_i;\r\n        scanf(\"%d\", &day_i);\r\n\r\n        no_of_days_to_reach[rank_i] = no_of_days_to_reach[rank_i - 1] + day_i;\r\n    }\r\n\r\n    int starting_rank, ending_rank;\r\n    scanf(\"%d %d\", &starting_rank, &ending_rank);\r\n\r\n    printf(\"%d\\n\", no_of_days_to_reach[ending_rank] - no_of_days_to_reach[starting_rank]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Between the Offices.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_days;\r\n    const int MAX_DAYS = 102;\r\n    char flights[MAX_DAYS];\r\n    scanf(\"%d %s\", &no_of_days, flights);\r\n\r\n    int flights_from_seattle = 0, flights_to_seattle = 0;\r\n    for(int i = 1; i < no_of_days; i++)\r\n    {\r\n        flights_to_seattle += (flights[i - 1] == 'F' && flights[i] == 'S');\r\n        flights_from_seattle += (flights[i - 1] == 'S' && flights[i] == 'F');\r\n    }\r\n\r\n    printf(\"%s\\n\", flights_from_seattle > flights_to_seattle ? \"YES\" : \"NO\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Cableway.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int red, blue, green;\r\n    scanf(\"%d %d %d\", &red, &green, &blue);\r\n\r\n    int red_rides = red/2 + red%2;\r\n    int blue_rides = blue/2 + blue%2;\r\n    int green_rides = green/2 + green%2;\r\n\r\n    const int ONE_RIDE_DURATION = 30;\r\n    int no_of_minutes, last_ride_arrival;\r\n\r\n    if(red_rides > blue_rides && red_rides > green_rides)\r\n    {\r\n        last_ride_arrival = 3*(red_rides - 1);\r\n        no_of_minutes = last_ride_arrival + ONE_RIDE_DURATION;\r\n    }\r\n    else if(green_rides >= red_rides && green_rides > blue_rides)\r\n    {\r\n        last_ride_arrival = 3*(green_rides - 1) + 1;\r\n        no_of_minutes = last_ride_arrival + ONE_RIDE_DURATION;\r\n    }\r\n    else if(blue_rides >= red_rides && blue_rides >= green_rides)\r\n    {\r\n        last_ride_arrival = 3*(blue_rides - 1) + 2;\r\n        no_of_minutes = last_ride_arrival + ONE_RIDE_DURATION;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Ciferia.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int k, n;\r\n    scanf(\"%d %d\", &k, &n);\r\n\r\n    int power = 0;\r\n    while(n%k == 0)\r\n    {\r\n        n = n/k;\r\n        power++;\r\n    }\r\n\r\n    printf(n > 1 ? \"NO\\n\" : \"YES\\n%d\\n\", power - 1);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Coins.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\r\n\tvector <int> denominations;\r\n\tdenominations.push_back(n);\r\n\r\n\tfor(int i = 2; n > 1; i++)\r\n\t{\r\n\t\twhile(n%i == 0)\r\n\t\t{\r\n\t\t\tn = n/i;\r\n\t\t\tdenominations.push_back(n);\r\n\t\t}\r\n\t}\r\n\r\n\tfor(int i = 0; i < denominations.size(); i++)\r\n\t\tprintf(\"%d \", denominations[i]);\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Divisibility by Eight.cpp",
    "content": "#include <cstdio>\r\n#include <string>\r\n#include <iostream>\r\n\r\n#define MAX_DIGITS 100 + 2\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string number;\r\n    cin >> number;\r\n\r\n    int found = false;\r\n    int answer;\r\n\r\n    typedef unsigned int u_int;\r\n\r\n    for(u_int i = 0; i < number.size() && !found; i++)\r\n    {\r\n        if(number[i] == '8' || number[i] == '0')\r\n            found = true, answer = number[i] - '0';\r\n    }\r\n\r\n    for(u_int i = 0; i < number.size() && !found; i++)\r\n    {\r\n        for(u_int j = i + 1; j < number.size() && !found; j++)\r\n        {\r\n            int first_digit = number[i] - '0', second_digit = number[j] - '0';\r\n            int number_formed = 10*first_digit + second_digit;\r\n\r\n            if(number_formed%8 == 0)\r\n                found = true, answer = number_formed;\r\n        }\r\n    }\r\n\r\n    for(u_int i = 0; i < number.size() && !found; i++)\r\n    {\r\n        for(u_int j = i + 1; j < number.size() && !found; j++)\r\n        {\r\n            for(u_int k = j + 1; k < number.size() && !found; k++)\r\n            {\r\n                int first_digit = number[i] - '0', second_digit = number[j]- '0', third_digit = number[k] - '0';\r\n                int number_formed = 100*first_digit + 10*second_digit + third_digit;\r\n\r\n                if(number_formed%8 == 0)\r\n                {\r\n                    answer = number_formed;\r\n                    found = true;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    if(found)\r\n        printf(\"YES\\n%d\\n\", answer);\r\n    else\r\n        printf(\"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Exams.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_exams;\r\n    scanf(\"%d\", &no_of_exams);\r\n\r\n    vector < pair <int, int> > exam_day(no_of_exams + 1);\r\n    for(int i = 1; i <= no_of_exams; i++)\r\n    {\r\n        scanf(\"%d %d\", &exam_day[i].first, &exam_day[i].second);\r\n    }\r\n\r\n    sort(all(exam_day));\r\n\r\n    int last_day = 0;\r\n    for(int i = 1; i <= no_of_exams;i++)\r\n    {\r\n        int choice_1 = exam_day[i].first, choice_2 = exam_day[i].second;\r\n\r\n        if(choice_1 >= last_day && choice_2 >= last_day)\r\n            last_day = min(choice_1, choice_2);\r\n        else if(choice_1 >= last_day)\r\n            last_day = choice_1;\r\n        else if(choice_2 >= last_day)\r\n            last_day = choice_2;\r\n    }\r\n\r\n    printf(\"%d\\n\", last_day);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Given Length and Sum of Digits.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int sum, no_of_digits;\n    scanf(\"%d %d\", &no_of_digits, &sum);\n\n    if(sum == 0 && no_of_digits == 1)\n    {\n        printf(\"0 0\\n\"); return 0;\n    }\n    else if(sum == 0 || sum > 9*no_of_digits)\n    {\n        printf(\"-1 -1\\n\"); return 0;\n    }\n\n    vector <int> minimum_number(no_of_digits + 1, 0);\n\n    int remaining_sum = sum - 1, i;\n    for(i = no_of_digits; i > 0 && remaining_sum > 0; i--)\n    {\n        if(remaining_sum >= 9)\n        {\n            minimum_number[i] = 9;\n            remaining_sum -= 9;\n        }\n        else\n        {\n            minimum_number[i] = remaining_sum;\n            remaining_sum = 0;\n        }\n    }\n\n    minimum_number[1] = (minimum_number[1] == 0 ? 1 : minimum_number[1] + 1);\n\n    vector <int> maximum_number(no_of_digits + 1, 0);\n    remaining_sum = sum;\n    for(i = 1; i <= no_of_digits && remaining_sum > 0; i++)\n    {\n        if(remaining_sum >= 9)\n        {\n            maximum_number[i] = 9;\n            remaining_sum -= 9;\n        }\n        else\n        {\n            maximum_number[i] = remaining_sum;\n            remaining_sum = 0;\n        }\n    }\n    for(int i = 1; i <= no_of_digits; i++) printf(\"%d\", minimum_number[i]);\n\n    printf(\" \");\n\n    for(int i = 1; i <= no_of_digits; i++) printf(\"%d\", maximum_number[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 15/Ilya and Sticks.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_sticks;\r\n    scanf(\"%d\", &no_of_sticks);\r\n\r\n    vector <int> length(no_of_sticks);\r\n    for(int i = 0; i < no_of_sticks; i++)\r\n        scanf(\"%d\", &length[i]);\r\n\r\n    sort(all(length));\r\n\r\n    int side_1 = 0, side_2 = 0;\r\n    long long area = 0;\r\n    for(int i = no_of_sticks - 1; i - 1 >= 0; i--)\r\n    {\r\n        if(length[i] - length[i - 1] <= 1)\r\n        {\r\n            if(side_1 == 0)\r\n            {\r\n                side_1 = length[i - 1];\r\n            }\r\n            else if(side_2 == 0)\r\n            {\r\n                side_2 = length[i - 1];\r\n\r\n                area += side_1*1LL*side_2;\r\n\r\n                side_1 = side_2 = 0;\r\n            }\r\n            i--;\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", area);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Inna and Huge Candy Matrix.cpp",
    "content": "#include <cstdio>\r\n\r\ninline void swap(int &a, int &b)\r\n{\r\n    a = a^b; b = b^a; a = a^b;\r\n}\r\n\r\ninline void horizontal_rotate(int &column, int no_of_columns)\r\n{\r\n    column = no_of_columns + 1 - column;\r\n}\r\n\r\ninline void clockwise_transformation(int &row, int &column, int &no_of_rows, int &no_of_columns)\r\n{\r\n    int current_column = column, current_row = row;\r\n\r\n    row = current_column;\r\n    column = no_of_rows + 1 - current_row;\r\n\r\n    swap(no_of_columns, no_of_rows);\r\n}\r\n\r\ninline void anti_clockwise_transformation(int &row, int &column, int &no_of_rows, int &no_of_columns)\r\n{\r\n    int current_row = row, current_column = column;\r\n\r\n    column = current_row;\r\n    row = no_of_columns + 1 - current_column;\r\n\r\n    swap(no_of_columns, no_of_rows);\r\n}\r\n\r\nint main()\r\n{\r\n    int original_no_of_rows, original_no_of_columns, clockwise, horizontal, anti_clockwise, no_of_points;\r\n    scanf(\"%d %d %d %d %d %d\", &original_no_of_rows, &original_no_of_columns, &clockwise, &horizontal, &anti_clockwise, &no_of_points);\r\n\r\n    clockwise %= 4;\r\n    horizontal %= 2;\r\n    anti_clockwise %= 4;\r\n\r\n    while(no_of_points--)\r\n    {\r\n        int no_of_rows = original_no_of_rows;\r\n        int no_of_columns = original_no_of_columns;\r\n        int row, column;\r\n        scanf(\"%d %d\", &row, &column);\r\n\r\n        for(int i = 1; i <= clockwise; i++)\r\n            clockwise_transformation(row, column, no_of_rows, no_of_columns); //printf(\"%d %d\\n\", row, column);\r\n\r\n        for(int i = 1; i <= horizontal; i++)\r\n            horizontal_rotate(column, no_of_columns); //printf(\"%d %d\\n\", row, column);\r\n\r\n        for(int i = 1; i <= anti_clockwise; i++)\r\n            anti_clockwise_transformation(row, column, no_of_rows, no_of_columns); //printf(\"%d %d\\n\", row, column);\r\n\r\n        printf(\"%d %d\\n\", row, column);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/K-Multiple Free Set.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, k;\r\n    scanf(\"%d %d\", &no_of_elements, &k);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    sort(all(element));\r\n\r\n    int set_size = 0;\r\n    vector <int> crossed_out(no_of_elements, false);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        if(!crossed_out[i])\r\n        {\r\n            set_size++;\r\n\r\n            if(binary_search(all(element), k*1LL*element[i]))\r\n            {\r\n                int index = lower_bound(all(element), k*1LL*element[i]) - element.begin();\r\n                crossed_out[index] = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", set_size);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Kefa and Park.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_VERTICES = 2e5 + 1;\r\nint visited[MAX_VERTICES] = {false};\r\nint has_cat[MAX_VERTICES] = {false};\r\nint no_of_consecutive_cats_till[MAX_VERTICES] = {0};\r\nvector <int> tree[MAX_VERTICES];\r\n\r\nint max_cats;\r\n\r\nvoid dfs(int current_park, int &no_of_paths)\r\n{\r\n    if(tree[current_park].size() == 1 && visited[tree[current_park][0]])\r\n        no_of_paths++;\r\n\r\n    for(int i = 0; i < tree[current_park].size(); i++)\r\n    {\r\n        int next_park = tree[current_park][i];\r\n\r\n        if(!visited[next_park])\r\n        {\r\n            visited[next_park] = true;\r\n\r\n            no_of_consecutive_cats_till[next_park] = (has_cat[next_park] ? no_of_consecutive_cats_till[current_park] + 1 : 0);\r\n\r\n            if(no_of_consecutive_cats_till[next_park] <= max_cats)\r\n                dfs(next_park, no_of_paths);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d %d\", &no_of_vertices, &max_cats);\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        scanf(\"%d\", &has_cat[i]);\r\n\r\n    for(int i = 1; i <= no_of_vertices - 1; i++)\r\n    {\r\n        int x, y;\r\n        scanf(\"%d %d\", &x, &y);\r\n\r\n        tree[x].push_back(y);\r\n        tree[y].push_back(x);\r\n    }\r\n\r\n    no_of_consecutive_cats_till[1] = has_cat[1];\r\n    visited[1] = true;\r\n    int no_of_paths = 0;\r\n\r\n    dfs(1, no_of_paths);\r\n\r\n    printf(\"%d\\n\", no_of_paths);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Mahmoud and Ehab and the MEX.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, x;\r\n    scanf(\"%d %d\", &no_of_elements, &x);\r\n\r\n    const int MAX = 101;\r\n    vector <int> frequency(MAX, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        frequency[element_i]++;\r\n    }\r\n\r\n    int no_of_missing_elements_before_x = 0;\r\n    int x_present = frequency[x];\r\n\r\n    for(int i = 0; i < x; i++)\r\n    {\r\n        no_of_missing_elements_before_x += (frequency[i] == 0);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_missing_elements_before_x + x_present);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Mahmoud and Ehab and the bipartiteness.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int BLACK = 0, WHITE = 1, NO_OF_COLOURS = 2, MAX_VERTICES = 1e5 + 1;\r\n\r\nvector <int> tree[MAX_VERTICES];\r\nint visited[MAX_VERTICES] = {false};\r\nint no_of_elements[NO_OF_COLOURS] = {0};\r\n\r\nvoid dfs_and_colour(int v, int current_colour)\r\n{\r\n    int next_colour = (current_colour + 1)%2;\r\n\r\n    if(!visited[v])\r\n    {\r\n        no_of_elements[current_colour]++;\r\n        visited[v] = true;\r\n\r\n        for(int i = 0; i < tree[v].size(); i++)\r\n            dfs_and_colour(tree[v][i], next_colour);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d\", &no_of_vertices);\r\n\r\n    for(int edge = 1; edge <= no_of_vertices - 1; edge++)\r\n    {\r\n        int x, y;\r\n        scanf(\"%d %d\", &x, &y);\r\n\r\n        tree[x].push_back(y);\r\n        tree[y].push_back(x);\r\n    }\r\n\r\n    dfs_and_colour(1, BLACK);\r\n\r\n    printf(\"%I64d\\n\", no_of_elements[BLACK]*1LL*no_of_elements[WHITE] - (no_of_vertices - 1));\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Mahmoud and Ehab and the xor.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, x;\r\n    scanf(\"%d %d\", &no_of_numbers, &x);\r\n\r\n    if(no_of_numbers == 1)\r\n    {\r\n        printf(\"YES\\n%d\\n\", x);\r\n    }\r\n    else if(no_of_numbers == 2)\r\n    {\r\n        if(x == 0)\r\n            printf(\"NO\\n\");\r\n        else\r\n            printf(\"YES\\n0 %d\\n\", x);\r\n    }\r\n    else\r\n    {\r\n        const int POWER_2 = 1 << 19, PREVIOUS_POWER_2 = 1 << 18;\r\n        int bitwise_xor = 0;\r\n\r\n        printf(\"YES\\n\");\r\n        for(int i = 1; i <= no_of_numbers - 3; i++)\r\n        {\r\n            bitwise_xor ^= i;\r\n            printf(\"%d \", i);\r\n        }\r\n\r\n        if(bitwise_xor == x)\r\n            printf(\"%d %d %d\\n\", POWER_2, PREVIOUS_POWER_2, (POWER_2|PREVIOUS_POWER_2));\r\n        else\r\n            printf(\"%d %d %d\\n\", PREVIOUS_POWER_2, (POWER_2^bitwise_xor^x), (POWER_2|PREVIOUS_POWER_2));\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Number of Ways.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <long long> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        sum_till[i] = sum_till[i - 1] + element_i;\r\n    }\r\n\r\n    vector <long long> sum_from(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_from[i] = sum_till[no_of_elements] - sum_till[i - 1];\r\n    }\r\n\r\n    long long no_of_ways = 0, total_sum = sum_till[no_of_elements];\r\n\r\n    if(total_sum%3 != 0)\r\n    {\r\n        printf(\"%I64d\\n\", no_of_ways);\r\n        return 0;\r\n    }\r\n\r\n    vector <int> no_of_places_that_sum_to_a_third_from(no_of_elements + 2, 0);\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        no_of_places_that_sum_to_a_third_from[i] = no_of_places_that_sum_to_a_third_from[i + 1] +\r\n                                                   (3*sum_from[i] == total_sum);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements - 2; i++)\r\n    {\r\n        if(3*sum_till[i] == total_sum)\r\n        {\r\n            no_of_ways += no_of_places_that_sum_to_a_third_from[i + 2];\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_ways);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Pearls in a Row.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_pearls;\r\n    scanf(\"%d\", &no_of_pearls);\r\n\r\n    set <int> current_segment_pearls;\r\n    vector <pair <int, int> > segment;\r\n    int left = 1;\r\n\r\n    for(int right = 1; right <= no_of_pearls; right++)\r\n    {\r\n        int pearl_type;\r\n        scanf(\"%d\", &pearl_type);\r\n\r\n        if(current_segment_pearls.count(pearl_type) == 1)\r\n        {\r\n            segment.push_back(make_pair(left, right));\r\n            current_segment_pearls.clear();\r\n\r\n            left = right + 1;\r\n        }\r\n        else\r\n        {\r\n            current_segment_pearls.insert(pearl_type);\r\n        }\r\n    }\r\n\r\n    if(segment.size() == 0)\r\n        printf(\"-1\\n\");\r\n    else\r\n    {\r\n        segment.back().second = max(segment.back().second, no_of_pearls);\r\n\r\n        printf(\"%u\\n\", segment.size());\r\n        for(int i = 0; i < segment.size(); i++)\r\n            printf(\"%d %d\\n\", segment[i].first, segment[i].second);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Pie Rules.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_pieces;\r\n    scanf(\"%d\", &no_of_pieces);\r\n\r\n    vector <int> pie(no_of_pieces + 1);\r\n    for(int i = 1; i <= no_of_pieces; i++)\r\n        scanf(\"%d\", &pie[i]);\r\n\r\n    vector <int> sum_from(no_of_pieces + 3, 0);\r\n    const int NO_OF_PLAYERS = 2, ALICE = 0, BOB = 1;\r\n    int maximum_from[no_of_pieces + 1][NO_OF_PLAYERS];\r\n\r\n    for(int i = no_of_pieces; i >= 1; i--)\r\n    {\r\n        sum_from[i] = sum_from[i + 1] + pie[i];\r\n\r\n        if(i == no_of_pieces)\r\n        {\r\n            maximum_from[i][ALICE] = maximum_from[i][BOB] = pie[i];\r\n        }\r\n        else\r\n        {\r\n            maximum_from[i][ALICE] = max(maximum_from[i + 1][ALICE], pie[i] + sum_from[i + 1] - maximum_from[i + 1][BOB]);\r\n            maximum_from[i][BOB] = max(maximum_from[i + 1][BOB], pie[i] + sum_from[i + 1] - maximum_from[i + 1][BOB]);\r\n        }\r\n    }\r\n\r\n    int maximum_for_alice = sum_from[1] - maximum_from[1][BOB];\r\n\r\n    printf(\"%d %d\\n\", maximum_for_alice, maximum_from[1][BOB]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Quasi-palindrome.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_palindrome(int n)\r\n{\r\n    int reverse_n = 0, original_n = n;\r\n\r\n    while(n > 0)\r\n    {\r\n        reverse_n = reverse_n*10 + n%10;\r\n        n = n/10;\r\n    }\r\n\r\n    return (reverse_n == original_n);\r\n}\r\n\r\nint palindrome_without_trailing_zeroes(int n)\r\n{\r\n    while(n%10 == 0)\r\n        n = n/10;\r\n\r\n    return is_palindrome(n);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(\"%s\\n\", palindrome_without_trailing_zeroes(n) ? \"YES\" : \"NO\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Soldier and Number Game.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid precompute(vector <int> &no_of_prime_divisors_till, int LIMIT)\r\n{\r\n    vector <int> largest_prime_factor(LIMIT, 0);\r\n    vector <int> no_of_prime_divisors(LIMIT, 0);\r\n\r\n    for(int i = 2; i < LIMIT; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple < LIMIT; multiple += i)\r\n                largest_prime_factor[multiple] = i;\r\n        }\r\n\r\n        int p = largest_prime_factor[i];\r\n        no_of_prime_divisors[i] = 1 + no_of_prime_divisors[i/p];\r\n\r\n        no_of_prime_divisors_till[i] += no_of_prime_divisors[i] + no_of_prime_divisors_till[i - 1];\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 5e6 + 1;\r\n    vector <int> no_of_prime_divisors_till(LIMIT, 0);\r\n    precompute(no_of_prime_divisors_till, LIMIT);\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int left, right;\r\n        scanf(\"%d %d\", &right, &left);\r\n\r\n        printf(\"%d\\n\", no_of_prime_divisors_till[right] - no_of_prime_divisors_till[left]);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Tanya and Toys.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_toys, money;\r\n    scanf(\"%d %d\", &no_of_toys, &money);\r\n\r\n    set <int> toy_type;\r\n    for(int i = 1; i <= no_of_toys; i++)\r\n    {\r\n        int toy_i;\r\n        scanf(\"%d\", &toy_i);\r\n\r\n        toy_type.insert(toy_i);\r\n    }\r\n\r\n    vector <int> new_toys;\r\n    for(int toy = 1; money >= toy; toy++)\r\n    {\r\n        if(toy_type.count(toy) == 0)\r\n        {\r\n            new_toys.push_back(toy);\r\n            money -= toy;\r\n        }\r\n    }\r\n\r\n    printf(\"%u\\n\", new_toys.size());\r\n    for(int i = 0; i < new_toys.size(); i++)\r\n        printf(\"%d \", new_toys[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Team.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_1s, no_of_0s;\r\n    scanf(\"%d %d\", &no_of_0s, &no_of_1s);\r\n\r\n    if(no_of_1s > 2*(no_of_0s + 1) || no_of_0s > no_of_1s + 1)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    while(no_of_0s > 0 && no_of_1s > 0)\r\n    {\r\n        if(no_of_1s > no_of_0s)\r\n        {\r\n            printf(\"110\");\r\n            no_of_1s -= 2, no_of_0s--;\r\n        }\r\n        else if(no_of_1s == no_of_0s)\r\n        {\r\n            printf(\"10\");\r\n            no_of_0s--, no_of_1s--;\r\n        }\r\n        else if(no_of_1s < no_of_0s)\r\n        {\r\n            printf(\"01\");\r\n            no_of_0s--, no_of_1s--;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_0s; i++) printf(\"0\");\r\n    for(int i = 1; i <= no_of_1s; i++) printf(\"1\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/The Eternal Immortality.cpp",
    "content": "#include <cstdio>\r\n\r\ntypedef long long LL;\r\n\r\nint main()\r\n{\r\n    LL a, b;\r\n    scanf(\"%I64d %I64d\", &a, &b);\r\n\r\n    int answer = 1;\r\n    if(b - a < 5)\r\n    {\r\n        for(LL i = a + 1; i <= b; i++)\r\n            answer = answer*(i%10);\r\n\r\n        answer %= 10;\r\n    }\r\n    else\r\n    {\r\n        answer = 0;\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/Triangle.cpp",
    "content": "#include <cstdio>\r\n\r\nint triangle(int side_a, int side_b, int side_c)\r\n{\r\n    return ( (side_a + side_b > side_c) && (side_b + side_c > side_a) && (side_c + side_a > side_b) );\r\n}\r\n\r\nint segment(int side_a, int side_b, int side_c)\r\n{\r\n    return ( (side_a + side_b == side_c) || (side_b + side_c == side_a) || (side_c + side_a == side_b) );\r\n}\r\n\r\nint main()\r\n{\r\n    int side_a, side_b, side_c, side_d;\r\n    scanf(\"%d %d %d %d\", &side_a, &side_b, &side_c, &side_d);\r\n\r\n    if(triangle(side_a, side_b, side_c) || triangle(side_b, side_c, side_d) || triangle(side_c, side_d, side_a) || triangle(side_b, side_a, side_d) )\r\n        printf(\"TRIANGLE\\n\");\r\n    else if(segment(side_a, side_b, side_c) || segment(side_b, side_c, side_d) || segment(side_c, side_d, side_a) || segment(side_b, side_a, side_d) )\r\n        printf(\"SEGMENT\\n\");\r\n    else\r\n        printf(\"IMPOSSIBLE\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 15/USB Flash Drives.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nint main()\r\n{\r\n    int no_of_drives, file_size;\r\n    scanf(\"%d %d\", &no_of_drives, &file_size);\r\n\r\n    vector <int> capacity(no_of_drives);\r\n    for(int i = 0; i < no_of_drives; i++)\r\n        scanf(\"%d\", &capacity[i]);\r\n\r\n    sort(all(capacity));\r\n\r\n    int no_of_drives_used = 0;\r\n    for(int drive_i = no_of_drives - 1; file_size > 0 && drive_i >= 0; drive_i--, no_of_drives_used++)\r\n        file_size -= capacity[drive_i];\r\n\r\n    printf(\"%d\\n\", no_of_drives_used);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Amusing Joke.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    const int NO_OF_ALPHABETS = 26;\r\n    int frequency[NO_OF_ALPHABETS] = {0};\r\n\r\n    for(int i = 1; i <= 3; i++)\r\n    {\r\n        const int MAX_LENGTH = 103;\r\n        char name[MAX_LENGTH];\r\n        scanf(\"%s\", name);\r\n\r\n        for(int j = 0; name[j] != '\\0'; j++)\r\n            frequency[name[j] - 'A'] += (i == 3 ? -1 : 1);\r\n    }\r\n\r\n    int is_possible = true;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n        if(frequency[i] != 0)\r\n            is_possible = false;\r\n\r\n    printf(is_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Anton and Letters.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <set>\r\n\r\n#define is_alpha(x) ('a' <= x && x <= 'z')\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string line;\r\n    getline(cin, line);\r\n\r\n    set <char> letters;\r\n    for(int i = 0; i < line.size(); i++)\r\n    {\r\n        if(is_alpha(line[i]))\r\n            letters.insert(line[i]);\r\n    }\r\n\r\n    cout << letters.size();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Cards with Numbers.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <fstream>\r\n\r\nusing namespace std;\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nstruct card\r\n{\r\n    int index, value;\r\n};\r\n\r\nbool sort_by_value(const card &A, const card &B)\r\n{\r\n    return (A.value < B.value);\r\n}\r\n\r\nint main()\r\n{\r\n    FILE *input = fopen(\"input.txt\", \"r\");\r\n    int no_of_cards;\r\n    fscanf(input, \"%d\", &no_of_cards);\r\n\r\n    vector <card> cards(2*no_of_cards);\r\n    for(int i = 0; i < 2*no_of_cards; i++)\r\n    {\r\n        fscanf(input, \"%d\", &cards[i].value);\r\n        cards[i].index = i + 1;\r\n    }\r\n\r\n    sort(all(cards), sort_by_value);\r\n\r\n    FILE *output = fopen(\"output.txt\", \"w\");\r\n\r\n    vector <pair <int, int> > solution;\r\n    for(int i = 0; i < 2*no_of_cards; i += 2)\r\n    {\r\n        if(cards[i].value == cards[i + 1].value)\r\n            solution.push_back(make_pair(cards[i].index, cards[i + 1].index));\r\n        else\r\n        {\r\n            fprintf(output, \"-1\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < no_of_cards; i++)\r\n        fprintf(output, \"%d %d\\n\", solution[i].first, solution[i].second);\r\n\r\n    fclose(input);\r\n    fclose(output);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Classroom Watch.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint digit_sum(int n)\r\n{\r\n    int sum = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        sum += n%10;\r\n        n = n/10;\r\n    }\r\n\r\n    return sum;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int MAX_DIGIT_SUM = 81;\r\n    int x = max(0, n - MAX_DIGIT_SUM);\r\n\r\n    vector <int> answer;\r\n    while(x <= n)\r\n    {\r\n        if(x + digit_sum(x) == n)\r\n            answer.push_back(x);\r\n\r\n        x++;\r\n    }\r\n\r\n    printf(\"%d\\n\", answer.size());\r\n    for(int i = 0; i < answer.size(); i++)\r\n        printf(\"%d \", answer[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Cupboards.cpp",
    "content": "#include <cstdio>\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n\tconst int OPEN = 1, CLOSED = 0;\r\n\tint no_of_cupboards;\r\n\tscanf(\"%d\", &no_of_cupboards);\r\n\r\n\tint left_open_doors = 0, left_closed_doors = 0;\r\n\tint right_open_doors = 0, right_closed_doors = 0;\r\n\r\n    while(no_of_cupboards--)\r\n\t{\r\n\t\tint left, right;\r\n\t\tscanf(\"%d %d\", &left, &right);\r\n\r\n\t\tleft_open_doors += (left == OPEN);\r\n\t\tleft_closed_doors += (left == CLOSED);\r\n\r\n\t\tright_open_doors += (right == OPEN);\r\n\t\tright_closed_doors += (right == CLOSED);\r\n\t}\r\n\r\n\tint minimum_left_operations = min(left_closed_doors, left_open_doors);\r\n\tint minimum_right_operations = min(right_open_doors, right_closed_doors);\r\n\r\n\tprintf(\"%d\\n\", minimum_left_operations + minimum_right_operations);\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Dishonest Sellers.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nstruct prices\r\n{\r\n    int now, discount, difference;\r\n};\r\n\r\nbool sort_By_Difference(const prices &A, const prices &B)\r\n{\r\n    return (A.difference < B.difference);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_days, minimum_now_buys;\r\n    scanf(\"%d %d\", &no_of_days, &minimum_now_buys);\r\n\r\n    vector <prices> price(no_of_days);\r\n    for(int i = 0; i < no_of_days; i++)\r\n        scanf(\"%d\", &price[i].now);\r\n\r\n    for(int i = 0; i < no_of_days; i++)\r\n        scanf(\"%d\", &price[i].discount);\r\n\r\n    for(int i = 0; i < no_of_days; i++)\r\n        price[i].difference = price[i].now - price[i].discount;\r\n\r\n    sort(all(price), sort_By_Difference);\r\n\r\n    int money_used = 0;\r\n    for(int i = 0; i < no_of_days; i++)\r\n    {\r\n        if(i < minimum_now_buys)\r\n            money_used += price[i].now;\r\n        else\r\n            money_used += min(price[i].now, price[i].discount);\r\n    }\r\n\r\n    printf(\"%d\\n\", money_used);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Dubstep.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string song;\r\n    cin >> song;\r\n\r\n    string word;\r\n    for(int i = 0; i < song.length(); i++)\r\n    {\r\n        if(i + 2 < song.length() && song[i] == 'W' && song[i + 1] == 'U' && song[i + 2] == 'B')\r\n        {\r\n            i += 2;\r\n            if(!word.empty())\r\n            {\r\n                cout << word << \" \";\r\n                word.clear();\r\n            }\r\n        }\r\n        else\r\n        {\r\n            word += song[i];\r\n        }\r\n    }\r\n\r\n    if(!word.empty())\r\n        cout << word << \" \";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Easy Number Challenge.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid precompute(vector <int> &number_of_divisors, int LIMIT)\r\n{\r\n    number_of_divisors[1] = 1;\r\n\r\n    vector <int> largest_prime_factor(LIMIT + 1, 0);\r\n    for(int i = 2; i <= LIMIT; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple <= LIMIT; multiple += i)\r\n                largest_prime_factor[multiple] = i;\r\n        }\r\n\r\n        int exponent = 0;\r\n\r\n        int reduced_i = i;\r\n        while(reduced_i%largest_prime_factor[i] == 0)\r\n        {\r\n            reduced_i /= largest_prime_factor[i];\r\n            exponent++;\r\n        }\r\n\r\n        number_of_divisors[i] = (exponent + 1)*number_of_divisors[reduced_i];\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 1e6;\r\n    vector <int> number_of_divisors(LIMIT + 1, 0);\r\n    precompute(number_of_divisors, LIMIT);\r\n\r\n    int a, b, c;\r\n    scanf(\"%d %d %d\", &a, &b, &c);\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= a; i++)\r\n    {\r\n        for(int j = 1; j <= b; j++)\r\n        {\r\n            for(int k = 1; k <= c; k++)\r\n            {\r\n                sum += number_of_divisors[i*j*k];\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", sum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Fox and Snake.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        int different_cell = -1;\r\n        char default_char = (i%2 == 0 ? '.' : '#');\r\n\r\n        if(i%2 == 0)\r\n            different_cell = (i%4 == 0 ? 1 : columns);\r\n\r\n        for(int j = 1; j <= columns; j++)\r\n            printf(\"%c\", (j != different_cell ? default_char : '#'));\r\n\r\n        printf(\"\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Greg and Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nstruct operation\r\n{\r\n    int left, right, value;\r\n};\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_operations, no_of_queries;\r\n    scanf(\"%d %d %d\", &no_of_elements, &no_of_operations, &no_of_queries);\r\n\r\n    vector <long long> element(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &element[i]);\r\n\r\n    vector <operation> operations(no_of_operations + 1);\r\n    for(int i = 1; i <= no_of_operations; i++)\r\n        scanf(\"%d %d %d\", &operations[i].left, &operations[i].right, &operations[i].value);\r\n\r\n    vector <int> no_of_operations_starting(no_of_operations + 2, 0);\r\n    while(no_of_queries--)\r\n    {\r\n        int left_operation, right_operation;\r\n        scanf(\"%d %d\", &left_operation, &right_operation);\r\n\r\n        no_of_operations_starting[left_operation]++;\r\n        no_of_operations_starting[right_operation + 1]--;\r\n    }\r\n\r\n    vector <int> no_of_uses(no_of_operations + 1, 0);\r\n    for(int i = 1; i <= no_of_operations; i++)\r\n        no_of_uses[i] = no_of_uses[i - 1] + no_of_operations_starting[i];\r\n\r\n    vector <long long> no_of_updates_starting(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_operations; i++)\r\n    {\r\n        int start_point = operations[i].left, end_point = operations[i].right, d = operations[i].value;\r\n\r\n        no_of_updates_starting[start_point] += no_of_uses[i]*1LL*d;\r\n        no_of_updates_starting[end_point + 1]-= no_of_uses[i]*1LL*d;\r\n    }\r\n\r\n    vector <long long> amount_to_be_added(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        amount_to_be_added[i] = amount_to_be_added[i - 1] + no_of_updates_starting[i];\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        element[i] += amount_to_be_added[i];\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        printf(\"%I64d \", element[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Hacking Cypher.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <string>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    string number;\r\n    cin >> number >> a >> b;\r\n\r\n    int no_of_numbers = number.size();\r\n\r\n    vector <int> remainder_a_till(no_of_numbers);\r\n    remainder_a_till[0] = (number[0] - '0')%a;\r\n\r\n    for(int i = 1 ; number[i] != '\\0'; i++)\r\n    {\r\n        remainder_a_till[i] = (10*remainder_a_till[i - 1] + number[i] - '0')%a;\r\n    }\r\n\r\n\r\n    vector <int> remainder_b_from(no_of_numbers);\r\n    remainder_b_from[no_of_numbers - 1] = (number[no_of_numbers - 1] - '0')%b;\r\n\r\n    for(int i = no_of_numbers - 2, ten_power = 10; i >= 0; i--)\r\n    {\r\n        remainder_b_from[i] = (ten_power*(number[i] - '0') + remainder_b_from[i + 1])%b;\r\n\r\n        ten_power = (ten_power*10)%b;\r\n    }\r\n\r\n    int end_of_a = -1;\r\n    for(int i = 0; i + 1 < no_of_numbers; i++)\r\n    {\r\n        if(remainder_a_till[i] == 0 && remainder_b_from[i + 1] == 0 && number[i + 1] != '0')\r\n            end_of_a = i;\r\n    }\r\n\r\n    if(end_of_a == -1 || number[0] == '0')\r\n    {\r\n        printf(\"NO\\n\");\r\n        return 0;\r\n    }\r\n\r\n    printf(\"YES\\n\");\r\n\r\n    for(int i = 0; i <= end_of_a; i++) printf(\"%c\", number[i]);\r\n\r\n    printf(\"\\n\");\r\n\r\n    for(int i = end_of_a + 1; i < no_of_numbers; i++) printf(\"%c\", number[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/I Wanna Be The Guy.cpp",
    "content": "#include <cstdio>\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_levels;\r\n    scanf(\"%d\", &no_of_levels);\r\n\r\n    int crossed_levels[no_of_levels + 1] = {false};\r\n    int x_levels;\r\n    scanf(\"%d\", &x_levels);\r\n\r\n    while(x_levels--)\r\n    {\r\n        int level;\r\n        scanf(\"%d\", &level);\r\n        crossed_levels[level] = true;\r\n    }\r\n\r\n    int y_levels;\r\n    scanf(\"%d\", &y_levels);\r\n\r\n    while(y_levels--)\r\n    {\r\n        int level;\r\n        scanf(\"%d\", &level);\r\n        crossed_levels[level] = true;\r\n    }\r\n\r\n    int possible = true;\r\n    for(int i = 1; i <= no_of_levels; i++)\r\n        if(!crossed_levels[i])\r\n            possible = false;\r\n\r\n    printf(possible ? \"I become the guy.\" : \"Oh, my keyboard!\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/IQ Test.cpp",
    "content": "#include <cstdio>\r\n\r\nint possible_to_make_square(char square[][5], int x, int y)\r\n{\r\n    int black = (square[x][y] == '#') + (square[x - 1][y] == '#') + (square[x - 1][y - 1] == '#') + (square[x][y - 1] == '#');\r\n    int white = (square[x][y] == '.') + (square[x - 1][y] == '.') + (square[x - 1][y - 1] == '.') + (square[x][y - 1] == '.');\r\n\r\n    return (black >= 3 || white >= 3);\r\n}\r\n\r\nint main()\r\n{\r\n    const int N = 4;\r\n    char square[N + 1][N + 1];\r\n\r\n    for(int i = 0; i < N; i++)\r\n        scanf(\"%s\", square[i]);\r\n\r\n    int is_possible = false;\r\n\r\n    for(int i = 1; i < 4; i++)\r\n    {\r\n        for(int j = 1; j < 4; j++)\r\n        {\r\n            if(possible_to_make_square(square, i, j))\r\n                is_possible = true;\r\n        }\r\n    }\r\n\r\n    printf(is_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Jeff and Periods.cpp",
    "content": "#include <cstdio>\r\n\r\nconst int NOT_POSSIBLE = -1, MAX_ELEMENTS = 1e5 + 1;\r\n\r\nstruct number\r\n{\r\n    int last_index, second_last_index, difference;\r\n\r\n    number(){ last_index = second_last_index = 0; difference = NOT_POSSIBLE;}\r\n};\r\n\r\nint main()\r\n{\r\n    number elements[MAX_ELEMENTS];\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int n;\r\n        scanf(\"%d\", &n);\r\n\r\n        if(elements[n].last_index == 0)\r\n        {\r\n            elements[n].last_index = i;\r\n            elements[n].difference = 0;\r\n        }\r\n        else if(elements[n].second_last_index == 0)\r\n        {\r\n            elements[n].second_last_index = elements[n].last_index;\r\n            elements[n].last_index = i;\r\n            elements[n].difference = elements[n].last_index - elements[n].second_last_index;\r\n        }\r\n        else\r\n        {\r\n            if(i - elements[n].last_index == elements[n].difference)\r\n            {\r\n                elements[n].second_last_index = elements[n].last_index;\r\n                elements[n].last_index = i;\r\n            }\r\n            else\r\n            {\r\n                elements[n].difference = NOT_POSSIBLE;\r\n            }\r\n        }\r\n    }\r\n\r\n    int no_of_aps = 0;\r\n    for(int i = 1; i < MAX_ELEMENTS; i++)\r\n        no_of_aps += (elements[i].difference != NOT_POSSIBLE);\r\n\r\n    printf(\"%d\\n\", no_of_aps);\r\n    for(int i = 1; i < MAX_ELEMENTS; i++)\r\n        if(elements[i].difference != NOT_POSSIBLE)\r\n            printf(\"%d %d\\n\", i, elements[i].difference);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Pashmak and Garden.cpp",
    "content": "#include <cstdio>\r\n#define abs(x) ( (x) > 0 ? (x) : -(x) )\r\n\r\nint main()\r\n{\r\n    int x_1, x_2, y_1, y_2;\r\n    scanf(\"%d %d %d %d\", &x_1, &y_1, &x_2, &y_2);\r\n\r\n    int x_3, y_3, x_4, y_4;\r\n\r\n    if(x_1 == x_2)\r\n    {\r\n        int distance = abs(y_1 - y_2);\r\n\r\n        x_3 = x_1 + distance;\r\n        y_3 = y_1;\r\n\r\n        x_4 = x_2 + distance;\r\n        y_4 = y_2;\r\n    }\r\n    else if(y_1 == y_2)\r\n    {\r\n        int distance = abs(x_1 - x_2);\r\n\r\n        y_3 = y_1 + distance;\r\n        x_3 = x_1;\r\n\r\n        y_4 = y_2 + distance;\r\n        x_4 = x_2;\r\n    }\r\n    else if(abs(x_1 - x_2) == abs(y_1 - y_2))\r\n    {\r\n        x_3 = x_1;\r\n        y_3 = y_2;\r\n\r\n        x_4 = x_2;\r\n        y_4 = y_1;\r\n    }\r\n    else\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n    printf(\"%d %d %d %d\\n\", x_3, y_3, x_4, y_4);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Primes or Palindromes.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint reverse(int n)\r\n{\r\n    int rev = 0;\r\n    while(n)\r\n    {\r\n        rev = rev*10 + n%10;\r\n        n /= 10;\r\n    }\r\n    return rev;\r\n}\r\n\r\nint is_palindrome(int n)\r\n{\r\n    return (n == reverse(n));\r\n}\r\n\r\nvoid precompute(vector <int> &no_of_primes_till, vector <int> &no_of_palindromes_till, int LIMIT)\r\n{\r\n    vector <int> is_prime(LIMIT + 1, true);\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    vector <int> primes;\r\n    for(int i = 2; i <= LIMIT; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] < LIMIT; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= LIMIT; i++)\r\n        no_of_primes_till[i] = no_of_primes_till[i - 1] + is_prime[i];\r\n\r\n    for(int i = 1; i <= LIMIT; i++)\r\n        no_of_palindromes_till[i] = no_of_palindromes_till[i - 1] + is_palindrome(i);\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 2e6;\r\n    vector <int> no_of_primes_till(LIMIT + 1, 0);\r\n    vector <int> no_of_palindromes_till(LIMIT + 1, 0);\r\n    precompute(no_of_primes_till, no_of_palindromes_till, LIMIT);\r\n\r\n    int p, q;\r\n    scanf(\"%d %d\", &p, &q);\r\n\r\n    for(int n = LIMIT; n >= 1; n--)\r\n    {\r\n        if(q*no_of_primes_till[n] <= p*no_of_palindromes_till[n])\r\n        {\r\n            printf(\"%d\\n\", n);\r\n            break;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Quasi Binary.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int MAX_SIZE = 7;\r\n    vector <int> no_of_bits(MAX_SIZE + 1, 0);\r\n\r\n    int greatest_bit = 0;\r\n\r\n    for(int i = 0; n > 0; i++)\r\n    {\r\n        no_of_bits[i] = n%10;\r\n        n /= 10;\r\n\r\n        greatest_bit = max(greatest_bit, no_of_bits[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", greatest_bit);\r\n\r\n    for(int i = 1; i <= greatest_bit; i++)\r\n    {\r\n        int number = 0;\r\n\r\n        for(int j = no_of_bits.size() - 1; j >= 0; j--)\r\n        {\r\n            number *= 10;\r\n\r\n            if(no_of_bits[j] > 0)\r\n                number++;\r\n\r\n            no_of_bits[j]--;\r\n        }\r\n        printf(\"%d \", number);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Sereja and Bottles.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_bottles;\r\n    scanf(\"%d\", &no_of_bottles);\r\n\r\n    vector <int> brand(no_of_bottles + 1, 0);\r\n    vector <int> can_open(no_of_bottles + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_bottles; i++)\r\n        scanf(\"%d %d\", &brand[i], &can_open[i]);\r\n\r\n    int impossible_bottles = 0;\r\n    for(int i = 1; i <= no_of_bottles; i++)\r\n    {\r\n        int openable = false;\r\n\r\n        for(int j = 1; j <= no_of_bottles; j++)\r\n        {\r\n            if(can_open[j] == brand[i] && i != j)\r\n                openable = true;\r\n        }\r\n\r\n        impossible_bottles += (!openable);\r\n    }\r\n\r\n    printf(\"%d\\n\", impossible_bottles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Team Olympiad.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define min_3(a, b, c) min(a, min(b, c))\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    vector <int> mathematician;\r\n    vector <int> programmer;\r\n    vector <int> sportsperson;\r\n\r\n    int no_of_players;\r\n    scanf(\"%d\", &no_of_players);\r\n\r\n    for(int i = 1; i <= no_of_players; i++)\r\n    {\r\n        int activity;\r\n        scanf(\"%d\", &activity);\r\n\r\n        switch(activity)\r\n        {\r\n            case 1: mathematician.push_back(i); break;\r\n            case 2: programmer.push_back(i); break;\r\n            case 3: sportsperson.push_back(i); break;\r\n        }\r\n    }\r\n\r\n    int no_of_teams = min_3(mathematician.size(), programmer.size(), sportsperson.size());\r\n    printf(\"%d\\n\", no_of_teams);\r\n\r\n    for(int i = 1; i <= no_of_teams; i++)\r\n        printf(\"%d %d %d\\n\", mathematician[i - 1], programmer[i - 1], sportsperson[i - 1]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/The Fibonacci Segment.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <int> longest_segment_ending(no_of_elements + 1, 1);\r\n    int longest_segment = 1;\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        if(i == 2)\r\n            longest_segment_ending[i] = 2;\r\n        else\r\n            longest_segment_ending[i] = (element[i] == element[i - 1] + element[i - 2] ? longest_segment_ending[i - 1] + 1 : 2);\r\n\r\n        longest_segment = max(longest_segment, longest_segment_ending[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_segment);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Twins.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_coins;\r\n    scanf(\"%d\", &no_of_coins);\r\n\r\n    int total = 0;\r\n    vector <int> coin(no_of_coins);\r\n    for(int i = 0; i < no_of_coins; i++)\r\n    {\r\n        scanf(\"%d\", &coin[i]);\r\n        total += coin[i];\r\n    }\r\n\r\n    sort(all(coin));\r\n\r\n    int no_of_coins_taken = 0, sum_of_taken = 0;\r\n    for(int i = no_of_coins - 1; i >= 0 && sum_of_taken <= total ; i--)\r\n    {\r\n        sum_of_taken += coin[i];\r\n        total -= coin[i];\r\n\r\n        no_of_coins_taken++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_coins_taken);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Valera and Tubes.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_ROWS = 301, MAX_COLUMNS = 301;\r\nint visited[MAX_ROWS][MAX_COLUMNS] = {{false}};\r\n\r\nvoid get_next(int &x, int &y, int columns)\r\n{\r\n    if( (y == 1 && visited[x][y + 1]) || (y == columns && visited[x][y - 1]) )\r\n        x++;\r\n    else\r\n        if(y < columns && !visited[x][y + 1])\r\n            y++;\r\n        else\r\n            y--;\r\n}\r\n\r\nint main()\r\n{\r\n    int rows, columns, no_of_tubes;\r\n    scanf(\"%d %d %d\", &rows, &columns, &no_of_tubes);\r\n\r\n    vector <vector <pair <int, int> > >tubes(no_of_tubes + 1);\r\n    int x = 1, y = 1, i = 1;\r\n\r\n    while(x <= rows)\r\n    {\r\n        tubes[i].push_back(make_pair(x, y));\r\n\r\n        if(i != no_of_tubes && tubes[i].size() == 2)\r\n            i++;\r\n\r\n        visited[x][y] = true;\r\n        get_next(x, y, columns);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_tubes; i++)\r\n    {\r\n        printf(\"%d \", tubes[i].size());\r\n\r\n        for(int j = 0; j < tubes[i].size(); j++)\r\n            printf(\"%d %d \", tubes[i][j].first, tubes[i][j].second);\r\n\r\n        printf(\"\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/Xenia and Bit Operations.cpp",
    "content": "#include <cstdio>\n\nconst int OR = 0, XOR = 1, MAX_SIZE = 1e6;\n\nint tree[3*MAX_SIZE];\nint element[MAX_SIZE];\n\nint perform(int a, int operation, int b)\n{\n    switch(operation)\n    {\n        case OR  :  return (a|b);\n        case XOR :  return (a^b);\n    }\n}\n\nint other(int operation)\n{\n    return (operation^1);\n}\n\nvoid build(int node, int start, int end, int operation)\n{\n    if(start == end)\n    {\n        tree[node] = element[start];\n        return;\n    }\n\n    int mid = (start + end)/2;\n\n    build(2*node, start, mid, other(operation));\n    build(2*node + 1, mid + 1, end, other(operation));\n\n    tree[node] = perform(tree[2*node], operation, tree[2*node + 1]);\n}\n\nvoid update(int node, int start, int end, int index, int value, int operation)\n{\n    if(start == end)\n    {\n        tree[node] = element[index] = value;\n        return;\n    }\n\n    int mid = (start + end)/2;\n\n    if(index >= start && index <= mid)\n    {\n        update(2*node, start, mid, index, value, other(operation));\n    }\n    else if(index > mid && index <= end)\n    {\n        update(2*node + 1, mid + 1, end, index, value, other(operation));\n    }\n\n    tree[node] = perform(tree[2*node], operation, tree[2*node + 1]);\n}\n\nint main()\n{\n    int n, no_of_queries;\n    scanf(\"%d %d\", &n, &no_of_queries);\n\n    int no_of_elements = (1 << n);\n    for(int i = 1; i <= no_of_elements; i++)\n        scanf(\"%d\", &element[i]);\n\n    int first_operation = (n%2 == 0 ? XOR : OR);\n    build(1, 1, no_of_elements, first_operation);\n\n    while(no_of_queries--)\n    {\n        int index, value;\n        scanf(\"%d %d\", &index, &value);\n\n        update(1, 1, no_of_elements, index, value, first_operation);\n        printf(\"%d\\n\", tree[1]);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 16/Xenia and Ringroad.cpp",
    "content": "#include <cstdio>\r\n\r\nint get_travel_time(int previous, int current, int no_of_houses)\r\n{\r\n    return (previous <= current ? current - previous : no_of_houses - previous + current);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_houses, no_of_tasks;\r\n    scanf(\"%d %d\", &no_of_houses, &no_of_tasks);\r\n\r\n    int previous_house = 1;\r\n    long long total_time = 0;\r\n    while(no_of_tasks--)\r\n    {\r\n        int current_house;\r\n        scanf(\"%d\", &current_house);\r\n\r\n        total_time += get_travel_time(previous_house, current_house, no_of_houses);\r\n\r\n        previous_house = current_house;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 16/k-String.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int k;\r\n    string input;\r\n    cin >> k >> input;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    int frequency[NO_OF_ALPHABETS] = {0};\r\n\r\n    for(int i = 0; i < input.length(); i++)\r\n        frequency[input[i] - 'a']++;\r\n\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n        if(frequency[i]%k != 0)\r\n        {\r\n            cout << \"-1\";\r\n            return 0;\r\n        }\r\n\r\n    string smaller_string;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        for(int j = 0; j < frequency[i]/k; j++)\r\n            smaller_string += ('a' + i);\r\n    }\r\n\r\n    for(int i = 1; i <= k; i++)\r\n        cout << smaller_string;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Adding Digits.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int a, b, no_of_operations;\r\n    scanf(\"%d %d %d\", &a, &b, &no_of_operations);\r\n\r\n    int appended_digit = -1;\r\n    for(int digit = 0; digit <= 9; digit++)\r\n    {\r\n        if((a*10 + digit)%b == 0)\r\n        {\r\n            appended_digit = digit;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(appended_digit == -1)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"%d%d\", a, appended_digit);\r\n        for(int i = 2; i <= no_of_operations; i++) printf(\"0\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Christmas Spruce.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d\", &no_of_vertices);\r\n\r\n    int no_of_children[no_of_vertices + 1] = {0};\r\n    int parent[no_of_vertices + 1];\r\n\r\n    for(int i = 2; i <= no_of_vertices; i++)\r\n    {\r\n        scanf(\"%d\", &parent[i]);\r\n\r\n        no_of_children[parent[i]]++;\r\n    }\r\n\r\n    int no_of_leaf_children[no_of_vertices + 1] = {0};\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(no_of_children[i] == 0)\r\n        {\r\n            no_of_leaf_children[parent[i]]++;\r\n        }\r\n    }\r\n\r\n    int is_spruce = true;\r\n    for(int i = 1; i<= no_of_vertices; i++)\r\n    {\r\n        if(no_of_children[i] > 0 && no_of_leaf_children[i] < 3)\r\n        {\r\n            is_spruce = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(is_spruce ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Dreamoon and Wi-Fi.cpp",
    "content": "#include <cstdio>\r\n\r\nint choose(int n, int r)\r\n{\r\n    if(r > n)\r\n        return 0;\r\n\r\n    int answer = 1;\r\n\r\n    for(int i = 0; i < r; i++)\r\n        answer = (answer*(n - i))/(i + 1);\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    const int MAX_LENGTH = 11;\r\n    char sent_commands[MAX_LENGTH], received_commands[MAX_LENGTH];\r\n    scanf(\"%s %s\", sent_commands, received_commands);\r\n\r\n    int destination = 0;\r\n    for(int i = 0; sent_commands[i] != '\\0'; i++)\r\n        destination += (sent_commands[i] == '+' ? 1 : -1);\r\n\r\n    int reached = 0, unrecognised_symbols = 0;\r\n    for(int i = 0; received_commands[i] != '\\0'; i++)\r\n    {\r\n        if(received_commands[i] == '?')\r\n            unrecognised_symbols++;\r\n        else\r\n            reached += (received_commands[i] == '+' ? 1 : -1);\r\n    }\r\n\r\n    int remaining = destination - reached;\r\n\r\n    int no_of_plus = 0, no_of_minus = unrecognised_symbols;\r\n\r\n    while(no_of_plus - no_of_minus != remaining)\r\n    {\r\n        no_of_plus++;\r\n        no_of_minus--;\r\n    }\r\n\r\n    int no_of_ways = choose(unrecognised_symbols, no_of_plus);\r\n    int total_ways = (1 << unrecognised_symbols);\r\n\r\n    double probability = (no_of_ways*1.0f)/(total_ways*1.0f);\r\n    printf(\"%.9lf\", probability);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Exams - 122.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_exams, minimum_marks;\r\n    scanf(\"%d %d\", &no_of_exams, &minimum_marks);\r\n\r\n    int marks_scored = 2*no_of_exams;\r\n    int remaining_marks = minimum_marks - marks_scored;\r\n\r\n    int exams_with_2_marks = (remaining_marks >= no_of_exams ? 0 : no_of_exams - remaining_marks);\r\n\r\n    printf(\"%d\\n\", exams_with_2_marks);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Garden.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int n, length;\r\n    scanf(\"%d %d\", &n, &length);\r\n\r\n    int ans = 1e9;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int a_i;\r\n        scanf(\"%d\", &a_i);\r\n\r\n        if(length%a_i == 0)\r\n            ans = min(ans, length/a_i);\r\n    }\r\n\r\n    printf(\"%d\\n\", ans);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Jamie and Alarm Snooze.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_lucky(int n)\r\n{\r\n    while(n)\r\n    {\r\n        if(n%10 == 7)\r\n            return true;\r\n\r\n        n = n/10;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int decrement_time, hour, minute;\r\n    scanf(\"%d %d %d\", &decrement_time, &hour, &minute);\r\n\r\n    int no_of_hits = 0;\r\n\r\n    while(!is_lucky(hour) && !is_lucky(minute))\r\n    {\r\n        const int NO_OF_MINUTES_IN_HOUR = 60, NO_OF_HOURS_IN_DAY = 24;\r\n\r\n        minute -= decrement_time;\r\n\r\n        if(minute < 0)\r\n        {\r\n            minute += NO_OF_MINUTES_IN_HOUR;\r\n            hour--;\r\n        }\r\n\r\n        if(hour < 0)\r\n        {\r\n            hour += NO_OF_HOURS_IN_DAY;\r\n        }\r\n\r\n        no_of_hits++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_hits);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Jamie and Interesting Graph.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_prime(int n)\r\n{\r\n    if(n <= 1)\r\n        return false;\r\n\r\n    for(int i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint find_nearest_prime(int n)\r\n{\r\n    int ans = n + 1;\r\n    while(!is_prime(ans))\r\n        ans++;\r\n\r\n    return ans;\r\n}\r\n\r\nint main()\r\n{\r\n    int n, no_of_edges;\r\n    scanf(\"%d %d\", &n, &no_of_edges);\r\n\r\n    int cost_to_n = find_nearest_prime(n - 2) - (n - 2);\r\n\r\n    int mst_cost = cost_to_n + (n - 2);\r\n    int min_path = mst_cost;\r\n\r\n    printf(\"%d %d\\n\", mst_cost, min_path);\r\n\r\n    for(int i = 1; i < n - 1; i++)\r\n        printf(\"%d %d %d\\n\", i, i + 1, 1);\r\n\r\n    printf(\"%d %d %d\\n\", n - 1, n, cost_to_n);\r\n\r\n    int edges = n - 1;\r\n\r\n    for(int u = 1; u <= n - 1 && edges < no_of_edges; u++)\r\n    {\r\n        for(int v = u + 2; v <= n && edges < no_of_edges; v++)\r\n        {\r\n            printf(\"%d %d %d\\n\", u, v, mst_cost);\r\n            edges++;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Kolya and Tanya.cpp",
    "content": "#include <cstdio>\r\n\r\nlong long power_mod(long long x, int power, int MOD)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%MOD;\r\n\r\n        x = (x*x)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long no_of_ways = power_mod(27, n, MOD) + (MOD - power_mod(7, n, MOD));\r\n\r\n    no_of_ways %= MOD;\r\n\r\n    printf(\"%I64d\\n\", no_of_ways);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Mashmokh and ACM.cpp",
    "content": "#include <cstdio>\r\n\r\nconst int N = 2001;\r\nlong long no_of_sequences[N][N];\r\n\r\nint main()\r\n{\r\n    const int MOD = 1e9 + 7;\r\n\r\n    int max_number, length;\r\n    scanf(\"%d %d\", &max_number, &length);\r\n\r\n    for(int first_number = 1; first_number <= max_number; first_number++)\r\n        no_of_sequences[first_number][1] = 1;\r\n\r\n    for(int l = 2; l <= length; l++)\r\n    {\r\n        for(int first_number = 1; first_number <= max_number; first_number++)\r\n        {\r\n            no_of_sequences[first_number][l] = 0;\r\n\r\n            for(int i = 1; first_number*i <= max_number; i++)\r\n            {\r\n                no_of_sequences[first_number][l] += no_of_sequences[first_number*i][l - 1];\r\n            }\r\n\r\n            no_of_sequences[first_number][l] %= MOD;\r\n        }\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int first_number = 1; first_number <= max_number; first_number++)\r\n        answer += no_of_sequences[first_number][length];\r\n\r\n    answer %= MOD;\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Maximum Splitting.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int n;\r\n        scanf(\"%d\", &n);\r\n\r\n        int no_of_parts = -1;\r\n\r\n        if( !(n <= 3 || n == 5 || n == 7 || n == 11) )\r\n        {\r\n            switch(n%4)\r\n            {\r\n                case 0: no_of_parts = n/4; break;\r\n                case 1: no_of_parts = (n - 9)/4 + 1; break;\r\n                case 2: no_of_parts = (n - 6)/4 + 1; break;\r\n                case 3: no_of_parts = (n - 15)/4 + 2; break;\r\n            }\r\n        }\r\n\r\n        printf(\"%d\\n\", no_of_parts);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Minimum Sum.cpp",
    "content": "#include <bits/stdc++.h>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct code\r\n{\r\n    int is_first_digit, coefficient;\r\n\r\n    code(){\r\n        is_first_digit = false, coefficient = 0;\r\n    }\r\n};\r\n\r\nint compare(const code &A, const code &B)\r\n{\r\n    return (A.coefficient < B.coefficient);\r\n}\r\n\r\nint main()\r\n{\r\n    const int NO_OF_DIGITS = 10;\r\n    vector <code> letter(NO_OF_DIGITS);\r\n\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    while(no_of_numbers--)\r\n    {\r\n        string number;\r\n        cin >> number;\r\n\r\n        letter[number[0] - 'a'].is_first_digit = true;\r\n\r\n        int power_of_10 = 1;\r\n\r\n        for(int i = number.size() - 1; i >= 0; i--)\r\n        {\r\n            letter[number[i] - 'a'].coefficient += power_of_10;\r\n            power_of_10 *= 10;\r\n        }\r\n    }\r\n\r\n    sort(all(letter), compare);\r\n\r\n    vector <int> assigned(NO_OF_DIGITS, false);\r\n\r\n    int sum = 0;\r\n\r\n    for(int i = NO_OF_DIGITS - 1; i >= 0; i--)\r\n    {\r\n        int digit = (letter[i].is_first_digit ? 1 : 0);\r\n\r\n        while(assigned[digit])\r\n            digit++;\r\n\r\n        assigned[digit] = true;\r\n\r\n        sum += letter[i].coefficient*digit;\r\n    }\r\n\r\n    printf(\"%d\\n\", sum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Modular Exponentiation.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, m;\r\n    scanf(\"%d %d\", &n, &m);\r\n\r\n    int answer = (n > 31 ? m : m%(1 << n));\r\n    printf(\"%d \", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/New Year and Domino.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n\r\n    char cell[rows + 1][columns + 2];\r\n    for(int i = 1; i <= rows; i++)\r\n        scanf(\"%s\", cell[i] + 1);\r\n\r\n    int horizontal_dominos[rows + 1][columns + 2] = {{0}};\r\n    int vertical_dominos[rows + 1][columns + 2] = {{0}};\r\n\r\n    memset(vertical_dominos, 0, sizeof(vertical_dominos));\r\n    memset(horizontal_dominos, 0, sizeof(horizontal_dominos));\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns + 1; j++)\r\n        {\r\n            horizontal_dominos[i][j] = (cell[i][j] == '.' && cell[i][j - 1] == '.');\r\n\r\n            horizontal_dominos[i][j] += horizontal_dominos[i - 1][j] + horizontal_dominos[i][j - 1] - horizontal_dominos[i - 1][j - 1];\r\n\r\n            vertical_dominos[i][j] = (cell[i][j] == '.' && cell[i - 1][j] == '.');\r\n\r\n            vertical_dominos[i][j] += vertical_dominos[i][j - 1] + vertical_dominos[i - 1][j] - vertical_dominos[i - 1][j - 1];\r\n        }\r\n    }\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int row_1, column_1, row_2, column_2;\r\n        scanf(\"%d %d %d %d\", &row_1, &column_1, &row_2, &column_2);\r\n\r\n        int total_horizontal = horizontal_dominos[row_2][column_2]\r\n                              - horizontal_dominos[row_2][column_1] - horizontal_dominos[row_1 - 1][column_2]\r\n                              +horizontal_dominos[row_1 - 1][column_1];\r\n\r\n\r\n        int total_vertical = vertical_dominos[row_2][column_2]\r\n                           - vertical_dominos[row_2][column_1 - 1] - vertical_dominos[row_1][column_2]\r\n                           + vertical_dominos[row_1][column_1 - 1];\r\n\r\n        int total_dominos = total_horizontal + total_vertical;\r\n\r\n        printf(\"%d\\n\", total_dominos);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/New Year's Eve.cpp",
    "content": "#include <cstdio>\r\n\r\nint no_of_bits(long long n)\r\n{\r\n    int bit_count = 0;\r\n\r\n    while(n)\r\n    {\r\n        n = n >> 1;\r\n        bit_count++;\r\n    }\r\n\r\n    return bit_count;\r\n}\r\n\r\nint main()\r\n{\r\n    long long n, k;\r\n    scanf(\"%I64d %I64d\", &n, &k);\r\n\r\n    long long answer;\r\n\r\n    if(k == 1)\r\n    {\r\n        answer = n;\r\n    }\r\n    else\r\n    {\r\n        answer = (1LL << no_of_bits(n) ) - 1;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Palindrome Pairs.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <string>\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    int length = A.size();\r\n\r\n    int is_palindrome[length + 1][length + 1] = {{false}};\r\n\r\n    vector <int> palindrome_starts(length + 1, 0);\r\n    vector <int> palindrome_ends(length + 1, 0);\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        is_palindrome[i][i] = true;\r\n        palindrome_starts[i] = palindrome_ends[i] = 1;\r\n    }\r\n\r\n    for(int substring_length = 2; substring_length < length; substring_length++)\r\n    {\r\n\r\n        for(int start = 0, end = start + substring_length - 1; end < length; start++, end++)\r\n        {\r\n\r\n            if(A[start] == A[end] && (substring_length == 2 || is_palindrome[start + 1][end - 1]))\r\n            {\r\n                is_palindrome[start][end] = true;\r\n                palindrome_starts[start]++;\r\n                palindrome_ends[end]++;\r\n            }\r\n        }\r\n    }\r\n\r\n    vector <int> palindromes_from(length + 1, 0);\r\n    for(int i = length - 1; i >= 0; i--)\r\n        palindromes_from[i] = palindromes_from[i + 1] + palindrome_starts[i];\r\n\r\n    long long palindromic_pairs = 0;\r\n\r\n    for(int i = 0; i < length; i++)\r\n        palindromic_pairs += palindrome_ends[i]*1LL*palindromes_from[i + 1];\r\n\r\n    printf(\"%I64d\\n\", palindromic_pairs);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Perfect Number.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint sum_of_digits(int n)\r\n{\r\n    int sum = 0;\r\n\r\n    while(n)\r\n    {\r\n        sum += n%10;\r\n        n /= 10;\r\n    }\r\n\r\n    return sum;\r\n}\r\n\r\nint main()\r\n{\r\n    vector <int> perfect_number;\r\n\r\n    for(int i = 19; perfect_number.size() <= 1e4; i+=9)\r\n    {\r\n        if(sum_of_digits(i) == 10)\r\n            perfect_number.push_back(i);\r\n    }\r\n\r\n    int k;\r\n    scanf(\"%d\", &k);\r\n    printf(\"%d\\n\", perfect_number[k - 1]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/QAQ.cpp",
    "content": "#include <cstring>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int N = 101;\r\n    char input[N];\r\n    scanf(\"%s\", input);\r\n\r\n    int length = strlen(input);\r\n\r\n    int no_of_Q_till[length] = {0};\r\n    no_of_Q_till[0] = (input[0] == 'Q');\r\n    for(int i = 1; i < length; i++)\r\n        no_of_Q_till[i] = no_of_Q_till[i - 1] + (input[i] == 'Q');\r\n\r\n    int no_of_Q_after[length] = {0};\r\n    no_of_Q_after[length - 1] = (input[length - 1] == 'Q');\r\n    for(int i = length - 2; i >= 0; i--)\r\n        no_of_Q_after[i] = no_of_Q_after[i + 1] + (input[i] == 'Q');\r\n\r\n    int no_of_QAQ = 0;\r\n    for(int i = 0; i < length; i++)\r\n        if(input[i] == 'A')\r\n            no_of_QAQ += no_of_Q_till[i]*no_of_Q_after[i];\r\n\r\n    printf(\"%d\\n\", no_of_QAQ);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Seat Arrangements.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\nint main()\r\n{\r\n    int no_of_rows, no_of_columns, k;\r\n    scanf(\"%d %d %d\", &no_of_rows, &no_of_columns, &k);\r\n\r\n    char seat[no_of_rows + 1][no_of_columns + 2];\r\n    for(int row = 1; row <= no_of_rows; row++)\r\n        scanf(\"%s\", seat[row] + 1);\r\n\r\n    int up_empty_seats[no_of_rows + 1][no_of_columns + 1];\r\n    memset(up_empty_seats, 0, sizeof(up_empty_seats));\r\n\r\n    int left_empty_seats[no_of_rows + 1][no_of_columns + 1];\r\n    memset(left_empty_seats, 0, sizeof(left_empty_seats));\r\n\r\n    int total_seatings = 0;\r\n\r\n    for(int row = 1; row <= no_of_rows; row++)\r\n    {\r\n        for(int column = 1; column <= no_of_columns; column++)\r\n        {\r\n            up_empty_seats[row][column] = (seat[row][column] == '.' ? 1 + up_empty_seats[row - 1][column] : 0);\r\n            left_empty_seats[row][column] = (seat[row][column] == '.' ? 1 + left_empty_seats[row][column - 1] : 0);\r\n\r\n            total_seatings += (up_empty_seats[row][column] >= k) + (left_empty_seats[row][column] >= k);\r\n        }\r\n    }\r\n\r\n    if(k == 1)\r\n        total_seatings = total_seatings >> 1;\r\n\r\n    printf(\"%d\\n\", total_seatings);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Supermarket.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int n, m;\r\n    scanf(\"%d %d\", &n, &m);\r\n\r\n    double ans = 1E9;\r\n    while(n--)\r\n    {\r\n        int a, b;\r\n        scanf(\"%d %d\", &a, &b);\r\n\r\n        ans = min(ans, (a*1.0*m)/(b*1.0));\r\n    }\r\n\r\n    printf(\"%lf\\n\", ans);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Swap Adjacent Elements.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1, 0);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    vector <int> ones_till(n + 1, 0);\r\n    for(int i = 1; i <= n - 1; i++)\r\n    {\r\n        int digit;\r\n        scanf(\"%1d\", &digit);\r\n\r\n        ones_till[i] = (digit == 1) + ones_till[i - 1];\r\n    }\r\n\r\n    int is_sortable = true;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(permutation[i] != i)\r\n        {\r\n            int right = max(i, permutation[i]);\r\n            int left = min(i, permutation[i]);\r\n\r\n            int distance = (right - 1) - (left - 1);\r\n\r\n            if(ones_till[right - 1] - ones_till[left - 1] != distance)\r\n                is_sortable = false;\r\n        }\r\n    }\r\n\r\n    printf(is_sortable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Tea Queue.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int number_of_students;\r\n    scanf(\"%d\", &number_of_students);\r\n\r\n    vector <int> left(number_of_students + 1);\r\n    vector <int> right(number_of_students + 1);\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        scanf(\"%d %d\", &left[i], &right[i]);\r\n\r\n    vector <int> served_time(number_of_students + 1, 0);\r\n\r\n    for(int current_time = left[1], student = 1; student <= number_of_students; student++)\r\n    {\r\n            current_time = max(current_time, left[student]);\r\n\r\n            if(current_time <= right[student])\r\n            {\r\n                served_time[student] = current_time++;\r\n            }\r\n    }\r\n\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        printf(\"%d \", served_time[i]);\r\n\r\n    printf(\"\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Testing Pants for Sadness.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_questions;\r\n    scanf(\"%d\", &no_of_questions);\r\n\r\n    long long no_of_clicks = 0;\r\n\r\n    for(int i = 1; i <= no_of_questions; i++)\r\n    {\r\n        int no_of_options;\r\n        scanf(\"%d\", &no_of_options);\r\n\r\n        no_of_clicks += 1 + i*1LL*(no_of_options - 1);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_clicks);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/The World is a Theatre.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    const int N = 60;\n    long long combinations[N + 1][N + 1];\n\n    combinations[0][0] = 1;\n\n    for(int n = 1; n <= N; n++)\n    {\n        for(int r = 0; r <= n; r++)\n        {\n            if(r == 0 || r == n)\n                combinations[n][r] = 1;\n            else\n                combinations[n][r] = combinations[n - 1][r] + combinations[n - 1][r - 1];\n        }\n    }\n\n\n    int no_of_actors, boys, girls;\n    scanf(\"%d %d %d\", &boys, &girls, &no_of_actors);\n\n    long long no_of_ways = 0;\n    for(int i = 4; i < no_of_actors; i++)\n        no_of_ways += combinations[boys][i]*combinations[girls][no_of_actors - i];\n\n    printf(\"%I64d\\n\", no_of_ways);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 17/Tricky Alchemy.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int yellow, blue;\r\n    scanf(\"%d %d\", &yellow, &blue);\r\n\r\n    int x, y, z;\r\n    scanf(\"%d %d %d\", &x, &y, &z);\r\n\r\n    long long required_yellow = 2LL*x + y;\r\n    long long required_blue = y + 3LL*z;\r\n\r\n    long long required = max(0LL, required_yellow - yellow) + max(0LL, required_blue - blue);\r\n    printf(\"%I64d\\n\", required);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 17/Water the Gardens.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int number_of_taps, number_of_beds;\r\n    scanf(\"%d %d\", &number_of_beds, &number_of_taps);\r\n\r\n    vector <int> tap(number_of_taps + 1, 0);\r\n    for(int i = 1; i <= number_of_taps; i++)\r\n        scanf(\"%d\", &tap[i]);\r\n\r\n    int time = tap[1];\r\n\r\n    for(int i = 1; i < number_of_taps; i++)\r\n    {\r\n        int distance = tap[i + 1] - tap[i] + 1;\r\n\r\n        int time_for_this_patch = distance/2 + distance%2 ;\r\n\r\n        time = max(time, time_for_this_patch);\r\n    }\r\n\r\n    time = max(time, number_of_beds - tap.back() + 1);\r\n\r\n    printf(\"%d\\n\", time);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Art Union.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int number_of_paintings, number_of_painters;\r\n    scanf(\"%d %d\", &number_of_paintings, &number_of_painters);\r\n\r\n    int time[number_of_paintings + 1][number_of_painters + 1];\r\n    for(int i = 1; i <= number_of_paintings; i++)\r\n        for(int j = 1; j <= number_of_painters; j++)\r\n            scanf(\"%d\", &time[i][j]);\r\n\r\n    int time_for[number_of_paintings + 1][number_of_painters + 1];\r\n    memset(time_for, 0, sizeof(time_for));\r\n\r\n    for(int painter_i = 1; painter_i <= number_of_painters; painter_i++)\r\n    {\r\n        for(int painting = 1; painting <= number_of_paintings; painting++)\r\n        {\r\n            time_for[painting][painter_i] = max(time_for[painting - 1][painter_i], time_for[painting][painter_i - 1]) +\r\n                                            time[painting][painter_i];\r\n        }\r\n    }\r\n\r\n    int all_painters = number_of_painters;\r\n\r\n    for(int i = 1; i <= number_of_paintings; i++)\r\n        printf(\"%d \", time_for[i][all_painters]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Bear and Colours.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_balls;\r\n    scanf(\"%d\", &no_of_balls);\r\n\r\n    vector <int> colour(no_of_balls + 1, 0);\r\n    for(int i = 1; i <= no_of_balls; i++)\r\n        scanf(\"%d\", &colour[i]);\r\n\r\n    vector <int> no_of_winning_intervals(no_of_balls + 1);\r\n    for(int start = 1; start <= no_of_balls; start++)\r\n    {\r\n        vector <int> frequency(no_of_balls + 1, 0);\r\n        int winner = 0;\r\n\r\n        for(int i = start; i <= no_of_balls; i++)\r\n        {\r\n            frequency[colour[i]]++;\r\n\r\n            if(frequency[colour[i]] > frequency[winner] || (frequency[colour[i]] == frequency[winner] && colour[i] < winner))\r\n                winner = colour[i];\r\n\r\n            no_of_winning_intervals[winner]++;\r\n        }\r\n    }\r\n\r\n    for(int ball_i = 1; ball_i <= no_of_balls; ball_i++)\r\n        printf(\"%d \", no_of_winning_intervals[ball_i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Cave Painting.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    long long n, k;\r\n    scanf(\"%I64d %I64d\", &n, &k);\r\n\r\n    const int LIMIT = 43;\r\n    int divisible_by_lcm_1_till_k = true;\r\n\r\n    if(k < LIMIT)\r\n    {\r\n        for(int i = 1; i <= k; i++)\r\n        {\r\n            if( (n + 1)%i != 0)\r\n            {\r\n                divisible_by_lcm_1_till_k = false;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(k < LIMIT && divisible_by_lcm_1_till_k ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Cloning Toys.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int originals, copies;\r\n    scanf(\"%d %d\", &copies, &originals);\r\n\r\n    originals--;\r\n\r\n    printf( (originals == 0 && copies == 0) || (originals >= 1 && copies >= originals && (copies - originals)%2 == 0) ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Eternal Victory.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_CITIES = 1e5 + 5;\r\n\r\nvector <pair <int, int> > tree[MAX_CITIES];\r\nint max_distance[MAX_CITIES];\r\n\r\nvoid dfs(int v, int parent_v)\r\n{\r\n        max_distance[v] = 0;\r\n\r\n        for(int i = 0; i < tree[v].size(); i++)\r\n        {\r\n            int child_v = tree[v][i].first;\r\n            int child_distance = tree[v][i].second;\r\n\r\n            if(child_v == parent_v)\r\n                continue;\r\n\r\n            dfs(child_v, v);\r\n\r\n            max_distance[v] = max(max_distance[v], child_distance + max_distance[child_v]);\r\n        }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_cities;\r\n    scanf(\"%d\", &no_of_cities);\r\n\r\n    long long sum_of_edges = 0;\r\n\r\n    for(int i = 1; i < no_of_cities; i++)\r\n    {\r\n        int x, y, weight;\r\n        scanf(\"%d %d %d\", &x, &y, &weight);\r\n\r\n        tree[x].push_back(make_pair(y, weight));\r\n        tree[y].push_back(make_pair(x, weight));\r\n\r\n        sum_of_edges += weight;\r\n    }\r\n\r\n    dfs(1, 0);\r\n\r\n    long long total_travel_distance = (sum_of_edges == max_distance[1] ? sum_of_edges : 2*sum_of_edges - max_distance[1]);\r\n\r\n    printf(\"%I64d\\n\", total_travel_distance);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Hard Problem.cpp",
    "content": "#include <cstdio>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstring rev(string s)\r\n{\r\n    reverse(all(s));\r\n\r\n    return s;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_strings;\r\n    scanf(\"%d\", &no_of_strings);\r\n\r\n    vector <int> cost(no_of_strings + 1);\r\n    for(int i = 1; i <= no_of_strings; i++)\r\n        scanf(\"%d\", &cost[i]);\r\n\r\n    vector <string> s(no_of_strings + 1);\r\n    for(int i = 1; i <= no_of_strings; i++)\r\n        cin >> s[i];\r\n\r\n    const long long oo = 1e16;\r\n    const int WITHOUT_REVERSING = 0, REVERSING = 1;\r\n    long long minimum_till[no_of_strings + 1][2];\r\n    minimum_till[0][REVERSING] = minimum_till[0][WITHOUT_REVERSING] = 0;\r\n\r\n    for(int i = 1; i <= no_of_strings; i++)\r\n    {\r\n        minimum_till[i][REVERSING] = minimum_till[i][WITHOUT_REVERSING] = oo;\r\n\r\n        if(s[i] >= s[i - 1])\r\n            minimum_till[i][WITHOUT_REVERSING] = minimum_till[i - 1][WITHOUT_REVERSING];\r\n\r\n        if(s[i] >= rev(s[i - 1]))\r\n            minimum_till[i][WITHOUT_REVERSING] = min(minimum_till[i][WITHOUT_REVERSING], minimum_till[i - 1][REVERSING]);\r\n\r\n        if(rev(s[i]) >= s[i - 1])\r\n            minimum_till[i][REVERSING] = cost[i] + minimum_till[i - 1][WITHOUT_REVERSING];\r\n\r\n        if(rev(s[i]) >= rev(s[i - 1]))\r\n            minimum_till[i][REVERSING] = min(minimum_till[i][REVERSING], cost[i] + minimum_till[i - 1][REVERSING]);\r\n\r\n    }\r\n\r\n    long long answer = min(minimum_till[no_of_strings][REVERSING], minimum_till[no_of_strings][WITHOUT_REVERSING]);\r\n\r\n    printf(\"%I64d\\n\", answer >= oo ? -1 : answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Joystick.cpp",
    "content": "#include <cstdio>\r\n#define max(a, b) (a > b ? a : b)\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int charge_a, charge_b;\r\n    scanf(\"%d %d\", &charge_a, &charge_b);\r\n\r\n    int no_of_minutes = 0;\r\n\r\n    while(max(charge_a, charge_b) > 1 && min(charge_a, charge_b) > 0)\r\n    {\r\n        if(charge_a < charge_b)\r\n            charge_a++, charge_b -= 2;\r\n        else\r\n            charge_a -= 2, charge_b++;\r\n\r\n        no_of_minutes++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/K-Special Tables.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int N, k;\r\n    scanf(\"%d %d\", &N, &k);\r\n\r\n    int special_table[N + 1][N + 1];\r\n    int front_ptr = 1, back_ptr = N*N;\r\n\r\n    for(int row = 1; row <= N; row++)\r\n    {\r\n        for(int column = N; column >= k; column--)\r\n            special_table[row][column] = back_ptr--;\r\n\r\n        for(int column = 1; column < k; column++)\r\n            special_table[row][column] = front_ptr++;\r\n    }\r\n\r\n    int k_column_sum = 0;\r\n\r\n\r\n    for(int row = 1; row <= N; row++)\r\n        k_column_sum += special_table[row][k];\r\n\r\n    printf(\"%d\\n\", k_column_sum);\r\n\r\n    for(int row = 1; row <= N; row++)\r\n    {\r\n        for(int column = 1; column <= N; column++)\r\n        {\r\n            printf(\"%d \", special_table[row][column]);\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Lucky Sum.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n#define min(a, b) (a < b ? a : b)\r\nusing namespace std;\r\n\r\nvoid compute(vector <long long> &lucky_numbers, long long last_lucky_number)\r\n{\r\n    lucky_numbers.push_back(last_lucky_number);\r\n\r\n    if(last_lucky_number > 1e10)\r\n        return ;\r\n\r\n    compute(lucky_numbers, last_lucky_number*10 + 4);\r\n    compute(lucky_numbers, last_lucky_number*10 + 7);\r\n}\r\n\r\nlong long get_answer(vector <long long> &lucky_numbers, int limit)\r\n{\r\n    long long answer = 0;\r\n\r\n    for(int i = 1; i < lucky_numbers.size() && lucky_numbers[i - 1] < limit; i++)\r\n    {\r\n        long long next_lucky_number = lucky_numbers[i];\r\n        long long range = min(limit, lucky_numbers[i]) - lucky_numbers[i - 1];\r\n\r\n        answer += next_lucky_number*range;\r\n    }\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    vector <long long> lucky_numbers;\r\n    compute(lucky_numbers, 0);\r\n\r\n    sort(all(lucky_numbers));\r\n\r\n    int left, right;\r\n    scanf(\"%d %d\", &left, &right);\r\n\r\n    long long answer = get_answer(lucky_numbers, right) - get_answer(lucky_numbers, left - 1);\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Magic Forest.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_nondegenerate_triangle(int a, int b, int c)\r\n{\r\n    return (a + b > c);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int no_of_triangles = 0;\r\n    for(int a = 1; a <= n; a++)\r\n    {\r\n        for(int b = a; b <= n; b++)\r\n        {\r\n            int c = a^b;\r\n\r\n            if(c >= b && c <= n && is_nondegenerate_triangle(a, b, c))\r\n                no_of_triangles++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_triangles);\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Marvolo Gaunt's Ring Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    long long p, q, r;\r\n    scanf(\"%d %I64d %I64d %I64d\", &no_of_elements, &p, &q, &r);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> left_min(no_of_elements + 1);\r\n    vector <int> left_max(no_of_elements + 1);\r\n    left_min[1] = left_max[1] = A[1];\r\n\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        left_min[i] = min(left_min[i - 1], A[i]);\r\n        left_max[i] = max(left_max[i - 1], A[i]);\r\n    }\r\n\r\n    vector <int> right_min(no_of_elements + 1);\r\n    vector <int> right_max(no_of_elements + 1);\r\n    right_min[no_of_elements] = right_max[no_of_elements] = A[no_of_elements];\r\n\r\n    for(int i = no_of_elements - 1; i >= 1; i--)\r\n    {\r\n        right_max[i] = max(right_max[i + 1], A[i]);\r\n        right_min[i] = min(right_min[i + 1], A[i]);\r\n    }\r\n\r\n    long long ans = p*A[1] + q*A[1] + r*A[1];\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long y = q*A[i];\r\n        long long x = (p > 0 ? p*left_max[i] : p*left_min[i]);\r\n        long long z = (r > 0 ? r*right_max[i] : r*right_min[i]);\r\n\r\n        ans = max(ans, x + y + z);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", ans);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Marvolo Gaunt's Ring.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    long long p, q, r;\r\n    scanf(\"%d %I64d %I64d %I64d\", &no_of_elements, &p, &q, &r);\r\n\r\n    vector <int> a(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &a[i]);\r\n\r\n    vector <long long> max_P(no_of_elements);\r\n    max_P[0] = p*a[0];\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        max_P[i] = max(max_P[i - 1], p*a[i]);\r\n\r\n    vector <long long> max_Q(no_of_elements);\r\n    max_Q[0] = q*a[0] + p*a[0];\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        max_Q[i] = max(max_Q[i - 1], q*a[i] + max_P[i]);\r\n\r\n    vector <long long> max_R(no_of_elements);\r\n    max_R[0] = r*a[0] + q*a[0] + p*a[0];\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        max_R[i] = max(max_R[i - 1], r*a[i] + max_Q[i]);\r\n\r\n\r\n    printf(\"%I64d\\n\", max_R[no_of_elements - 1]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Not Equal on a Segment.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_elements, number_of_queries;\r\n    scanf(\"%d %d\", &number_of_elements, &number_of_queries);\r\n\r\n    vector <int> A(number_of_elements + 1, 0);\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> first_unequal_position_left(number_of_elements + 1, 0);\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n        first_unequal_position_left[i] = (A[i] != A[i - 1] ? i - 1 : first_unequal_position_left[i - 1]);\r\n\r\n    while(number_of_queries--)\r\n    {\r\n        int left, right, x;\r\n        scanf(\"%d %d %d\", &left, &right, &x);\r\n\r\n        int answer;\r\n\r\n        if(A[right] != x)\r\n            answer = right;\r\n        else if(A[right] == x)\r\n            answer = (first_unequal_position_left[right] >= left ? first_unequal_position_left[right] : -1);\r\n\r\n        printf(\"%d\\n\", answer);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Perfect Squares.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> A(n);\r\n\r\n    for(int i = 0; i < n; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    vector <int> is_square(1e6 + 1, false);\r\n    for(int i = 0; i*i <= 1e6; i++)\r\n        is_square[i*i] = true;\r\n\r\n    int answer;\r\n\r\n    for(int i = n - 1; i >= 0; i--)\r\n    {\r\n        if(A[i] < 0 || !is_square[A[i]])\r\n        {\r\n            answer = A[i];\r\n            break;\r\n        }\r\n    }\r\n\r\n\r\n    printf(\"%d \", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Petya and Inequiations.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, sum_limit;\r\n    long long square_sum_lower_bound;\r\n    scanf(\"%d %I64d %d\", &n, &square_sum_lower_bound, &sum_limit);\r\n\r\n    long long largest_element = sum_limit - (n - 1);\r\n    long long max_square_sum = (n - 1) + largest_element*largest_element;\r\n\r\n    if(max_square_sum < square_sum_lower_bound || n > sum_limit)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n        printf(\"%I64d\\n\", (i == n ? largest_element : 1));\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Polo the Penguin and Matrix.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_rows, no_of_columns, difference;\r\n    scanf(\"%d %d %d\", &no_of_rows, &no_of_columns, &difference);\r\n\r\n    vector <int> A(no_of_rows*no_of_columns, 0);\r\n\r\n    set <int> remainder;\r\n\r\n    int possible = true;\r\n    for(int i = 0; i < no_of_rows*no_of_columns; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n\r\n        remainder.insert(A[i]%difference);\r\n    }\r\n\r\n    if(remainder.size() > 1)\r\n        possible = false;\r\n\r\n    sort(all(A));\r\n\r\n    int middle = A.size()/2;\r\n    int median = A[middle];\r\n\r\n    int minimum_no_of_moves = 0;\r\n    for(int i = 0; i < A.size(); i++)\r\n        minimum_no_of_moves += abs(A[i] - median)/difference;\r\n\r\n    printf(\"%d\\n\", possible ? minimum_no_of_moves : -1);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Polo the Penguin and Strings.cpp",
    "content": "#include <cstdio>\r\n#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, distinct_letters;\r\n    scanf(\"%d %d\", &length, &distinct_letters);\r\n\r\n    if(length < distinct_letters || (length > 1 && distinct_letters == 1))\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    string answer;\r\n    for(int i = 0; i < length; i++)\r\n        answer += ('a' + i%2);\r\n\r\n    for(int i = length - 1, letter = distinct_letters - 1; letter >= 2; i--, letter--)\r\n        answer[i] = ('a' + letter);\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Replacement.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    sort(all(element));\r\n\r\n    if(no_of_elements == 1)\r\n    {\r\n        printf(\"%d\", element[0] == 1 ? 2 : 1);\r\n        return 0;\r\n    }\r\n\r\n    printf(\"1 \");\r\n    for(int i = 1; i < no_of_elements - 1; i++)\r\n        printf(\"%d \", element[i - 1]);\r\n\r\n    if(element[no_of_elements - 1] == 1)\r\n        printf(\"2\");\r\n    else\r\n        printf(\"%d\", element[no_of_elements - 2]);\r\n\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Robot Vaccuum Cleaner.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nstruct info\r\n{\r\n    long long no_of_s, no_of_h;\r\n    string text;\r\n};\r\n\r\nint compare(const info &A, const info &B)\r\n{\r\n    long long no_of_new_sh_if_A_front = A.no_of_s*B.no_of_h;\r\n    long long no_of_new_sh_if_B_front = B.no_of_s*A.no_of_h;\r\n\r\n    if(no_of_new_sh_if_A_front > no_of_new_sh_if_B_front)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_strings;\r\n    cin >> no_of_strings;\r\n\r\n    vector <info> A(no_of_strings);\r\n    for(int i = 0; i < no_of_strings; i++)\r\n    {\r\n        cin >> A[i].text;\r\n\r\n        A[i].no_of_s = 0;\r\n        A[i].no_of_h = 0;\r\n\r\n        for(int j = 0; j < A[i].text.size(); j++)\r\n        {\r\n            A[i].no_of_s += (A[i].text[j] == 's');\r\n            A[i].no_of_h += (A[i].text[j] == 'h');\r\n        }\r\n    }\r\n\r\n    sort(all(A), compare);\r\n\r\n    string final_text;\r\n    for(int i = 0; i < no_of_strings; i++)\r\n        final_text += A[i].text;\r\n\r\n    long long no_of_s_till_here = 0, no_of_sh = 0;\r\n    for(int i = 0; i < final_text.size(); i++)\r\n    {\r\n        no_of_s_till_here += (final_text[i] == 's');\r\n\r\n        if(final_text[i] == 'h')\r\n            no_of_sh += no_of_s_till_here;\r\n    }\r\n\r\n    cout << no_of_sh;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Rumour.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e5 + 5;\r\nvector <int> graph[MAX_N];\r\nvector <int> component[MAX_N];\r\nint visited[MAX_N];\r\n\r\nvoid dfs_and_mark_component(int v, int component_no)\r\n{\r\n    visited[v] = true;\r\n    component[component_no].push_back(v);\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(!visited[child])\r\n            dfs_and_mark_component(child, component_no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_people, no_of_friendships;\r\n    scanf(\"%d %d\", &no_of_people, &no_of_friendships);\r\n\r\n    vector <int> gold(no_of_people + 1, 0);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &gold[i]);\r\n\r\n    for(int i = 1; i <= no_of_friendships; i++)\r\n    {\r\n        int person_1, person_2;\r\n        scanf(\"%d %d\", &person_1, &person_2);\r\n\r\n        graph[person_1].push_back(person_2);\r\n        graph[person_2].push_back(person_1);\r\n    }\r\n\r\n    memset(visited, false, sizeof(visited));\r\n\r\n    int component_no = 1;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            dfs_and_mark_component(i, component_no++);\r\n        }\r\n    }\r\n\r\n    long long total_cost = 0;\r\n\r\n    for(int component_i = 1; component_i < component_no; component_i++)\r\n    {\r\n        long long min_cost_for_this_component = 1e15;\r\n\r\n        for(int v = 0; v < component[component_i].size(); v++)\r\n        {\r\n            int person = component[component_i][v];\r\n\r\n            min_cost_for_this_component = min(min_cost_for_this_component, gold[person]);\r\n        }\r\n\r\n        total_cost += min_cost_for_this_component;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Search for Pretty Integers.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int list_1_size, list_2_size;\r\n    scanf(\"%d %d\", &list_1_size, &list_2_size);\r\n\r\n    vector <int> in_A(10, false);\r\n    for(int i = 1; i <= list_1_size; i++)\r\n    {\r\n        int a_i;\r\n        scanf(\"%d\", &a_i);\r\n\r\n        in_A[a_i] = true;\r\n    }\r\n\r\n    vector <int> in_B(10, false);\r\n    for(int i = 1; i <= list_2_size; i++)\r\n    {\r\n        int b_i;\r\n        scanf(\"%d\", &b_i);\r\n\r\n        in_B[b_i] = true;\r\n    }\r\n\r\n    int answer = -1;\r\n\r\n    for(int i = 1; i <= 9; i++)\r\n    {\r\n        if(in_A[i] && in_B[i])\r\n        {\r\n            answer = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(answer != -1)\r\n    {\r\n        printf(\"%d\\n\", answer);\r\n        return 0;\r\n    }\r\n\r\n    for(int i = 1; i <= 9 && answer == -1; i++)\r\n    {\r\n        for(int j = i + 1; j <= 9; j++)\r\n        {\r\n            if( (in_A[i] && in_B[j]) || (in_A[j] && in_B[i]) )\r\n            {\r\n                answer = 10*i + j;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Tom Riddle's Diary.cpp",
    "content": "#include <cstdio>\r\n#include <iostream>\r\n#include <set>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_people;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    set <string> people;\r\n    while(no_of_people--)\r\n    {\r\n        string current_possesser;\r\n        cin >> current_possesser;\r\n\r\n        printf(people.count(current_possesser) == 1 ? \"YES\\n\" : \"NO\\n\");\r\n        people.insert(current_possesser);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Two Substrings.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    vector <int> ab;\r\n    vector <int> ba;\r\n\r\n    for(int i = 0; i < A.size() - 1; i++)\r\n    {\r\n        if(A[i] == 'A' && A[i + 1] == 'B')\r\n            ab.push_back(i);\r\n\r\n        if(A[i] == 'B' && A[i + 1] == 'A')\r\n            ba.push_back(i);\r\n    }\r\n\r\n    if(ab.size() == 0 || ba.size() == 0 || !(ab[0] + 1 < ba.back() || ba[0] + 1 < ab.back()))\r\n       cout << \"NO\\n\";\r\n    else\r\n        cout << \"YES\\n\";\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Vladik and Fractions.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int x = n;\r\n    int y = n + 1;\r\n    int z = n*(n + 1);\r\n\r\n    printf(n == 1 ? \"-1\\n\" : \"%d %d %d\\n\", x, y, z);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 18/Woodcutter.cpp",
    "content": "#include <cstdio>\n\n#define max(a, b) (a > b ? a : b)\n#define max_3(a, b, c) max(a, max(b, c))\n\nint main()\n{\n    int no_of_trees;\n    scanf(\"%d\", &no_of_trees);\n\n    long long height[no_of_trees + 1];\n    long long x[no_of_trees + 1];\n    for(int i = 1; i <= no_of_trees; i++)\n        scanf(\"%I64d %I64d\", &x[i], &height[i]);\n\n    const int RIGHT = 1, STRAIGHT = 0, LEFT = 2;\n    int max_cut[no_of_trees + 1][3];\n    max_cut[0][RIGHT] = max_cut[0][STRAIGHT] = max_cut[0][LEFT] = 0;\n\n    for(int i = 1; i <= no_of_trees; i++)\n    {\n        max_cut[i][STRAIGHT] = max_3(max_cut[i - 1][LEFT], max_cut[i - 1][STRAIGHT], max_cut[i - 1][RIGHT]);\n\n        max_cut[i][LEFT] = max_cut[i][RIGHT] = max_cut[i][STRAIGHT];\n\n        if(i == 1 || x[i] - height[i] > x[i - 1])\n            max_cut[i][LEFT] = 1 + max(max_cut[i - 1][LEFT], max_cut[i - 1][STRAIGHT]);\n\n        if(height[i - 1] + height[i] + x[i - 1] < x[i])\n            max_cut[i][LEFT] = max(max_cut[i][LEFT], 1 + max_cut[i - 1][RIGHT]);\n\n        if(i == no_of_trees || height[i] + x[i] < x[i + 1])\n            max_cut[i][RIGHT] = 1 + max_cut[i][STRAIGHT];\n\n    }\n\n    int answer = max_3(max_cut[no_of_trees][RIGHT], max_cut[no_of_trees][STRAIGHT], max_cut[no_of_trees][LEFT]);\n\n    printf(\"%d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 19/A Compatible Pair.cpp",
    "content": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int a_elements, b_elements;\r\n    scanf(\"%d %d\", &a_elements, &b_elements);\r\n\r\n    vector <long long> A(a_elements);\r\n    for(int i =0; i < a_elements; i++) scanf(\"%I64d\", &A[i]);\r\n\r\n    vector <long long> B(b_elements);\r\n    for(int i = 0; i < b_elements; i++) scanf(\"%I64d\", &B[i]);\r\n\r\n    long long max_product = -1e18;\r\n    int best_choice_A;\r\n    for(int i = 0; i < a_elements; i++)\r\n    {\r\n        for(int j = 0; j < b_elements; j++)\r\n        {\r\n            if(A[i]*1LL*B[j] > max_product)\r\n            {\r\n                best_choice_A = i;\r\n                max_product = A[i]*1LL*B[j];\r\n            }\r\n        }\r\n    }\r\n\r\n    long long max_product_without_best_A = -1e18;\r\n    for(int i = 0; i < a_elements; i++)\r\n    {\r\n        if(i == best_choice_A)\r\n            continue;\r\n\r\n        for(int j = 0; j < b_elements; j++)\r\n        {\r\n            max_product_without_best_A = max(max_product_without_best_A, A[i]*1LL*B[j]);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", max_product_without_best_A);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 19/A Prosperous Lot.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_loops;\r\n    scanf(\"%d\", &no_of_loops);\r\n\r\n    const int MAX_LOOPS = 36;\r\n\r\n    if(no_of_loops > MAX_LOOPS)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    while(no_of_loops >= 2)\r\n    {\r\n        printf(\"8\");\r\n        no_of_loops -= 2;\r\n    }\r\n\r\n    if(no_of_loops == 1)\r\n        printf(\"9\\n\");\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Almost Identity Permutations.cpp",
    "content": "#include <cstdio>\r\n\r\nlong long choose(int n, int r)\r\n{\r\n    if(r == 0 || r == n)\r\n        return 1;\r\n    if(r == 1 || r == n - 1)\r\n        return n;\r\n\r\n    return choose(n - 1, r) + choose(n - 1, r - 1);\r\n}\r\n\r\nlong long derangements(int n)\r\n{\r\n    if(n == 0)\r\n        return 1;\r\n    if(n == 1)\r\n        return 0;\r\n    if(n == 2)\r\n        return 1;\r\n\r\n    return (n - 1)*(derangements(n - 1) + derangements(n - 2));\r\n}\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    long long answer = 0;\r\n    for(int i = 0; i <= k; i++)\r\n    {\r\n        answer += choose(n, i)*derangements(i);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Amr and Large Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int LIMIT = 1e6;\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    vector <int> frequency(LIMIT + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(int i = 1; i <= LIMIT; i++)\r\n        max_frequency = max(max_frequency, frequency[i]);\r\n\r\n    vector <int> rightmost_occurence(LIMIT + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        rightmost_occurence[A[i]] = i;\r\n\r\n    vector <int> leftmost_occurence(LIMIT + 1, 0);\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n        leftmost_occurence[A[i]] = i;\r\n\r\n    int minimum_segment_length = no_of_elements + 1;\r\n    int answer;\r\n    for(int i = 1; i <= LIMIT; i++)\r\n    {\r\n        if(frequency[i] == max_frequency)\r\n        {\r\n            int subsegment_length = rightmost_occurence[i] - (leftmost_occurence[i] - 1);\r\n\r\n            if(subsegment_length < minimum_segment_length)\r\n            {\r\n                answer = i;\r\n                minimum_segment_length = subsegment_length;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d %d\\n\", leftmost_occurence[answer], rightmost_occurence[answer]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Beautiful Sets of Points.cpp",
    "content": "#include <cstdio>\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int m, n;\r\n    scanf(\"%d %d\", &m, &n);\r\n\r\n    int limit = min(m, n) + 1;\r\n    printf(\"%d\\n\", limit);\r\n\r\n    for(int i = 0; i < limit; i++)\r\n        printf(\"%d %d\\n\", i, limit - i - 1);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Buggy Robot.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_instructions;\r\n    string instructions;\r\n    cin >> no_of_instructions >> instructions;\r\n\r\n    int lefts = 0, rights = 0, ups = 0, downs = 0;\r\n\r\n    for(int i = 0; i < no_of_instructions; i++)\r\n    {\r\n        lefts  += (instructions[i] == 'L');\r\n        rights += (instructions[i] == 'R');\r\n        downs  += (instructions[i] == 'D');\r\n        ups    += (instructions[i] == 'U');\r\n    }\r\n\r\n    int max_correct_instructions = 2*min(lefts, rights) + 2*min(ups, downs);\r\n    cout << max_correct_instructions;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Cellular Network.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int number_of_cities, number_of_towers;\r\n    scanf(\"%d %d\", &number_of_cities, &number_of_towers);\r\n\r\n    vector <int> city(number_of_cities);\r\n    for(int i = 0; i < number_of_cities; i++)\r\n        scanf(\"%d\", &city[i]);\r\n\r\n    vector <int> tower(number_of_towers);\r\n    for(int i = 0; i <  number_of_towers; i++)\r\n        scanf(\"%d\", &tower[i]);\r\n\r\n    int min_range = 0;\r\n\r\n    for(int i = 0; i < number_of_cities; i++)\r\n    {\r\n        int position = lower_bound(all(tower), city[i]) - tower.begin();\r\n\r\n        int closest_tower = 2e9;\r\n\r\n        if(position != number_of_towers) closest_tower = min(closest_tower, abs(tower[position] - city[i]));\r\n\r\n        if(position != 0) closest_tower = min(closest_tower, abs(tower[position - 1] - city[i]));\r\n\r\n        min_range = max(min_range, closest_tower);\r\n    }\r\n\r\n    printf(\"%d\\n\", min_range);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Coder.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_rows;\r\n    scanf(\"%d\", &no_of_rows);\r\n\r\n    int maximum_pieces = (no_of_rows)*(no_of_rows/2) + (no_of_rows%2)*(no_of_rows/2 + no_of_rows%2);\r\n    printf(\"%d\\n\", maximum_pieces);\r\n\r\n    for(int i = 1; i <= no_of_rows; i++)\r\n    {\r\n        if(i%2 == 1)\r\n        {\r\n            for(int j = 1; j <= no_of_rows; j++)\r\n                printf(\"%c\", j%2 == 0 ? '.' : 'C');\r\n        }\r\n        else\r\n        {\r\n            for(int j = 1; j <= no_of_rows; j++)\r\n                printf(\"%c\", j%2 == 0 ? 'C' : '.');\r\n        }\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Diversity.cpp",
    "content": "#include <cstdio>\r\n\r\n#define NO_OF_ALPHABETS 26\r\n#define MAX_LENGTH 1000 + 5\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    char string[MAX_LENGTH];\r\n    int min_distinct_characters;\r\n    scanf(\"%s %d\", string, &min_distinct_characters);\r\n\r\n    int frequency[NO_OF_ALPHABETS] = {0};\r\n    for(int i = 0; string[i] != '\\0'; i++)\r\n    {\r\n        frequency[string[i] - 'a']++;\r\n    }\r\n\r\n    int no_of_distinct_characters = 0, no_of_changeable_characters = 0;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(frequency[i] > 0)\r\n        {\r\n            no_of_distinct_characters++;\r\n            no_of_changeable_characters += (frequency[i] - 1); //Keep one character\r\n        }\r\n    }\r\n\r\n    int minimum_changes = max(min_distinct_characters - no_of_distinct_characters, 0); //printf(\"NO of changes = %d\\n\", no_of_changeable_characters);\r\n\r\n    printf(minimum_changes > no_of_changeable_characters ? \"impossible\\n\" : \"%d\\n\",minimum_changes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Guest From The Past.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ?  a : b)\r\n\r\nint main()\r\n{\r\n    long long money, plastic_bottle_price, glass_bottle_price, return_amount;\r\n    scanf(\"%I64d %I64d %I64d %I64d\", &money, &plastic_bottle_price, &glass_bottle_price, &return_amount);\r\n\r\n    long long effective_glass_bottle_price = glass_bottle_price - return_amount;\r\n    long long no_of_bottles = 0;\r\n\r\n    if(plastic_bottle_price <= effective_glass_bottle_price || glass_bottle_price > money)\r\n    {\r\n        no_of_bottles = money/plastic_bottle_price;\r\n    }\r\n    else if(effective_glass_bottle_price < plastic_bottle_price && glass_bottle_price <= money)\r\n    {\r\n        no_of_bottles = (money - return_amount)/effective_glass_bottle_price;\r\n\r\n        long long remaining_money = money - no_of_bottles*effective_glass_bottle_price;\r\n        long long remaining_bottles = remaining_money/plastic_bottle_price;\r\n\r\n        no_of_bottles += remaining_bottles;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_bottles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Hamster Farm.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    long long no_of_hamsters;\r\n    int no_of_boxes;\r\n    scanf(\"%I64d %d\", &no_of_hamsters, &no_of_boxes);\r\n\r\n    long long leftover_hamsters = 1e18, boxes_bought;\r\n    int box_type;\r\n\r\n    for(int i = 1; i <= no_of_boxes; i++)\r\n    {\r\n        long long box_i;\r\n        scanf(\"%I64d\", &box_i);\r\n\r\n        if(no_of_hamsters%box_i < leftover_hamsters)\r\n        {\r\n            leftover_hamsters = no_of_hamsters%box_i;\r\n            boxes_bought = no_of_hamsters/box_i;\r\n            box_type = i;\r\n        }\r\n    }\r\n\r\n    printf(\"%d %I64d\\n\", box_type, boxes_bought);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/K-Dominant Character.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_LETTERS = 26;\r\n    int length = S.size(), answer = S.size();\r\n\r\n    for(int alphabet = 0; alphabet < NO_OF_LETTERS; alphabet++)\r\n    {\r\n        int last_occurence = -1, largest_gap_for_this_alphabet = 0;\r\n\r\n        for(int i = 0; S[i] != '\\0'; i++)\r\n        {\r\n            if(S[i] == 'a' + alphabet)\r\n            {\r\n                largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, i - last_occurence);\r\n                last_occurence = i;\r\n            }\r\n        }\r\n\r\n        largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, length - last_occurence);\r\n\r\n        answer = min(answer, largest_gap_for_this_alphabet);\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Little Artem and Grasshopper.cpp",
    "content": "#include <cstdio>\r\n#define NO_OF_STRIPS 100000 + 2\r\n\r\nint main()\r\n{\r\n    int no_of_strips;\r\n    char strip[NO_OF_STRIPS];\r\n    scanf(\"%d %s\", &no_of_strips, strip);\r\n\r\n    int jump[no_of_strips + 1];\r\n    int visited[no_of_strips + 1] = {false};\r\n\r\n    for(int i = 0; i < no_of_strips; i++)\r\n        scanf(\"%d\", &jump[i]);\r\n\r\n    int square = 0, stuck_forever;\r\n\r\n    while(true)\r\n    {\r\n        if(visited[square] == true)\r\n        {\r\n            stuck_forever = true;\r\n            break;\r\n        }\r\n\r\n        visited[square] = true;\r\n\r\n        if(strip[square] == '<')\r\n        {\r\n            if(square - jump[square] < 0)\r\n            {\r\n                stuck_forever = false;\r\n                break;\r\n            }\r\n\r\n            square -= jump[square];\r\n        }\r\n        else\r\n        {\r\n            if(square + jump[square] >= no_of_strips)\r\n            {\r\n                stuck_forever = false;\r\n                break;\r\n            }\r\n\r\n            square += jump[square];\r\n        }\r\n    }\r\n\r\n    printf(stuck_forever ? \"INFINITE\\n\" : \"FINITE\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Longest K-Good Segment.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, k;\r\n    scanf(\"%d %d\", &no_of_elements, &k);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    const int MAX = 1e6 + 1;\r\n    vector <int> frequency(MAX, 0);\r\n\r\n    int left = 1, right = 1, best_left, best_right, distinct_elements = 0, maximum_length = 0;\r\n    while(right <= no_of_elements)\r\n    {\r\n        frequency[element[right]]++;\r\n        distinct_elements += (frequency[element[right]] == 1);\r\n\r\n        while(distinct_elements > k)\r\n        {\r\n            frequency[element[left]]--;\r\n            distinct_elements -= (frequency[element[left]] == 0);\r\n            left++;\r\n        }\r\n\r\n        int current_segment_length = right - (left - 1);\r\n        if(current_segment_length > maximum_length)\r\n        {\r\n            maximum_length = current_segment_length;\r\n            best_left = left;\r\n            best_right = right;\r\n        }\r\n\r\n        right++;\r\n\r\n    }\r\n\r\n    printf(\"%d %d\\n\", best_left, best_right);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Love Triangle.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_planes;\r\n    scanf(\"%d\", &no_of_planes);\r\n\r\n    vector <int> liked_by(no_of_planes + 1);\r\n    for(int i = 1; i <= no_of_planes; i++)\r\n        scanf(\"%d\", &liked_by[i]);\r\n\r\n    int love_triangle_exists = false;\r\n    for(int i = 1; i <= no_of_planes; i++)\r\n    {\r\n        int a = i;\r\n        int b = liked_by[a];\r\n        int c = liked_by[b];\r\n\r\n        if(a == liked_by[c])\r\n        {\r\n            love_triangle_exists = true;\r\n        }\r\n    }\r\n\r\n    printf(love_triangle_exists ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Nuts.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int k, total_nuts, dividers, capacity;\r\n    scanf(\"%d %d %d %d\", &k, &total_nuts, &dividers, &capacity);\r\n\r\n    int boxes_used = 0, nuts_stored_till_here = 0;\r\n\r\n    while(nuts_stored_till_here < total_nuts)\r\n    {\r\n        boxes_used++;\r\n\r\n        int dividers_used_in_this_box = min(dividers, k - 1);\r\n        int nuts_in_this_box = (dividers_used_in_this_box + 1)*capacity;\r\n\r\n\r\n        dividers -= dividers_used_in_this_box;\r\n        nuts_stored_till_here += nuts_in_this_box;\r\n    }\r\n\r\n    printf(\"%d\\n\", boxes_used);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Palindrome Transformation.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    string A;\r\n    int cursor;\r\n    cin >> n >> cursor >> A;\r\n\r\n    cursor--;\r\n    n--;\r\n\r\n    cursor = min(cursor, n - cursor);\r\n\r\n    int middle = n/2;\r\n\r\n    int leftmost = cursor, rightmost = cursor;\r\n    for(int i = cursor; i <= middle; i++)\r\n        if(A[i] != A[n - i])\r\n            rightmost = i;\r\n\r\n    for(int i = cursor; i >= 0; i--)\r\n        if(A[i] != A[n - i])\r\n            leftmost = i;\r\n\r\n    int vertical_moves = 0;\r\n    for(int i = leftmost; i <= rightmost; i++)\r\n        vertical_moves += min(abs(A[i] - A[n - i]), 26 - abs(A[i] - A[n - i]));\r\n\r\n\r\n    int horizontal_moves = min((cursor - leftmost) + (rightmost - leftmost), (rightmost - cursor) + (rightmost - leftmost));\r\n\r\n    int total_moves = horizontal_moves + vertical_moves;\r\n    cout << total_moves;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Palindromic Supersequence.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nstring reverse(string A)\r\n{\r\n    string rev;\r\n\r\n    for(int i = A.size() - 1; i >= 0; i--)\r\n        rev += A[i];\r\n\r\n    return rev;\r\n}\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    string A_rev = reverse(A);\r\n    string B = A_rev + A;\r\n\r\n    cout << B;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Recursive Queries.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int LIMIT = 1e6 + 5;\r\nint answer[LIMIT][10];\r\n\r\nint non_zero_digit_product(int n)\r\n{\r\n    int product = 1;\r\n\r\n    while(n)\r\n    {\r\n        product *= (n%10 != 0 ? n%10 : 1);\r\n        n /= 10;\r\n    }\r\n\r\n    return product;\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    vector <int> g(LIMIT, 0);\r\n    for(int i = 1; i < LIMIT; i++)\r\n        g[i] = (i < 10 ? i : g[non_zero_digit_product(i)]);\r\n\r\n    for(int i = 1; i < LIMIT; i++)\r\n        answer[i][0] = 0;\r\n\r\n    for(int i = 1; i < LIMIT; i++)\r\n    {\r\n        for(int digit = 1; digit < 10; digit++)\r\n        {\r\n            answer[i][digit] = answer[i - 1][digit];\r\n        }\r\n\r\n        if(g[i] < 10)\r\n            answer[i][g[i]]++;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int left, right, k;\r\n        scanf(\"%d %d %d\", &left, &right, &k);\r\n\r\n        printf(\"%d\\n\", answer[right][k] - answer[left - 1][k]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Run For Your Prize.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> items(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &items[i]);\r\n\r\n    const int A_POSITION = 1;\r\n    vector <int> time_A(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) time_A[i] = (items[i] - A_POSITION);\r\n\r\n    const int B_POSITION = 1e6;\r\n    vector <int> time_B(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) time_B[i] = (B_POSITION - items[i]);\r\n\r\n    int minimum_time = B_POSITION + A_POSITION;\r\n\r\n    for(int i = 0; i <= no_of_elements; i++)\r\n    {\r\n        int time_if_A_picks_first_i = max(time_A[i], time_B[i + 1]);\r\n        minimum_time = min(minimum_time, time_if_A_picks_first_i);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Simple Strings.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nchar some_char_other_than(char a, char b)\r\n{\r\n    for(char ch = 'a'; ch <= 'z' ; ch++)\r\n        if(ch != a && ch != b)\r\n            return ch;\r\n}\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    string answer;\r\n    answer += A[0];\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        char predecessor = answer[answer.size() - 1];\r\n        char successor = (i + 1 == A.size() ? predecessor : A[i + 1]);\r\n\r\n        if(A[i] == predecessor)\r\n        {\r\n            answer += some_char_other_than(predecessor, successor);\r\n        }\r\n        else\r\n        {\r\n            answer += A[i];\r\n        }\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/The Useless Toy.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    map <char, int> positions;\r\n\r\n    positions['v'] = 0;\r\n    positions['<'] = 1;\r\n    positions['^'] = 2;\r\n    positions['>'] = 3;\r\n\r\n    char start_position, end_position;\r\n    int no_of_spins;\r\n\r\n    scanf(\"%c %c %d\", &start_position, &end_position, &no_of_spins);\r\n    int first_position = positions[start_position];\r\n    int final_position = positions[end_position];\r\n\r\n    if( (first_position + no_of_spins%4)%4 == final_position && (first_position + (4 - no_of_spins%4))%4 == final_position)\r\n        printf(\"undefined\\n\");\r\n    else if( (first_position + no_of_spins%4)%4 == final_position)\r\n        printf(\"cw\\n\");\r\n    else if( (first_position + (4 - no_of_spins%4))%4 == final_position)\r\n        printf(\"ccw\\n\");\r\n    else\r\n        printf(\"undefined\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Vasya and Socks.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int socks, new_sock_day;\r\n    scanf(\"%d %d\", &socks, &new_sock_day);\r\n\r\n    int no_of_days = 0;\r\n\r\n    while(socks > 0)\r\n    {\r\n        no_of_days++;\r\n\r\n        if(no_of_days%new_sock_day == 0)\r\n            socks++;\r\n\r\n        socks--;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_days);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 19/Watchmen.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_watchmen;\n    scanf(\"%d\", &no_of_watchmen);\n\n    map <int, int> x_frequency;\n    map <int, int> y_frequency;\n    map <pair<int, int>, int> x_and_y_frequency;\n\n    for(int i = 1; i <= no_of_watchmen; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n\n        x_frequency[x]++;\n        y_frequency[y]++;\n        x_and_y_frequency[make_pair(x,y)]++;\n    }\n\n    long long same_x_pairs = 0;\n    for(map <int, int> :: iterator it = x_frequency.begin(); it != x_frequency.end(); it++)\n    {\n        long long current_frequency = it->second;\n\n        same_x_pairs += (current_frequency*(current_frequency - 1))/2;\n    }\n\n    long long same_y_pairs = 0;\n    for(map <int, int> :: iterator it = y_frequency.begin(); it != y_frequency.end(); it++)\n    {\n        long long current_frequency = it->second;\n\n        same_y_pairs += (current_frequency*(current_frequency - 1))/2;\n    }\n\n    long long same_x_and_y_pairs = 0;\n    for(map <pair <int,int>, int> :: iterator it = x_and_y_frequency.begin(); it != x_and_y_frequency.end(); it++)\n    {\n        long long current_frequency = it->second;\n\n        same_x_and_y_pairs += (current_frequency*(current_frequency - 1))/2;\n    }\n\n    long long answer = same_x_pairs + same_y_pairs - same_x_and_y_pairs;\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 19/Word Correction.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint is_vowel(char ch)\r\n{\r\n    switch(ch)\r\n    {\r\n        case 'a':\r\n        case 'e':\r\n        case 'i':\r\n        case 'o':\r\n        case 'u':\r\n        case 'y': return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string text;\r\n    cin >> length >> text;\r\n\r\n    string final_text;\r\n    final_text += text[0];\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        if(is_vowel(text[i]) && is_vowel(final_text[final_text.size() - 1]))\r\n        {\r\n               continue;\r\n        }\r\n\r\n        final_text += text[i];\r\n    }\r\n\r\n    cout << final_text;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Alena and the Heater.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define max_4(a, b, c, d) max(max(a, b), max(c, d))\r\n#define min_4(a, b, c, d) min(min(a, b), min(c, d))\r\n#define max_5(a, b, c, d, e) max(max_4(a, b, c, d), e)\r\n#define min_5(a, b, c, d, e) min(min_4(a, b, c, d), e)\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    vector <int> A(length + 1);\r\n    for(int i = 0; i < length; i++) cin >> A[i];\r\n\r\n    string B;\r\n    cin >> B;\r\n\r\n    int left = -1e9, right = 1e9;\r\n\r\n    for(int i = 4; i < length; i++)\r\n    {\r\n        if(B[i] == B[i - 1])\r\n            continue;\r\n\r\n        if(B[i] == '1')\r\n            left = max(left, max_5(A[i], A[i - 1], A[i - 2], A[i - 3], A[i - 4]) + 1);\r\n\r\n        if(B[i] == '0')\r\n            right = min(right, min_5(A[i], A[i - 1], A[i - 2], A[i - 3], A[i - 4]) - 1);\r\n    }\r\n\r\n    cout << left << \" \" << right;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Fafa and Ancient Alphabet.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long power(long long n, long long power, int MOD)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*n)%MOD;\r\n\r\n        n = (n*n)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nlong long inverse(long long n, long long m)\r\n{\r\n    return power(n, m - 2, m);\r\n}\r\n\r\nlong long choose_2(long long n)\r\n{\r\n    return (n*(n - 1))/2;\r\n}\r\n\r\nint main()\r\n{\r\n    const int MOD = 1e9 + 7;\r\n\r\n    int length, no_of_alphabets;\r\n    scanf(\"%d %d\", &length, &no_of_alphabets);\r\n\r\n    vector <int> A(length + 1);\r\n    for(int i = 1; i <= length; i++) scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> B(length + 1);\r\n    for(int i = 1; i <= length; i++) scanf(\"%d\", &B[i]);\r\n\r\n    int no_of_zeroes = 0;\r\n    for(int i = 1; i <= length; i++) no_of_zeroes += (A[i] == 0) + (B[i] == 0);\r\n\r\n    const int ANY_WAY = 0, GREATER = 1;\r\n    typedef vector <long long> v_ll;\r\n    vector <v_ll> no_of_ways(length + 5, v_ll(2, 1));\r\n\r\n    no_of_ways[length + 1][ANY_WAY] = 1;\r\n    no_of_ways[length + 1][GREATER] = 0;\r\n\r\n    for(int i = length; i >= 1; i--)\r\n    {\r\n        no_of_ways[i][ANY_WAY] = no_of_ways[i + 1][ANY_WAY];\r\n\r\n        if(A[i] == 0) no_of_ways[i][ANY_WAY] = (no_of_ways[i][ANY_WAY]*no_of_alphabets)%MOD;\r\n        if(B[i] == 0) no_of_ways[i][ANY_WAY] = (no_of_ways[i][ANY_WAY]*no_of_alphabets)%MOD;\r\n\r\n        if(A[i] == 0 && B[i] == 0)\r\n        {\r\n            long long choose_different_alphabets = choose_2(no_of_alphabets);\r\n            long long choose_same_alphabet = no_of_alphabets;\r\n\r\n            no_of_ways[i][GREATER] = choose_different_alphabets*no_of_ways[i + 1][ANY_WAY] + choose_same_alphabet*no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(A[i] == 0)\r\n        {\r\n            no_of_ways[i][GREATER] = (no_of_alphabets - B[i])*no_of_ways[i + 1][ANY_WAY] + no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(B[i] == 0)\r\n        {\r\n            no_of_ways[i][GREATER] = (A[i] - 1)*no_of_ways[i + 1][ANY_WAY] + no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(A[i] > B[i])\r\n        {\r\n            no_of_ways[i][GREATER] = no_of_ways[i + 1][ANY_WAY];\r\n        }\r\n        else if(A[i] == B[i])\r\n        {\r\n            no_of_ways[i][GREATER] = no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(A[i] < B[i])\r\n        {\r\n            no_of_ways[i][GREATER] = 0;\r\n        }\r\n\r\n        no_of_ways[i][ANY_WAY] %= MOD;\r\n        no_of_ways[i][GREATER] %= MOD;\r\n    }\r\n\r\n    long long numerator = no_of_ways[1][GREATER];\r\n    long long denominator = power(no_of_alphabets, no_of_zeroes, MOD);\r\n\r\n    long long answer = numerator*inverse(denominator, MOD);\r\n    answer %= MOD;\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Fafa and His Company.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int answer = 1;\r\n    for(int i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            answer += (i*i == n ? 1 : 2);\r\n\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Fafa and the Gates.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_steps;\r\n    string steps;\r\n    cin >> no_of_steps >> steps;\r\n\r\n    int x = 0, y = 0, no_of_changes = 0;\r\n\r\n    for(int i = 0; i < no_of_steps - 1; i++)\r\n    {\r\n        if(steps[i] == 'U') y++;\r\n        if(steps[i] == 'R') x++;\r\n\r\n        no_of_changes += (x == y && steps[i] == steps[i + 1]);\r\n    }\r\n\r\n    cout << no_of_changes;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Fixing Typos.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    string answer;\r\n\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        char last_character, second_last_character, third_last_character;\r\n\r\n        if(answer.size() >= 1) last_character = answer[answer.size() - 1];\r\n        if(answer.size() >= 2) second_last_character = answer[answer.size() - 2];\r\n        if(answer.size() >= 3) third_last_character = answer[answer.size() - 3];\r\n\r\n        if(answer.size() >= 2 && A[i] == last_character && last_character == second_last_character)\r\n            continue;\r\n\r\n        if(answer.size() >= 3 && A[i] == last_character && second_last_character == third_last_character)\r\n            continue;\r\n\r\n        answer += A[i];\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Gargari and Bishops.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\nconst int WHITE = 1, BLACK = 0, MAX_N = 2015;\r\nint points[MAX_N][MAX_N];\r\nlong long principal_diagonal_sum[2*MAX_N];\r\nlong long secondary_diagonal_sum[2*MAX_N];\r\n\r\nint colour(int x, int y)\r\n{\r\n    int sum = x + y;\r\n\r\n    return (sum%2 == 0 ? WHITE : BLACK);\r\n}\r\n\r\nint get_principal_diagonal_no(int x, int y, int n)\r\n{\r\n    return (x - y + n);\r\n}\r\n\r\nint get_secondary_diagonal_no(int x, int y)\r\n{\r\n    return (x + y);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    memset(principal_diagonal_sum, 0, sizeof(principal_diagonal_sum));\r\n    memset(secondary_diagonal_sum, 0, sizeof(secondary_diagonal_sum));\r\n\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            scanf(\"%d\", &points[x][y]);\r\n\r\n            int principal_diagonal_no = get_principal_diagonal_no(x, y, n);\r\n            int secondary_diagonal_no = get_secondary_diagonal_no(x, y);\r\n\r\n            principal_diagonal_sum[principal_diagonal_no] += points[x][y];\r\n            secondary_diagonal_sum[secondary_diagonal_no] += points[x][y];\r\n        }\r\n    }\r\n\r\n    int white_x, white_y; long long white_best = 0;\r\n    int black_x, black_y; long long black_best = 0;\r\n\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            int principal_diagonal_no = get_principal_diagonal_no(x, y, n);\r\n            int secondary_diagonal_no = get_secondary_diagonal_no(x, y);\r\n            long long bishop_score = principal_diagonal_sum[principal_diagonal_no] + secondary_diagonal_sum[secondary_diagonal_no] - points[x][y];\r\n\r\n            if(colour(x, y) == WHITE)\r\n            {\r\n                if(bishop_score >= white_best)\r\n                {\r\n                    white_best = bishop_score, white_x = x, white_y = y;\r\n                }\r\n            }\r\n            else if(colour(x, y) == BLACK)\r\n            {\r\n                if(bishop_score >= black_best)\r\n                {\r\n                    black_best = bishop_score, black_x = x, black_y = y;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    long long best = black_best + white_best;\r\n    printf(\"%I64d\\n\", best);\r\n    printf(\"%d %d %d %d\", white_x, white_y, black_x, black_y);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Gargari and Permutations Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nconst int MAX_N = 1005, MAX_PERMUTATIONS = 5;\r\nint P[MAX_PERMUTATIONS + 1][MAX_N], maximum_length_till[MAX_N];\r\nint position[MAX_PERMUTATIONS + 1][MAX_N];\r\n\r\nint main()\r\n{\r\n    int no_of_permutations, length;\r\n    scanf(\"%d %d\", &length, &no_of_permutations);\r\n\r\n    for(int k = 1; k <= no_of_permutations; k++)\r\n    {\r\n        for(int i = 1; i <= length; i++)\r\n        {\r\n            scanf(\"%d\", &P[k][i]);\r\n            int element = P[k][i];\r\n            position[k][element] = i;\r\n        }\r\n    }\r\n\r\n    int answer = 1;\r\n\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        maximum_length_till[i] = 1;\r\n\r\n        for(int j = 1; j < i; j++)\r\n        {\r\n            int current = P[1][i], previous = P[1][j];\r\n            int previous_always_before_current = true;\r\n\r\n            for(int k = 1; k <= no_of_permutations; k++)\r\n            {\r\n                if(position[k][previous] > position[k][current])\r\n                {\r\n                    previous_always_before_current = false;\r\n                }\r\n            }\r\n\r\n            if(previous_always_before_current)\r\n            {\r\n                maximum_length_till[i] = max(maximum_length_till[i], 1 + maximum_length_till[j]);\r\n            }\r\n        }\r\n\r\n        answer = max(answer, maximum_length_till[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Gargari and Permutations.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1005, MAX_PERMUTATIONS = 5;\r\nint P[MAX_PERMUTATIONS + 1][MAX_N];\r\nint position[MAX_PERMUTATIONS + 1][MAX_N];\r\n\r\nvector <int> graph[MAX_N];\r\nint longest_path[MAX_N];\r\n\r\nint get_longest_path(int v)\r\n{\r\n    if(longest_path[v] != -1)\r\n        return longest_path[v];\r\n\r\n    longest_path[v] = 1;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        longest_path[v] = max(longest_path[v], 1 + get_longest_path(child));\r\n    }\r\n\r\n    return longest_path[v];\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_permutations, length;\r\n    scanf(\"%d %d\", &length, &no_of_permutations);\r\n\r\n    for(int k = 1; k <= no_of_permutations; k++)\r\n    {\r\n        for(int i = 1; i <= length; i++)\r\n        {\r\n            int element;\r\n            scanf(\"%d\", &element);\r\n            position[k][element] = i;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        for(int j = i + 1; j <= length; j++)\r\n        {\r\n            int i_always_before_j = true, j_always_before_i = true;\r\n\r\n            for(int k = 1; k <= no_of_permutations; k++)\r\n            {\r\n                if(position[k][i] > position[k][j])\r\n                {\r\n                    i_always_before_j = false;\r\n                }\r\n                if(position[k][j] > position[k][i])\r\n                {\r\n                    j_always_before_i = false;\r\n                }\r\n            }\r\n\r\n            if(i_always_before_j)\r\n            {\r\n                graph[i].push_back(j);\r\n            }\r\n            if(j_always_before_i)\r\n            {\r\n                graph[j].push_back(i);\r\n            }\r\n        }\r\n    }\r\n\r\n    memset(longest_path, -1, sizeof(longest_path));\r\n    int graph_longest_path = 0;\r\n    for(int i = 1; i <= length; i++)\r\n        graph_longest_path = max(graph_longest_path, get_longest_path(i));\r\n\r\n    printf(\"%d\\n\", graph_longest_path);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Hard Process.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, max_zeroes;\r\n    scanf(\"%d %d\", &no_of_elements, &max_zeroes);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int no_of_0s = 0;\r\n    int change_left = 0, change_right = 0, left = 1, right = 1, max_window_size = 0;\r\n\r\n    while(right <= no_of_elements)\r\n    {\r\n        if(A[right] == 0)\r\n            no_of_0s++;\r\n\r\n        while(no_of_0s > max_zeroes)\r\n        {\r\n            if(A[left] == 0)\r\n                no_of_0s--;\r\n\r\n            left++;\r\n        }\r\n\r\n        int window_size = right - (left - 1);\r\n        if(window_size > max_window_size)\r\n        {\r\n            max_window_size = window_size, change_left = left, change_right = right;\r\n        }\r\n\r\n        right++;\r\n    }\r\n\r\n    for(int i = change_left; i <= change_right; i++) A[i] = 1;\r\n\r\n    printf(\"%d\\n\", max_window_size);\r\n    for(int i = 1; i <= no_of_elements; i++) printf(\"%d \", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Lisa and Dima.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_prime(int n)\r\n{\r\n    for(int i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nvoid sieve(vector <int> &is_prime)\r\n{\r\n    int N = is_prime.size();\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i*i <= N; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            for(int multiple = i*i; multiple <= N; multiple += i)\r\n            {\r\n                is_prime[multiple] = false;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nvoid break_into_sum_of_primes(int N, int &prime_1, int &prime_2)\r\n{\r\n    vector <int> is_prime(N + 1, true);\r\n    sieve(is_prime);\r\n\r\n    for(int i = 2; i <= N; i++)\r\n    {\r\n        if(is_prime[i] && is_prime[N - i])\r\n        {\r\n            prime_1 = i;\r\n            prime_2 = N - i;\r\n            return;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    if(is_prime(n))\r\n    {\r\n        printf(\"1\\n%d\\n\", n);\r\n        return 0;\r\n    }\r\n\r\n    if(is_prime(n - 2))\r\n    {\r\n        printf(\"2\\n%d %d\", 2, n - 2);\r\n        return 0;\r\n    }\r\n\r\n    int prime_1, prime_2, prime_3;\r\n\r\n    for(int i = n - 4; ; i--)\r\n    {\r\n        if(is_prime(i))\r\n        {\r\n            prime_3 = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    break_into_sum_of_primes(n - prime_3, prime_1, prime_2);\r\n    printf(\"3\\n%d %d %d\\n\", prime_1, prime_2, prime_3);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Love Rescue.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 26;\r\nvector <int> graph[MAX_N];\r\nvector <int> visited(MAX_N, false);\r\nvector <int> component[MAX_N] ;\r\n\r\nvoid mark(int v, int component_no)\r\n{\r\n    visited[v] = true;\r\n    component[component_no].push_back(v);\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(!visited[child])\r\n            mark(child, component_no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string A, B;\r\n    cin >> length >> A >> B;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            graph[A[i] - 'a'].push_back(B[i] - 'a');\r\n            graph[B[i] - 'a'].push_back(A[i] - 'a');\r\n        }\r\n    }\r\n\r\n    int component_no = 0, no_of_edges = 0;\r\n    for(int i = 0; i < MAX_N; i++)\r\n    {\r\n        if(graph[i].size() != 0 && !visited[i])\r\n        {\r\n            mark(i, component_no);\r\n            no_of_edges += component[component_no].size() - 1;\r\n\r\n            component_no++;\r\n        }\r\n    }\r\n\r\n    cout << no_of_edges << \"\\n\";\r\n    for(int i = 0; i < component_no; i++)\r\n    {\r\n        for(int j = 1; j < component[i].size(); j++)\r\n        {\r\n            cout << char('a' + component[i][j - 1]) << \" \" << char('a' + component[i][j]) << \"\\n\";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Mashmokh and Numbers.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n\r\nint main()\r\n{\r\n    int n, score;\r\n    scanf(\"%d %d\", &n, &score);\r\n\r\n    int minimum_score = n/2;\r\n\r\n    if(n == 1 && score == 0) {printf(\"1\\n\"); return ;}\r\n\r\n    if(n == 1 || score < minimum_score)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    int score_except_last_two = (n - 2)/2;\r\n    int second_term = score - score_except_last_two;\r\n\r\n    printf(\"%d %d \", second_term, 2*second_term);\r\n\r\n    for(int i = 3; i <= n; i++) printf(\"%d \", 2*second_term + i);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Non-Secret Cypher.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_equal_elements;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_equal_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int left = 1, right = 1;\r\n    long long no_of_subarrays = 0;\r\n\r\n    map <int, int> frequency;\r\n\r\n    while(right <= no_of_elements)\r\n    {\r\n        frequency[A[right]]++;\r\n\r\n        while(frequency[A[right]] == no_of_equal_elements)\r\n        {\r\n            no_of_subarrays += (no_of_elements - right + 1);\r\n\r\n            frequency[A[left]]--;\r\n            left++;\r\n        }\r\n\r\n        right++;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_subarrays);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Olympiad.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    set <int> awards;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int score;\r\n        scanf(\"%d\", &score);\r\n\r\n        if(score > 0) awards.insert(score);\r\n    }\r\n\r\n    printf(\"%u\\n\", awards.size());\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Partition.cpp",
    "content": "#include <cstdio>\r\n\r\n#define abs(x) (x > 0 ? x : -x)\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    int answer = 0;\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n\r\n        answer += abs(element);\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Petya and His Friends Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid precompute(vector <int> &primes, int LIMIT)\r\n{\r\n    vector <int> is_prime(LIMIT + 1, true);\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= LIMIT; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] <= LIMIT; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n}\r\n\r\nint nearest_power_of_2_greater_than(int n)\r\n{\r\n    int power = 1;\r\n\r\n    while(power <= n)\r\n        power = power << 1;\r\n\r\n    return power;\r\n}\r\n\r\nint is_bit_set(int n, int position)\r\n{\r\n    return ( (n & (1 << position)) != 0);\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 300;\r\n    vector <int> primes;\r\n    precompute(primes, LIMIT);\r\n\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    if(n == 2)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    int N = nearest_power_of_2_greater_than(n);\r\n    vector <long long> A(N + 5, 1);\r\n\r\n    int first_free_prime = 0;\r\n\r\n    for(int bit = 0; (1 << bit) < N; bit++)\r\n    {\r\n        int set_bit_prime = primes[first_free_prime++];\r\n        int unset_bit_prime = primes[first_free_prime++];\r\n\r\n        for(int i = 1; i <= N; i++)\r\n        {\r\n            if(is_bit_set(i, bit))\r\n                A[i] *= set_bit_prime;\r\n            else\r\n                A[i] *= unset_bit_prime;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; 2*i <= N; i++, first_free_prime++)\r\n    {\r\n        A[i]   *= primes[first_free_prime];\r\n        A[(N - 1)^i] *= primes[first_free_prime];\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n        printf(\"%I64d\\n\", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Petya and His Friends.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n\n    if(n == 2)\n    {\n        printf(\"-1\\n\");\n        return 0;\n    }\n\n    printf(\"6\\n10\\n15\\n\");\n    for(int i = 4; i <= n; i++)\n    {\n        printf(\"6\"); for(int zero = 1; zero <= i - 4 + 1; zero++) printf(\"0\");\n        printf(\"\\n\");\n    }\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 20/Phone Numbers.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, answer_length;\r\n    string A;\r\n    cin >> length >> answer_length >> A;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> present(NO_OF_ALPHABETS, false);\r\n    for(int i = 0; i < A.size(); i++) present[A[i] - 'a'] = true;\r\n\r\n    char smallest_alphabet;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(present[i])\r\n        {\r\n            smallest_alphabet = 'a' + i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(answer_length > length)\r\n    {\r\n        cout << A;\r\n        for(int i = A.size(); i < answer_length; i++) cout << smallest_alphabet;\r\n\r\n        return 0;\r\n    }\r\n\r\n    int first_change_point, greater_char_available = false;\r\n    char char_at_first_change_point;\r\n\r\n    for(int i = answer_length - 1; i >= 0 && !greater_char_available; i--)\r\n    {\r\n        for(char alphabet = A[i] + 1; alphabet <= 'z'; alphabet++)\r\n        {\r\n            if(present[alphabet - 'a'])\r\n            {\r\n                greater_char_available = true;\r\n\r\n                first_change_point = i;\r\n                char_at_first_change_point = alphabet;\r\n\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < first_change_point; i++) cout << A[i];\r\n    cout << char_at_first_change_point;\r\n    for(int i = first_change_point + 1; i < answer_length; i++) cout << smallest_alphabet;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Pocket Book.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_names, length;\r\n    cin >> no_of_names >> length;\r\n\r\n    set <int> distinct_characters[length];\r\n\r\n    while(no_of_names--)\r\n    {\r\n        string name;\r\n        cin >> name;\r\n\r\n        for(int i = 0; i < length; i++)\r\n            distinct_characters[i].insert(name[i]);\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long total_strings = 1;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        total_strings = (total_strings*distinct_characters[i].size())%MOD;\r\n    }\r\n\r\n    cout << total_strings;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Points on the Line.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n, d;\r\n    scanf(\"%d %d\", &n, &d);\r\n\r\n    vector <int> A(n + 1, 0);\r\n    for(int i = 1; i <= n; i++) scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int removed_elements = n;\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int removed_elements_to_start_at_i = i - 1, j = i;\r\n\r\n        while(j <= n && A[j] - A[i] <= d)\r\n            j++;\r\n\r\n        removed_elements_to_start_at_i += (n - j + 1);\r\n\r\n        removed_elements = min(removed_elements, removed_elements_to_start_at_i);\r\n    }\r\n\r\n    printf(\"%d\\n\", removed_elements);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Protect Sheep.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n    char pasture[rows + 5][columns + 5];\r\n\r\n    for(int r = 1; r <= rows; r++)\r\n        scanf(\"%s\", pasture[r] + 1);\r\n\r\n    int is_possible = true;\r\n\r\n    for(int r = 1; r <= rows; r++)\r\n    {\r\n        for(int c = 1; c <= columns; c++)\r\n        {\r\n            if(pasture[r][c] == 'W')\r\n            {\r\n                if(pasture[r + 1][c] == 'S' || pasture[r][c + 1] == 'S' || pasture[r - 1][c] == 'S' || pasture[r][c - 1] == 'S')\r\n                {\r\n                    is_possible = false;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    if(!is_possible)\r\n    {\r\n        printf(\"No\\n\");\r\n        return 0;\r\n    }\r\n\r\n    printf(\"Yes\\n\");\r\n    for(int r = 1; r <= rows; r++)\r\n    {\r\n        for(int c = 1; c <= columns; c++)\r\n        {\r\n            char current_cell = (pasture[r][c] == '.' ? 'D' : pasture[r][c]);\r\n\r\n            printf(\"%c\", current_cell);\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/String Transformation.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    int last_found = 'a' - 1;\r\n\r\n    for(int i = 0; i < S.size() && last_found < 'z'; i++)\r\n    {\r\n        if(S[i] <= last_found + 1)\r\n        {\r\n            S[i] = last_found + 1;\r\n            last_found = S[i];\r\n        }\r\n    }\r\n\r\n    cout << (last_found == 'z' ? S : \"-1\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Sum and Replace.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define LEFT(n) ( (n << 1) )\r\n#define RIGHT(n) ( (n << 1)|1 )\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e6 + 10, MAX_ELEMENTS = 5e5 + 6;\r\nvector <int> no_of_divisors(MAX_N, 0);\r\n\r\nint max_tree[3*MAX_ELEMENTS];\r\nlong long sum_tree[3*MAX_ELEMENTS];\r\nint A[MAX_ELEMENTS];\r\n\r\nvoid precompute_divisors()\r\n{\r\n    vector <int> largest_prime_factor(MAX_N, 0);\r\n    no_of_divisors[1] = 1;\r\n\r\n    for(int i = 2; i < MAX_N; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple < MAX_N; multiple += i)\r\n            {\r\n                largest_prime_factor[multiple] = i;\r\n            }\r\n        }\r\n\r\n        int exponent = 0, reduced_i = i;\r\n\r\n        while(reduced_i%largest_prime_factor[i] == 0)\r\n        {\r\n            reduced_i /= largest_prime_factor[i];\r\n            exponent++;\r\n        }\r\n\r\n        no_of_divisors[i] = (exponent + 1)*no_of_divisors[reduced_i];\r\n    }\r\n}\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nlong long get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    long long left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    long long right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nvoid update(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left || max_tree[n] <= 2)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        A[left] = no_of_divisors[A[left]];\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    update(LEFT(n), left, mid, query_left, query_right);\r\n    update(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_divisors();\r\n\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        const int SUM = 2, REPLACE = 1;\r\n        int query_type, left, right;\r\n        scanf(\"%d %d %d\", &query_type, &left, &right);\r\n\r\n        if(query_type == SUM)\r\n        {\r\n            long long sum = get_sum(1, 1, no_of_elements, left, right);\r\n            printf(\"%I64d\\n\", sum);\r\n        }\r\n        else if(query_type == REPLACE)\r\n        {\r\n            update(1, 1, no_of_elements, left, right);\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Vile Grasshoppers.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int p, y;\r\n    scanf(\"%d %d\", &p, &y);\r\n\r\n    int answer = y;\r\n\r\n    while(answer > p)\r\n    {\r\n        int coprime_till_p = true;\r\n\r\n        for(int i = 2; i <= p && i*i <= y; i++)\r\n        {\r\n            if(answer%i == 0)\r\n            {\r\n                coprime_till_p = false;\r\n                break;\r\n            }\r\n        }\r\n\r\n        if(coprime_till_p) break;\r\n\r\n        answer--;\r\n    }\r\n\r\n\r\n    printf(\"%d\\n\", answer == p ? -1 : answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 20/Weird Subtraction Process.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long a, b;\r\n    cin >> a >> b;\r\n\r\n    while(a != 0 && b != 0 && (a >= 2*b || b >= 2*a))\r\n    {\r\n        if(a >= 2*b)\r\n        {\r\n            a %= (2*b);\r\n        }\r\n        else if(b >= 2*a)\r\n        {\r\n            b %= (2*a);\r\n        }\r\n    }\r\n\r\n    cout << a << \" \" << b;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Aramic Script Bitmask Solution.cpp",
    "content": "#include <iostream>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <int> mask;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        int current_mask = 0;\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            current_mask |= (1 << (word[i] - 'a'));\r\n\r\n        mask.insert(current_mask);\r\n    }\r\n\r\n    cout << mask.size();\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Aramic Script.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all (v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <string> distinct_words;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        const int NO_OF_ALPHABETS = 26;\r\n        vector <int> present(NO_OF_ALPHABETS, false);\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            present[word[i] - 'a'] = true;\r\n\r\n        string root;\r\n        for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n            if(present[i])\r\n                root += (char)('a' + i);\r\n\r\n        distinct_words.insert(root);\r\n    }\r\n\r\n    cout << distinct_words.size();\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Arithmetic Progression.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_cards;\r\n    scanf(\"%d\", &no_of_cards);\r\n\r\n    vector <int> card(no_of_cards);\r\n    for(int i = 0; i < no_of_cards; i++) scanf(\"%d\", &card[i]);\r\n\r\n    if(no_of_cards == 1)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    vector <int> new_cards;\r\n\r\n    if(no_of_cards == 2 && (card[0] != card[1]) && (card[0] + card[1])%2 == 0)\r\n    {\r\n        new_cards.push_back( (card[0] + card[1])/2 );\r\n    }\r\n\r\n    sort(all(card));\r\n\r\n    int min_difference = card[1] - card[0];\r\n    for(int i = 2; i < no_of_cards; i++)\r\n        min_difference = min(min_difference, card[i] - card[i - 1]);\r\n\r\n    int ap_possible = true, new_middle_cards = 0;\r\n    for(int i = 1; i < no_of_cards; i++)\r\n    {\r\n        if(card[i] - card[i - 1] != min_difference)\r\n        {\r\n            if(card[i] - card[i - 1] == 2*min_difference)\r\n            {\r\n                new_middle_cards++;\r\n            }\r\n            else\r\n            {\r\n                ap_possible = false;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(ap_possible)\r\n    {\r\n        if(min_difference == 0)\r\n        {\r\n            new_cards.push_back(card[0]);\r\n        }\r\n        else if(new_middle_cards == 0)\r\n        {\r\n            new_cards.push_back(card[0] - min_difference);\r\n            new_cards.push_back(card[no_of_cards - 1] + min_difference);\r\n        }\r\n        else if(new_middle_cards == 1)\r\n        {\r\n            for(int i = 1; i < no_of_cards; i++)\r\n                if(card[i] - card[i - 1] == 2*min_difference)\r\n                    new_cards.push_back(card[i - 1] + min_difference);\r\n        }\r\n    }\r\n\r\n    sort(all(new_cards));\r\n\r\n    printf(\"%d\\n\", new_cards.size());\r\n    for(int i = 0; i < new_cards.size(); i++)\r\n        printf(\"%d \", new_cards[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Bash and a Tough Math Puzzle.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define max(a, b) (a > b ? a : b)\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nconst int MAX_N = 5e5 + 15, NOT_FOUND = -1;\r\n\r\nint gcd_tree[3*MAX_N], A[MAX_N], no_of_elements;\r\n\r\nint gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        gcd_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    gcd_tree[n] = gcd(gcd_tree[LEFT(n)], gcd_tree[RIGHT(n)]);\r\n}\r\n\r\nvoid update(int n, int left, int right, int index, int value)\r\n{\r\n    if(right < index || index < left)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        gcd_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update(LEFT(n), left, mid, index, value);\r\n    update(RIGHT(n), mid + 1, right, index, value);\r\n\r\n    gcd_tree[n] = gcd(gcd_tree[LEFT(n)], gcd_tree[RIGHT(n)]);\r\n}\r\n\r\nint get_first_indivisible_element(int n, int left, int right, int query_left, int query_right, int x)\r\n{\r\n    if(gcd_tree[n]%x == 0 || right < query_left || query_right < left || right < left || query_right < query_left)\r\n        return NOT_FOUND;\r\n\r\n    if(left == right) //Leaf node and it's not divisible. So, it has to be this element.\r\n        return left;\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    int left_answer = get_first_indivisible_element(LEFT(n), left, mid, query_left, query_right, x);\r\n\r\n    if(left_answer != NOT_FOUND)\r\n        return left_answer;\r\n\r\n    int right_answer = get_first_indivisible_element(RIGHT(n), mid + 1, right, query_left, query_right, x);\r\n\r\n    return right_answer;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    const int GUESS_GCD = 1, UPDATE = 2;\r\n\r\n    int query_type;\r\n    scanf(\"%d \", &query_type);\r\n\r\n    if(query_type == GUESS_GCD)\r\n    {\r\n        int left, right, x;\r\n        scanf(\"%d %d %d\", &left, &right, &x);\r\n\r\n        int first_indivisible_element = get_first_indivisible_element(1, 1, no_of_elements, left, right, x);\r\n\r\n        if(first_indivisible_element == NOT_FOUND) //Entire range divisible by x.\r\n        {\r\n            printf(\"YES\\n\");\r\n        }\r\n        else if(first_indivisible_element != NOT_FOUND) //If 2 elements are not divisible by x, answer is NO. Else, if it is <= 1, answer is YES\r\n        {\r\n            int second_indivisible_element = get_first_indivisible_element(1, 1, no_of_elements, first_indivisible_element + 1, right, x);\r\n\r\n            printf(second_indivisible_element == NOT_FOUND ? \"YES\\n\" : \"NO\\n\");\r\n        }\r\n    }\r\n    else if(query_type == UPDATE)\r\n    {\r\n        int index, value;\r\n        scanf(\"%d %d\", &index, &value);\r\n\r\n        update(1, 1, no_of_elements, index, value);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Consecutive Subsequences.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int last_element, longest_sequence = 0;\r\n\r\n    map <int, int> answer_with_last_element;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer_with_last_element[A[i]] = 1 + answer_with_last_element[A[i] - 1];\r\n\r\n        if(answer_with_last_element[A[i]] > longest_sequence)\r\n        {\r\n            longest_sequence = answer_with_last_element[A[i]];\r\n            last_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <int> index;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(index.size() == 0)\r\n        {\r\n            if(A[i] == last_element - longest_sequence + 1)\r\n                index.push_back(i);\r\n        }\r\n        else if(A[i] == A[index.back()] + 1)\r\n        {\r\n            index.push_back(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_sequence);\r\n    for(int i = 0; i < longest_sequence; i++) printf(\"%d \", index[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Cyclic Components.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 15, UNMARKED = -1;\r\nvector <int> graph[MAX_N];\r\nvector <int> component[MAX_N];\r\nint component_no[MAX_N];\r\n\r\nvoid dfs_and_mark_component(int v, int no)\r\n{\r\n    component[no].push_back(v);\r\n    component_no[v] = no;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(component_no[child] == UNMARKED)\r\n            dfs_and_mark_component(child, no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    memset(component_no, UNMARKED, sizeof(component_no));\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(component_no[i] == UNMARKED)\r\n            dfs_and_mark_component(i, no_of_components++);\r\n    }\r\n\r\n    int no_of_cycles = 0;\r\n\r\n    for(int i = 0; i < no_of_components; i++)\r\n    {\r\n        int is_cycle = true;\r\n\r\n        for(int j = 0; j < component[i].size(); j++)\r\n        {\r\n            int v = component[i][j];\r\n\r\n            if(graph[v].size() != 2)\r\n            {\r\n                is_cycle = false;\r\n            }\r\n        }\r\n\r\n        no_of_cycles += (is_cycle == true);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_cycles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Divide by Three, Multiply by Two Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n\r\ntypedef unsigned long long ULL;\r\nusing namespace std;\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    map <ULL, int> present;\r\n    vector <ULL> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64u\", &A[i]);\r\n        present[A[i]] = true;\r\n    }\r\n\r\n    ULL first_element;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int comes_from_multiplication = (A[i]%2 == 0 && present[A[i]/2]);\r\n        int comes_from_division = (A[i] <= 1e18 && present[3*A[i]]);\r\n\r\n        if(!comes_from_multiplication && !comes_from_division)\r\n        {\r\n            first_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <ULL> solution;\r\n    solution.push_back(first_element);\r\n    while(solution.size() < no_of_elements)\r\n    {\r\n        ULL last_element = solution.back();\r\n        if(last_element%3 == 0 && present[last_element/3])\r\n        {\r\n               solution.push_back(last_element/3);\r\n        }\r\n        else\r\n        {\r\n            solution.push_back(2*last_element);\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", solution[i]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Divide by Three, Multiply by Two.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct info\r\n{\r\n    int two, three;\r\n    unsigned long long number;\r\n};\r\n\r\nint compare(const info &A, const info &B)\r\n{\r\n    if(A.two - A.three < B.two - B.three)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <info> A(no_of_elements);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        unsigned long long element;\r\n        scanf(\"%I64u\", &element);\r\n\r\n        A[i].number = element;\r\n        A[i].two = 0, A[i].three = 0;\r\n\r\n        while(element%2 == 0) A[i].two++, element /= 2;\r\n        while(element%3 == 0) A[i].three++, element /= 3;\r\n    }\r\n\r\n    sort(all(A), compare);\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", A[i].number);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Dreamoon and Sets.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_sets, k;\r\n    scanf(\"%d %d\", &no_of_sets, &k);\r\n\r\n    int maximum_number = (6*(no_of_sets - 1) + 5)*k;\r\n    printf(\"%d\\n\", maximum_number);\r\n\r\n    for(int i = 0; i < no_of_sets; i++)\r\n    {\r\n        const int NO_OF_TERMS = 4;\r\n        int mod[NO_OF_TERMS] = {1, 2, 3, 5};\r\n\r\n        for(int m = 0; m < NO_OF_TERMS; m++)\r\n        {\r\n            int term = (6*i + mod[m])*k;\r\n            printf(\"%d \", term);\r\n        }\r\n        printf(\"\\n\");\r\n\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/File Name.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int removable_characters = 0;\r\n    for(int i = 2; i < length; i++)\r\n       removable_characters += (S[i] == 'x' && S[i - 1] == 'x' && S[i - 2] == 'x');\r\n\r\n    cout << removable_characters;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Fox and Box Accumulation.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <queue>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint is_possible(vector <int> &strength, int no_of_piles)\r\n{\r\n    priority_queue <int> pile_tops;\r\n\r\n    int box_ptr = strength.size() - 1;\r\n\r\n    for(int i = 1; i <= no_of_piles; i++)\r\n        pile_tops.push(strength[box_ptr--]);\r\n\r\n    while(box_ptr >= 0)\r\n    {\r\n        int strongest_pile = pile_tops.top();\r\n        pile_tops.pop();\r\n\r\n        if(strongest_pile == 0) return false;\r\n\r\n        int next_box = strength[box_ptr];\r\n        pile_tops.push(min(strongest_pile - 1, next_box));\r\n\r\n        box_ptr--;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_boxes;\r\n    scanf(\"%d\", &no_of_boxes);\r\n\r\n    vector <int> strength(no_of_boxes);\r\n    for(int i = 0; i < no_of_boxes; i++) scanf(\"%d\", &strength[i]);\r\n\r\n    sort(all(strength));\r\n\r\n    int left = 1, right = no_of_boxes, answer;\r\n    while(left <= right)\r\n    {\r\n        int mid = (left + right) >> 1;\r\n\r\n        if(is_possible(strength, mid))\r\n        {\r\n            if(mid == 1 || !is_possible(strength, mid - 1))\r\n            {\r\n                answer = mid;\r\n                break;\r\n            }\r\n            else\r\n            {\r\n                right = mid - 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            left = mid + 1;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Ghosts.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_points, a, b;\r\n    scanf(\"%d %d %d\", &no_of_points, &a, &b);\r\n\r\n    long long total_collisions = 0;\r\n    map < pair<int, int>, int > slope_count;\r\n    map <long long, int> intersections;\r\n\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        int x, vx, vy;\r\n        scanf(\"%d %d %d\", &x, &vx, &vy);\r\n\r\n        total_collisions += intersections[a*1LL*vx - vy] - slope_count[make_pair(vx, vy)]; //Parallel points don't meet.\r\n\r\n        slope_count[make_pair(vx, vy)]++;\r\n        intersections[a*1LL*vx - vy]++;\r\n    }\r\n\r\n    total_collisions *= 2;\r\n\r\n    printf(\"%I64d\\n\", total_collisions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Less or Equal.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, position;\r\n    scanf(\"%d %d\", &no_of_elements, &position);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int answer;\r\n    if(position == 0)\r\n    {\r\n        answer = (A[1] > 1 ? 1 : -1);\r\n    }\r\n    else\r\n    {\r\n        answer = (position < no_of_elements && A[position] == A[position + 1] ? -1 : A[position]);\r\n    }\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Little Girl and Maximum XOR.cpp",
    "content": "#include <cstdio>\r\n\r\nlong long all_ones(int n)\r\n{\r\n    return (1LL << (n + 1)) - 1;\r\n}\r\n\r\nint main()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    if(left == right)\r\n    {\r\n        printf(\"0\\n\");\r\n        return 0;\r\n    }\r\n\r\n    int largest_unequal_bit_position;\r\n\r\n    for(int i = 0; left > 0 || right > 0; i++)\r\n    {\r\n        if(left%2 != right%2)\r\n            largest_unequal_bit_position = i;\r\n\r\n        left >>= 1;\r\n        right >>= 1;\r\n    }\r\n\r\n    long long answer = all_ones(largest_unequal_bit_position); //This gives a number consisting of n 1's in binary\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Lucky Sum of Digits.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    int sum;\n    scanf(\"%d\", &sum);\n\n    int possible = false;\n    int no_of_4s = 0, no_of_7s = sum/7;\n\n    while(no_of_7s >= 0)\n    {\n        if( (sum - 7*no_of_7s)%4 == 0)\n        {\n            no_of_4s = (sum - 7*no_of_7s)/4;\n            possible = true;\n            break;\n        }\n        no_of_7s--;\n    }\n\n    if(!possible)\n    {\n        printf(\"-1\\n\");\n        return 0;\n    }\n\n    for(int i = 1; i <= no_of_4s; i++) printf(\"4\");\n    for(int i = 1; i <= no_of_7s; i++) printf(\"7\");\n\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 21/Mahmoud  and Ehab and another array construction task.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid sieve(vector <int> &is_prime, int LIMIT)\r\n{\r\n    is_prime[0] = is_prime[1] = false;\r\n    for(long long i = 2; i*i <= LIMIT; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            for(long long multiple = i*i; multiple <= LIMIT; multiple += i)\r\n            {\r\n                is_prime[multiple] = false;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nint all_prime_factors_available(int n, vector <int> &used)\r\n{\r\n    for(int p = 2; p*p <= n; p++)\r\n    {\r\n        while(n%p == 0)\r\n        {\r\n            if(used[p] == true) return false;\r\n\r\n            n /= p;\r\n        }\r\n    }\r\n\r\n    if(n > 1 && used[n]) return false;\r\n\r\n    return true;\r\n}\r\n\r\nvoid mark_prime_factors(int n, vector <int> &used)\r\n{\r\n    for(int p = 2; p*p <= n; p++)\r\n    {\r\n        while(n%p == 0)\r\n        {\r\n            used[p] = true;\r\n\r\n            n /= p;\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n        used[n] = true;\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 2e6;\r\n    vector <int> is_prime(LIMIT, true);\r\n    sieve(is_prime, LIMIT);\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> original(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &original[i]);\r\n\r\n    vector <int> solution;\r\n\r\n    vector <int> used(LIMIT, false);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        if(all_prime_factors_available(original[i], used))\r\n        {\r\n            solution.push_back(original[i]);\r\n\r\n            mark_prime_factors(original[i], used);\r\n        }\r\n        else\r\n        {\r\n            int x = original[i] + 1;\r\n            while(!all_prime_factors_available(x, used))\r\n                x++;\r\n\r\n            mark_prime_factors(x, used);\r\n\r\n            solution.push_back(x);\r\n            break;\r\n        }\r\n    }\r\n\r\n    for(int i = 2; i < LIMIT && solution.size() < no_of_elements; i++)\r\n    {   //printf(\"i = %d, u %d, p %d\\n\", i, used[i], is_prime[i]);\r\n        if(!used[i] && is_prime[i])\r\n            solution.push_back(i);\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%d \", solution[i]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Mahmoud and Ehab and Even Odd Game.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(n%2 == 0 ? \"Mahmoud\\n\" : \"Ehab\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Mahmoud and a Triangle.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nint main()\r\n{\r\n    int no_of_sides;\r\n    cin >> no_of_sides;\r\n\r\n    const int FIBO_LIMIT_MAX_SIDES = 45;\r\n    if(no_of_sides > FIBO_LIMIT_MAX_SIDES)\r\n    {\r\n        cout << \"YES\\n\";\r\n        return 0;\r\n    }\r\n\r\n    vector <int> side(no_of_sides);\r\n    for(int i = 0; i < no_of_sides; i++) cin >> side[i];\r\n\r\n    sort(all(side));\r\n\r\n    int triangle_possible = false;\r\n    for(int i = no_of_sides - 1; i >= 2; i--)\r\n    {\r\n        if(side[i] < side[i - 1] + side[i - 2])\r\n        {\r\n            triangle_possible = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (triangle_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Make a Square Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n\r\nint no_of_digits(int n)\r\n{\r\n    int digits = 0;\r\n\r\n    while(n)\r\n    {\r\n        n /= 10;\r\n        digits++;\r\n    }\r\n\r\n    return digits;\r\n}\r\n\r\nlong long square(long long n)\r\n{\r\n    return n*n;\r\n}\r\n\r\nint is_subsequence(int sequence, int n)\r\n{\r\n    while(sequence > 0 && n > 0)\r\n    {\r\n        if(n%10 == sequence%10)\r\n        {\r\n            sequence /= 10;\r\n\r\n            if(sequence == 0)\r\n                return true;\r\n        }\r\n\r\n        n /= 10;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int digit_count = no_of_digits(n), maximum_digits = 0;\r\n\r\n    for(int i = 0; square(i) <= n; i++)\r\n    {\r\n        if(is_subsequence(square(i), n) && no_of_digits(square(i)) > maximum_digits)\r\n        {\r\n            maximum_digits = no_of_digits(square(i));\r\n        }\r\n    }\r\n\r\n    int deleted_digits = digit_count - maximum_digits;\r\n    printf(deleted_digits == digit_count ? \"-1\\n\" : \"%d\\n\", deleted_digits);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Make a Square.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_bit_set(int n, int position)\r\n{\r\n    return ( ( (1LL << position)&n ) != 0);\r\n}\r\n\r\nint no_of_ones(int n)\r\n{\r\n    int ones = 0;\r\n    while(n)\r\n    {\r\n        if(n&1)\r\n            ones++;\r\n\r\n        n >>= 1;\r\n    }\r\n\r\n    return ones;\r\n}\r\n\r\nint no_of_digits(int n)\r\n{\r\n    int digits = 0;\r\n\r\n    while(n)\r\n    {\r\n        n /= 10;\r\n        digits++;\r\n    }\r\n\r\n    return digits;\r\n}\r\n\r\nlong long square(long long n)\r\n{\r\n    return n*n;\r\n}\r\n\r\nint is_square(int n)\r\n{\r\n    int left = 0, right = 1e5, mid = (left + right) >> 1;\r\n\r\n    while(left <= right)\r\n    {\r\n        mid = (left + right) >> 1;\r\n\r\n        if(square(mid) <= n)\r\n        {\r\n            if(square(mid + 1) > n)\r\n            {\r\n                break;\r\n            }\r\n            else\r\n            {\r\n                left = mid + 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            right = mid - 1;\r\n        }\r\n    }\r\n\r\n    return (square(mid) == n);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int digit_count = no_of_digits(n), maximum_digits = 0;\r\n    int digit[11];\r\n\r\n    for(int i = 0; i < digit_count; i++, n /= 10)\r\n        digit[i] = n%10;\r\n\r\n    for(int mask = (1 << digit_count) - 1; mask > 0; mask--)\r\n    {\r\n        int number = 0;\r\n\r\n        for(int i = digit_count - 1; i >= 0; i--)\r\n        {\r\n            if(is_bit_set(mask, i))\r\n                number = number*10 + digit[i];\r\n        }\r\n\r\n        if(is_square(number) && no_of_digits(number) > maximum_digits)\r\n            maximum_digits = no_of_digits(number);\r\n    }\r\n\r\n\r\n    int deleted_digits = digit_count - maximum_digits;\r\n    printf(deleted_digits == digit_count ? \"-1\\n\" : \"%d\\n\", deleted_digits);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Mancala.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long score_by_distributing(int chosen, vector <long long> stone, int no_of_holes)\r\n{\r\n    int quotient = stone[chosen]/no_of_holes, remainder = stone[chosen]%no_of_holes;\r\n\r\n    stone[chosen] = 0;\r\n\r\n    int current = chosen;\r\n    do\r\n    {\r\n        stone[current] += quotient;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n    while(current != chosen);\r\n\r\n    current = (chosen + 1)%no_of_holes;\r\n    while(remainder > 0)\r\n    {\r\n        stone[current]++;\r\n        remainder--;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n\r\n    long long score = 0;\r\n    for(int i = 0; i < stone.size(); i++)\r\n        if(stone[i]%2 == 0)\r\n            score += stone[i];\r\n\r\n    return score;\r\n}\r\n\r\nint main()\r\n{\r\n    const int NO_OF_HOLES = 14;\r\n    vector <long long> stone(NO_OF_HOLES);\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        cin >> stone[i];\r\n\r\n    long long maximum_score = 0;\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        maximum_score = max(maximum_score, score_by_distributing(i, stone, NO_OF_HOLES));\r\n\r\n    cout << maximum_score;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Mentors.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_programmers, no_of_pairs;\r\n    scanf(\"%d %d\", &no_of_programmers, &no_of_pairs);\r\n\r\n    vector <int> skill(no_of_programmers + 1, 0);\r\n    for(int i = 1; i <= no_of_programmers; i++)\r\n        scanf(\"%d\", &skill[i]);\r\n\r\n    vector <int> sorted_skill(no_of_programmers + 1, 0);\r\n    for(int i = 1; i <= no_of_programmers; i++) sorted_skill[i] = skill[i];\r\n\r\n    sort(all(sorted_skill));\r\n\r\n    vector <int> no_of_juniors(no_of_programmers + 1);\r\n    for(int i = 1; i <= no_of_programmers; i++)\r\n    {\r\n        no_of_juniors[i] = upper_bound(all(sorted_skill), skill[i] - 1) - sorted_skill.begin() - 1;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_pairs; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        if(skill[u] > skill[v])\r\n        {\r\n            no_of_juniors[u]--;\r\n        }\r\n        else if(skill[v] - skill[u])\r\n        {\r\n            no_of_juniors[v]--;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_programmers; i++) printf(\"%d \", no_of_juniors[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Pairs of Lines.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nstruct Point{\r\n\r\nlong long x, y;\r\n\r\n};\r\n\r\nint is_on_line(Point a, Point b, Point c)\r\n{\r\n    //Checking slope product to avoid division\r\n    return ( (c.y - b.y)*(b.x - a.x) == (b.y - a.y)*(c.x - b.x) );\r\n}\r\n\r\nint check_line(vector <Point> &line)\r\n{\r\n    for(int i = 2; i < line.size(); i++)\r\n        if(!is_on_line(line[0], line[1], line[i]))\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint check_one_line_passing_through(int a, int b, vector <Point> &P)\r\n{\r\n    vector <Point> line_2;\r\n\r\n    for(int i = 1; i < P.size(); i++)\r\n    {\r\n        if(!is_on_line(P[a], P[b], P[i]))\r\n           line_2.push_back(P[i]);\r\n    }\r\n\r\n    int two_lines_possible = check_line(line_2);\r\n    return two_lines_possible;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <Point> P(no_of_points + 1);\r\n    for(int i = 1; i <= no_of_points; i++)\r\n        scanf(\"%I64d %I64d\", &P[i].x, &P[i].y);\r\n\r\n    int two_lines_possible = (no_of_points <= 4 || check_one_line_passing_through(1, 2, P)\r\n                              || check_one_line_passing_through(2, 3, P) || check_one_line_passing_through(3, 1, P));\r\n\r\n    printf(two_lines_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Two Gram.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    map <string, int> frequency;\r\n    int max_frequency = 0;\r\n    string answer;\r\n\r\n    for(int i = 0; i + 1 < length; i++)\r\n    {\r\n        string two_gram = S.substr(i, 2);\r\n        frequency[two_gram]++;\r\n\r\n        if(frequency[two_gram] > max_frequency)\r\n            max_frequency = frequency[two_gram], answer = two_gram;\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Valhalla Seige.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_soldiers, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_soldiers, &no_of_queries);\r\n\r\n    vector <long long> strength(no_of_soldiers + 1);\r\n    for(int i = 1; i <= no_of_soldiers; i++)\r\n        scanf(\"%I64d\", &strength[i]);\r\n\r\n    vector <long long> sum(no_of_soldiers + 1, 0);\r\n    for(int i = 1; i <= no_of_soldiers; i++)\r\n        sum[i] = sum[i - 1] + strength[i];\r\n\r\n    long long total_arrows = 0;\r\n    while(no_of_queries--)\r\n    {\r\n        long long arrows;\r\n        scanf(\"%I64d\", &arrows);\r\n\r\n        total_arrows += arrows;\r\n\r\n        if(total_arrows >= sum[no_of_soldiers])\r\n            total_arrows = 0;\r\n\r\n        int no_of_dead_soldiers = upper_bound(all(sum), total_arrows) - sum.begin() - 1;\r\n\r\n        int no_of_alive_soldiers = no_of_soldiers - no_of_dead_soldiers;\r\n\r\n        printf(\"%d\\n\", no_of_alive_soldiers);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 21/Wrong Subtraction.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, no_of_operations;\r\n    scanf(\"%d %d\", &n, &no_of_operations);\r\n\r\n    while(no_of_operations--)\r\n    {\r\n        n = (n%10 == 0 ? n/10 : n - 1);\r\n    }\r\n\r\n    printf(\"%d\\n\", n);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 22/AND Graph.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = (1LL << 22);\r\nvector <int> visited(MAX_N, false);\r\nvector <int> is_present(MAX_N, false);\r\n\r\nint complement(int x, int no_of_bits)\r\n{\r\n    return ( ( (1LL << no_of_bits) - 1) - x);\r\n}\r\n\r\nvoid dfs(int mask, int no_of_bits)\r\n{\r\n    if(visited[mask])\r\n        return;\r\n\r\n    visited[mask] = true;\r\n\r\n    for(int bit = 0; bit < no_of_bits; bit++)\r\n    {\r\n        if(mask&(1LL << bit))\r\n        {\r\n            int submask = mask - (1LL << bit);\r\n            dfs(submask, no_of_bits);\r\n        }\r\n    }\r\n\r\n    if(is_present[mask])\r\n        dfs(complement(mask, no_of_bits), no_of_bits);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_bits, no_of_vertices;\r\n    scanf(\"%d %d\", &no_of_bits, &no_of_vertices);\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        int x;\r\n        scanf(\"%d\", &x);\r\n        is_present[x] = true;\r\n    }\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 0; i < (1LL << no_of_bits); i++)\r\n    {\r\n        if(is_present[i] && !visited[i])\r\n        {\r\n            dfs(complement(i, no_of_bits), no_of_bits);\r\n            no_of_components++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_components);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Almost Arithmetic Progression.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    const int oo = 1e7;\r\n    int add[3] = {-1, 0, 1}, min_operations = oo;\r\n\r\n    for(int i = 0; i < 3; i++)\r\n    {\r\n        int term_1 = A[0] + add[i];\r\n\r\n        for(int j = 0; j < 3; j++)\r\n        {\r\n            int term_2 = A[1] + add[j];\r\n\r\n            int difference = term_2 - term_1;\r\n\r\n            int no_of_operations = (term_1 != A[0]) + (term_2 != A[1]);\r\n\r\n            for(int k = 2; k < no_of_elements; k++)\r\n            {\r\n                if(abs(term_1 + k*difference - A[k]) == 1)\r\n                {\r\n                    no_of_operations++;\r\n                }\r\n                else if(abs(term_1 + k*difference - A[k]) > 1)\r\n                {\r\n                    no_of_operations = oo;\r\n                }\r\n            }\r\n\r\n            min_operations = min(min_operations, no_of_operations);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", min_operations >= oo ? -1 : min_operations);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Antipalindrome Alternate Solution.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint is_palindrome(string S, int left, int right)\r\n{\r\n    while(left <= right)\r\n    {\r\n        if(S[left++] != S[right--])\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n    int length = S.size();\r\n\r\n    if(!is_palindrome(S, 0, length - 1))\r\n        cout << length;\r\n    else if(!is_palindrome(S, 0, length - 2) || !is_palindrome(S, 1, length - 1))\r\n        cout << length - 1;\r\n    else\r\n        cout << \"0\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Antipalindrome.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint is_palindrome(string S)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n        if(S[i] != S[S.size() - 1 - i])\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    for(int length = S.size(); length >= 1; length--)\r\n    {\r\n        for(int i = 0; i + length - 1 < S.size(); i++)\r\n        {\r\n            if(!is_palindrome(S.substr(i, length)))\r\n            {\r\n                cout << length;\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"0\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Ball.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n#include <vector>\r\n#include <map>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 5e5 + 15;\r\nint max_tree[3*MAX_N];\r\n\r\nstruct info\r\n{\r\n    int beauty, richness, intellect;\r\n};\r\n\r\nint sort_by_beauty(info &A, info &B)\r\n{\r\n    return (A.beauty < B.beauty);\r\n}\r\n\r\nvoid insert_richness(int n, int left, int right, int index, int value)\r\n{\r\n    if(index < left || right < index)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = max(max_tree[n], value);\r\n        return ;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    insert_richness(LEFT(n), left, mid, index, value);\r\n    insert_richness(RIGHT(n), mid + 1, right, index, value);\r\n\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nint get_max_richness(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(right < query_left || query_right < left || right < left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return max_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    int left_max = get_max_richness(LEFT(n), left, mid, query_left, query_right);\r\n    int right_max = get_max_richness(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return max(left_max, right_max);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_ladies;\r\n    scanf(\"%d\", &no_of_ladies);\r\n\r\n    vector <info> lady(no_of_ladies + 1);\r\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].beauty);\r\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].richness);\r\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].intellect);\r\n\r\n    sort(all(lady), sort_by_beauty);\r\n\r\n    vector <int> intelligence(no_of_ladies + 1, 0);\r\n    for(int i = 1; i <= no_of_ladies; i++) intelligence[i] = lady[i].intellect;\r\n\r\n    sort(all(intelligence));\r\n    map <int, int> iq_rank;\r\n\r\n    for(int i = 1; i <= no_of_ladies; i++)\r\n    {\r\n        iq_rank[intelligence[i]] = (intelligence[i] == intelligence[i - 1] ? iq_rank[intelligence[i - 1]] : i);\r\n    }\r\n\r\n    memset(max_tree, 0, sizeof(max_tree));\r\n\r\n    int suicides = 0;\r\n\r\n    for(int i = no_of_ladies; i >= 1; )\r\n    {\r\n        int j;\r\n\r\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\r\n        {\r\n            int max_richness_with_other_2_greater = get_max_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect] + 1, no_of_ladies);\r\n\r\n            if(max_richness_with_other_2_greater > lady[j].richness)\r\n                suicides++;\r\n        }\r\n\r\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\r\n        {\r\n            insert_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect], lady[j].richness);\r\n        }\r\n\r\n        i = j;\r\n    }\r\n\r\n    printf(\"%d\", suicides);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Bits.cpp",
    "content": "#include <cstdio>\r\n\r\nlong long all_ones(int n)\r\n{\r\n    return (1LL << n) - 1;\r\n}\r\n\r\nint is_set(long long n, int bit)\r\n{\r\n    return ((n & (1LL << bit)) != 0);\r\n}\r\n\r\nint no_of_bits(long long n)\r\n{\r\n    int answer = 0;\r\n\r\n    while(n)\r\n    {\r\n        n >>= 1;\r\n        answer++;\r\n    }\r\n\r\n    return answer;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    long long answer = 0;\r\n\r\n    if(all_ones(no_of_bits(right)) == right)\r\n    {\r\n        answer = right;\r\n    }\r\n    else if(no_of_bits(left) != no_of_bits(right))\r\n    {\r\n        answer = all_ones(no_of_bits(right) - 1);\r\n    }\r\n    else if(no_of_bits(left) == no_of_bits(right))\r\n    {\r\n        for(int bit = 63; bit >= 0; bit--)\r\n        {\r\n            if(is_set(left, bit) && is_set(right, bit))\r\n            {\r\n                answer |= (1LL << bit);\r\n            }\r\n            else if(!is_set(left, bit) && is_set(right, bit)) //If L[i] = 0, and R[i] = 1\r\n            {\r\n                answer |= all_ones(bit); //Setting the current bit to 0, and then padding with 1s till the end.\r\n\r\n                if((answer|(1LL << bit)) <= right) //Checking if the current bit can also be 1\r\n                    answer |= (1LL << bit);\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Bookshelves.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\nconst int MAX_BIT = 61, MAX_N = 55;\r\ntypedef long long LL;\r\n\r\nint no_of_elements, no_of_parts;\r\nLL A[MAX_N], sum[MAX_N];\r\nint possible[MAX_N][MAX_N];\r\n\r\nint is_possible(LL goal)\r\n{\r\n    memset(possible, false, sizeof(possible));\r\n\r\n    possible[0][0] = true;\r\n\r\n    for(int part = 1; part <= no_of_parts; part++)\r\n    {\r\n        for(int right = 1; right <= no_of_elements; right++)\r\n        {\r\n            for(int left = 0; left < right; left++)\r\n            {\r\n                if( possible[left][part - 1] && ( ( (sum[right] - sum[left])&goal ) == goal ) )\r\n                {\r\n                    possible[right][part] = true;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    return possible[no_of_elements][no_of_parts];\r\n}\r\n\r\nint main()\r\n{\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_parts);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    sum[0] = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum[i] = sum[i - 1] + A[i];\r\n\r\n    LL answer = 0;\r\n\r\n    for(int bit = MAX_BIT; bit >= 0; bit--)\r\n    {\r\n        if(is_possible(answer|(1LL << bit)))\r\n        {\r\n            answer |= (1LL << bit);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Businessman Problems.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int a_element_is;\r\n    scanf(\"%d\", &a_element_is);\r\n\r\n    map <int, int> cost;\r\n    for(int i = 1; i <= a_element_is; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n        cost[element_i] = cost_i;\r\n    }\r\n\r\n    int b_element_is;\r\n    scanf(\"%d\", &b_element_is);\r\n\r\n    for(int i = 1; i <= b_element_is; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n\r\n        cost[element_i] = max(cost[element_i], cost_i);\r\n    }\r\n\r\n    long long total_cost = 0;\r\n    for(map <int, int> :: iterator it = cost.begin(); it != cost.end(); it++)\r\n    {\r\n        total_cost += it->second;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Chess Placing.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    vector <int> A(n/2 + 1);\r\n    for(int i = 1; 2*i <= n; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n\r\n    int black_moves = 0;\r\n    for(int i = 1; 2*i <= n; i++)\r\n        black_moves += abs(A[i] - (2*i - 1));\r\n\r\n    int white_moves = 0;\r\n    for(int i = 1; 2*i <= n; i++)\r\n        white_moves += abs(A[i] - 2*i);\r\n\r\n    int minimum_moves = min(black_moves, white_moves);\r\n    cout << minimum_moves;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Correct Solution.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstring solve(string S)\r\n{\r\n    vector <char> digits;\r\n    for(int i = 0; i < S.size(); i++)\r\n        digits.push_back(S[i]);\r\n\r\n    sort(all(digits));\r\n\r\n    if(digits[0] == '0' && digits.size() > 1)\r\n    {\r\n        int first_nonzero = 1;\r\n        while(digits[first_nonzero] == '0')\r\n            first_nonzero++;\r\n\r\n        swap(digits[0], digits[first_nonzero]);\r\n    }\r\n\r\n    string answer;\r\n    for(int i = 0; i < digits.size(); i++)\r\n        answer += digits[i];\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    string answer = solve(A);\r\n\r\n    cout << ((answer == B) ? \"OK\\n\" : \"WRONG_ANSWER\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Counting Kangaroos is Fun.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_kangaroos;\r\n    scanf(\"%d\", &no_of_kangaroos);\r\n\r\n    vector <int> kangaroo_size(no_of_kangaroos);\r\n    for(int i = 0; i < no_of_kangaroos; i++)\r\n        scanf(\"%d\", &kangaroo_size[i]);\r\n\r\n    sort(all(kangaroo_size));\r\n\r\n    int no_of_pairs = 0;\r\n    int front_i = 0, back_i = no_of_kangaroos/2;\r\n    for( ; front_i < no_of_kangaroos/2 && back_i < no_of_kangaroos; front_i++)\r\n    {\r\n        while(back_i < no_of_kangaroos)\r\n        {\r\n            if(kangaroo_size[front_i]*2 <= kangaroo_size[back_i])\r\n            {\r\n                back_i++;\r\n                no_of_pairs++;\r\n                break;\r\n            }\r\n            else\r\n            {\r\n                back_i++;\r\n            }\r\n        }\r\n    }\r\n\r\n    int no_of_visible_kangaroos = no_of_pairs + (no_of_kangaroos - 2*no_of_pairs);\r\n    printf(\"%d\\n\", no_of_visible_kangaroos);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Fruits.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_prices, no_of_fruits;\r\n    cin >> no_of_prices >> no_of_fruits;\r\n\r\n    vector <int> price(no_of_prices, 0);\r\n    for(int i = 0; i < no_of_prices; i++) cin >> price[i];\r\n\r\n    sort(all(price));\r\n\r\n    map <string, int> frequency;\r\n    for(int i = 1; i <= no_of_fruits; i++)\r\n    {\r\n        string fruit;\r\n        cin >> fruit;\r\n        frequency[fruit]++;\r\n    }\r\n\r\n    vector <int> fruit_frequency;\r\n    for(map <string, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n        fruit_frequency.push_back(it->second);\r\n\r\n    sort(all(fruit_frequency));\r\n    reverse(all(fruit_frequency));\r\n\r\n    long long min_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        min_price += price[i]*1LL*fruit_frequency[i];\r\n\r\n    reverse(all(price));\r\n    long long max_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        max_price += price[i]*1LL*fruit_frequency[i];\r\n\r\n    cout << min_price << \" \" << max_price;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/High School Become Human.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    long long x, y;\r\n    scanf(\"%I64d %I64d\", &x, &y);\r\n\r\n    if(x == y || (min(x, y) == 2 && max(x, y) == 4))\r\n    {\r\n        printf(\"=\");\r\n    }\r\n    else if(min(x, y) == 1)\r\n    {\r\n        printf(x == 1 ? \"<\" : \">\");\r\n    }\r\n    else if(min(x, y) == 2)\r\n    {\r\n        if(x == 2)\r\n        {\r\n            printf(y < 4 ? \"<\" : \">\");\r\n        }\r\n        else if(y == 2)\r\n        {\r\n            printf(x < 4? \">\" : \"<\");\r\n        }\r\n    }\r\n    else if(min(x, y) >= 3) //Both greater than e\r\n    {\r\n        printf(x < y ? \">\" : \"<\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Infinity Gauntlet.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    map <string, string> power;\r\n    power[\"red\"] = \"Reality\";\r\n    power[\"purple\"] = \"Power\";\r\n    power[\"green\"] = \"Time\";\r\n    power[\"yellow\"] = \"Mind\";\r\n    power[\"orange\"] = \"Soul\";\r\n    power[\"blue\"] = \"Space\";\r\n\r\n    map <string, int> present;\r\n\r\n    int no_of_names;\r\n    cin >> no_of_names;\r\n\r\n    while(no_of_names--)\r\n    {\r\n        string colour;\r\n        cin >> colour;\r\n\r\n        present[colour] = true;\r\n    }\r\n\r\n    vector <string> answer;\r\n    for(map <string, string> :: iterator it = power.begin(); it != power.end(); it++)\r\n    {\r\n        if(!present[it->first])\r\n            answer.push_back(it->second);\r\n    }\r\n\r\n    cout << answer.size() << \"\\n\";\r\n    for(int i = 0; i < answer.size(); i++)\r\n        cout << answer[i] << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Knights of a Polygonal Table.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <set>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <map>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\nusing namespace std;\r\n\r\nstruct knight\r\n{\r\n    int position, power, coin;\r\n};\r\n\r\nint sort_by_power(const knight &A, const knight &B)\r\n{\r\n    return (A.power < B.power);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_knights, max_coins;\r\n    scanf(\"%d %d\", &no_of_knights, &max_coins);\r\n\r\n    vector <knight> knights(no_of_knights + 1);\r\n    for(int i = 1; i <= no_of_knights; i++) knights[i].position = i;\r\n    for(int i = 1; i <= no_of_knights; i++) scanf(\"%d\", &knights[i].power);\r\n    for(int i = 1; i <= no_of_knights; i++) scanf(\"%d\", &knights[i].coin);\r\n\r\n    sort(all(knights), sort_by_power);\r\n\r\n    vector <long long> answer(no_of_knights + 1, 0);\r\n    multiset <int> best_coin;\r\n\r\n    for(int i = 1; i <= no_of_knights; i++)\r\n    {\r\n        if(knights[i].power == knights[i - 1].power)\r\n        {\r\n            answer[knights[i].position] = answer[knights[i - 1].position] - knights[i - 1].coin + knights[i].coin;\r\n        }\r\n        else\r\n        {\r\n            int c = 1;\r\n            answer[knights[i].position] = knights[i].coin;\r\n\r\n            for(multiset <int> :: reverse_iterator it = best_coin.rbegin(); it != best_coin.rend() && c <= max_coins; it++, c++)\r\n            {\r\n                answer[knights[i].position] += *it;\r\n            }\r\n        }\r\n\r\n        best_coin.insert(knights[i].coin);\r\n    }\r\n\r\n\r\n    for(int i = 1; i <= no_of_knights; i++)\r\n        printf(\"%I64d \", answer[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Letters.cpp",
    "content": "#include <vector>\n#include <cstdio>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, no_of_queries;\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\n\n    vector <long long> A(no_of_elements + 1);\n    vector <long long > sum_till(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%I64d\", &A[i]);\n        sum_till[i] = sum_till[i - 1] + A[i];\n    }\n\n    while(no_of_queries--)\n    {\n        long long x;\n        scanf(\"%I64d\", &x);\n\n        int dorm_no = upper_bound(all(sum_till), x - 1) - sum_till.begin();\n        long long room_no = x - sum_till[dorm_no - 1];\n\n        printf(\"%d %I64d\\n\", dorm_no, room_no);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 22/Local Extrema.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_extrema(int mid, int start, int end)\r\n{\r\n    return ((start < mid && end < mid) || (mid < start && mid < end));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    int local_extrema = 0;\r\n    for(int i = 2; i < no_of_elements; i++)\r\n        local_extrema += is_extrema(A[i], A[i - 1], A[i + 1]);\r\n\r\n    printf(\"%d\\n\", local_extrema);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Remove Duplicates.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    const int MAX = 1015;\r\n    vector <int> used(MAX, false);\r\n    vector <int> ans;\r\n\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        if(!used[A[i]])\r\n        {\r\n            used[A[i]] = true;\r\n            ans.push_back(A[i]);\r\n        }\r\n    }\r\n\r\n    reverse(all(ans));\r\n\r\n    printf(\"%d\\n\", ans.size());\r\n    for(int i = 0; i < ans.size(); i++) printf(\"%d \", ans[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Super Agent.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    const int N = 3;\r\n    char grid[N + 2][N + 2];\r\n    for(int i = 1; i <= N; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    int symmetric = (grid[1][1] == grid[3][3]) && (grid[1][2] == grid[3][2]) && (grid[1][3] == grid[3][1]) && (grid[2][3] == grid[2][1]);\r\n    printf(symmetric ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Switches and Lamps.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_switches, no_of_lamps;\r\n    cin >> no_of_switches >> no_of_lamps;\r\n\r\n    vector <string> switches(no_of_switches);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        cin >> switches[i];\r\n\r\n    vector <int> no_of_switches_for(no_of_lamps, 0);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n            no_of_switches_for[lamp] += (switches[i][lamp] == '1');\r\n\r\n    int one_ignorable = false;\r\n\r\n    for(int i = 0; i < no_of_switches; i++)\r\n    {\r\n        int can_ignore_this_one = true;\r\n\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n        {\r\n            if(switches[i][lamp] == '1' && no_of_switches_for[lamp] == 1)\r\n                can_ignore_this_one = false;\r\n        }\r\n\r\n        if(can_ignore_this_one)\r\n            one_ignorable = true;\r\n    }\r\n\r\n    cout << (one_ignorable ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Tafurama.cpp",
    "content": "#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nconst int MAX_N = 2e5 + 15;\r\nint sum_tree[3*MAX_N];\r\n\r\nvoid update(int n, int left, int right, int index, int value)\r\n{\r\n    if(right < left || right < index || index < left)\r\n        return;\r\n\r\n    if(right == left)\r\n    {\r\n        sum_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update(LEFT(n), left, mid, index, value);\r\n    update(RIGHT(n), mid + 1, right, index, value);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nint get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(right < left || right < query_left || query_right < left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    int left_answer = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    int right_answer = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_answer + right_answer);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> index[no_of_elements + 1];\r\n\r\n    memset(sum_tree, 0, sizeof(sum_tree));\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        A[i] = min(A[i], no_of_elements);\r\n\r\n        update(1, 1, no_of_elements, i, 1);\r\n\r\n        index[A[i]].push_back(i);\r\n    }\r\n\r\n    long long answer = 0;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer += get_sum(1, 1, no_of_elements, i + 1, A[i]);\r\n\r\n        for(int j = 0; j < index[i].size(); j++)\r\n        {\r\n            update(1, 1, no_of_elements, index[i][j], 0);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Three Displays Segment Tree Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nconst int MAX_N = 3015;\r\nconst long long oo = 1e10;\r\n\r\nstruct info\r\n{\r\n    int font_size, cost, position;\r\n};\r\n\r\nlong long min_tree[4*MAX_N];\r\nlong long max_tree[4*MAX_N];\r\n\r\nint compare_by_size(const info &A, const info &B)\r\n{\r\n    if(A.font_size == B.font_size)\r\n        return (A.position > B.position);\r\n    else\r\n        return (A.font_size < B.font_size);\r\n}\r\n\r\nvoid build_min_tree(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        min_tree[n] = oo;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build_min_tree(LEFT(n), left, mid);\r\n    build_min_tree(RIGHT(n), mid + 1, right);\r\n\r\n    min_tree[n] = min(min_tree[LEFT(n)], min_tree[RIGHT(n)]);\r\n}\r\n\r\nvoid update_min(int n, int left, int right, int position, int value)\r\n{\r\n    if(position < left || right < position)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        min_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update_min(LEFT(n), left, mid, position, value);\r\n    update_min(RIGHT(n), mid + 1, right, position, value);\r\n\r\n    min_tree[n] = min(min_tree[LEFT(n)], min_tree[RIGHT(n)]);\r\n}\r\n\r\nlong long get_min(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left || query_right < query_left)\r\n        return oo;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return min_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    long long left_min = get_min(LEFT(n), left, mid, query_left, query_right);\r\n    long long right_min = get_min(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return min(left_min, right_min);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <info> A(no_of_displays + 1);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        A[i].position = i;\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].font_size);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].cost);\r\n\r\n    sort(A.begin() + 1, A.end(), compare_by_size);\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_left[i] = get_min(1, 1, no_of_displays, 1, A[i].position - 1);\r\n    }\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n    for(int i = no_of_displays; i >= 1; i--)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_right[i] = get_min(1, 1, no_of_displays, A[i].position + 1, no_of_displays);\r\n    }\r\n\r\n    long long best_cost = oo;\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        best_cost = min(best_cost, best_left[i] + A[i].cost + best_right[i]);\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Three Displays.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <int> text_size(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &text_size[i]);\r\n\r\n    vector <int> cost(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &cost[i]);\r\n\r\n    const long long oo = 1e10;\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n\r\n    long long best_cost = oo;\r\n\r\n    for(int mid = 1; mid <= no_of_displays; mid++)\r\n    {\r\n        for(int right = mid + 1; right <= no_of_displays; right++)\r\n        {\r\n            if(text_size[mid] < text_size[right])\r\n                best_right[mid] = min(best_right[mid], cost[right]);\r\n        }\r\n\r\n        for(int left = 1; left < mid; left++)\r\n        {\r\n            if(text_size[left] < text_size[mid])\r\n                best_left[mid] = min(best_left[mid], cost[left]);\r\n        }\r\n\r\n        best_cost = min(best_cost, best_right[mid] + cost[mid] + best_left[mid]);\r\n    }\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 22/Useful Decomposition.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 15;\r\nvector <int> graph[MAX_N];\r\n\r\nint dfs_leaf_from(int v, int parent)\r\n{\r\n    if(graph[v].size() == 1)\r\n        return v;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(child == parent) continue;\r\n\r\n        return dfs_leaf_from(child, v);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d\", &no_of_vertices);\r\n\r\n    for(int i = 1; i < no_of_vertices; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    int no_of_roots = 0, root = 1;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(graph[i].size() > 2)\r\n        {\r\n            no_of_roots++;\r\n            root = i;\r\n        }\r\n    }\r\n\r\n    if(no_of_roots > 1)\r\n    {\r\n        printf(\"No\\n\");\r\n        return 0;\r\n    }\r\n\r\n    printf(\"Yes\\n\");\r\n\r\n    int no_of_paths = graph[root].size();\r\n\r\n    printf(\"%d\\n\", no_of_paths);\r\n\r\n    for(int i = 0; i < graph[root].size(); i++)\r\n    {\r\n        int child = graph[root][i];\r\n\r\n        int leaf = dfs_leaf_from(child, root);\r\n\r\n        printf(\"%d %d\\n\", root, leaf);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/An Impassioned Circulation of Affection.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nconst int MAX_ALPHABETS = 26, MAX_N = 1505;\r\nint maximum_segment[MAX_ALPHABETS][MAX_N];\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    for(int ch = 0; ch < MAX_ALPHABETS; ch++)\r\n    {\r\n        for(int left = 0; left < length; left++)\r\n        {\r\n            int replacements = 0;\r\n\r\n            for(int right = left; right < length; right++)\r\n            {\r\n                replacements += (S[right] != 'a' + ch);\r\n\r\n                maximum_segment[ch][replacements] = max(maximum_segment[ch][replacements], right - left + 1);\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int ch = 0; ch < MAX_ALPHABETS; ch++)\r\n    {\r\n        for(int replacements = 1; replacements <= length; replacements++)\r\n        {\r\n            maximum_segment[ch][replacements] = max(maximum_segment[ch][replacements], maximum_segment[ch][replacements - 1]);\r\n        }\r\n    }\r\n\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int max_replacements;\r\n        char character;\r\n\r\n        cin >> max_replacements >> character;\r\n        cout << maximum_segment[character - 'a'][max_replacements] << '\\n';\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Another Problem on Strings.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int target_no_of_1s;\r\n    scanf(\"%d\", &target_no_of_1s);\r\n\r\n    const int MAX = 1e6 + 3;\r\n    char S[MAX];\r\n    scanf(\"%s\", S);\r\n\r\n    vector <int> sum(MAX, 0);\r\n    sum[0] = (S[0] == '1');\r\n    for(int i = 1; S[i] != '\\0'; i++)\r\n        sum[i] = sum[i - 1] + (S[i] == '1');\r\n\r\n    vector <int> sum_frequency(MAX, 0);\r\n    sum_frequency[0] = 1; //Empty string\r\n\r\n    long long no_of_good_substrings = 0;\r\n    for(int i = 0; S[i] != '\\0'; i++)\r\n    {\r\n        if(sum[i] >= target_no_of_1s)\r\n            no_of_good_substrings += (sum_frequency[sum[i] - target_no_of_1s]);\r\n\r\n        sum_frequency[sum[i]]++;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_good_substrings);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Babaei and Birthday Cake.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nconst int MAX_N = 1e5 + 5;\r\ndouble max_tree[3*MAX_N];\r\n\r\nvoid insert(int n, int left, int right, double value, int position)\r\n{\r\n    if(right < position || position < left)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    insert(LEFT(n), left, mid, value, position);\r\n    insert(RIGHT(n), mid + 1, right, value, position);\r\n\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\ndouble get_max(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < query_left || query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return max_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    double left_max = get_max(LEFT(n), left, mid, query_left, query_right);\r\n    double right_max = get_max(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return max(left_max, right_max);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_cylinders;\r\n    scanf(\"%d\", &no_of_cylinders);\r\n\r\n    vector <double> volume(no_of_cylinders + 1);\r\n    vector <double> sorted_volume(no_of_cylinders + 1);\r\n    for(int i = 1; i <= no_of_cylinders; i++)\r\n    {\r\n        int radius, height;\r\n        scanf(\"%d %d\", &radius, &height);\r\n\r\n        const double PI = 3.14159;\r\n\r\n        volume[i] = (PI*radius*radius*1LL*height);\r\n        sorted_volume[i] = volume[i];\r\n    }\r\n\r\n    sort(all(sorted_volume));\r\n\r\n    map <double, int> rank;\r\n    for(int i = 1; i <= no_of_cylinders; i++)\r\n        rank[sorted_volume[i]] = i;\r\n\r\n    map <double, double> answer_with_last;\r\n\r\n    for(int i = 1; i <= no_of_cylinders; i++)\r\n    {\r\n        answer_with_last[volume[i]] = volume[i] + get_max(1, 1, no_of_cylinders, 1, rank[volume[i]] - 1);\r\n\r\n        insert(1, 1, no_of_cylinders, answer_with_last[volume[i]], rank[volume[i]]);\r\n    }\r\n\r\n    double answer = 0;\r\n    for(int i = 1; i <= no_of_cylinders; i++)\r\n        answer = max(answer, answer_with_last[volume[i]]);\r\n\r\n    printf(\"%.10f\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Bear and Prime Numbers.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid precompute(vector <int> &is_prime, int N)\r\n{\r\n    is_prime[0] = is_prime[1] = false;\r\n    vector <int> primes;\r\n\r\n    for(int i = 2; i <= N; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] <= N; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int MAX_N = 1e7;\r\n    vector <int> frequency(MAX_N + 1, 0);\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n        frequency[element]++;\r\n    }\r\n\r\n    vector <int> is_prime(MAX_N + 1, true);\r\n    precompute(is_prime, MAX_N);\r\n\r\n    vector <int> no_of_multiples(MAX_N + 1, 0);\r\n    for(int i = 1; i <= MAX_N; i++)\r\n    {\r\n        if(!is_prime[i]) continue;\r\n\r\n        for(int multiple = i; multiple <= MAX_N; multiple += i)\r\n        {\r\n            no_of_multiples[i] += frequency[multiple];\r\n        }\r\n    }\r\n\r\n    vector <int> answer(MAX_N + 1, 0);\r\n    for(int i = 1; i <= MAX_N; i++)\r\n        answer[i] = answer[i - 1] + no_of_multiples[i];\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int left, right;\r\n        scanf(\"%d %d\", &left, &right);\r\n\r\n        right = min(right, MAX_N);\r\n        left = min(left, MAX_N);\r\n\r\n        printf(\"%d\\n\", answer[right] - answer[left - 1]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Cirriculum Vitae.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_games;\r\n    scanf(\"%d\", &no_of_games);\r\n\r\n    vector <int> won(no_of_games + 1);\r\n    for(int i = 1; i <= no_of_games; i++)\r\n        scanf(\"%d\", &won[i]);\r\n\r\n    vector <int> wins_from(no_of_games + 2, 0);\r\n    for(int i = no_of_games; i >= 1; i--)\r\n        wins_from[i] = wins_from[i + 1] + (won[i]);\r\n\r\n    int final_no_of_games = 0;\r\n    int losses_so_far = 0;\r\n    for(int i = 1; i <= no_of_games; i++)\r\n    {\r\n        losses_so_far += (!won[i]);\r\n\r\n        final_no_of_games = max(final_no_of_games, losses_so_far + wins_from[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", final_no_of_games);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Classy Numbers Precomputing Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nconst int MAX_DIGITS = 18;\r\nvector <long long> classy_numbers;\r\n\r\nvoid precompute(int position, int non_zero_count, long long current_num)\r\n{\r\n    if(non_zero_count > 3)\r\n        return;\r\n\r\n    if(position == MAX_DIGITS)\r\n    {\r\n        classy_numbers.push_back(current_num);\r\n        return;\r\n    }\r\n\r\n    for(int digit = 0; digit <= 9; digit++)\r\n    {\r\n        precompute(position + 1, non_zero_count + (digit != 0), current_num*10 + digit);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute(0, 0, 0);\r\n    classy_numbers.push_back(1e18); //This has 19 digits\r\n\r\n    int no_of_tests;\r\n    scanf(\"%d\", &no_of_tests);\r\n\r\n    while(no_of_tests--)\r\n    {\r\n        long long left, right;\r\n        scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n        int classy_number_count = upper_bound(all(classy_numbers), right) - lower_bound(all(classy_numbers), left);\r\n        printf(\"%d\\n\", classy_number_count);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Counting Arrays.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e6, MOD =1e9 + 7;\r\nvector <long long> factorial(MAX_N + 1), inverse_factorial(MAX_N + 1);\r\nvector <long long> primes;\r\n\r\nvoid sieve()\r\n{\r\n    vector <int> is_prime(MAX_N + 1, true);\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= MAX_N; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] <= MAX_N; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n}\r\n\r\nlong long power_mod(long long x, long long power)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%MOD;\r\n\r\n        x = (x*x)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    factorial[0] = 1;\r\n    for(int i = 1; i <= MAX_N; i++)\r\n        factorial[i] = (i*factorial[i - 1])%MOD;\r\n\r\n    inverse_factorial[MAX_N] = power_mod(factorial[MAX_N], MOD - 2);\r\n    for(int i = MAX_N - 1; i >= 0; i--)\r\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\r\n}\r\n\r\nlong long choose(long long n, long long r)\r\n{\r\n    long long numerator = factorial[n];\r\n    long long inverse_denominator = (inverse_factorial[r]*inverse_factorial[n - r])%MOD;\r\n\r\n    return (numerator*inverse_denominator)%MOD;\r\n}\r\n\r\nvoid factorise(int n, map <int, int> &exponent)\r\n{\r\n    for(int i = 0; primes[i]*primes[i] <=n; i++)\r\n    {\r\n        while(n%primes[i] == 0)\r\n        {\r\n            exponent[primes[i]]++;\r\n\r\n            n /= primes[i];\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n        exponent[n]++;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int x, no_of_summands;\r\n    cin >> x >> no_of_summands;\r\n\r\n    map <int, int> prime_exponents;\r\n    factorise(x, prime_exponents);\r\n\r\n    long long answer = 1;\r\n    for(map <int, int> :: iterator it = prime_exponents.begin(); it != prime_exponents.end(); it++)\r\n    {\r\n        int exponent = it->second;\r\n\r\n        answer *= choose(no_of_summands + exponent - 1, no_of_summands - 1);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    long long ways_to_distribute_signs = power_mod(2, no_of_summands - 1);\r\n\r\n    answer = (answer*ways_to_distribute_signs)%MOD;\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    sieve();\r\n    precompute();\r\n\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Crazy Town.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int start_x, start_y, end_x, end_y;\r\n    scanf(\"%d %d %d %d\", &start_x, &start_y, &end_x, &end_y);\r\n\r\n    int no_of_lines;\r\n    scanf(\"%d\", &no_of_lines);\r\n\r\n    int crossed_lines = 0;\r\n    while(no_of_lines--)\r\n    {\r\n        long long a, b, c;\r\n        scanf(\"%I64d %I64d %I64d\", &a, &b, &c);\r\n\r\n        long long start_side = a*start_x + b*start_y + c;\r\n        long long end_side = a*end_x + b*end_y + c;\r\n\r\n        if( (start_side > 0 && end_side < 0) || (start_side < 0 && end_side > 0) )\r\n            crossed_lines++;\r\n    }\r\n\r\n    printf(\"%d\\n\", crossed_lines);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Find Maximum.cpp",
    "content": "#include <cstdio>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> A(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <long long> prefix_sum(n + 1, 0);\r\n    for(int i = 1; i <= n; i++)\r\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\r\n\r\n    const int MAX_N = 1e5 + 5;\r\n    char S[MAX_N];\r\n    scanf(\"%s\", S + 1);\r\n\r\n    long long answer = 0, set_bit_sum = 0;\r\n\r\n    for(int i = n; i > 0; i--)\r\n    {\r\n        if(S[i] == '1')\r\n        {\r\n            answer = max(answer, set_bit_sum + prefix_sum[i - 1]);\r\n\r\n            set_bit_sum += A[i];\r\n        }\r\n    }\r\n\r\n    answer = max(answer, set_bit_sum);\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Fish.cpp",
    "content": "#include <cstdio>\n\nconst int MAX_FISH = 20;\ndouble probability[(1 << MAX_FISH)];\ndouble eat_probability[MAX_FISH][MAX_FISH];\n\nint is_alive(int n, int bit)\n{\n    return ( (n&(1LL << bit)) != 0);\n}\n\nint kill(int n, int bit)\n{\n    return (n^(1LL << bit));\n}\n\nint no_of_set_bits(int n)\n{\n    int no_of_1s = 0;\n\n    while(n)\n    {\n        no_of_1s += n%2;\n        n /= 2;\n    }\n\n    return no_of_1s;\n}\n\nint choose_2(int n)\n{\n    return (n*(n - 1))/2;\n}\n\nint main()\n{\n    int no_of_fish;\n    scanf(\"%d\", &no_of_fish);\n\n    for(int i = 0; i < no_of_fish; i++)\n        for(int j = 0; j < no_of_fish; j++)\n            scanf(\"%lf\", &eat_probability[i][j]);\n\n    int max_mask = (1LL << no_of_fish) - 1; //Mask has a bit set if fish i is alive.\n    probability[max_mask] = 1.0; //All fish alive in the beginning\n\n\n    for(int mask = max_mask; mask >= 1; mask--)\n    {\n        for(int eating_fish = 0; eating_fish < no_of_fish; eating_fish++)\n        {\n            if(is_alive(mask, eating_fish)) //Eating fish is alive\n            {\n                for(int victim_fish = 0; victim_fish < no_of_fish; victim_fish++)\n                {\n                    if(is_alive(mask, victim_fish) && eating_fish != victim_fish)\n                    {\n                        int mask_without_victim = kill(mask, victim_fish);\n\n                        int no_of_alive_fish = no_of_set_bits(mask);\n                        int no_of_combinations = choose_2(no_of_alive_fish);\n\n                        probability[mask_without_victim] += (probability[mask]*eat_probability[eating_fish][victim_fish])/no_of_combinations;\n                    }\n                }\n            }\n        }\n    }\n\n\n    for(int i = 0; i < no_of_fish; i++)\n        printf(\"%.12lf \", probability[(1LL << i)]);\n\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 23/Garbage Disposal.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_days, k;\r\n    cin >> no_of_days >> k;\r\n\r\n    vector <long long> A(no_of_days + 1);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        cin >> A[i];\r\n\r\n    long long minimum_bags = 0;\r\n\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        minimum_bags += A[i]/k;\r\n        A[i] %= k;\r\n\r\n        if(A[i] > 0)\r\n        {\r\n            minimum_bags++;\r\n\r\n            if(i + 1 <= no_of_days)\r\n                A[i + 1] = max(0LL, A[i + 1] - (k - A[i]));\r\n        }\r\n    }\r\n\r\n    cout << minimum_bags;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Guest From The Past.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ?  a : b)\r\n\r\nint main()\r\n{\r\n    long long money, plastic_bottle_price, glass_bottle_price, return_amount;\r\n    scanf(\"%I64d %I64d %I64d %I64d\", &money, &plastic_bottle_price, &glass_bottle_price, &return_amount);\r\n\r\n    long long effective_glass_bottle_price = glass_bottle_price - return_amount;\r\n    long long no_of_bottles = 0;\r\n\r\n    if(plastic_bottle_price <= effective_glass_bottle_price || glass_bottle_price > money)\r\n    {\r\n        no_of_bottles = money/plastic_bottle_price;\r\n    }\r\n    else if(effective_glass_bottle_price < plastic_bottle_price && glass_bottle_price <= money)\r\n    {\r\n        no_of_bottles = (money - return_amount)/effective_glass_bottle_price;\r\n\r\n        long long remaining_money = money - no_of_bottles*effective_glass_bottle_price;\r\n        long long remaining_bottles = remaining_money/plastic_bottle_price;\r\n\r\n        no_of_bottles += remaining_bottles;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_bottles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Ice Skater.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 105;\r\nvector <int> visited(MAX_N, false);\r\nvector <int> graph[MAX_N];\r\n\r\nvoid dfs(int v)\r\n{\r\n    visited[v] = true;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(!visited[child])\r\n            dfs(child);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <int> X(no_of_points + 1);\r\n    vector <int> Y(no_of_points + 1);\r\n    for(int i = 1; i <= no_of_points; i++)\r\n        scanf(\"%d %d\", &X[i], &Y[i]);\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        for(int j = 1; j < i; j++)\r\n        {\r\n            if(X[i] == X[j] || Y[i] == Y[j])\r\n            {\r\n                graph[i].push_back(j);\r\n                graph[j].push_back(i);\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            no_of_components++;\r\n\r\n            dfs(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_components - 1);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Lazyland.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <map>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_people, distinct_targets;\r\n    scanf(\"%d %d\", &no_of_people, &distinct_targets);\r\n\r\n    vector <int> A(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> time(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &time[i]);\r\n\r\n    map <int, int> max_time_for_task;\r\n    vector <int> free_time;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        if(max_time_for_task[A[i]] != 0)\r\n            free_time.push_back(min(time[i], max_time_for_task[A[i]]));\r\n\r\n        max_time_for_task[A[i]] = max(max_time_for_task[A[i]], time[i]);\r\n    }\r\n\r\n    sort(all(free_time));\r\n\r\n    int distinct_numbers = max_time_for_task.size();\r\n    int required_new_distinct_numbers = distinct_targets - distinct_numbers;\r\n\r\n    long long total_time = 0;\r\n    for(int i = 0; i < required_new_distinct_numbers; i++)\r\n        total_time += free_time[i];\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Lesha and Array Splitting.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> prefix_sum(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\r\n\r\n    vector <int> suffix_sum(no_of_elements + 2, 0);\r\n    for(int i = no_of_elements; i>= 1; i--)\r\n        suffix_sum[i] = suffix_sum[i + 1] + A[i];\r\n\r\n    int all_zeroes = true;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] != 0)\r\n            all_zeroes = false;\r\n    }\r\n\r\n    if(all_zeroes)\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"YES\\n\");\r\n\r\n        if(no_of_elements == 1 || prefix_sum[no_of_elements] != 0)\r\n        {\r\n            printf(\"1\\n1 %d\\n\", no_of_elements);\r\n        }\r\n        else\r\n        {\r\n            int division_point;\r\n            for(int i = 1; i < no_of_elements; i++)\r\n            {\r\n                if(prefix_sum[i] != 0 && suffix_sum[i + 1] != 0)\r\n                {\r\n                    division_point = i;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            printf(\"2\\n\");\r\n            printf(\"1 %d\\n\", division_point);\r\n            printf(\"%d %d\\n\", division_point + 1, no_of_elements);\r\n        }\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Lost Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_possible(vector <int> &A, int k)\r\n{\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if(A[i] != A[(i%k)])\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> X(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        X[i] = A[i + 1] - A[i];\r\n\r\n    vector <int> answer;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(is_possible(X, i))\r\n        {\r\n            answer.push_back(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", answer.size() == 0 ? -1 : answer.size());\r\n    for(int i = 0; i < answer.size(); i++)\r\n        printf(\"%d \", answer[i]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Maximum Value.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int MAX = 2e6 + 5;\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> is_present(MAX, false);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n\r\n        is_present[A[i]] = true;\r\n    }\r\n\r\n    vector <int> nearest(MAX, 0);\r\n    for(int i = 1; i < MAX; i++)\r\n    {\r\n        nearest[i] = (is_present[i - 1] ? i - 1 : nearest[i - 1]);\r\n    }\r\n\r\n    int max_mod = 0;\r\n    for(int i = 1; i < MAX; i++)\r\n    {\r\n        if(!is_present[i]) continue;\r\n\r\n        for(int j = 2*i; j < MAX; j += i)\r\n        {\r\n            max_mod = max(max_mod, nearest[j]%i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", max_mod);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Maze.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\nconst int MAX_N = 505;\r\n\r\nint visited[MAX_N][MAX_N];\r\nchar grid[MAX_N][MAX_N];\r\nint no_of_visits = 0, rows, columns;\r\n\r\nvoid dfs(int r, int c, int target)\r\n{\r\n    if(no_of_visits >= target)\r\n        return;\r\n\r\n    visited[r][c] = true;\r\n\r\n    no_of_visits++;\r\n\r\n    const int NO_OF_NEIGHBOURS = 4;\r\n    int next_x[NO_OF_NEIGHBOURS] = {-1, 0, 0, 1};\r\n    int next_y[NO_OF_NEIGHBOURS] = {0, 1, -1, 0};\r\n\r\n    for(int i = 0; i < NO_OF_NEIGHBOURS; i++)\r\n    {\r\n        int next_r = r + next_x[i], next_c = c + next_y[i];\r\n\r\n        if(0 < next_r && next_r <= rows && 0 < next_c && next_c <= columns &&\r\n           !visited[next_r][next_c] && grid[next_r][next_c] == '.')\r\n        {\r\n            dfs(next_r, next_c, target);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int k;\r\n    scanf(\"%d %d %d\", &rows, &columns, &k);\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    memset(visited, sizeof(visited), false);\r\n\r\n    int total_free = 0;\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            total_free += (grid[i][j] == '.');\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            if(grid[i][j] == '.')\r\n            {\r\n                dfs(i, j, total_free - k);\r\n\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            printf(\"%c\", (grid[i][j] == '.' && !visited[i][j]) ? 'X' : grid[i][j]);\r\n        }\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Minesweeper.cpp",
    "content": "#include <cstdio>\r\n\r\nconst int MAX_N = 105;\r\nconst char BOMB = '*', EMPTY = '.';\r\nchar grid[MAX_N][MAX_N];\r\n\r\nint neighbour_bomb_count(int x, int y)\r\n{\r\n    const int NO_OF_NEIGHBOURS = 8;\r\n    int step_x[NO_OF_NEIGHBOURS] = {-1, 0, 1, -1, 1, - 1, 0, 1};\r\n    int step_y[NO_OF_NEIGHBOURS] = {-1, -1, -1, 0, 0, 1, 1, 1};\r\n\r\n    int no_of_bombs = 0;\r\n    for(int i = 0; i < NO_OF_NEIGHBOURS; i++)\r\n    {\r\n        no_of_bombs += (grid[x + step_x[i]][y + step_y[i]] == BOMB);\r\n    }\r\n\r\n    return no_of_bombs;\r\n}\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    int valid = true;\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            if(grid[i][j] == EMPTY)\r\n            {\r\n                if(neighbour_bomb_count(i, j) != 0)\r\n                    valid = false;\r\n            }\r\n            else if('0' <= grid[i][j] && grid[i][j] <= '9')\r\n            {\r\n                if(neighbour_bomb_count(i, j) != grid[i][j] - '0')\r\n                    valid = false;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(valid ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Minimum Diameter Tree.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, total_weight;\r\n    scanf(\"%d %d\", &no_of_vertices, &total_weight);\r\n\r\n    vector <int> degree(no_of_vertices + 1, 0);\r\n    for(int i = 1; i <= no_of_vertices - 1; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        degree[u]++;\r\n        degree[v]++;\r\n    }\r\n\r\n    int no_of_leafs = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        no_of_leafs += (degree[i] == 1);\r\n\r\n    double leaf_weight = ( (double) total_weight)/ no_of_leafs;\r\n    double diameter = leaf_weight*2;\r\n\r\n    printf(\"%.12f\\n\", diameter);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/No To Palindromes.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, max_alphabet;\r\n    cin >> length >> max_alphabet;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    if( (max_alphabet == 1 && length > 1) || (max_alphabet == 2 && length > 2) )\r\n    {\r\n        cout << \"NO\\n\";\r\n        return 0;\r\n    }\r\n\r\n    const int NOT_FOUND = -1;\r\n    int first_greater_position = NOT_FOUND;\r\n    char replacement;\r\n\r\n    for(int i = length - 1; first_greater_position == NOT_FOUND && i >= 0; i--)\r\n    {\r\n\r\n\r\n        for(char new_ch = S[i] + 1; new_ch <= 'a' + max_alphabet - 1; new_ch++)\r\n        {\r\n            int possible = true;\r\n            for(int j = i - 1; j >= max(i - 2, 0); j--)\r\n            {\r\n                if(new_ch == S[j])\r\n                    possible = false;\r\n            }\r\n\r\n            if(possible)\r\n            {\r\n                first_greater_position = i;\r\n                replacement = new_ch;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(first_greater_position == NOT_FOUND)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return 0;\r\n    }\r\n\r\n    string next_good_string;\r\n    for(int i = 0 ; i < first_greater_position; i++)\r\n        next_good_string += S[i];\r\n\r\n    next_good_string += replacement;\r\n\r\n    for(int i = first_greater_position + 1; i < length; i++)\r\n    {\r\n        char current_char;\r\n\r\n        for(current_char = 'a'; current_char <= 'c'; current_char++)\r\n        {\r\n            if( (i - 1 >= 0 && next_good_string[i - 1] == current_char) ||\r\n                (i - 2 >= 0 && next_good_string[i - 2] == current_char) )\r\n            {\r\n                continue;\r\n            }\r\n            else\r\n            {\r\n                next_good_string += current_char;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << next_good_string;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/On Number of Decompositions into Multipliers.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e5, MOD =1e9 + 7;\r\nvector <long long> factorial(MAX_N + 1), inverse_factorial(MAX_N + 1);\r\nvector <long long> primes;\r\n\r\nvoid sieve()\r\n{\r\n    const int L = 1e5;\r\n\r\n    vector <int> is_prime(L + 1, true);\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= L; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] <= MAX_N; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n}\r\n\r\nlong long power_mod(long long x, long long power)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%MOD;\r\n\r\n        x = (x*x)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    factorial[0] = 1;\r\n    for(int i = 1; i <= MAX_N; i++)\r\n        factorial[i] = (i*factorial[i - 1])%MOD;\r\n\r\n    inverse_factorial[MAX_N] = power_mod(factorial[MAX_N], MOD - 2);\r\n    for(int i = MAX_N - 1; i >= 0; i--)\r\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%MOD;\r\n}\r\n\r\nlong long choose(long long n, long long r)\r\n{\r\n    long long numerator = factorial[n];\r\n    long long inverse_denominator = (inverse_factorial[r]*inverse_factorial[n - r])%MOD;\r\n\r\n    return (numerator*inverse_denominator)%MOD;\r\n}\r\n\r\nvoid factorise(int n, map <int, int> &exponent)\r\n{\r\n    for(int i = 0; primes[i]*primes[i] <=n; i++)\r\n    {\r\n        while(n%primes[i] == 0)\r\n        {\r\n            exponent[primes[i]]++;\r\n\r\n            n /= primes[i];\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n        exponent[n]++;\r\n}\r\n\r\nint main()\r\n{\r\n    sieve();\r\n    precompute();\r\n\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    map <int, int> prime_exponents;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        factorise(element, prime_exponents);\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long answer = 1;\r\n    for(map <int, int> :: iterator it = prime_exponents.begin(); it != prime_exponents.end(); it++)\r\n    {\r\n        int exponent = it->second;\r\n\r\n        answer *= choose(no_of_elements + exponent - 1, no_of_elements - 1);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/Summarise to Powers of Two.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    int no_of_deletions = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int complement_exists = false;\r\n\r\n        for(int power = 0; power <= 32; power++)\r\n        {\r\n            int complement = (1LL << power) - A[i];\r\n\r\n            if(complement == A[i])\r\n            {\r\n                if(frequency[A[i]] >= 2)\r\n                    complement_exists = true;\r\n            }\r\n            else if(frequency.find(complement) != frequency.end())\r\n            {\r\n                complement_exists = true;\r\n            }\r\n        }\r\n\r\n        if(!complement_exists)\r\n            no_of_deletions++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_deletions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/The Fair Nut and String.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long total_sequences = 1, current_block_of_a = 0;\r\n    for(int i = 0; i <= S.size(); i++)\r\n    {\r\n        if(S[i] == 'a')\r\n        {\r\n            current_block_of_a++;\r\n        }\r\n        else if(i == S.size() || S[i] == 'b')\r\n        {\r\n            total_sequences = (total_sequences*(current_block_of_a + 1))%MOD;\r\n\r\n            current_block_of_a = 0;\r\n        }\r\n    }\r\n\r\n    total_sequences = (total_sequences + MOD - 1)%MOD;\r\n    cout << total_sequences;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 23/The Meaningless Game.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    map <long long, int> cube_root;\r\n    const int MAX_CUBE_ROOT = 1e6;\r\n    for(long long i = 1; i <= MAX_CUBE_ROOT; i++)\r\n        cube_root[i*i*i] = i;\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        long long a, b;\r\n        scanf(\"%I64d %I64d\", &a, &b);\r\n\r\n        int possible = true;\r\n        if(cube_root[a*b] == 0)\r\n        {\r\n            possible = false;\r\n            printf(\"No\\n\");\r\n            continue;\r\n        }\r\n\r\n        long long winnings_a = (a)/cube_root[a*b];\r\n        long long winnings_b = (b)/cube_root[a*b];\r\n\r\n        long long expected_a = (winnings_a*winnings_a*winnings_b);\r\n        long long expected_b = (winnings_b*winnings_b*winnings_a);\r\n\r\n        if(a != expected_a || b != expected_b)\r\n            possible = false;\r\n\r\n        printf(possible ? \"Yes\\n\" : \"No\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Brutality.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nconst int NO_OF_ALPHABETS = 26;\r\nvector <long long> cost[NO_OF_ALPHABETS];\r\n\r\nint main()\r\n{\r\n    int length, max_elements;\r\n    cin >> length >> max_elements;\r\n\r\n    vector <int> A(length);\r\n    for(int i = 0; i < length; i++)\r\n        cin >> A[i];\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    long long total = 0;\r\n    vector <int> last_pressed_costs;\r\n    char last_pressed = '#';\r\n\r\n    for(int i = 0; i <= length; i++)\r\n    {\r\n        if(i == length ||S[i] != last_pressed)\r\n        {\r\n            sort(all(last_pressed_costs));\r\n\r\n            reverse(all(last_pressed_costs));\r\n\r\n            for(int j = 0; j < min(max_elements, last_pressed_costs.size()); j++)\r\n            {\r\n                total += last_pressed_costs[j];\r\n            }\r\n\r\n            last_pressed_costs.clear();\r\n        }\r\n\r\n        if(i == length) continue;\r\n\r\n        last_pressed = S[i];\r\n        last_pressed_costs.push_back(A[i]);\r\n\r\n    }\r\n\r\n    cout << total;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Connect.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nstruct Point\r\n{\r\n    int x, y;\r\n\r\n    Point(){}\r\n\r\n    Point(int X, int Y)\r\n    {\r\n        x = X, y = Y;\r\n    }\r\n};\r\n\r\n\r\nconst int NO_OF_NEIGHBOURS = 4, MAX_N = 55, oo = 1e9;\r\nint next_x[NO_OF_NEIGHBOURS] = {-1, 0, 0 , 1};\r\nint next_y[NO_OF_NEIGHBOURS] = {0, 1, -1, 0};\r\nint component_no[MAX_N][MAX_N], is_water[MAX_N][MAX_N];\r\n\r\nint calculate_distance(Point P, Point Q)\r\n{\r\n    return (P.x - Q.x)*(P.x - Q.x) + (P.y - Q.y)*(P.y - Q.y);\r\n}\r\n\r\nint is_outside(int x, int y, int n)\r\n{\r\n    return (x < 1 || n < x || y < 1 || n < y);\r\n}\r\n\r\nvoid dfs(int x, int y, int n, int number)\r\n{\r\n    if(is_water[x][y] || is_outside(x, y, n) || component_no[x][y] != 0)\r\n        return;\r\n\r\n    component_no[x][y] = number;\r\n\r\n    for(int i = 0; i < NO_OF_NEIGHBOURS; i++)\r\n    {\r\n        dfs(x + next_x[i], y + next_y[i], n, number);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    Point start, finish;\r\n    cin >> start.x >> start.y >> finish.x >> finish.y;\r\n\r\n    memset(is_water, false, sizeof(is_water));\r\n    for(int i = 0; i < n; i++)\r\n    {\r\n        string row;\r\n        cin >> row;\r\n\r\n        for(int j = 0; j < n; j++)\r\n        {\r\n            if(row[j] == '1')\r\n            {\r\n                is_water[i + 1][j + 1] = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    memset(component_no, 0, sizeof(component_no));\r\n    int last_component_no = 0;\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            if(component_no[x][y] == 0)\r\n            {\r\n                dfs(x, y, n, ++last_component_no);\r\n            }\r\n        }\r\n    }\r\n\r\n    vector <Point> start_component, finish_component;\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            if(component_no[x][y] == component_no[start.x][start.y])\r\n                start_component.push_back(Point(x, y));\r\n\r\n            if(component_no[x][y] == component_no[finish.x][finish.y])\r\n                finish_component.push_back(Point(x, y));\r\n        }\r\n    }\r\n\r\n    int distance = oo;\r\n    for(int i = 0; i < start_component.size(); i++)\r\n    {\r\n        for(int j = 0; j < finish_component.size(); j++)\r\n        {\r\n            distance = min(distance, calculate_distance(start_component[i], finish_component[j]));\r\n        }\r\n    }\r\n\r\n    cout << distance;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Div Times Mod.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    cin >> n >> k;\r\n\r\n    const int oo = 1e9;\r\n    int answer = oo;\r\n\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            int quotient = i, remainder = n/i;\r\n\r\n            if(remainder < k)\r\n                answer = min(answer, quotient*k + remainder);\r\n\r\n            quotient = n/i, remainder = i;\r\n            if(remainder < k)\r\n                answer = min(answer, quotient*k + remainder);\r\n        }\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Diverse Garland.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    string colour = \"RGB\";\r\n    int replacements = 0;\r\n\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        if(S[i] == S[i - 1])\r\n        {\r\n            for(int j = 0; j < colour.size(); j++)\r\n            {\r\n                if( (i + 1 == length && colour[j] != S[i - 1]) || (colour[j] != S[i + 1] && colour[j] != S[i - 1]) )\r\n                {\r\n                    replacements++;\r\n                    S[i] = colour[j];\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << replacements << \"\\n\" << S;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Division and Union.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct line\r\n{\r\n    int left, right, position;\r\n\r\n    line(int l, int r, int p)\r\n    {\r\n        left = l, right = r, position = p;\r\n    }\r\n\r\n    int operator <(const line &L)\r\n    {\r\n        return (right < L.right);\r\n    }\r\n};\r\n\r\nvoid solve()\r\n{\r\n    int no_of_segments;\r\n    cin >> no_of_segments;\r\n\r\n    vector <line> L;\r\n    for(int i = 0; i < no_of_segments; i++)\r\n    {\r\n        int left, right;\r\n        cin >> left >> right;\r\n\r\n        L.push_back(line(left, right, i));\r\n    }\r\n\r\n    sort(all(L));\r\n\r\n    vector <int> minimum_left_from(no_of_segments);\r\n    for(int i = no_of_segments - 1; i >= 0; i--)\r\n    {\r\n        if(i == no_of_segments - 1)\r\n            minimum_left_from[i] = L[i].left;\r\n        else\r\n            minimum_left_from[i] = min(minimum_left_from[i + 1], L[i].left);\r\n    }\r\n\r\n    const int NOT_FOUND = -1;\r\n    int first_group_ending = NOT_FOUND;\r\n\r\n    for(int i = 0; i < no_of_segments - 1; i++)\r\n    {\r\n        if(L[i].right < minimum_left_from[i + 1])\r\n            first_group_ending = i;\r\n    }\r\n\r\n    if(first_group_ending == NOT_FOUND)\r\n    {\r\n        cout << NOT_FOUND << \"\\n\";\r\n        return ;\r\n    }\r\n\r\n    vector <int> group(no_of_segments);\r\n    for(int i = 0; i < no_of_segments; i++)\r\n        group[L[i].position] = (i <= first_group_ending ? 1 : 2);\r\n\r\n    for(int i = 0; i < no_of_segments; i++)\r\n        cout << group[i] << \" \";\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Finite or Not.cpp",
    "content": "#include <cstdio>\n\n#define min(a, b) (a < b ? a : b)\n#define max(a, b) (a > b ? a : b)\n\ntypedef long long LL;\n\nLL gcd(LL x, LL y)\n{\n    if(x == 0 || y == 0)\n        return (x + y);\n    else\n        return gcd(min(x, y), max(x, y)%min(x, y));\n}\n\nvoid solve()\n{\n    LL numerator, denominator, base;\n    scanf(\"%I64d %I64d %I64d\", &numerator, &denominator, &base);\n\n    LL gcd_fraction = gcd(numerator, denominator);\n    numerator /= gcd_fraction;\n    denominator /= gcd_fraction;\n\n    base = gcd(base, denominator);\n\n    while(base > 1)\n    {\n        while(denominator%base == 0) denominator /= base;\n\n        base = gcd(base, denominator);\n    }\n\n    printf(denominator == 1 ? \"Finite\\n\" : \"Infinite\\n\");\n}\n\nint main()\n{\n    int no_of_queries;\n    scanf(\"%d\", &no_of_queries);\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "C Programs/C Programs 24/Illya and Escalator.cpp",
    "content": "#include <iostream>\r\n#include <cstdio>\r\n#include <iomanip>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2005;\r\ndouble probability[MAX_N][MAX_N];\r\n\r\nint main()\r\n{\r\n    int no_of_people, total_time;\r\n    double new_person_probability;\r\n    cin >> no_of_people >> new_person_probability >> total_time;\r\n\r\n    double no_new_person_probability = 1 - new_person_probability;\r\n\r\n    memset(probability, 0, sizeof(probability));\r\n    probability[0][0] = 1;\r\n\r\n    for(int t = 1; t <= total_time; t++)\r\n    {\r\n        probability[0][t] = no_new_person_probability*probability[0][t - 1];\r\n\r\n        for(int i = 1; i < no_of_people; i++)\r\n        {\r\n            probability[i][t] = new_person_probability*probability[i - 1][t - 1] +\r\n                                no_new_person_probability*probability[i][t - 1];\r\n\r\n        }\r\n\r\n        probability[no_of_people][t] = probability[no_of_people][t - 1] +\r\n                        new_person_probability*probability[no_of_people - 1][t - 1];\r\n    }\r\n\r\n    double expectation = 0;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        expectation += i*probability[i][total_time];\r\n\r\n    cout << setprecision(7) << expectation;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Increasing by Modulo.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint possible(int operations, int m, vector <int> &A)\r\n{\r\n    int minimum = 0;\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if( (A[i] <= minimum && A[i] + operations >= minimum) || (A[i] > minimum && A[i] + operations - m >= minimum) )\r\n            continue;\r\n\r\n        if(A[i] < minimum)\r\n            return false;\r\n\r\n        minimum = A[i];\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, m;\r\n    cin >> no_of_elements >> m;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    int left = -1, right = m;\r\n    while(right - left > 1)\r\n    {\r\n        int mid = (left + right)/2;\r\n\r\n        if(possible(mid, m, A))\r\n            right = mid;\r\n        else\r\n            left = mid;\r\n    }\r\n\r\n    cout << right;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Nice Garland.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint replacements(string &R, string &S)\r\n{\r\n    int difference_count = 0;\r\n\r\n    for(int i = 0; i < S.size(); i++)\r\n        difference_count += (S[i] != R[i%3]);\r\n\r\n    return difference_count;\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_OPTIONS = 6, oo = 1e9;\r\n\r\n    string option[NO_OF_OPTIONS] = {\"RGB\", \"RBG\", \"BRG\", \"BGR\", \"GRB\", \"GBR\"};\r\n\r\n    int minimum_replacement = oo, best_option = 0;\r\n\r\n    for(int i = 0; i < NO_OF_OPTIONS; i++)\r\n    {\r\n        int replacements_here = replacements(option[i], S);\r\n\r\n        if(replacements_here < minimum_replacement)\r\n        {\r\n            minimum_replacement = replacements_here;\r\n            best_option = i;\r\n        }\r\n    }\r\n\r\n    cout << minimum_replacement << \"\\n\";\r\n    for(int i = 0; i < length; i++)\r\n        cout << option[best_option][i%3];\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Planning the Expedition.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint possible(vector <int> A, int days, int min_participants)\r\n{\r\n    int participants = 0;\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        participants += A[i]/days;\r\n        A[i] %= days;\r\n    }\r\n\r\n    return (participants >= min_participants);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_participants, no_of_packages;\r\n    scanf(\"%d %d\", &no_of_participants, &no_of_packages);\r\n\r\n    const int MAX = 100;\r\n    vector <int> frequency(MAX + 1, 0);\r\n    for(int i = 1; i <= no_of_packages; i++)\r\n    {\r\n        int type;\r\n        scanf(\"%d\", &type);\r\n\r\n        frequency[type]++;\r\n    }\r\n\r\n    if(no_of_packages < no_of_participants)\r\n    {\r\n        printf(\"0\");\r\n        return 0;\r\n    }\r\n\r\n    int left_days = 1, right_days = MAX;\r\n    while(left_days <= right_days)\r\n    {\r\n        int mid_days = (left_days + right_days) >> 1;\r\n\r\n        if(possible(frequency, mid_days, no_of_participants))\r\n        {\r\n            if(mid_days == right_days || !possible(frequency, mid_days + 1, no_of_participants))\r\n            {\r\n                printf(\"%d\\n\", mid_days);\r\n                return 0;\r\n            }\r\n            else\r\n            {\r\n                left_days = mid_days + 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            right_days = mid_days - 1;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Playing Piano.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int NO_OF_FINGERS = 5, MAX_NOTES = 2e5 + 5;\r\nint is_possible[MAX_NOTES][NO_OF_FINGERS];\r\n\r\nint main()\r\n{\r\n    int no_of_notes;\r\n    cin >> no_of_notes;\r\n\r\n    vector <int> notes(no_of_notes + 1);\r\n    for(int i = 1; i <= no_of_notes; i++)\r\n        cin >> notes[i];\r\n\r\n    memset(is_possible, false, sizeof(is_possible));\r\n\r\n    for(int i = 1; i <= no_of_notes; i++)\r\n    {\r\n        for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n        {\r\n            if(i == 1)\r\n            {\r\n                is_possible[i][finger] = true;\r\n                continue;\r\n            }\r\n\r\n            if(notes[i - 1] <= notes[i])\r\n            {\r\n                for(int previous_finger = 1; previous_finger < finger; previous_finger++)\r\n                {\r\n                    if(is_possible[i - 1][previous_finger])\r\n                    {\r\n                        is_possible[i][finger] = true;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if(notes[i - 1] >= notes[i])\r\n            {\r\n                for(int previous_finger = NO_OF_FINGERS; previous_finger > finger; previous_finger--)\r\n                {\r\n                    if(is_possible[i - 1][previous_finger])\r\n                    {\r\n                        is_possible[i][finger] = true;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    int fingering_possible = false;\r\n    for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n    {\r\n        if(is_possible[no_of_notes][finger])\r\n            fingering_possible = true;\r\n    }\r\n\r\n    if(!fingering_possible)\r\n    {\r\n        cout << \"-1\\n\";\r\n        return 0;\r\n    }\r\n\r\n    vector <int> playing_finger(no_of_notes + 1);\r\n    for(int i = no_of_notes; i >= 1; i--)\r\n    {\r\n        if(i == no_of_notes)\r\n        {\r\n            for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n            {\r\n                if(is_possible[i][finger])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            continue;\r\n        }\r\n\r\n        if(notes[i] < notes[i + 1])\r\n        {\r\n            for(int finger = playing_finger[i + 1] - 1; finger >= 1; finger--)\r\n            {\r\n                if(is_possible[i][finger])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        if(notes[i] > notes[i + 1])\r\n        {\r\n            for(int finger = playing_finger[i + 1] + 1; finger <= NO_OF_FINGERS; finger++)\r\n            {\r\n                if(is_possible[i][finger])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        if(notes[i] == notes[i + 1])\r\n        {\r\n            for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n            {\r\n                if(is_possible[i][finger] && finger != playing_finger[i + 1])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_notes; i++)\r\n        cout << playing_finger[i] << \" \";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Posterized.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_colours, group_size;\r\n    scanf(\"%d %d\", &no_of_colours, &group_size);\r\n\r\n    const int MAX_COLOUR = 255;\r\n    vector <int> colour(no_of_colours + 1);\r\n\r\n    for(int i = 1; i <= no_of_colours; i++)\r\n        scanf(\"%d\", &colour[i]);\r\n\r\n    vector <int> key(MAX_COLOUR + 1);\r\n\r\n    vector <int> used(MAX_COLOUR + 1, false);\r\n\r\n    for(int i = 1; i <= no_of_colours; i++)\r\n    {\r\n        int current_colour = colour[i];\r\n\r\n        if(!used[current_colour])\r\n        {\r\n            int first_colour = max(0, current_colour - group_size + 1);\r\n\r\n            while(used[first_colour] && key[first_colour] + group_size - 1 < current_colour)\r\n                first_colour++;\r\n\r\n            if(!used[first_colour])\r\n                key[first_colour] = first_colour, used[first_colour] = true;\r\n\r\n            for(int j = first_colour + 1; j <= current_colour; j++)\r\n            {\r\n                key[j] = key[first_colour];\r\n                used[j] = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_colours; i++)\r\n        printf(\"%d \", key[colour[i]]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Powers of Two.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_bit_set(int position, int n)\r\n{\r\n    return ( (n&(1 << position)) != 0);\r\n}\r\n\r\nint main()\r\n{\r\n    int n, no_of_summands;\r\n    cin >> n >> no_of_summands;\r\n\r\n    int no_of_summands_made = 0;\r\n    const int MAX_POWER = 32;\r\n    vector <int> frequency(MAX_POWER, 0);\r\n\r\n    for(int i = 0; i < MAX_POWER; i++)\r\n    {\r\n        if(is_bit_set(i, n))\r\n        {\r\n            frequency[i]++;\r\n\r\n            no_of_summands_made++;\r\n        }\r\n    }\r\n\r\n    if(no_of_summands < no_of_summands_made || no_of_summands > n)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return 0;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n\r\n    while(no_of_summands_made < no_of_summands)\r\n    {\r\n        for(int i = 1; i < MAX_POWER; i++)\r\n        {\r\n            if(frequency[i] > 0) //Break 2^i into 2^{i - 1} and 2^{i - 1}\r\n            {\r\n                frequency[i]--;\r\n                frequency[i - 1] += 2;\r\n\r\n                no_of_summands_made++;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < MAX_POWER; i++)\r\n    {\r\n        for(int j = 0; j < frequency[i]; j++)\r\n        {\r\n            cout << (1 << i) << \" \";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Splitting into Digits.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    cout << n << \"\\n\";\r\n    for(int i = 1; i <= n; i++) cout << \"1 \";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Stages.cpp",
    "content": "#include <cstdio>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <iostream>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_letters, required_letters;\r\n    string S;\r\n    cin >> no_of_letters >> required_letters >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> present(NO_OF_ALPHABETS, false);\r\n    for(int i = 0; i < no_of_letters; i++)\r\n        present[S[i] - 'a'] = true;\r\n\r\n    int sum = 0, chosen = 0;\r\n    for(int i = 0; i < NO_OF_ALPHABETS && chosen < required_letters; i++)\r\n    {\r\n        if(present[i])\r\n        {\r\n            chosen++;\r\n\r\n            sum += i + 1;\r\n            i++;\r\n        }\r\n    }\r\n\r\n    cout << (chosen < required_letters ? -1 : sum);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Tanya and Candies.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 5, EVEN = 0, ODD = 1;\r\nlong long sum_till[MAX_N][2], sum_from[MAX_N][2];\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    sum_till[0][ODD] = sum_till[0][EVEN] = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i][ODD] = sum_till[i - 1][ODD];\r\n        sum_till[i][EVEN] = sum_till[i - 1][EVEN];\r\n\r\n        sum_till[i][i%2] += A[i];\r\n    }\r\n\r\n    sum_from[no_of_elements + 1][ODD] = sum_from[no_of_elements + 1][EVEN] = 0;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        sum_from[i][ODD] = sum_from[i + 1][ODD];\r\n        sum_from[i][EVEN] = sum_from[i + 1][EVEN];\r\n\r\n        sum_from[i][i%2] += A[i];\r\n    }\r\n\r\n    int no_of_points = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        no_of_points += (sum_till[i - 1][EVEN] + sum_from[i + 1][ODD] == sum_till[i - 1][ODD] + sum_from[i + 1][EVEN]);\r\n    }\r\n\r\n    cout << no_of_points;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/The Way to Home.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, max_jump;\r\n    cin >> length >> max_jump;\r\n\r\n    string path;\r\n    cin >> path;\r\n\r\n    const int oo = 1e9;\r\n    vector <int> minimum_jumps_to_reach(length, 0);\r\n    minimum_jumps_to_reach[0] = 0;\r\n\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        minimum_jumps_to_reach[i] = oo;\r\n\r\n        if(path[i] == '0') continue;\r\n\r\n        for(int j = 1; j <= max_jump && i - j >= 0; j++)\r\n        {\r\n            minimum_jumps_to_reach[i] = min(minimum_jumps_to_reach[i], 1 + minimum_jumps_to_reach[i - j]);\r\n        }\r\n    }\r\n\r\n    cout << (minimum_jumps_to_reach[length - 1] == oo ? -1 : minimum_jumps_to_reach[length - 1]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Vanya and Label.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <cstdio>\r\n\r\nusing namespace std;\r\n\r\nint is_bit_set(int n, int position)\r\n{\r\n    return ( (n&(1 << position)) != 0);\r\n}\r\n\r\nint value(char n)\r\n{\r\n    if('0' <= n && n <= '9') return n - '0';\r\n    if('A' <= n && n <= 'Z') return 10 + n - 'A';\r\n    if('a' <= n && n <= 'z') return 36 + n - 'a';\r\n    if(n == '-')return 62;\r\n    if(n == '_') return 63;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    long long no_of_ways = 1;\r\n\r\n    const int MOD = 1e9 + 7;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        for(int bit = 0; bit < 6; bit++)\r\n        {\r\n            if(!is_bit_set(value(S[i]), bit))\r\n            {\r\n                no_of_ways = (no_of_ways*3)%MOD;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << no_of_ways;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Where_Do_I_Turn.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int a_x, a_y, b_x, b_y, c_x, c_y;\r\n    scanf(\"%d %d %d %d %d %d\", &a_x, &a_y, &b_x, &b_y, &c_x, &c_y);\r\n\r\n    //Cross_product\r\n    if( (c_y - b_y)*1LL*(b_x - a_x) - (b_y - a_y)*1LL*(c_x - b_x) == 0 )\r\n        printf(\"TOWARDS\\n\");\r\n    else if( (c_y - b_y)*1LL*(b_x - a_x) - (b_y - a_y)*1LL*(c_x - b_x) > 0 )\r\n        printf(\"LEFT\\n\");\r\n    else\r\n        printf(\"RIGHT\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "C Programs/C Programs 24/Zero Quantity Maximisation.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\ntypedef long long LL;\r\n\r\nusing namespace std;\r\n\r\nstruct fraction\r\n{\r\n    long long numerator, denominator;\r\n\r\n    fraction(){}\r\n\r\n    fraction(long long N, long long D)\r\n    {\r\n        long long G = __gcd(abs(N), abs(D));\r\n\r\n        numerator = N/G;\r\n        denominator = D/G;\r\n\r\n        if(denominator < 0)\r\n        {\r\n            numerator *= -1;\r\n            denominator *= -1;\r\n        }\r\n    }\r\n\r\n    const int operator <(const fraction &F) const\r\n    {\r\n        return (denominator*F.numerator - numerator*F.denominator < 0);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <LL> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    vector <LL> B(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> B[i];\r\n\r\n    int both_zeroes = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        both_zeroes += (A[i] == 0 && B[i] == 0);\r\n\r\n    map <fraction, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] == 0)\r\n            continue;\r\n\r\n        frequency[fraction(-B[i], A[i])]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(map <fraction, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        max_frequency = max(max_frequency, it->second);\r\n    }\r\n\r\n    int answer = max_frequency + both_zeroes;\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/463 Div 1 + 2 ICM Technex/Explanations/Team Work Explanation.txt",
    "content": "We want to find sum_{i = 1}^n C(n, i) i^k\n\nWe know that (1 + x)^n = sum_{i = 0}^n C(n, i) x^i\n\nIf we replace x = 1, then we get 2^n. How do we get the term i^k there ? \n\nThere is a well known technique in evaluating sums of this nature. \n\nWe will find the derivative of this function with x, and then multiply it with x\n\nn (1 + x)^{n - 1} = x sum_{i = 0}^n C(n, i) i x^{i - 1}\n                  = sum_{i = 0}^n C(n, i) i x^i\n\nWe have succeeded in getting i inside the summation !\n\nIf we repeat this step k times, we will get i^k inside and then we just need to \nreplace x = 1 in the LHS to get the value of the sum.\n\nThe question is how do we do this through programming.\n\n------\n\nThere is a very instructive technique. \n\nLet f(k, b, c) denote the result of applying the 'differentiate-and-then-multiply' step 'k' times \non the polynomial x^b (1 + x)^c\n\nIn one step, it becomes x[b.x^{b - 1} (1 + x)^c + c.x^b(1 + x)^{c - 1}]\n\n= b.x^b (1 + x)^c + c x^{b + 1} (1 + x)^{c - 1}\n\n= b.f(k - 1, b, c) + c.f(k - 1, b + 1, c - 1)\n\n------\n\nAnother small, but important thing - Although it looks like it is O(n^3) space, it is O(n^2) space because b + c is invariant.\nWe do not need to keep track of both states in space.\n\n------\n\nlong long f(long long differentiations, long long b, long long c)\n{\n    if(no_of_ways[differentiations][b] != -1)\n    {\n        return no_of_ways[differentiations][b];\n    }\n    \n    //x^b(1 + x)^c becomes x[bx^{b - 1}(1 + x)^c + cx^b(1 + x)^{c - 1}]\n    //f(a, b, c) = b.f(a - 1, b, c) + c.f(a - 1, b + 1, c - 1)\n    \n    if(differentiations == 0)\n    {\n        return no_of_ways[differentiations][b] = power_mod(2, c);\n    }\n    \n    long long term_1 = b*f(differentiations - 1, b, c);\n    long long term_2 = (c == 0 ? 0 : c*f(differentiations - 1, b + 1, c - 1));\n    \n    return no_of_ways[differentiations][b] = (term_1 + term_2)%MOD;\n}\n"
  },
  {
    "path": "Contests/463 Div 1 + 2 ICM Technex/Programs/Team Work.cpp",
    "content": "#include <iostream>\n#include <cstring>\n\nusing namespace std;\n\nconst int MAX_N = 5005, MOD = 1e9 + 7;\nlong long no_of_ways[MAX_N][MAX_N];\n\nlong long power_mod(long long x, long long power)\n{\n    long long result = 1;\n    \n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*x)%MOD;\n        \n        x = (x*x)%MOD;\n        power = power >> 1;\n    }\n    \n    return result;\n}\n\nlong long f(long long differentiations, long long b, long long c)\n{\n    if(no_of_ways[differentiations][b] != -1)\n    {\n        return no_of_ways[differentiations][b];\n    }\n    \n    //x^b(1 + x)^c becomes x[bx^{b - 1}(1 + x)^c + cx^b(1 + x)^{c - 1}]\n    //f(a, b, c) = b.f(a - 1, b, c) + c.f(a - 1, b + 1, c - 1)\n    \n    if(differentiations == 0)\n    {\n        return no_of_ways[differentiations][b] = power_mod(2, c);\n    }\n    \n    long long term_1 = b*f(differentiations - 1, b, c);\n    long long term_2 = (c == 0 ? 0 : c*f(differentiations - 1, b + 1, c - 1));\n    \n    return no_of_ways[differentiations][b] = (term_1 + term_2)%MOD;\n}\n\nint main()\n{\n    long long no_of_people, k;\n    cin >> no_of_people >> k;\n    \n    memset(no_of_ways, -1, sizeof(no_of_ways));\n    cout << f(k, 0, no_of_people) << \"\\n\";\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Explanations/Azamon Web Services Explanation.txt",
    "content": "Swap a character to the minimum character in it's suffix. \n\nIn case of a tie, choose the rightmost character. \n\n-----\n\nvoid solve()\n{\n    string word_1, word_2;\n    cin >> word_1 >> word_2;\n    \n    for(int i = 0; i < word_1.size(); i++)\n    {\n        char minimum = word_1[i];\n        int position = i;\n        \n        for(int j = i + 1; j < word_1.size(); j++)\n        {\n            if(word_1[j] <= minimum)\n            {\n                minimum = word_1[j];\n                position = j;\n            }\n        }\n        \n        if(minimum < word_1[i])\n        {\n            swap(word_1[i], word_1[position]);\n            break;\n        }\n    }\n    \n    cout << (word_1 < word_2 ? word_1 : \"---\") << \"\\n\";\n}"
  },
  {
    "path": "Contests/607 Div 1 + 2/Explanations/Beingawesomeism Explanation.txt",
    "content": "The crucial insight here is that the answer is always 4. \n\nLet us see how. \n\nImpossible Case - \n\nThe entire grid is P and so it can't be made A, regardless of what we do.\n\n-----\n\nCase 1 - The answer is 0 - \n\nThis is when the entire grid is A and there is nothing left for us to do.\n\n-----\n\nCase 2 - The answer is 1\n\nThis happens if any corner row or corner column is all A. \n\nWe can simply make it propagate throughout the entire grid in 1 move. \n\n-----\n\nCase 3 - The answer is 2\n\nThis happens if any of the 4 corner squares are A \n\nOr any non-corner edge is completely full. \n\nIf any square of the corner edge is full, then\n\n\ta. Move 1 - Make the entire edge A\n\tb. Move 2 - Reduces to Case 1\n\nIf any non-corner edge is completely full, then \n\n\ta. Move 1 - Propagate it towards the right/up \n\tb. Move 2 - Propagate it towards the left/down \n\n-----\n\nCase 4 - The answer is 3 \n\nThis happens if any square of the corner edge is full. \n\n\ta. Move 1 - Make right/up of the corner edge full\n\tb. Move 2 - Make left/down of the corner edge full\n\tc. Move 3 - We have a complete corner edge. This is Case 1\n\n----\n\nCase 5 - The answer is 4\n\nIf there is at least 1 A somewhere in the grid\n\n\ta. Move 1 - Make right/up of the edge full \n\tb. Move 2 - Make left/down of the edge full \n\tc. Move 3 - Propagate the edge in right/up direction\n\td. Move 4 - Propagate the edge in left/down direction\n\n-----\n\n\n    \n    return true;\n}\n\nint all_p(int rows, int columns)\n{\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(grid[i][j] == 'A')\n            {\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\nint all_a(int rows, int columns)\n{\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(grid[i][j] == 'P')\n            {\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\nint corner_square(int rows, int columns)\n{\n    return (grid[0][0] == 'A' || grid[0][columns - 1] == 'A' ||\n            grid[rows - 1][0] == 'A' || grid[rows - 1][columns - 1] == 'A');\n}\n\nint corner_edge_square(int rows, int columns)\n{\n    for(int c = 0; c < columns; c++)\n    {\n        if(grid[0][c] == 'A' || grid[rows - 1][c] == 'A')\n        {\n            return true;\n        }\n    }\n    \n    for(int r = 0; r < rows; r++)\n    {\n        if(grid[r][0] == 'A' || grid[r][columns - 1] == 'A')\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nint full_corner_edges(int rows, int columns)\n{\n    if(full_row_a(0, columns) || full_row_a(rows - 1, columns))\n    {\n        return true;\n    }\n    \n    if(full_column_a(rows, 0) || full_column_a(rows, columns - 1))\n    {\n        return true;\n    }\n    \n    return false;\n}\n\nint any_full_edge(int rows, int columns)\n{\n    for(int i = 0; i < rows; i++)\n    {\n        if(full_row_a(i, columns))\n        {\n            return true;\n        }\n    }\n    \n    for(int i = 0; i < columns; i++)\n    {\n        if(full_column_a(rows, i))\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    for(int i = 0; i < rows; i++)\n    {\n        cin >> grid[i];\n    }\n    \n    if(all_p(rows, columns))\n    {\n        cout << \"MORTAL\\n\";\n        \n        return;\n    }\n    else if(all_a(rows, columns))\n    {\n        cout << \"0\\n\";\n        \n        return;\n    }\n    else if(full_corner_edges(rows, columns))\n    {\n        cout << \"1\\n\";\n        \n        return;\n    }\n    else if(corner_square(rows, columns) || any_full_edge(rows, columns))\n    {\n        cout << \"2\\n\";\n        \n        return;\n    }\n    else if(corner_edge_square(rows, columns))\n    {\n        cout << \"3\\n\";\n        \n        return;\n    }\n    else\n    {\n        cout << \"4\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n\n\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Explanations/Cut and Paste Explanation.txt",
    "content": "We can simulate the process.\n\nWe only need the first x characters so we will simulate it\ntill the length of the string is <= x\n\nFor each i, we will count how many times the suffix is added to the end of the string\n\n-----\n\nvoid solve()\n{\n    int no_of_steps;\n    cin >> no_of_steps;\n\n    string S;\n    cin >> S;\n\n    const int MAX = 1e6, MOD = 1e9 + 7;\n    long long length = S.size();\n\n    for(int i = 0; i < no_of_steps; i++)\n    {\n        long long suffix = ((length - 1) - i + MOD)%MOD;\n\n        if(S[i] == '1')\n        {\n            continue;\n        }\n        else if(S[i] == '2')\n        {\n            length = (length + suffix)%MOD;\n\n            for(int j = 1; j <= suffix && S.size() <= min(MAX, no_of_steps); j++)\n            {\n                S += S[i + j];\n            }\n        }\n        else if(S[i] == '3')\n        {\n            length = (length + 2*suffix)%MOD;\n\n            for(int k = 1; k <= 2; k++)\n            {\n                for(int j = 1; j <= suffix && S.size() <= min(MAX, no_of_steps); j++)\n                {\n                    S += S[i + j];\n                }\n            }\n        }\n    }\n\n    cout << length << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Explanations/Jeremy Bearimy Explanation.txt",
    "content": "We need to think about how many times a particular edge is counted.\n\nThe main insight here is that each edge of a tree is a bridge between 2 Components.\n\nMinimizing Weight -\n\nWhen we try to minimize the weight, we will look at each edge and try to minimise the number of times it is counted.\n\nWe will put pairs into 1 component.\nIf both components are of even size, then it will be counted 0 times.\nIf both components are odd, then this edge will be counted once.\n\nMaximizing Weight -\n\nWhen we try to maximize the weight, we want each edge to be counted as many times as possible.\nWe will try to make each pair cross this edge.\nSuppose the component sizes are C and D, and C < D, then we will put C distinct numbers in the component and all their counterparts on the other end.\n Hence, the edge is counted min(C, D) times.\n\n ---\n\n How do we find out the size of the subtree on either side of an edge (u, v) ? \n\n 1. We will perform a DFS and compute the size of the subtree rooted at v. \n\n 2. For every vertex v, we will keep track of it's parent u\n\n 3. While calculating the sizes of the 2 components (u, v)\n\n One of the components will be the subtree rooted at u and the other will be \n all the other vertices. \n\n -----\n\n void dfs(int v, int parent_v)\n {\n     parent[v] = parent_v;\n     subtree_size[v] = 1;\n     \n     for(int i = 0; i < tree[v].size(); i++)\n     {\n         int child_v = tree[v][i];\n         \n         if(child_v == parent_v)\n         {\n             continue;\n         }\n         \n         dfs(child_v, v);\n         \n         subtree_size[v] += subtree_size[child_v];\n     }\n }\n\n----\n\nstruct Edge\n{\n    int u, v;\n    long long weight;\n    \n    Edge(){};\n    \n    Edge(int U, int V, long long W)\n    {\n        u = U; v = V;\n        weight = W;\n    }\n};\n\n\nvoid solve()\n{\n    int no_of_pairs;\n    cin >> no_of_pairs;\n    \n    int no_of_vertices = 2*no_of_pairs;\n    int no_of_edges = no_of_vertices - 1;\n    \n    vector <Edge> E(no_of_edges + 1);\n    \n    tree.resize(no_of_vertices + 1);\n    subtree_size.resize(no_of_vertices + 1);\n    parent.resize(no_of_vertices + 1);\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        tree[i].clear();\n        \n        subtree_size[i] = 0;\n        \n        parent[i] = 0;\n    }\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        cin >> E[i].u >> E[i].v >> E[i].weight;\n        \n        tree[E[i].u].push_back(E[i].v);\n        tree[E[i].v].push_back(E[i].u);\n    }\n    \n    dfs(1, 0);\n    \n    long long minimum = 0, maximum = 0;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u_subtree, v_subtree;\n        \n        if(parent[E[i].v] == E[i].u)\n        {\n            v_subtree  = subtree_size[E[i].v];\n            u_subtree = no_of_vertices - v_subtree;\n        }\n        else\n        {\n            u_subtree = subtree_size[E[i].u];\n            v_subtree = no_of_vertices - u_subtree;\n        }\n        \n        int minimum_component = min(u_subtree, v_subtree);\n        \n        maximum += minimum_component*E[i].weight;\n        minimum += (u_subtree%2 == 1 || v_subtree%2 == 1 ? E[i].weight : 0);\n    }\n    \n    cout << minimum << \" \" << maximum << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Explanations/Suffix Three Explanation.txt",
    "content": "We can just use a switch-case construct to answer this problem.\n\n-----\n\nvoid solve()\n{\n    string word;\n    cin >> word;\n\n    switch(word[word.size() - 1])\n    {\n        case 'o': cout << \"FILIPINO\\n\"; return;\n        case 'u': cout << \"JAPANESE\\n\"; return;\n        case 'a': cout << \"KOREAN\\n\"; return;\n    }\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Programs/Azamon Web Services.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    string word_1, word_2;\n    cin >> word_1 >> word_2;\n    \n    for(int i = 0; i < word_1.size(); i++)\n    {\n        char minimum = word_1[i];\n        int position = i;\n        \n        for(int j = i + 1; j < word_1.size(); j++)\n        {\n            if(word_1[j] <= minimum)\n            {\n                minimum = word_1[j];\n                position = j;\n            }\n        }\n        \n        if(minimum < word_1[i])\n        {\n            swap(word_1[i], word_1[position]);\n            break;\n        }\n    }\n    \n    cout << (word_1 < word_2 ? word_1 : \"---\") << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Programs/Beingawesomeism.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nconst int MAX_N = 67;\nchar grid[MAX_N][MAX_N];\n\nint full_row_a(int r, int columns)\n{\n    for(int c = 0; c < columns; c++)\n    {\n        if(grid[r][c] != 'A')\n        {\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nint full_column_a(int rows, int c)\n{\n    for(int r = 0; r < rows; r++)\n    {\n        if(grid[r][c] != 'A')\n        {\n            return false;\n        }\n    }\n    \n    return true;\n}\n\nint all_p(int rows, int columns)\n{\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(grid[i][j] == 'A')\n            {\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\nint all_a(int rows, int columns)\n{\n    for(int i = 0; i < rows; i++)\n    {\n        for(int j = 0; j < columns; j++)\n        {\n            if(grid[i][j] == 'P')\n            {\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\nint corner_square(int rows, int columns)\n{\n    return (grid[0][0] == 'A' || grid[0][columns - 1] == 'A' ||\n            grid[rows - 1][0] == 'A' || grid[rows - 1][columns - 1] == 'A');\n}\n\nint corner_edge_square(int rows, int columns)\n{\n    for(int c = 0; c < columns; c++)\n    {\n        if(grid[0][c] == 'A' || grid[rows - 1][c] == 'A')\n        {\n            return true;\n        }\n    }\n    \n    for(int r = 0; r < rows; r++)\n    {\n        if(grid[r][0] == 'A' || grid[r][columns - 1] == 'A')\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nint full_corner_edges(int rows, int columns)\n{\n    if(full_row_a(0, columns) || full_row_a(rows - 1, columns))\n    {\n        return true;\n    }\n    \n    if(full_column_a(rows, 0) || full_column_a(rows, columns - 1))\n    {\n        return true;\n    }\n    \n    return false;\n}\n\nint any_full_edge(int rows, int columns)\n{\n    for(int i = 0; i < rows; i++)\n    {\n        if(full_row_a(i, columns))\n        {\n            return true;\n        }\n    }\n    \n    for(int i = 0; i < columns; i++)\n    {\n        if(full_column_a(rows, i))\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nvoid solve()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n    \n    for(int i = 0; i < rows; i++)\n    {\n        cin >> grid[i];\n    }\n    \n    if(all_p(rows, columns))\n    {\n        cout << \"MORTAL\\n\";\n        \n        return;\n    }\n    else if(all_a(rows, columns))\n    {\n        cout << \"0\\n\";\n        \n        return;\n    }\n    else if(full_corner_edges(rows, columns))\n    {\n        cout << \"1\\n\";\n        \n        return;\n    }\n    else if(corner_square(rows, columns) || any_full_edge(rows, columns))\n    {\n        cout << \"2\\n\";\n        \n        return;\n    }\n    else if(corner_edge_square(rows, columns))\n    {\n        cout << \"3\\n\";\n        \n        return;\n    }\n    else\n    {\n        cout << \"4\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Programs/Cut and Paste.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_steps;\n    cin >> no_of_steps;\n    \n    string S;\n    cin >> S;\n    \n    const int MAX = 1e6, MOD = 1e9 + 7;\n    long long length = S.size();\n    \n    for(int i = 0; i < no_of_steps; i++)\n    {\n        long long suffix = ((length - 1) - i + MOD)%MOD;\n        \n        if(S[i] == '1')\n        {\n            continue;\n        }\n        else if(S[i] == '2')\n        {\n            length = (length + suffix)%MOD;\n            \n            for(int j = 1; j <= suffix && S.size() <= min(MAX, no_of_steps); j++)\n            {\n                S += S[i + j];\n            }\n        }\n        else if(S[i] == '3')\n        {\n            length = (length + 2*suffix)%MOD;\n            \n            for(int k = 1; k <= 2; k++)\n            {\n                for(int j = 1; j <= suffix && S.size() <= min(MAX, no_of_steps); j++)\n                {\n                    S += S[i + j];\n                }\n            }\n        }\n    }\n    \n    cout << length << \"\\n\";\n}\n\nint main()\n{\n    ios_base::sync_with_stdio(false);\n    cin.tie(NULL);\n    \n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Programs/Jeremy Bearimy.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nstruct Edge\n{\n    int u, v;\n    long long weight;\n    \n    Edge(){};\n    \n    Edge(int U, int V, long long W)\n    {\n        u = U; v = V;\n        weight = W;\n    }\n};\n\nvector <vector <int> > tree;\nvector <int> subtree_size;\nvector <int> parent;\n\nvoid dfs(int v, int parent_v)\n{\n    parent[v] = parent_v;\n    subtree_size[v] = 1;\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i];\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        dfs(child_v, v);\n        \n        subtree_size[v] += subtree_size[child_v];\n    }\n}\n\nvoid solve()\n{\n    int no_of_pairs;\n    cin >> no_of_pairs;\n    \n    int no_of_vertices = 2*no_of_pairs;\n    int no_of_edges = no_of_vertices - 1;\n    \n    vector <Edge> E(no_of_edges + 1);\n    \n    tree.resize(no_of_vertices + 1);\n    subtree_size.resize(no_of_vertices + 1);\n    parent.resize(no_of_vertices + 1);\n    \n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        tree[i].clear();\n        \n        subtree_size[i] = 0;\n        \n        parent[i] = 0;\n    }\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        cin >> E[i].u >> E[i].v >> E[i].weight;\n        \n        tree[E[i].u].push_back(E[i].v);\n        tree[E[i].v].push_back(E[i].u);\n    }\n    \n    dfs(1, 0);\n    \n    long long minimum = 0, maximum = 0;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u_subtree, v_subtree;\n        \n        if(parent[E[i].v] == E[i].u)\n        {\n            v_subtree  = subtree_size[E[i].v];\n            u_subtree = no_of_vertices - v_subtree;\n        }\n        else\n        {\n            u_subtree = subtree_size[E[i].u];\n            v_subtree = no_of_vertices - u_subtree;\n        }\n        \n        int minimum_component = min(u_subtree, v_subtree);\n        \n        maximum += minimum_component*E[i].weight;\n        minimum += (u_subtree%2 == 1 || v_subtree%2 == 1 ? E[i].weight : 0);\n    }\n    \n    cout << minimum << \" \" << maximum << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/607 Div 1 + 2/Programs/Suffix Three.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    string word;\n    cin >> word;\n    \n    switch(word[word.size() - 1])\n    {\n        case 'o': cout << \"FILIPINO\\n\"; return;\n        case 'u': cout << \"JAPANESE\\n\"; return;\n        case 'a': cout << \"KOREAN\\n\"; return;\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n    \n    while(no_of_test_cases--)\n        solve();\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/609 Div 2/Explanations/Equation Explanation.txt",
    "content": "There are many ways to solve it but the simplest will use the observation\nthat if n is not composite then some multiple of n will be composite.\n\nn = (X + 1).n - X.n\n\nWe just need two values where we are sure X.n is composite.\n\nX = 8 does that.\n\nn = 9n - 8n\n\n------\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    cout << 9*n << \" \" << 8*n << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/609 Div 2/Programs/Equation.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n    \n    cout << 9*n << \" \" << 8*n << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Explanations/Antipalindrome Alternate Solution Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUT345\r\n\r\nThe constraints are small enough to allow for an O(n^3) solution where all substrings are checked but there's an elegant O(n) solution !\r\n\r\nCase 1:\r\n\r\n\tS is not a palindrome, then answer = n.\r\n\r\nCase 2:\r\n\r\n\tS is a palindrome. \r\n\r\n\tthen we check S[1, ... , n - 1] and S[2, ... n]\r\n\r\n\tIf either of these strings are not a palindrome, then the answer = n - 1\r\n\r\nCase 3:\r\n\r\n\tS, S[1, ... , n - 1] and S[2, ... , n] are all palindromes. \r\n\r\nIn that case, \r\n\r\nNotice \r\n\r\nS[1] = S[n], from 1\r\n \r\nS[2] = S[n], from 3\r\n\r\nAlso, S[2] = S[n - 1], from 1\r\n\r\nAnd S[1] = S[n - 1], from 2\r\n\r\nSo, this implies S[1] = S[2] = S[n - 1] = S[n - 2]\r\n\r\nSimilarly, we see from 1, that S[i] = S[n - i]\r\nAnd S[i] = S[n - 1 - i]\r\n\r\nSo, S[n - i] = S[n - 1 - i]\r\n\r\nWe continually apply the above inequality to show that all characters are the same. \r\n\r\nIf that's the case, then ANY substring will be a palindrome. \r\n\r\n--------------------------------\r\n\r\nTherefore, the answer is either n, n - 1 or 0.\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n    int length = S.size();\r\n\r\n    if(!is_palindrome(S, 0, length - 1))\r\n        cout << length;\r\n    else if(!is_palindrome(S, 0, length - 2) || !is_palindrome(S, 1, length - 1))\r\n        cout << length - 1;\r\n    else\r\n        cout << \"0\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Explanations/Antipalindrome Explanation.txt",
    "content": "N is very small. Check all choose(N, 2) substrings if they're palindromes, starting from the longest substrings.\r\n\r\nThis is O(N^3). \r\n\r\n---------------------------------------\r\n\r\nint is_palindrome(string S)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n        if(S[i] != S[S.size() - 1 - i])\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    for(int length = S.size(); length >= 1; length--)\r\n    {\r\n        for(int i = 0; i + length - 1 < S.size(); i++)\r\n        {\r\n            if(!is_palindrome(S.substr(i, length)))\r\n            {\r\n                cout << length;\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"0\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Explanations/Bookshelves Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTmQ6\r\n\r\nLet us answer, a related question. \r\n\r\nIf given a number x, how do we determine if it is possible to divide the numbers into K segments such that the bitwise AND of the sum of the K segments = x ? \r\n\r\nEach segment[L, R] has to obey the following property - \r\n\r\n(Sum[R] - Sum[L - 1])&x = x, \r\n\r\ni.e. all the bits that are set in x, must be set in the sum from [L, ... , R] for each of the K segments !\r\n\r\nWe can check this with dynamic programming. \r\n\r\nLet f(n, k) = true, if it is possible for the bitwise-AND of the sums of the first K segments = x, with the last segment ending on n.\r\nAnd f(n, k) = false, otherwise. \r\n\r\nf(R, K) = true, if there exists some L < R, such that \r\n\r\nSum[L ... R]&x = x and f(L - 1, K - 1) = true.\r\n\r\nIt takes us O(N^2 K) time to answer one such question. \r\n\r\nNow, let us be greedy and start from i = 60, and check if answer + 2^i is possible, if it is then the answer = answer + 2^i.\r\n\r\nThis is always optimal.\r\n\r\nOverall Complexity = O(log(S) N^2 K)\r\n\r\n-----------------------------------------------\r\n\r\nint is_possible(LL goal)\r\n{\r\n    memset(possible, false, sizeof(possible));\r\n\r\n    possible[0][0] = true;\r\n\r\n    for(int part = 1; part <= no_of_parts; part++)\r\n    {\r\n        for(int right = 1; right <= no_of_elements; right++)\r\n        {\r\n            for(int left = 0; left < right; left++)\r\n            {\r\n                if( possible[left][part - 1] && ( ( (sum[right] - sum[left])&goal ) == goal ) )\r\n                {\r\n                    possible[right][part] = true;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    return possible[no_of_elements][no_of_parts];\r\n}\r\n\r\nint main()\r\n{\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_parts);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    sum[0] = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum[i] = sum[i - 1] + A[i];\r\n\r\n    LL answer = 0;\r\n\r\n    for(int bit = MAX_BIT; bit >= 0; bit--)\r\n    {\r\n        if(is_possible(answer|(1LL << bit)))\r\n        {\r\n            answer |= (1LL << bit);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Explanations/Businessman Problems Explanation.txt",
    "content": "For every item x, \r\n\r\nwe add max{A_cost[x], B_cost[x]}\r\n\r\nIf x does not exist in either A or B, then it is 0. \r\n\r\nWe can use maps to do this !\r\n\r\nWhile reading A_cost, just read in cost[x].\r\n\r\nWhile reading B_cost, then cost[x] = max{cost[x], cost}\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a_elements;\r\n    scanf(\"%d\", &a_elements);\r\n\r\n    map <int, int> cost;\r\n    for(int i = 1; i <= a_elements; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n        cost[element_i] = cost_i;\r\n    }\r\n\r\n    int b_elements;\r\n    scanf(\"%d\", &b_elements);\r\n\r\n    for(int i = 1; i <= b_elements; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n\r\n        cost[element_i] = max(cost[element_i], cost_i);\r\n    }\r\n\r\n    long long total_cost = 0;\r\n    for(map <int, int> :: iterator it = cost.begin(); it != cost.end(); it++)\r\n    {\r\n        total_cost += it->second;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Explanations/Useful Decomposition Explanation.txt",
    "content": "We root the tree at a vertex V, and we make a path from V to each of it's leaves. \n\nWe can always decompose a tree, unless V has some descendant that has more than one child. \n\nSo, here's what we do \n\n1. If the graph has more than one vertex which has 3 or more edges, then it is not possible. \n\n2. If the graph has exactly one vertex which has 3 or more edges, then we root the tree at that vertex. \nIf the graph has no such vertex, then it means every vertex has at most two edges (one parent and one child). We can arbitrarily root the graph at any of these vertices, then.\n\nOnce we have a root, then make a path from the root the leaf vertex by going through each of the root's children.\n\nNote - You don't need to minimise the number of paths. Otherwise, the root is the vertex which has degree > 2, or the vertex with degree = 1, if all vertices have degree <= 2\n\nLet us suppose we were asked to minimise or maximise the number of paths. \n\nCall a vertex a root if it's degree > 2.\n\nCase 1 : There is atleast one vertex with degree > 2\n\nIf there is more than one root, then the solution stays the same as a decomposition is not possible. If there was exactly one root, then we have to make it the root and the solution stays the same. Making any other vertex the root will not satisfy the given conditions.\n\nCase 2 : All vertices have degree <= 2\n\nTo minimise the number of paths, we must choose a leaf vertex since it has only one child and it will result in 1 simple path from one leaf to another.\n\nFor maximising the number of paths, we will have to pick any non-leaf vertex which has a degree of 2. There will be two paths, one to each leaf.\n\n----------------------------------------\n\nint dfs_leaf_from(int v, int parent)\n{\n    if(graph[v].size() == 1)\n        return v;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n\n        if(child == parent) continue;\n\n        return dfs_leaf_from(child, v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n\n    for(int i = 1; i < no_of_vertices; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n\n    int no_of_roots = 0, root = 1;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(graph[i].size() > 2)\n        {\n            no_of_roots++;\n            root = i;\n        }\n    }\n\n    if(no_of_roots > 1)\n    {\n        printf(\"No\\n\");\n        return 0;\n    }\n\n    printf(\"Yes\\n\");\n\n    int no_of_paths = graph[root].size();\n\n    printf(\"%d\\n\", no_of_paths);\n\n    for(int i = 0; i < graph[root].size(); i++)\n    {\n        int child = graph[root][i];\n\n        int leaf = dfs_leaf_from(child, root);\n\n        printf(\"%d %d\\n\", root, leaf);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Programs/Antipalindrome Alternate Solution.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint is_palindrome(string S, int left, int right)\r\n{\r\n    while(left <= right)\r\n    {\r\n        if(S[left++] != S[right--])\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n    int length = S.size();\r\n\r\n    if(!is_palindrome(S, 0, length - 1))\r\n        cout << length;\r\n    else if(!is_palindrome(S, 0, length - 2) || !is_palindrome(S, 1, length - 1))\r\n        cout << length - 1;\r\n    else\r\n        cout << \"0\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Programs/Antipalindrome.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint is_palindrome(string S)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n        if(S[i] != S[S.size() - 1 - i])\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    for(int length = S.size(); length >= 1; length--)\r\n    {\r\n        for(int i = 0; i + length - 1 < S.size(); i++)\r\n        {\r\n            if(!is_palindrome(S.substr(i, length)))\r\n            {\r\n                cout << length;\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"0\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Programs/Bookshelves.cpp",
    "content": "#include <cstdio>\r\n#include <cstring>\r\n\r\nconst int MAX_BIT = 61, MAX_N = 55;\r\ntypedef long long LL;\r\n\r\nint no_of_elements, no_of_parts;\r\nLL A[MAX_N], sum[MAX_N];\r\nint possible[MAX_N][MAX_N];\r\n\r\nint is_possible(LL goal)\r\n{\r\n    memset(possible, false, sizeof(possible));\r\n\r\n    possible[0][0] = true;\r\n\r\n    for(int part = 1; part <= no_of_parts; part++)\r\n    {\r\n        for(int right = 1; right <= no_of_elements; right++)\r\n        {\r\n            for(int left = 0; left < right; left++)\r\n            {\r\n                if( possible[left][part - 1] && ( ( (sum[right] - sum[left])&goal ) == goal ) )\r\n                {\r\n                    possible[right][part] = true;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    return possible[no_of_elements][no_of_parts];\r\n}\r\n\r\nint main()\r\n{\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_parts);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    sum[0] = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum[i] = sum[i - 1] + A[i];\r\n\r\n    LL answer = 0;\r\n\r\n    for(int bit = MAX_BIT; bit >= 0; bit--)\r\n    {\r\n        if(is_possible(answer|(1LL << bit)))\r\n        {\r\n            answer |= (1LL << bit);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Programs/Businessman Problems.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int a_element_is;\r\n    scanf(\"%d\", &a_element_is);\r\n\r\n    map <int, int> cost;\r\n    for(int i = 1; i <= a_element_is; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n        cost[element_i] = cost_i;\r\n    }\r\n\r\n    int b_element_is;\r\n    scanf(\"%d\", &b_element_is);\r\n\r\n    for(int i = 1; i <= b_element_is; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n\r\n        cost[element_i] = max(cost[element_i], cost_i);\r\n    }\r\n\r\n    long long total_cost = 0;\r\n    for(map <int, int> :: iterator it = cost.begin(); it != cost.end(); it++)\r\n    {\r\n        total_cost += it->second;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Avito Code Challenge 2018/Programs/Useful Decomposition.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 15;\nvector <int> graph[MAX_N];\n\nint dfs_leaf_from(int v, int parent)\n{\n    if(graph[v].size() == 1)\n        return v;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n\n        if(child == parent) continue;\n\n        return dfs_leaf_from(child, v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n\n    for(int i = 1; i < no_of_vertices; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n\n    int no_of_roots = 0, root = 1;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(graph[i].size() > 2)\n        {\n            no_of_roots++;\n            root = i;\n        }\n    }\n\n    if(no_of_roots > 1)\n    {\n        printf(\"No\\n\");\n        return 0;\n    }\n\n    printf(\"Yes\\n\");\n\n    int no_of_paths = graph[root].size();\n\n    printf(\"%d\\n\", no_of_paths);\n\n    for(int i = 0; i < graph[root].size(); i++)\n    {\n        int child = graph[root][i];\n\n        int leaf = dfs_leaf_from(child, root);\n\n        printf(\"%d %d\\n\", root, leaf);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Avito Cool Challenge 2018/Explanation/Colourful Bricks Explanation.txt",
    "content": "Blog Link - https://qr.ae/TUtWEt\n\nThe number of ways of making the K + 1 groups is given by stars and bars - C(N - 1, K)\n\nThe number of ways to colour them is M (M - 1)^K\n\n---------------\n\nint main()\n{\n    int no_of_bricks, no_of_colours, no_of_divisions;\n    scanf(\"%d %d %d\", &no_of_bricks, &no_of_colours, &no_of_divisions);\n\n    int no_of_groups = no_of_divisions + 1;\n\n    const int MOD = 998244353;\n    long long group_size_count = choose(no_of_bricks - 1, no_of_divisions, MOD);\n    long long colour_distribution_count = (no_of_colours* power_mod(no_of_colours - 1,no_of_groups - 1, MOD))%MOD;\n\n    long long answer = (group_size_count*colour_distribution_count)%MOD;\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Avito Cool Challenge 2018/Explanation/Definite Game Explanation.txt",
    "content": "Whatever N is, we can subtract with N - 1 and get 1. \r\n\r\nThe only exception is 2. Because it is the only integer for which N - 1 | N. \r\n\r\n------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    int minimum_value = (n <= 2 ? n : 1);\r\n    cout << minimum_value;\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Avito Cool Challenge 2018/Programs/Colourful Bricks.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nlong long power_mod(long long base, long long power, long long mod)\n{\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*base)%mod;\n\n        base = (base*base)%mod;\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nlong long inverse(long long n, long long mod)\n{\n    return power_mod(n, mod - 2, mod);\n}\n\nlong long choose(long long n, long long r, long long mod)\n{\n    vector <long long> factorial(n + 1);\n    factorial[0] = 1;\n    for(int i = 1; i <= n; i++)\n        factorial[i] = (i*factorial[i - 1])%mod;\n\n    vector <long long> inverse_factorial(n + 1); // i*(i - 1)! = i! => i^(-1) (i - 1)!^(-1) = i!^(-1)\n    inverse_factorial[n] = inverse(factorial[n], mod);\n    for(int i = n - 1; i >= 0; i--)\n        inverse_factorial[i] = ((i + 1)*inverse_factorial[i + 1])%mod;\n\n    long long numerator = factorial[n];\n    long long denominator_inverse = (inverse_factorial[r]*inverse_factorial[n - r])%mod;\n\n    return (numerator*denominator_inverse)%mod;\n}\n\nint main()\n{\n    int no_of_bricks, no_of_colours, no_of_divisions;\n    scanf(\"%d %d %d\", &no_of_bricks, &no_of_colours, &no_of_divisions);\n\n    int no_of_groups = no_of_divisions + 1;\n\n    const int MOD = 998244353;\n    long long group_size_count = choose(no_of_bricks - 1, no_of_divisions, MOD);\n    long long colour_distribution_count = (no_of_colours* power_mod(no_of_colours - 1,no_of_groups - 1, MOD))%MOD;\n\n    long long answer = (group_size_count*colour_distribution_count)%MOD;\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Avito Cool Challenge 2018/Programs/Definite Game.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    int minimum_value = (n <= 2 ? n : 1);\r\n    cout << minimum_value;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Barcelona Bootcamp 2018/Explanation/Maximum Sum of Digits Explanation.txt",
    "content": "We try to maximise the number of 9s in the digit sum \r\n\r\n\r\nLet A = all 9s except the first digit. \r\n\r\nB = N - A\r\n\r\n-----------------------\r\n\r\nint main()\r\n{\r\n    string N;\r\n    cin >> N;\r\n\r\n    string A;\r\n    A = N[0] - 1;\r\n    for(int i = 1; i < N.size(); i++)\r\n        A += '9';\r\n\r\n    long long n = to_int(N), a = to_int(A);\r\n    long long b = n - a;\r\n\r\n    cout << digit_sum(a) + digit_sum(b);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Barcelona Bootcamp 2018/Explanation/Phone Numbers Explanation.txt",
    "content": "We can have at most N/11 strings. \nThe number of strings can't be more than the number of 8s. \n\nIf the number of 8s > N/11, then there will be N/11 strings.\nIf N/11 > number of 8s, then there will be as many strings as there are 8s. \n\nIn total number of strings = min(number of 8s, N/11)\n\n-----------------------\n\n#include <iostream>\n#include <string>\n\n#define min(a, b) (a < b ? a : b)\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    int no_of_8 = 0;\n    for(int i = 0; i < length; i++)\n        no_of_8 += (S[i] == '8');\n\n    cout << min(no_of_8, length/11) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Barcelona Bootcamp 2018/Explanation/Social Circles Explanation.txt",
    "content": "Let us imagine everyone is sitting at their own table at first. \r\n\r\nThey will need max(l, r) + 1 chairs. \r\n\r\nNow, what happens if we want to combine first and second person to one table. \r\n\r\nWe will need ... Max(l[1], r[2]) + Max(l[2], r[1]) + 2\r\n\r\nThis is equal to = Max(l[1], r[2]) + 1 + Max(l[2], r[1]) + 1 chairs. \r\n\r\nThis is equal to what happens when there is a new person (l[1], r[2]) is sitting on his own table. \r\n\r\n------------------------------------\r\n\r\nLet Next(i) be the person sitting next to person i\r\n\r\nNow the number of chairs will be equal to \r\n\r\nN + sum[max{Left(i), Right(Next(i))}]\r\n\r\nNow we will prove that it is always optimal to match the smallest left to the smallest right. \r\n\r\nIf we have matched l2 to r1 and l1 to something else - rx, \r\n\r\nNote that we cannot get more chairs by swapping and matching (l1, r1) and (l2, rx)\r\n\r\n----------------------------\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_guests;\r\n    scanf(\"%d\", &no_of_guests);\r\n\r\n    vector <int> left(no_of_guests + 1, 0), right(no_of_guests + 1, 0);\r\n    for(int i = 1; i <= no_of_guests; i++)\r\n        scanf(\"%d %d\", &left[i], &right[i]);\r\n\r\n    sort(all(left));\r\n    sort(all(right));\r\n\r\n    long long no_of_chairs = 0;\r\n    for(int i = 1; i <= no_of_guests; i++)\r\n        no_of_chairs += max(left[i], right[i]) + 1;\r\n\r\n    printf(\"%I64d\\n\", no_of_chairs);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Barcelona Bootcamp 2018/Programs/Maximum Sum of Digits.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint digit_sum(long long n)\r\n{\r\n    int sum = 0;\r\n\r\n    while(n)\r\n    {\r\n        sum += n%10;\r\n        n = n/10;\r\n    }\r\n\r\n    return sum;\r\n}\r\n\r\nlong long to_int(string &S)\r\n{\r\n    long long n = 0;\r\n\r\n    for(int i = 0; i < S.size(); i++)\r\n        n = n*10 + (S[i] - '0');\r\n\r\n    return n;\r\n}\r\n\r\nint main()\r\n{\r\n    string N;\r\n    cin >> N;\r\n\r\n    string A;\r\n    A = N[0] - 1;\r\n    for(int i = 1; i < N.size(); i++)\r\n        A += '9';\r\n\r\n    long long n = to_int(N), a = to_int(A);\r\n    long long b = n - a;\r\n\r\n    cout << digit_sum(a) + digit_sum(b);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Barcelona Bootcamp 2018/Programs/Phone Numbers.cpp",
    "content": "#include <iostream>\n#include <string>\n\n#define min(a, b) (a < b ? a : b)\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    int no_of_8 = 0;\n    for(int i = 0; i < length; i++)\n        no_of_8 += (S[i] == '8');\n\n    cout << min(no_of_8, length/11) << endl;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Barcelona Bootcamp 2018/Programs/Social Circles.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_guests;\r\n    scanf(\"%d\", &no_of_guests);\r\n\r\n    vector <int> left(no_of_guests + 1, 0), right(no_of_guests + 1, 0);\r\n    for(int i = 1; i <= no_of_guests; i++)\r\n        scanf(\"%d %d\", &left[i], &right[i]);\r\n\r\n    sort(all(left));\r\n    sort(all(right));\r\n\r\n    long long no_of_chairs = 0;\r\n    for(int i = 1; i <= no_of_guests; i++)\r\n        no_of_chairs += max(left[i], right[i]) + 1;\r\n\r\n    printf(\"%I64d\\n\", no_of_chairs);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Explanations/Magic Stones Explanation.txt",
    "content": "Quora Blog Link - https://qr.ae/TUyM1P\r\n\r\nWhen we perform an operation, we swap adjacent elements of the difference array. \r\n\r\nIf it is possible to go from A to B, then their difference arrays must be permutations of each other and the first elements must be equal. \r\n\r\n----------\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL is_permutation(vector <LL> A, vector <LL> B)\r\n{\r\n    sort(all(A));\r\n    sort(all(B));\r\n\r\n    int is_equal = (A.size() == B.size() ? true : false);\r\n\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            is_equal = false;\r\n        }\r\n    }\r\n\r\n    return is_equal;\r\n}\r\n\r\nvoid read(vector <LL> &A, int n)\r\n{\r\n    for(int i = 0; i < n; i++)\r\n        cin >> A[i];\r\n}\r\n\r\nvoid get_difference(vector <LL> &A, vector <LL> &D)\r\n{\r\n    for(int i = 0; i + 1 < A.size(); i++)\r\n    {\r\n        D.push_back(A[i + 1] - A[i]);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <LL> A(no_of_elements);\r\n    read(A, no_of_elements);\r\n\r\n    vector <LL> B(no_of_elements);\r\n    read(B, no_of_elements);\r\n\r\n    vector <LL> beginning_difference;\r\n    get_difference(A, beginning_difference);\r\n\r\n    vector <LL> ending_difference;\r\n    get_difference(B, ending_difference);\r\n\r\n    cout << (A[0] == B[0] && is_permutation(beginning_difference, ending_difference) ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Explanations/Meaningless Operations Explanation.txt",
    "content": "Blog Link - https://qr.ae/TUreZ2\n\nIf X = 2^N - 1, then precompute the answer offline for all N from 1 to 25. \n\nElse, the answer is always 2^N - 1, where N is the number of bits in X. We can get this by choosing Y as the complement of X.\n\nX xor Y = 2^N - 1\nX and Y = 0\n\ngcd(0, 2^N - 1) = 2^N - 1\n\nThis is the highest possible because the XOR and AND of two N bit number cannot have more than N bits. \n\nAnd gcd(a, b) <= max(a, b)\n\n-----------------\n\nvoid solve()\n{\n    int x;\n    cin >> x;\n\n    int max_gcd = (is_all_ones(x) ? answer[x] : all_ones(no_of_bits(x)));\n    cout << max_gcd << \"\\n\";\n}\n\nvoid precompute()\n{\n    answer[1] = 0;\n    answer[3] = 1;\n    answer[7] = 1;\n    answer[15] = 5;\n    answer[31] = 1;\n    answer[63] = 21;\n    answer[127] = 1;\n    answer[255] = 85;\n    answer[511] = 73;\n    answer[1023] = 341;\n    answer[2047] = 89;\n    answer[4095] = 1365;\n    answer[8191] = 1;\n    answer[16383] = 5461;\n    answer[32767] = 4681;\n    answer[65535] = 21845;\n    answer[131071] = 1;\n    answer[262143] = 87381;\n    answer[524287] = 1;\n    answer[1048575] = 349525;\n    answer[2097151] = 299593;\n    answer[4194303] = 1398101;\n    answer[8388607] = 178481;\n    answer[16777215] = 5592405;\n    answer[33554431] = 1082401;\n\n}\n\nint main()\n{\n    precompute();\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Explanations/Parity Explanation.txt",
    "content": "N = \\sum b^K a_k\r\n\r\nWe merely find the parity by keeping track of each term mod 2. \r\n\r\nTake care that when k = 0, there is no term of b. It is just a_0\r\n\r\nIf b is even, then all powers of b are even and if b is odd, then all powers of b are odd.\r\n\r\n-----------------\r\n\r\nint main()\r\n{\r\n    int base, no_of_digits;\r\n    cin >> base >> no_of_digits;\r\n    int sum_parity = 0;\r\n\r\n    for(int d = no_of_digits - 1; d >= 0; d--)\r\n    {\r\n        int digit;\r\n        cin >> digit;\r\n\r\n        int digit_parity = digit%2;\r\n        int base_parity = base%2;\r\n\r\n        if(d > 0)\r\n            sum_parity += (digit_parity*base_parity);\r\n        else\r\n            sum_parity += digit_parity;\r\n    }\r\n\r\n    cout << (sum_parity%2 == 0 ? \"Even\\n\" : \"Odd\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Explanations/Tape Explanation.txt",
    "content": "First, let us sort the N points given to us - A1, A2, ... , An. \r\n\r\nNext, let us take their distances - \r\n\r\nWe will construct a difference array - D1, D2, ... , D(n - 1)\r\n\r\nDi = Ai - A(i - 1)\r\n\r\n-----------------\r\n\r\nWe will sort the N - 1 differences.\r\n\r\nWe will then be greedy. \r\n\r\nWe will start our first part from point 1, and then go right. If the distance between our current point Ai and next A(i + 1) is one of the (k - 1) greatest distances, then we will not use it.\r\n\r\n--------\r\n\r\nHere is how we implement it -\r\n\r\nIf a difference d belongs to one of the K - 1 greatest differences, then mark the ending i as 'not allowed'. \r\n\r\nThen start scanning the array A from 1 to N. Keep two pointers left and right. \r\n\r\nleft points to the first point which we haven't counted yet and right points to the last point that is allowed from left. Maintain this invariant. \r\n\r\nWe stop whenever right hits a point that is not allowed or reaches the end of the array. \r\n\r\nAfter we count the current segment [L, R], we set L = R + 1 and R to L + 1.\r\n\r\n-------------\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_points, total_length, max_parts;\r\n    cin >> no_of_points >> total_length >> max_parts;\r\n\r\n    vector <int> A(no_of_points);\r\n    for(int i = 0; i < no_of_points; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n\r\n    vector <Point> X;\r\n    for(int i = 1; i < no_of_points; i++)\r\n        X.push_back(Point(i, A[i] - A[i - 1]));\r\n\r\n    sort(all(X));\r\n\r\n    vector <int> allowed(no_of_points, true);\r\n\r\n    for(int count = 1, i = X.size() - 1; i >= 0 && count < max_parts; count++, i--)\r\n    {\r\n        allowed[X[i].position] = false;\r\n    }\r\n\r\n    int left = 0, right = 1;\r\n    int total_length_used = 0;\r\n\r\n    while(left < no_of_points)\r\n    {\r\n        while(right < no_of_points && allowed[right])\r\n        {\r\n            right++;\r\n        }\r\n\r\n        right--;\r\n\r\n        total_length_used += (A[right] - A[left] + 1);\r\n\r\n        left = right + 1;\r\n        right = left + 1;\r\n    }\r\n\r\n    cout << total_length_used << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Programs/Magic Stones.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\ntypedef long long LL;\n\nLL is_permutation(vector <LL> A, vector <LL> B)\n{\n    sort(all(A));\n    sort(all(B));\n\n    int is_equal = (A.size() == B.size() ? true : false);\n\n    for(int i = 0; i < A.size(); i++)\n    {\n        if(A[i] != B[i])\n        {\n            is_equal = false;\n        }\n    }\n\n    return is_equal;\n}\n\nvoid read(vector <LL> &A, int n)\n{\n    for(int i = 0; i < n; i++)\n        cin >> A[i];\n}\n\nvoid get_difference(vector <LL> &A, vector <LL> &D)\n{\n    for(int i = 0; i + 1 < A.size(); i++)\n    {\n        D.push_back(A[i + 1] - A[i]);\n    }\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <LL> A(no_of_elements);\n    read(A, no_of_elements);\n\n    vector <LL> B(no_of_elements);\n    read(B, no_of_elements);\n\n    vector <LL> beginning_difference;\n    get_difference(A, beginning_difference);\n\n    vector <LL> ending_difference;\n    get_difference(B, ending_difference);\n\n    cout << (A[0] == B[0] && is_permutation(beginning_difference, ending_difference) ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Programs/Meaningless Operations.cpp",
    "content": "#include <iostream>\n#include <map>\n\nusing namespace std;\n\nmap <int, int> answer;\n\nint all_ones(int n)\n{\n    return ( (1 << n) - 1);\n}\n\nint no_of_bits(int n)\n{\n    int bit_count = 0;\n\n    while(n)\n    {\n        bit_count++;\n\n        n /= 2;\n    }\n\n    return bit_count;\n}\n\nint is_all_ones(int n)\n{\n    return (all_ones(no_of_bits(n)) == n);\n}\n\nvoid solve()\n{\n    int x;\n    cin >> x;\n\n    int max_gcd = (is_all_ones(x) ? answer[x] : all_ones(no_of_bits(x)));\n    cout << max_gcd << \"\\n\";\n}\n\nvoid precompute()\n{\n    answer[1] = 0;\n    answer[3] = 1;\n    answer[7] = 1;\n    answer[15] = 5;\n    answer[31] = 1;\n    answer[63] = 21;\n    answer[127] = 1;\n    answer[255] = 85;\n    answer[511] = 73;\n    answer[1023] = 341;\n    answer[2047] = 89;\n    answer[4095] = 1365;\n    answer[8191] = 1;\n    answer[16383] = 5461;\n    answer[32767] = 4681;\n    answer[65535] = 21845;\n    answer[131071] = 1;\n    answer[262143] = 87381;\n    answer[524287] = 1;\n    answer[1048575] = 349525;\n    answer[2097151] = 299593;\n    answer[4194303] = 1398101;\n    answer[8388607] = 178481;\n    answer[16777215] = 5592405;\n    answer[33554431] = 1082401;\n\n}\n\nint main()\n{\n    precompute();\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Programs/Parity.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int base, no_of_digits;\r\n    cin >> base >> no_of_digits;\r\n    int sum_parity = 0;\r\n\r\n    for(int d = no_of_digits - 1; d >= 0; d--)\r\n    {\r\n        int digit;\r\n        cin >> digit;\r\n\r\n        int digit_parity = digit%2;\r\n        int base_parity = base%2;\r\n\r\n        if(d > 0)\r\n            sum_parity += (digit_parity*base_parity);\r\n        else\r\n            sum_parity += digit_parity;\r\n    }\r\n\r\n    cout << (sum_parity%2 == 0 ? \"Even\\n\" : \"Odd\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/CodeForces Global Round 1/Programs/Tape.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct Point\r\n{\r\n    int position, difference;\r\n\r\n    Point(int p, int d)\r\n    {\r\n        position = p, difference = d;\r\n    }\r\n\r\n    int operator <(const Point &P)\r\n    {\r\n        return (difference < P.difference);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_points, total_length, max_parts;\r\n    cin >> no_of_points >> total_length >> max_parts;\r\n\r\n    vector <int> A(no_of_points);\r\n    for(int i = 0; i < no_of_points; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n\r\n    vector <Point> D;\r\n    for(int i = 1; i < no_of_points; i++)\r\n        D.push_back(Point(i, A[i] - A[i - 1]));\r\n\r\n    sort(all(D));\r\n\r\n    vector <int> allowed(no_of_points, true);\r\n\r\n    for(int count = 1, i = D.size() - 1; i >= 0 && count < max_parts; count++, i--)\r\n    {\r\n        allowed[D[i].position] = false;\r\n    }\r\n\r\n    int left = 0, right = 1;\r\n    int total_length_used = 0;\r\n\r\n    while(left < no_of_points)\r\n    {\r\n        while(right < no_of_points && allowed[right])\r\n        {\r\n            right++;\r\n        }\r\n\r\n        right--;\r\n\r\n        total_length_used += (A[right] - A[left] + 1);\r\n\r\n        left = right + 1;\r\n        right = left + 1;\r\n    }\r\n\r\n    cout << total_length_used << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Explanations/Another One Bites the Dust Explanation.txt",
    "content": "We will match all the As with Bs and then append all the 'AB's. \n\nIf we have an extra A, we will put it at the end. \n\nIf we have an extra B, we will put it at the beginning.\n\n---\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    long long A, B, AB;\n    cin >> A >> B >> AB;\n\n    long long answer = (B != A ? 1 + 2*AB + 2*min(A, B) : 2*min(A, B) + 2*AB);\n    cout << answer;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Explanations/Born This Way Explanation.txt",
    "content": "If we delete k flights in total, we will be deleting\na from A and (b = k - a) from B.\n\nWe will go over all possibilities and choose the best result\n\nIt is always best to delete the first 'a' flights from A\n\nAfter that, the time we reach the airport will be A[a + 1] + T[a].\n\nWe will delete the immediate next (k - a) flights from B.\n\nWe can find out the closest b, such that B[b] >= A[a + 1] + T[a]\nand then delete [b, b + (k - a) - 1] flights\n\nIf we can delete all flights in A or all flights in B, we are done\n\n------\n\nint main()\n{\n    int A_to_B, B_to_C, time_A_to_B, time_B_to_C, deleted;\n    cin >> A_to_B >> B_to_C >> time_A_to_B >> time_B_to_C >> deleted;\n\n    vector <long long> A(A_to_B + 1);\n    for(int i = 1; i <= A_to_B; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> B(B_to_C + 1);\n    for(int i = 1; i <= B_to_C; i++)\n    {\n        cin >> B[i];\n    }\n\n    const long long oo = 1e15;\n    long long max_time = (deleted >= A_to_B || deleted >= B_to_C ? oo : 0);\n    A.push_back(oo);\n    B.push_back(oo);\n\n    for(int a_deletes = 0; a_deletes <= min(deleted, A_to_B - 1); a_deletes++)\n    {\n        long long reached_B = A[a_deletes + 1] + time_A_to_B;\n\n        int first_b = upper_bound(B.begin(), B.end(), reached_B - 1) - B.begin();\n\n        int b_deletes = deleted - a_deletes + first_b - 1;\n\n        if(b_deletes > B_to_C)\n        {\n            max_time = oo;\n            break;\n        }\n\n        max_time = max(max_time, B[b_deletes + 1] + time_B_to_C);\n    }\n\n    cout << (max_time >= oo ? -1 : max_time) << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Explanations/Crazy Diamond Explanation.txt",
    "content": "For every element x, let P(x) denote the position where x currently is. \n\nWe will scan the array from i = 1 to N. \n\nIf (i = A[i]), we will not do anything. \n\nOtherwise, we will find out the current position of i, it is P(i). \n\nWe want to swap A(i) and A(P(i)). We also want to update the array P. \n\nTo make things simpler, let us abstract the complexity and create a function for swapping elements - \n\nvoid arrange_swaps(int start, int destination)\n{\n    int original_start = A[start], original_destination = A[destination];\n    swap(A[start], A[destination]);\n\n    position[original_start] = destination;\n    position[original_destination] = start;\n\n    swaps.push_back(make_pair(start, destination));\n}\n\n---------\n\nNow, let us see how we will swap. \n\nLet L = min{i, P(i)} and R = max{i, P(i)}\n\nWe have to swap A[L] and A[R].\n\n---\n\nCase 1 - Both L and R are in the first half\n\nWe can swap like this - \n\nswap(A[R], A[N])\nswap(A[N], A[L]) => Now, A[R] has reached A[L]\nswap(A[N], A[R]) => Now, A[L] has reached A[R]\n\n------\n\nCase 2 - Both L and R are in the second half\n\nswap(A[L], A[1])\nswap(A[1], A[R]) => Now, A[L] has reached A[R]\nswap(A[1], A[L]) => Now, A[R] has reached A[L]. \n\nAlso, A[1] has reached it's correct position again. \n\nPlease note that when we are at position i, A[1, ... i - 1] is sorted. So A[1] will hold 1. We need to take care that A[1] contains 1 after we are done.\n\nWe do not need to worry about this in Case 1 since A[N] need not hold the correct value - N\n\n------\n\nCase 3 - L and R are in different halves\n\nHere, we will utilise both ends. \n\nswap(A[L], A[N])\nswap(A[N], A[1])\nswap(A[1], A[R]) => Now, A[L] has reached A[R]\n\nswap(A[1], A[N]) => Now, the correct value of A[1] has been put back in A[1]\nswap(A[N], A[L]) => Now, A[R] has reached A[L]\n\n------\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i =1 ; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    for(int i = 1; i <= no_of_elements; i++)\n        position[A[i]] = i;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(i == A[i])\n            continue;\n\n        int target = i;\n        int target_position = position[target];\n\n        int left = min(target_position, i);\n        int right = max(target_position, i);\n\n        if(right - left >= no_of_elements/2)\n        {\n            arrange_swaps(i, target_position);\n\n            continue;\n        }\n\n        if(left > no_of_elements/2)\n        {\n            arrange_swaps(1, left);\n            arrange_swaps(1, right);\n            arrange_swaps(left, 1);\n        }\n        else if(right <= no_of_elements/2)\n        {\n            arrange_swaps(right, no_of_elements);\n            arrange_swaps(no_of_elements, left);\n        }\n        else\n        {\n            arrange_swaps(left, no_of_elements);\n            arrange_swaps(no_of_elements, 1);\n            arrange_swaps(1, right);\n\n            arrange_swaps(1, no_of_elements);\n            arrange_swaps(no_of_elements, left);\n        }\n    }\n\n    cout << swaps.size() << \"\\n\";\n    for(int i = 0; i < swaps.size(); i++)\n        cout << swaps[i].first << \" \" << swaps[i].second << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Explanations/Dirty Deeds Done Dirt Cheap Explanation.txt",
    "content": "Let us notice that although the signs alternate between the numbers, the type of pairs stay the same. \r\n\r\nEither our sequence consists only of pairs (a, b) where (a < b)\r\n\r\nOr it consists only of pairs (a, b) where (a > b). \r\n\r\n----\r\n\r\n1. We will store all pairs of 1 kind in a list. \r\n\r\n2. We will sort it in such a way that we will get a valid ordering. \r\n\r\n----\r\n\r\nLet us consider pairs of the type (a < b)\r\n\r\nWe want to order them in such a way that if pairs (P, Q)  P comes before Q, then \r\n\r\n(P.a < P.b) > (Q.a < Q.b)\r\n\r\nWe can sort the pairs by (P.b > Q.a). However, this is an invalid way of ordering the pairs. It is possible for (P < Q) and for (Q < P) at the same time. This causes a run time error and it is not a valid way of comparing or ordering. \r\n\r\nInstead, we can get around this by sorting in order of (P.b > Q.b)\r\n\r\nThen, (P.b > Q.b > Q.a) => P.b > Q.a\r\n\r\n---\r\n\r\nSimilarly, we will sort the other pairs in (P.a < Q.a)\r\n\r\nWe want \r\n\r\n(P.a > P.b) < (Q.a < Q.b)\r\n\r\n(P.b < P.a < Q.a) => P.b < Q.a\r\n\r\n---\r\n\r\nWe can just sort by (P.a < Q.a) and we will get a valid ordering. \r\n\r\nThe answer is just whichever pair occurs more times. \r\n\r\n---\r\n\r\nstruct pairs\r\n{\r\n    int a, b, index;\r\n\r\n    pairs()\r\n    {\r\n        a = 0; b = 0;\r\n    };\r\n\r\n    pairs(int A, int B, int I)\r\n    {\r\n        a = A, b = B, index = I;\r\n    }\r\n};\r\n\r\n// (p1 < p2) > (q1 < q2)\r\nint sort_increasing_pairs(pairs &P, pairs &Q)\r\n{\r\n    return (P.b > Q.b);\r\n}\r\n\r\n// (p1 > p2) < (q1 > q2)\r\nint sort_decreasing_pairs(pairs&P, pairs &Q)\r\n{\r\n    return (P.a < Q.a);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_pairs;\r\n    cin >> no_of_pairs;\r\n\r\n    vector <pairs> increasing, decreasing;\r\n    for(int i = 1; i <= no_of_pairs; i++)\r\n    {\r\n        int x, y;\r\n        cin >> x >> y;\r\n\r\n        if(x < y)\r\n        {\r\n            increasing.push_back(pairs(x, y, i));\r\n        }\r\n        else\r\n        {\r\n            decreasing.push_back(pairs(x, y, i));\r\n        }\r\n    }\r\n\r\n    sort(all(increasing), sort_increasing_pairs);\r\n    sort(all(decreasing), sort_decreasing_pairs);\r\n\r\n    if(increasing.size() >= decreasing.size())\r\n    {\r\n        cout << increasing.size() << \"\\n\";\r\n\r\n        for(int i = 0; i < increasing.size(); i++)\r\n        {\r\n            cout << increasing[i].index << \" \";\r\n        }\r\n    }\r\n    else\r\n    {\r\n        cout << decreasing.size() << \"\\n\";\r\n\r\n        for(int i = 0; i < decreasing.size(); i++)\r\n        {\r\n            cout << decreasing[i].index << \" \";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n----\r\n\r\nBonus - Suppose, we were not allowed to change the orders of the pairs. \r\n\r\nThen, we would have stored the indices of all pairs of one type in their sorted order and then look for the Longest Increasing Subsequence\r\n\r\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Programs/Another One Bites the Dust.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long A, B, AB;\r\n    cin >> A >> B >> AB;\r\n\r\n    long long answer = (B != A ? 1 + 2*AB + 2*min(A, B) : 2*min(A, B) + 2*AB);\r\n    cout << answer;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Programs/Born This Way.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int A_to_B, B_to_C, time_A_to_B, time_B_to_C, deleted;\n    cin >> A_to_B >> B_to_C >> time_A_to_B >> time_B_to_C >> deleted;\n    \n    vector <long long> A(A_to_B + 1);\n    for(int i = 1; i <= A_to_B; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> B(B_to_C + 1);\n    for(int i = 1; i <= B_to_C; i++)\n    {\n        cin >> B[i];\n    }\n    \n    const long long oo = 1e15;\n    long long max_time = (deleted >= A_to_B || deleted >= B_to_C ? oo : 0);\n    A.push_back(oo);\n    B.push_back(oo);\n    \n    for(int a_deletes = 0; a_deletes <= min(deleted, A_to_B - 1); a_deletes++)\n    {\n        long long reached_B = A[a_deletes + 1] + time_A_to_B;\n        \n        int first_b = upper_bound(B.begin(), B.end(), reached_B - 1) - B.begin();\n        \n        int b_deletes = deleted - a_deletes + first_b - 1;\n        \n        if(b_deletes > B_to_C)\n        {\n            max_time = oo;\n            break;\n        }\n        \n        max_time = max(max_time, B[b_deletes + 1] + time_B_to_C);\n    }\n    \n    cout << (max_time >= oo ? -1 : max_time) << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Programs/Crazy Diamond.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nconst int MAX_N = 1e6 + 5;\nvector <int> A(MAX_N);\nvector <int> position(MAX_N);\nvector <pair <int, int> > swaps;\n\nvoid arrange_swaps(int start, int destination)\n{\n    int original_start = A[start], original_destination = A[destination];\n    swap(A[start], A[destination]);\n\n    position[original_start] = destination;\n    position[original_destination] = start;\n\n    swaps.push_back(make_pair(start, destination));\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i =1 ; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    for(int i = 1; i <= no_of_elements; i++)\n        position[A[i]] = i;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(i == A[i])\n            continue;\n\n        int target = i;\n        int target_position = position[target];\n\n        int left = min(target_position, i);\n        int right = max(target_position, i);\n\n        if(right - left >= no_of_elements/2)\n        {\n            arrange_swaps(i, target_position);\n\n            continue;\n        }\n\n        if(left > no_of_elements/2)\n        {\n            arrange_swaps(1, left);\n            arrange_swaps(1, right);\n            arrange_swaps(left, 1);\n        }\n        else if(right <= no_of_elements/2)\n        {\n            arrange_swaps(right, no_of_elements);\n            arrange_swaps(no_of_elements, left);\n        }\n        else\n        {\n            arrange_swaps(left, no_of_elements);\n            arrange_swaps(no_of_elements, 1);\n            arrange_swaps(1, right);\n\n            arrange_swaps(1, no_of_elements);\n            arrange_swaps(no_of_elements, left);\n        }\n    }\n\n    cout << swaps.size() << \"\\n\";\n    for(int i = 0; i < swaps.size(); i++)\n        cout << swaps[i].first << \" \" << swaps[i].second << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Programs/Dirty Deeds Done Dirt Cheap.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct pairs\r\n{\r\n    int a, b, index;\r\n\r\n    pairs()\r\n    {\r\n        a = 0; b = 0;\r\n    };\r\n\r\n    pairs(int A, int B, int I)\r\n    {\r\n        a = A, b = B, index = I;\r\n    }\r\n};\r\n\r\n// (p1 < p2) > (q1 < q2)\r\nint sort_increasing_pairs(pairs &P, pairs &Q)\r\n{\r\n    return (P.b > Q.b);\r\n}\r\n\r\n// (p1 > p2) < (q1 > q2)\r\nint sort_decreasing_pairs(pairs&P, pairs &Q)\r\n{\r\n    return (P.a < Q.a);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_pairs;\r\n    cin >> no_of_pairs;\r\n\r\n    vector <pairs> increasing, decreasing;\r\n    for(int i = 1; i <= no_of_pairs; i++)\r\n    {\r\n        int x, y;\r\n        cin >> x >> y;\r\n\r\n        if(x < y)\r\n        {\r\n            increasing.push_back(pairs(x, y, i));\r\n        }\r\n        else\r\n        {\r\n            decreasing.push_back(pairs(x, y, i));\r\n        }\r\n    }\r\n\r\n    sort(all(increasing), sort_increasing_pairs);\r\n    sort(all(decreasing), sort_decreasing_pairs);\r\n\r\n    if(increasing.size() >= decreasing.size())\r\n    {\r\n        cout << increasing.size() << \"\\n\";\r\n\r\n        for(int i = 0; i < increasing.size(); i++)\r\n        {\r\n            cout << increasing[i].index << \" \";\r\n        }\r\n    }\r\n    else\r\n    {\r\n        cout << decreasing.size() << \"\\n\";\r\n\r\n        for(int i = 0; i < decreasing.size(); i++)\r\n        {\r\n            cout << decreasing[i].index << \" \";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/CodeForces Global Round 3/Rough Notes Link",
    "content": "https://1drv.ms/b/s!AoiWcyvzkQXVhzwro8u-YeTes_kj\n"
  },
  {
    "path": "Contests/CodeForces Global Round 5/Explanations/Balanced Rating Changes Explanation.txt",
    "content": "First, we will make R[i] = R[i]/2 rounded down for all the N integers. \n\nThen, we will check the sum \n\nCase 1 = Sum S = 0\n\nThen, there is nothing further to do. \n\nCase 2 = Sum S < 0\n\nThat means the sum is too low and we need to raise some integers. \n\nThat means some of the odd integers need to be rounded up.\n\nWe will increment some of the odd integers by 1 till our sum is 0.\n\nCase 3 - Sum S > 0\n\nThat means the sum is too high. Some of the odd integers need to be rounded down instead of up.\n\nHowever, this can't happen here. We have already rounded down all the N integers. \n\n-----\n\nAnother alternative approach is that if there are X odd numbers, we will round up X/2 odd integers and round down X/2 odd integers.\n\n----\n\nint main()\n{\n    int no_of_students;\n    cin >> no_of_students;\n\n    vector <int> rating(no_of_students + 1);\n    vector <int> was_odd(no_of_students + 1, false);\n\n    int sum = 0;\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cin >> rating[i];\n\n        was_odd[i] = (abs(rating[i])%2 == 1);\n\n        rating[i] /= 2;\n\n        sum += rating[i];\n    }\n\n    if(sum < 0)\n    {\n        for(int i = 1; i <= no_of_students && sum != 0; i++)\n        {\n            if(was_odd[i] && rating[i] > 0)\n            {\n                rating[i]++;\n\n                sum++;\n            }\n        }\n    }\n    else if(sum > 0)\n    {\n        for(int i = 1; i <= no_of_students && sum != 0; i++)\n        {\n            if(was_odd[i] && rating[i] < 0)\n            {\n                rating[i]--;\n\n                sum--;\n            }\n        }\n    }\n\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cout << rating[i] << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 5/Explanations/Balanced Tunnel Explanation.txt",
    "content": "Let us keep track of the time in which each car enters and exits. \n\nWe will sort the cars by their entry time. \n\nThen, we will go from C1 to CN, C1.Entry < C2.Entry < .... < CN.Entry\n\nCar i is fined if it's exit comes before any of the (i - 1) cars\n\nThis means that Car i's exit muct come before some Exit of one of the first (i - 1) cars. \n\nIf that is true, then it will definitely come before the MAXIUMUM of the first (i - 1) exits. \n\nSo we will keep track of the maximum exit time we have seen so far. \n\nIf Car i.Exit is smaller than the maximum of the Exit time so far, then Car i will be fined. \n\n----\n\nstruct cars\n{\n    int entry, exit;\n\n    cars(){};\n\n    const int operator<(cars &C)\n    {\n        return (entry < C.entry);\n    }\n};\n\nint main()\n{\n    int no_of_cars;\n    cin >> no_of_cars;\n\n    vector <cars> car_no(no_of_cars);\n    for(int i = 0; i < no_of_cars; i++)\n    {\n        int car;\n        cin >> car;\n\n        car_no[car - 1].entry = i;\n    }\n\n    int cars_fined = 0;\n    for(int i = 0; i < no_of_cars; i++)\n    {\n        int car;\n        cin >> car;\n\n        car_no[car - 1].exit = i;\n    }\n\n    sort(all(car_no));\n\n    int maximum_exit_so_far = car_no[0].exit;\n    for(int i = 1; i < no_of_cars; i++)\n    {\n        if(car_no[i].exit < maximum_exit_so_far)\n        {\n            cars_fined++;\n        }\n\n        maximum_exit_so_far = max(maximum_exit_so_far, car_no[i].exit);\n    }\n\n    cout << cars_fined << \"\\n\";\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Contests/CodeForces Global Round 5/Programs/Balanced Rating Changes.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_students;\n    cin >> no_of_students;\n\n    vector <int> rating(no_of_students + 1);\n    vector <int> was_odd(no_of_students + 1, false);\n\n    int sum = 0;\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cin >> rating[i];\n\n        was_odd[i] = (abs(rating[i])%2 == 1);\n\n        rating[i] /= 2;\n\n        sum += rating[i];\n    }\n\n    if(sum < 0)\n    {\n        for(int i = 1; i <= no_of_students && sum != 0; i++)\n        {\n            if(was_odd[i] && rating[i] > 0)\n            {\n                rating[i]++;\n\n                sum++;\n            }\n        }\n    }\n    else if(sum > 0)\n    {\n        for(int i = 1; i <= no_of_students && sum != 0; i++)\n        {\n            if(was_odd[i] && rating[i] < 0)\n            {\n                rating[i]--;\n\n                sum--;\n            }\n        }\n    }\n\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cout << rating[i] << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/CodeForces Global Round 5/Programs/Balanced Tunnel.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct cars\r\n{\r\n    int entry, exit;\r\n\r\n    cars(){};\r\n\r\n    const int operator<(cars &C)\r\n    {\r\n        return (entry < C.entry);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_cars;\r\n    cin >> no_of_cars;\r\n\r\n    vector <cars> car_no(no_of_cars);\r\n    for(int i = 0; i < no_of_cars; i++)\r\n    {\r\n        int car;\r\n        cin >> car;\r\n\r\n        car_no[car - 1].entry = i;\r\n    }\r\n\r\n    int cars_fined = 0;\r\n    for(int i = 0; i < no_of_cars; i++)\r\n    {\r\n        int car;\r\n        cin >> car;\r\n\r\n        car_no[car - 1].exit = i;\r\n    }\r\n\r\n    sort(all(car_no));\r\n\r\n    int maximum_exit_so_far = car_no[0].exit;\r\n    for(int i = 1; i < no_of_cars; i++)\r\n    {\r\n        if(car_no[i].exit < maximum_exit_so_far)\r\n        {\r\n            cars_fined++;\r\n        }\r\n\r\n        maximum_exit_so_far = max(maximum_exit_so_far, car_no[i].exit);\r\n    }\r\n\r\n    cout << cars_fined << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Explanations/Cows and Snacks Explanation.txt",
    "content": "1. Since each cow likes only 2 snacks, we can treat the cows as edges and the snacks as vertices. \r\n\r\n2. Let us look at 1 connected component of this graph. 2 snacks can be had by the first edge. After that, each snack can only be eaten by 1 edge. \r\n\r\n3. A connected component of size C will have at most (C - 1) happy cows. \r\n\r\n4. We will take the sum of all the connected components and then the number of unhappy cows = Total Cows - Happy Cows \r\n\r\n5. The reason we cannot simply write the answer as Total Cows - Number of Connected Components, assuming each component produces exactly 1 unhappy cow is that multi-edges are allowed in this graph. \r\n\r\nOnly (C - 1) edges are enough to span the entire connected component but it can have many more edges and the cows correspond to edges. \r\n\r\n-----\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e5 + 5;\r\nvector <int> graph[MAX_N];\r\nvector <int> visited(MAX_N, false);\r\n\r\nint dfs_component_size(int v)\r\n{\r\n    if(visited[v])\r\n        return 0;\r\n\r\n    int component_size = 1;\r\n\r\n    visited[v] = true;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(visited[child])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        component_size += dfs_component_size(child);\r\n    }\r\n\r\n    return component_size;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_snacks, no_of_animals;\r\n    cin >> no_of_snacks >> no_of_animals;\r\n\r\n    for(int i = 1; i <= no_of_animals; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    int happy_animals = 0;\r\n    for(int i = 1; i <= no_of_snacks; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            int component_size = dfs_component_size(i);\r\n\r\n            happy_animals += (component_size - 1);\r\n        }\r\n    }\r\n\r\n    int unhappy_animals = no_of_animals - happy_animals;\r\n\r\n    cout << unhappy_animals;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Explanations/Koala and Lights Explanation",
    "content": "Just do a brute force simulation about a large enough time. (Suppose 1000). \n\nActually the sequences are all periodic. And the maximum period is the lcm of all the individual periods - 2, 4, 6, 8, 10\n\nWe can simulate upto a large number and then find the maximum number of simultaneous lights on. \n\n---\n\nint main()\n{\n    int no_of_lights;\n    cin >> no_of_lights;\n\n    string initial;\n    cin >> initial;\n\n    vector <int> start(no_of_lights);\n    vector <int> difference(no_of_lights);\n    for(int i = 0; i < no_of_lights; i++)\n    {\n        cin >> difference[i] >> start[i];\n    }\n\n    const int MAX_TIME = 1001, ON = 0, OFF = 1;\n    vector <int> lights_on_at(MAX_TIME, 0);\n\n    for(int i = 0; i < no_of_lights; i++)\n    {\n        int state = (initial[i] == '0' ? OFF : ON);\n\n        if(initial[i] == '1')\n        {\n            for(int time = 0; time < start[i]; time++)\n            {\n                lights_on_at[time]++;\n            }\n        }\n\n        for(int time = start[i]; time < MAX_TIME; time++)\n        {\n            if((time - start[i])%difference[i] == 0)\n            {\n                state = (state == ON ? OFF : ON);\n            }\n\n            if(state == ON)\n            {\n                lights_on_at[time]++;\n            }\n        }\n    }\n\n    int max_lights = 0;\n    for(int t = 0; t < MAX_TIME; t++)\n    {\n        max_lights = max(max_lights, lights_on_at[t]);\n    }\n\n    cout << max_lights;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Explanations/Paint The Digits Explanation",
    "content": "Here is what this question asks us. \n\nYou are given a string S. Split it into two sequences S1 and S2. \n\nS1 and S2 are both sorted in non-decreasing order. \nThe string (S1 S2) must also be sorted in non-decreasing oder.\n\nNow one observation to make is that the number of possible characters is small (10) even though the length is large. \n\nLet us iterate over all 10 digits. We will put all digits < d in S1 and > d in S2. \n\nThe reason we are not touching the digits = d is that they can be put into either of the strings based on convenience. \n\n1. Iterate over 10 digits. \n2. For the current digit d, put all characters < d in S1 and > d in S2. \n3. Check if S1 and S2 are non-decreasing\nHere is what this question asks us. \n\nYou are given a string S. Split it into two sequences S1 and S2. \n\nS1 and S2 are both sorted in non-decreasing order. \nThe string (S1 S2) must also be sorted in non-decreasing oder.\n\nNow one observation to make is that the number of possible characters is small (10) even though the length is large. \n\nLet us iterate over all 10 digits. We will put all digits < d in S1 and > d in S2. \n\nThe reason we are not touching the digits = d is that they can be put into either of the strings based on convenience. \n\n1. Iterate over 10 digits. \n2. For the current digit d, put all characters < d in S1 and > d in S2. \n3. Check if S1 and S2 are non-decreasing\n\n---\n\nint possible_to_split(string S, int n)\n{\n    string new_string_lesser_than_n, new_string_greater_than_n;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] - '0' < n)\n        {\n            new_string_lesser_than_n += S[i];\n        }\n        else if(S[i] - '0' > n)\n        {\n            new_string_greater_than_n += S[i];\n        }\n    }\n\n    return (is_non_decreasing(new_string_greater_than_n) && is_non_decreasing(new_string_lesser_than_n));\n}\n\n-----\n\nWe can use a very simple function to check if a string S in non-decreasing. \n\nint is_non_decreasing(string S)\n{\n    for(int i = 0; i + 1 < S.size(); i++)\n    {\n        if(S[i] > S[i + 1])\n            return false;\n    }\n\n    return true;\n}\n\n---\n\nLet us now suppose that there exists some digit d such that we can make 2 non-decreasing strings S1 and S2 such that all characters in S1 < d and all characters in S2 > d. \n\nIs this sufficient ? \nNo. We need to accomodate the digit d too. \n\n---\n\nLet x be the leftmost occurrence of any digit > d. \n\nint second_sequence_beginning = length - 1;\nfor(int i = length - 1; i >= 0; i--)\n{\n      if(S[i] - '0' > possible_endings_1)\n      {\n          second_sequence_beginning = i;\n      }\n}\n\n---\n\nLet y be the rightmost occurence of any digit < d\n\nint first_sequence_ending = 0;\nfor(int i = 0; i < length; i++)\n{\n     if(S[i] - '0' < possible_endings_1)\n     {\n          first_sequence_ending = i;\n     }\n}\n\n----\n\n1. Any occurence of d that is before x can be put in the beginning of S2\n\n2. Any occurence of d that is after y can be put at the end of S1\n\n3.Occurences of d that are in between x and y cannot be put in either S1 or S2 \n\nIf this is the case, then we will continue searching for another digit for which we can construct this\n\n----\n\nint colouring_possible = true;\nfor(int i = second_sequence_beginning; i < first_sequence_ending; i++)\n{\n      if(S[i] - '0' == possible_endings_1)\n      {\n           colouring_possible = false;\n      }\n }\n\n if(!colouring_possible)\n      continue;\n\n---------\n\nIf the colouring is possible, we will construct it according to the rules above\n\nstring colouring;\nfor(int i = 0; i < length; i++)\n{\n    if( (S[i] - '0' < possible_endings_1) || (S[i] - '0' == possible_endings_1 && i >= first_sequence_ending) )\n     {\n                colouring += '1';\n     }\n     else if( (S[i] - '0' > possible_endings_1) || (S[i] - '0' == possible_endings_1 && i <= second_sequence_beginning))\n     {\n                colouring += '2';\n     }\n}\n\n-----------\n---\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Explanations/Paint Your Numbers Explanation",
    "content": "The smallest number has to be painted with some colour. We will paint all the multiples of this smallest number with the same colour. \n\nThis suggests a sieve-like approach. \n\n1. Sort the elements\n2. If we find an uncoloured element, paint that element with a new colour\n  2a. Iterate over all multiples of this element and paint it with the same colour\n3. Continue scanning and look for the next uncoloured element\n\n---------\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    sort(all(A));\n\n    const int MAX = 101;\n    int last_colour = 0;\n    vector <int> colour(MAX, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(colour[A[i]] == 0)\n        {\n            last_colour++;\n\n            for(int j = A[i]; j < MAX; j += A[i])\n            {\n                colour[j] = last_colour;\n            }\n        }\n    }\n\n    cout << last_colour;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Programs/Cows and Snacks.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e5 + 5;\r\nvector <int> graph[MAX_N];\r\nvector <int> visited(MAX_N, false);\r\n\r\nint dfs_component_size(int v)\r\n{\r\n    if(visited[v])\r\n        return 0;\r\n\r\n    int component_size = 1;\r\n\r\n    visited[v] = true;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(visited[child])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        component_size += dfs_component_size(child);\r\n    }\r\n\r\n    return component_size;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_snacks, no_of_animals;\r\n    cin >> no_of_snacks >> no_of_animals;\r\n\r\n    for(int i = 1; i <= no_of_animals; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    int happy_animals = 0;\r\n    for(int i = 1; i <= no_of_snacks; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            int component_size = dfs_component_size(i);\r\n\r\n            happy_animals += (component_size - 1);\r\n        }\r\n    }\r\n\r\n    int unhappy_animals = no_of_animals - happy_animals;\r\n\r\n    cout << unhappy_animals;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Programs/Koala and Lights.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_lights;\r\n    cin >> no_of_lights;\r\n\r\n    string initial;\r\n    cin >> initial;\r\n\r\n    vector <int> start(no_of_lights);\r\n    vector <int> difference(no_of_lights);\r\n    for(int i = 0; i < no_of_lights; i++)\r\n    {\r\n        cin >> difference[i] >> start[i];\r\n    }\r\n\r\n    const int MAX_TIME = 1001, ON = 0, OFF = 1;\r\n    vector <int> lights_on_at(MAX_TIME, 0);\r\n\r\n    for(int i = 0; i < no_of_lights; i++)\r\n    {\r\n        int state = (initial[i] == '0' ? OFF : ON);\r\n\r\n        if(initial[i] == '1')\r\n        {\r\n            for(int time = 0; time < start[i]; time++)\r\n            {\r\n                lights_on_at[time]++;\r\n            }\r\n        }\r\n\r\n        for(int time = start[i]; time < MAX_TIME; time++)\r\n        {\r\n            if((time - start[i])%difference[i] == 0)\r\n            {\r\n                state = (state == ON ? OFF : ON);\r\n            }\r\n\r\n            if(state == ON)\r\n            {\r\n                lights_on_at[time]++;\r\n            }\r\n        }\r\n    }\r\n\r\n    int max_lights = 0;\r\n    for(int t = 0; t < MAX_TIME; t++)\r\n    {\r\n        max_lights = max(max_lights, lights_on_at[t]);\r\n    }\r\n\r\n    cout << max_lights;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Programs/Paint The Digits.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint is_non_decreasing(string S)\r\n{\r\n    for(int i = 0; i + 1 < S.size(); i++)\r\n    {\r\n        if(S[i] > S[i + 1])\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint possible_to_split(string S, int n)\r\n{\r\n    string new_string_lesser_than_n, new_string_greater_than_n;\r\n\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] - '0' < n)\r\n        {\r\n            new_string_lesser_than_n += S[i];\r\n        }\r\n        else if(S[i] - '0' > n)\r\n        {\r\n            new_string_greater_than_n += S[i];\r\n        }\r\n    }\r\n\r\n    return (is_non_decreasing(new_string_greater_than_n) && is_non_decreasing(new_string_lesser_than_n));\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int possible_endings_1 = 0;\r\n    for(possible_endings_1 = 0; possible_endings_1 < 10; possible_endings_1++)\r\n    {\r\n        if(!possible_to_split(S, possible_endings_1))\r\n        {\r\n            continue;\r\n        }\r\n\r\n        int first_sequence_ending = 0;\r\n        for(int i = 0; i < length; i++)\r\n        {\r\n            if(S[i] - '0' < possible_endings_1)\r\n            {\r\n                first_sequence_ending = i;\r\n            }\r\n        }\r\n\r\n        int second_sequence_beginning = length - 1;\r\n        for(int i = length - 1; i >= 0; i--)\r\n        {\r\n            if(S[i] - '0' > possible_endings_1)\r\n            {\r\n                second_sequence_beginning = i;\r\n            }\r\n        }\r\n\r\n        int colouring_possible = true;\r\n        for(int i = second_sequence_beginning; i < first_sequence_ending; i++)\r\n        {\r\n            if(S[i] - '0' == possible_endings_1)\r\n            {\r\n                colouring_possible = false;\r\n            }\r\n        }\r\n\r\n        if(!colouring_possible)\r\n            continue;\r\n\r\n        string colouring;\r\n        for(int i = 0; i < length; i++)\r\n        {\r\n            if( (S[i] - '0' < possible_endings_1) || (S[i] - '0' == possible_endings_1 && i >= first_sequence_ending) )\r\n            {\r\n                colouring += '1';\r\n            }\r\n            else if( (S[i] - '0' > possible_endings_1) || (S[i] - '0' == possible_endings_1 && i <= second_sequence_beginning))\r\n            {\r\n                colouring += '2';\r\n            }\r\n        }\r\n\r\n        cout << colouring << \"\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    if(possible_endings_1 == 10)\r\n    {\r\n        cout << \"-\\n\";\r\n\r\n        return;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Programs/Paint The Numbers.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n\r\n    const int MAX = 101;\r\n    int last_colour = 0;\r\n    vector <int> colour(MAX, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(colour[A[i]] == 0)\r\n        {\r\n            last_colour++;\r\n\r\n            for(int j = A[i]; j < MAX; j += A[i])\r\n            {\r\n                colour[j] = last_colour;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << last_colour;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Programs/Paint Your Numbers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    sort(all(A));\n\n    const int MAX = 101;\n    int last_colour = 0;\n    vector <int> colour(MAX, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(colour[A[i]] == 0)\n        {\n            last_colour++;\n\n            for(int j = A[i]; j < MAX; j += A[i])\n            {\n                colour[j] = last_colour;\n            }\n        }\n    }\n\n    cout << last_colour;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Dasha Code Championship Elimination Round 2019/Rough Notes",
    "content": "https://1drv.ms/b/s!AoiWcyvzkQXViGvYtE4yyrEofu3T?e=4Nqcdt\n"
  },
  {
    "path": "Contests/Div 1 492/Explanations/Game 995 Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpe5F\r\n\r\nExpectation is just the average !\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, no_of_changes;\r\n    scanf(\"%d %d\", &n, &no_of_changes);\r\n\r\n    int no_of_elements = (1LL << n);\r\n    long long sum = 0;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        sum += A[i];\r\n    }\r\n\r\n    double average = (sum*1.0)/no_of_elements;\r\n    printf(\"%.12f\\n\", average);\r\n\r\n    for(int i = 1; i <= no_of_changes; i++)\r\n    {\r\n        int position, new_value;\r\n        scanf(\"%d %d\", &position, &new_value);\r\n\r\n        sum = sum - A[position] + new_value;\r\n        A[position] = new_value;\r\n\r\n        average = (sum*1.0)/(no_of_elements);\r\n        printf(\"%.12f\\n\", average);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 1 492/Explanations/Leaving the Bar Explanation.txt",
    "content": "Blog link - https://mathprogrammer.quora.com/4253883-1?share=4cf393bf&srid=F7Hz\r\n\r\nTurns out randomly shuffling the vectors and being greedy is a very efficient heuristic !\r\n\r\n------------------------------\r\n\r\n do\r\n    {\r\n        random_shuffle(all(V));\r\n \r\n        P = Point(0, 0);\r\n \r\n        for(int i = 0; i < no_of_points; i++)\r\n        {\r\n            if(square_norm(P + V[i]) <= square_norm(P - V[i]))\r\n            {\r\n                P = P + V[i];\r\n                step[V[i].index] = 1;\r\n            }\r\n            else\r\n            {\r\n                P = P - V[i];\r\n                step[V[i].index] = -1;\r\n            }\r\n        }\r\n    }\r\n    while(square_norm(P) > square(oo));\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Div 1 492/Explanations/Suit and Tie Explanation.txt",
    "content": "We can be greedy. \n\nGo through the array. \n\nIf A[i] =/= A[i + 1], \n\nFind the rightmost occurence of A[i] and keep swapping. \n\nLet us prove that this is optimal. \n\nnow, if a and a are seperated\n\nAll other pairs, must be of the form\n\naa bb\n\nabab\na bb a\n\nNow in the first kind, our algorithm won't touch it. \n\nIn the seonc kind, we need to atleast do one swap. The greedy algorithm does one swap. \n\nIn the thrid, we need to do at least two, The greedy does two. \n\nWe see the greedy algorithm does no more swaps than necessary.\n\n-------------------------------------\n\nint main()\n{\n    int no_of_couples;\n    scanf(\"%d\", &no_of_couples);\n\n    vector <int> A(2*no_of_couples + 1);\n    for(int i = 1; i <= 2*no_of_couples; i++)\n        scanf(\"%d\", &A[i]);\n\n    int no_of_swaps = 0;\n    for(int i = 1; i <= 2*no_of_couples; i += 2)\n    {\n        for(int j = 2*no_of_couples; j > i + 1; j--)\n        {\n            if(A[j] == A[i])\n            {\n                swap(A[j], A[j - 1]);\n                no_of_swaps++;\n            }\n        }\n    }\n\n    printf(\"%d\\n\", no_of_swaps);\n    return 0;\n}\n\n\n\n"
  },
  {
    "path": "Contests/Div 1 492/Programs/Game 995D.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n, no_of_changes;\r\n    scanf(\"%d %d\", &n, &no_of_changes);\r\n\r\n    int no_of_elements = (1LL << n);\r\n    long long sum = 0;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        sum += A[i];\r\n    }\r\n\r\n    double average = (sum*1.0)/no_of_elements;\r\n    printf(\"%.12f\\n\", average);\r\n\r\n    for(int i = 1; i <= no_of_changes; i++)\r\n    {\r\n        int position, new_value;\r\n        scanf(\"%d %d\", &position, &new_value);\r\n\r\n        sum = sum - A[position] + new_value;\r\n        A[position] = new_value;\r\n\r\n        average = (sum*1.0)/(no_of_elements);\r\n        printf(\"%.12f\\n\", average);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 1 492/Programs/Leaving The Bar.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct Point\r\n{\r\n    int index;\r\n    LL x, y;\r\n\r\n    Point(LL a = 0, LL b = 0, int index = 0)\r\n    {\r\n        x = a, y = b, index = 0;\r\n    }\r\n\r\n    Point operator+(const Point &P)\r\n    {\r\n        return Point(x + P.x, y + P.y);\r\n    }\r\n    Point operator-(const Point &P)\r\n    {\r\n        return Point(x - P.x, y - P.y);\r\n    }\r\n};\r\n\r\nLL square(LL n)\r\n{\r\n    return n*n;\r\n}\r\n\r\nLL square_norm(Point P)\r\n{\r\n    return (P.x*P.x + P.y*P.y);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <Point> V(no_of_points);\r\n    for(int i = 0; i < no_of_points; i++)\r\n    {\r\n        scanf(\"%I64d %I64d\", &V[i].x, &V[i].y);\r\n        V[i].index = i;\r\n    }\r\n\r\n    const LL oo = 1.5e6;\r\n    Point P;\r\n    vector <int> step(no_of_points);\r\n\r\n    do\r\n    {\r\n        random_shuffle(all(V));\r\n\r\n        P = Point(0, 0);\r\n\r\n        for(int i = 0; i < no_of_points; i++)\r\n        {\r\n            if(square_norm(P + V[i]) <= square_norm(P - V[i]))\r\n            {\r\n                P = P + V[i];\r\n                step[V[i].index] = 1;\r\n            }\r\n            else\r\n            {\r\n                P = P - V[i];\r\n                step[V[i].index] = -1;\r\n            }\r\n        }\r\n    }\r\n    while(square_norm(P) > square(oo));\r\n\r\n    for(int i = 0; i < no_of_points; i++)\r\n        printf(\"%d \", step[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 1 492/Programs/Suit and Tie.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_couples;\n    scanf(\"%d\", &no_of_couples);\n\n    vector <int> A(2*no_of_couples + 1);\n    for(int i = 1; i <= 2*no_of_couples; i++)\n        scanf(\"%d\", &A[i]);\n\n    int no_of_swaps = 0;\n    for(int i = 1; i <= 2*no_of_couples; i += 2)\n    {\n        for(int j = 2*no_of_couples; j > i + 1; j--)\n        {\n            if(A[j] == A[i])\n            {\n                swap(A[j], A[j - 1]);\n                no_of_swaps++;\n            }\n        }\n    }\n\n    printf(\"%d\\n\", no_of_swaps);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 12/Explanations/Ball Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpFlU\n\nYou have N triplets (A, B, C). \n\nSort the triplets by A. \n\nMaintain an array S, where the index is B and the value is C. Initially C is empty. \n\nProcess triplets in descending order of A. \n\nCheck if max{S[B[i] + 1, B[i] + 2, ... , N]} > C_i, \n\nIf yes, then we have found a triplet j such that \n\nA_j > A_i, because it was processed first. \nB_j > B_i, because we have queried in the range > B_i\nC_j > C_i, as we have just found out !\n\nWe compress the coordinates of B and maintain a segment tree over S. Otherwise, it once again degrades to O(n^2). But, with our beautiful segment tree, it's now O(n log n).\n\n------------------------------------------------\n\nint main()\n{\n    int no_of_ladies;\n    scanf(\"%d\", &no_of_ladies);\n\n    vector <info> lady(no_of_ladies + 1);\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].beauty);\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].richness);\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].intellect);\n\n    sort(all(lady), sort_by_beauty);\n\n    vector <int> intelligence(no_of_ladies + 1, 0);\n    for(int i = 1; i <= no_of_ladies; i++) intelligence[i] = lady[i].intellect;\n\n    sort(all(intelligence));\n    map <int, int> iq_rank;\n\n    for(int i = 1; i <= no_of_ladies; i++)\n    {\n        iq_rank[intelligence[i]] = (intelligence[i] == intelligence[i - 1] ? iq_rank[intelligence[i - 1]] : i);\n    }\n\n    memset(max_tree, 0, sizeof(max_tree));\n\n    int suicides = 0;\n\n    for(int i = no_of_ladies; i >= 1; )\n    {\n        int j;\n\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\n        {\n            int max_richness_with_other_2_greater = get_max_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect] + 1, no_of_ladies);\n\n            if(max_richness_with_other_2_greater > lady[j].richness)\n                suicides++;\n        }\n\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\n        {\n            insert_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect], lady[j].richness);\n        }\n\n        i = j;\n    }\n\n    printf(\"%d\", suicides);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 12/Explanations/Correct Solution Explanation.txt",
    "content": "If you are given N, the answer is all the digits of N in ascending order. \r\n\r\nIf N[0] = 0, then swap it with the first non zero number. (There's always a non zero digit, if the number of digits > 1 as there is no number consisting of multiple zeroes. However, a single 0 is a special case. Be careful. If it's only 0, then there's no non zero digit to replace it with.)\r\n\r\nCompare the answer with B.\r\n\r\n--------------------------------------------------------------\r\n\r\nstring solve(string S)\r\n{\r\n    vector <char> digits;\r\n    for(int i = 0; i < S.size(); i++)\r\n        digits.push_back(S[i]);\r\n\r\n    sort(all(digits));\r\n\r\n    if(digits[0] == '0')\r\n    {\r\n        int first_nonzero = 1;\r\n        while(first_nonzero < digits.size() && digits[first_nonzero] == '0')\r\n            first_nonzero++;\r\n\r\n        swap(digits[0], digits[first_nonzero]);\r\n    }\r\n\r\n    string answer;\r\n    for(int i = 0; i < digits.size(); i++)\r\n        answer += digits[i];\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    string answer = solve(A);\r\n\r\n    cout << ((answer == B) ? \"OK\\n\" : \"WRONG_ANSWER\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 12/Explanations/Fruits Explanation.txt",
    "content": "Keep track of the frequency of each fruit. \r\n\r\nTo minimise prices, the most frequent fruits, get the lowest prices. \r\n\r\nTo maximise prices, the most frequent fruits get the highest prices.\r\n\r\n------------------------------\r\n\r\nsort(all(fruit_frequency));\r\n    reverse(all(fruit_frequency));\r\n\r\n    long long min_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        min_price += price[i]*1LL*fruit_frequency[i];\r\n\r\n    reverse(all(price));\r\n    long long max_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        max_price += price[i]*1LL*fruit_frequency[i];"
  },
  {
    "path": "Contests/Div 2 12/Explanations/Super Agent Explanation.txt",
    "content": "There are only 9 points and 4 pairs. Check all of them.\r\n\r\nint main()\r\n{\r\n    const int N = 3;\r\n    char grid[N + 2][N + 2];\r\n    for(int i = 1; i <= N; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    int symmetric = (grid[1][1] == grid[3][3]) && (grid[1][2] == grid[3][2]) && (grid[1][3] == grid[3][1]) && (grid[2][3] == grid[2][1]);\r\n    printf(symmetric ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 12/Programs/Ball.cpp",
    "content": "#include <cstdio>\n#include <cstring>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#define all(v) (v).begin() + 1, (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n\nusing namespace std;\n\nconst int MAX_N = 5e5 + 15;\nint max_tree[3*MAX_N];\n\nstruct info\n{\n    int beauty, richness, intellect;\n};\n\nint sort_by_beauty(info &A, info &B)\n{\n    return (A.beauty < B.beauty);\n}\n\nvoid insert_richness(int n, int left, int right, int index, int value)\n{\n    if(index < left || right < index)\n        return;\n\n    if(left == right)\n    {\n        max_tree[n] = max(max_tree[n], value);\n        return ;\n    }\n\n    int mid = (left + right) >> 1;\n    insert_richness(LEFT(n), left, mid, index, value);\n    insert_richness(RIGHT(n), mid + 1, right, index, value);\n\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\n}\n\nint get_max_richness(int n, int left, int right, int query_left, int query_right)\n{\n    if(right < query_left || query_right < left || right < left)\n        return 0;\n\n    if(query_left <= left && right <= query_right)\n        return max_tree[n];\n\n    int mid = (left + right) >> 1;\n    int left_max = get_max_richness(LEFT(n), left, mid, query_left, query_right);\n    int right_max = get_max_richness(RIGHT(n), mid + 1, right, query_left, query_right);\n\n    return max(left_max, right_max);\n}\n\nint main()\n{\n    int no_of_ladies;\n    scanf(\"%d\", &no_of_ladies);\n\n    vector <info> lady(no_of_ladies + 1);\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].beauty);\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].richness);\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].intellect);\n\n    sort(all(lady), sort_by_beauty);\n\n    vector <int> intelligence(no_of_ladies + 1, 0);\n    for(int i = 1; i <= no_of_ladies; i++) intelligence[i] = lady[i].intellect;\n\n    sort(all(intelligence));\n    map <int, int> iq_rank;\n\n    for(int i = 1; i <= no_of_ladies; i++)\n    {\n        iq_rank[intelligence[i]] = (intelligence[i] == intelligence[i - 1] ? iq_rank[intelligence[i - 1]] : i);\n    }\n\n    memset(max_tree, 0, sizeof(max_tree));\n\n    int suicides = 0;\n\n    for(int i = no_of_ladies; i >= 1; )\n    {\n        int j;\n\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\n        {\n            int max_richness_with_other_2_greater = get_max_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect] + 1, no_of_ladies);\n\n            if(max_richness_with_other_2_greater > lady[j].richness)\n                suicides++;\n        }\n\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\n        {\n            insert_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect], lady[j].richness);\n        }\n\n        i = j;\n    }\n\n    printf(\"%d\", suicides);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 12/Programs/Correct Solution.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstring solve(string S)\r\n{\r\n    vector <char> digits;\r\n    for(int i = 0; i < S.size(); i++)\r\n        digits.push_back(S[i]);\r\n\r\n    sort(all(digits));\r\n\r\n    if(digits[0] == '0' && digits.size() > 1)\r\n    {\r\n        int first_nonzero = 1;\r\n        while(digits[first_nonzero] == '0')\r\n            first_nonzero++;\r\n\r\n        swap(digits[0], digits[first_nonzero]);\r\n    }\r\n\r\n    string answer;\r\n    for(int i = 0; i < digits.size(); i++)\r\n        answer += digits[i];\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    string answer = solve(A);\r\n\r\n    cout << ((answer == B) ? \"OK\\n\" : \"WRONG_ANSWER\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 12/Programs/Fruits.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_prices, no_of_fruits;\r\n    cin >> no_of_prices >> no_of_fruits;\r\n\r\n    vector <int> price(no_of_prices, 0);\r\n    for(int i = 0; i < no_of_prices; i++) cin >> price[i];\r\n\r\n    sort(all(price));\r\n\r\n    map <string, int> frequency;\r\n    for(int i = 1; i <= no_of_fruits; i++)\r\n    {\r\n        string fruit;\r\n        cin >> fruit;\r\n        frequency[fruit]++;\r\n    }\r\n\r\n    vector <int> fruit_frequency;\r\n    for(map <string, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n        fruit_frequency.push_back(it->second);\r\n\r\n    sort(all(fruit_frequency));\r\n    reverse(all(fruit_frequency));\r\n\r\n    long long min_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        min_price += price[i]*1LL*fruit_frequency[i];\r\n\r\n    reverse(all(price));\r\n    long long max_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        max_price += price[i]*1LL*fruit_frequency[i];\r\n\r\n    cout << min_price << \" \" << max_price;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 12/Programs/Super Agent.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    const int N = 3;\r\n    char grid[N + 2][N + 2];\r\n    for(int i = 1; i <= N; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    int symmetric = (grid[1][1] == grid[3][3]) && (grid[1][2] == grid[3][2]) && (grid[1][3] == grid[3][1]) && (grid[2][3] == grid[2][1]);\r\n    printf(symmetric ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 136/Explanations/Little Elephant And Array Segment Tree Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpmul\r\n\r\nVery similar to DQUERY. \r\n\r\nThe idea is that we set the index of the last x-th occurence of x to 1, the one before that to -1 and all others to 0 and do offline processing !\r\n\r\nIt's quite beautiful actually ! This ensures that when we're processing queries that end at i, we have all the required information. We can't answer the queries online as it's not convenient and it gets messy but solving them offline makes the problem so beautiful !\r\n\r\n---------------------------------------------------\r\n\r\nfor(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] < MAX_N)\r\n        {\r\n            occurence[A[i]].push_back(i);\r\n\r\n            int A_i_frequency = occurence[A[i]].size();\r\n\r\n            if(A_i_frequency >= A[i])\r\n            {\r\n                int last = A_i_frequency - A[i];\r\n\r\n                int last_occurence = occurence[A[i]][last];\r\n\r\n                update(1, 1, no_of_elements, last_occurence, 1);\r\n            }\r\n\r\n            if(A_i_frequency >= A[i] + 1)\r\n            {\r\n                int second_last = A_i_frequency - (A[i] + 1);\r\n\r\n                int second_last_occurence = occurence[A[i]][second_last];\r\n\r\n                update(1, 1, no_of_elements, second_last_occurence, -1);\r\n            }\r\n\r\n            if(A_i_frequency >= A[i] + 2)\r\n            {\r\n                int third_last = A_i_frequency - (A[i] + 2);\r\n\r\n                int third_last_occurence = occurence[A[i]][third_last];\r\n\r\n                update(1, 1, no_of_elements, third_last_occurence, 0);\r\n            }\r\n        }\r\n\r\n        while(Q[last_query].right == i)\r\n        {\r\n            answer[Q[last_query].index] = get_sum(1, 1, no_of_elements, Q[last_query].left, Q[last_query].right);\r\n\r\n            last_query++;\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Div 2 136/Explanations/Little Elephant and Arrays Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpmul\n\nMain insight is there can be at most 2 root(n) numbers x who's frequency in the array is > x\n\n--------------------------\n\n vector <int> answer(no_of_queries + 1, 0);\n\n    for(int i = 1; i <= MAX_N; i++)\n    {\n        if(frequency[i] >= i) //There can't be more than 2 root(n) such elements\n        {\n            vector <int> frequency_till(no_of_elements + 1, 0);\n\n            for(int j = 1; j <= no_of_elements; j++) frequency_till[j] = frequency_till[j - 1] + (A[j] == i);\n\n            for(int q = 1; q <= no_of_queries; q++) answer[q] += (frequency_till[right[q]] - frequency_till[left[q] - 1] == i);\n        }\n    }\n"
  },
  {
    "path": "Contests/Div 2 136/Explanations/Little Elephant and Function Explanation.txt",
    "content": "The Little Elephant enjoys recursive functions.\r\n\r\nThis time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. \r\nThe Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:\r\n\r\nIf x?=?1, exit the function.\r\nOtherwise, call f(x?-?1), and then make swap(ax?-?1,?ax) (swap the x-th and (x?-?1)-th elements of a).\r\nThe Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, \r\nthe Little Elephant wants to show the performance of its function. Help him, \r\nfind a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.\r\n\r\n\r\n-------------------------------------------------------\r\n\r\nImportant to have some understanding of recursive stackframes for this one. \r\n\r\nAt first I thought it first swaps, ax and a(x-1) and then calls f(x - 1).\r\n\r\nIn that case the answer is a sorted array, rotated one place to the left. \r\n\r\nLike, 2 3 4 1\r\n\r\nBecause every swap will - 2 3 1 4, 2 1 3 4 and finally 1 2 3 4 ... The order of elements doesn't change ... The smallest element goes to the first position.\r\n\r\nBut, this is wrong.\r\n\r\nWhat happens is that it first calls f(x-1), f(x-2) ... and so on till it reaches f(1) and then starts swapping.\r\n\r\nSo, in other words starting from position 2 till n, ai and a(i - 1) are swapped. \r\n\r\nIn this case, the answer is a sorted array rotated one place to the RIGHT. \r\n\r\nthe order of elements doesn't change this way ... The first element occupies the last position.\r\n\r\n4 1 2 3, 1 4 2 3, 1 2 4 3 and finally 1 2 3 4.\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    printf(\"%d \", no_of_elements);\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        printf(\"%d \", i);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 136/Explanations/Little Elephant and Numbers Explanation.txt",
    "content": "Just implement it. O(root(n)) time\r\n\r\n--------------------------------------\r\n\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int answer = 0;\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            answer += common_digit(i, n);\r\n\r\n            answer += (i*i != n && common_digit(n/i, n));\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 136/Explanations/Little Elephant and Problem Explanation.txt",
    "content": "The Little Elephant has got a problem  somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.\r\n\r\nThe Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. \r\nHe thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). \r\nThat is, the Little Elephant could have accidentally swapped some two elements.\r\n\r\nHelp the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.\r\n\r\n-------------------------------------------------------\r\n\r\nSort the array and check how many positions differ with the original array.\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> original_array(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &original_array[i]);\r\n\r\n    vector <int> sorted_array = original_array;\r\n\r\n    sort(all(sorted_array));\r\n\r\n    int differences = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        differences += (sorted_array[i] != original_array[i]);\r\n\r\n    printf(differences <= 2 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 136/Programs/Little Elephant And Array Segment Tree Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <cstring>\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n#define all(v) (v).begin() + 1, (v).end()\r\n\r\nusing namespace std;\r\n\r\nstruct info\r\n{\r\n    int left, right, index;\r\n\r\n    int operator <(const info &A)\r\n    {\r\n        return (right < A.right);\r\n    }\r\n};\r\n\r\nconst int MAX_N = 1e5 + 1;\r\nint sum_tree[3*MAX_N];\r\nvector <int> occurence[MAX_N];\r\n\r\nvoid update(int n, int left, int right, int position, int value)\r\n{\r\n    if(right < position || position < left)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        sum_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update(LEFT(n), left, mid, position, value);\r\n    update(RIGHT(n), mid + 1, right, position, value);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nint get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    int left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    int right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <info> Q(no_of_queries + 1);\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        scanf(\"%d %d\", &Q[i].left, &Q[i].right);\r\n        Q[i].index = i;\r\n    }\r\n\r\n    sort(all(Q));\r\n\r\n    memset(sum_tree, 0, sizeof(sum_tree));\r\n\r\n    int last_query = 1;\r\n    vector <int> answer(no_of_queries + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] < MAX_N)\r\n        {\r\n            occurence[A[i]].push_back(i);\r\n\r\n            int A_i_frequency = occurence[A[i]].size();\r\n\r\n            if(A_i_frequency >= A[i])\r\n            {\r\n                int last = A_i_frequency - A[i];\r\n\r\n                int last_occurence = occurence[A[i]][last];\r\n\r\n                update(1, 1, no_of_elements, last_occurence, 1);\r\n            }\r\n\r\n            if(A_i_frequency >= A[i] + 1)\r\n            {\r\n                int second_last = A_i_frequency - (A[i] + 1);\r\n\r\n                int second_last_occurence = occurence[A[i]][second_last];\r\n\r\n                update(1, 1, no_of_elements, second_last_occurence, -1);\r\n            }\r\n\r\n            if(A_i_frequency >= A[i] + 2)\r\n            {\r\n                int third_last = A_i_frequency - (A[i] + 2);\r\n\r\n                int third_last_occurence = occurence[A[i]][third_last];\r\n\r\n                update(1, 1, no_of_elements, third_last_occurence, 0);\r\n            }\r\n        }\r\n\r\n        while(Q[last_query].right == i)\r\n        {\r\n            answer[Q[last_query].index] = get_sum(1, 1, no_of_elements, Q[last_query].left, Q[last_query].right);\r\n\r\n            last_query++;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n        printf(\"%d\\n\", answer[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 136/Programs/Little Elephant and Array.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    const int MAX_N = 1e5 + 1;\n    int no_of_elements, no_of_queries;\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\n\n    vector <int> A(no_of_elements + 1);\n    vector <int> frequency(MAX_N + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%d\", &A[i]);\n\n        if(A[i] < MAX_N)\n            frequency[A[i]]++;\n    }\n\n    vector <int> left(no_of_queries + 1);\n    vector <int> right(no_of_queries + 1);\n    for(int i = 1; i <= no_of_queries; i++)\n        scanf(\"%d %d\", &left[i], &right[i]);\n\n    vector <int> answer(no_of_queries + 1, 0);\n\n    for(int i = 1; i <= MAX_N; i++)\n    {\n        if(frequency[i] >= i) //There can't be more than 2 root(n) such elements\n        {\n            vector <int> frequency_till(no_of_elements + 1, 0);\n\n            for(int j = 1; j <= no_of_elements; j++) frequency_till[j] = frequency_till[j - 1] + (A[j] == i);\n\n            for(int q = 1; q <= no_of_queries; q++) answer[q] += (frequency_till[right[q]] - frequency_till[left[q] - 1] == i);\n        }\n    }\n\n    for(int i = 1; i <= no_of_queries; i++)\n        printf(\"%d\\n\", answer[i]);\n        \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 136/Programs/Little Elephant and Function.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    printf(\"%d \", no_of_elements);\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        printf(\"%d \", i);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 136/Programs/Little Elephant and Numbers.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid get(int n, vector <int> &frequency)\r\n{\r\n    while(n)\r\n    {\r\n        frequency[n%10]++;\r\n\r\n        n /= 10;\r\n    }\r\n}\r\n\r\nint common_digit(int a, int b)\r\n{\r\n    vector <int> a_frequency(10, 0);\r\n    get(a, a_frequency);\r\n\r\n    vector <int> b_frequency(10, 0);\r\n    get(b, b_frequency);\r\n\r\n    for(int i = 0; i < 10; i++)\r\n        if(a_frequency[i] > 0 && b_frequency[i] > 0)\r\n            return true;\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int answer = 0;\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            answer += common_digit(i, n);\r\n\r\n            answer += (i*i != n && common_digit(n/i, n));\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 136/Programs/Little Elephant and Problem.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> original_array(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &original_array[i]);\r\n\r\n    vector <int> sorted_array = original_array;\r\n\r\n    sort(all(sorted_array));\r\n\r\n    int differences = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        differences += (sorted_array[i] != original_array[i]);\r\n\r\n    printf(differences <= 2 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 197/Explanations/Helpful Maths Explanation.txt",
    "content": "Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.\r\n\r\nThe teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. \r\nStill, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. \r\nFor example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.\r\n\r\nYou've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.\r\n\r\n-----------------------------------------------\r\n\r\nSort the digits and print them one by one seperated by '+' signs.\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    string expression;\r\n    cin >> expression;\r\n\r\n    typedef unsigned int u_int;\r\n    vector <char> number;\r\n    for(u_int i = 0; i < expression.size(); i++)\r\n    {\r\n        if(expression[i] != '+')\r\n            number.push_back(expression[i]);\r\n    }\r\n\r\n    sort(all(number));\r\n\r\n    for(u_int i = 0; i < number.size() - 1; i++)\r\n    {\r\n        printf(\"%c+\", number[i]);\r\n    }\r\n    printf(\"%c\\n\", number.back());\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 197/Explanations/Xenia and Ringroad Explanation.txt",
    "content": "Simple implementation\r\n\r\nint get_travel_time(int previous, int current, int no_of_houses)\r\n{\r\n    return (previous <= current ? current - previous : no_of_houses - previous + current);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_houses, no_of_tasks;\r\n    scanf(\"%d %d\", &no_of_houses, &no_of_tasks);\r\n\r\n    int previous_house = 1;\r\n    long long total_time = 0;\r\n    while(no_of_tasks--)\r\n    {\r\n        int current_house;\r\n        scanf(\"%d\", &current_house);\r\n\r\n        total_time += get_travel_time(previous_house, current_house, no_of_houses);\r\n\r\n        previous_house = current_house;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 197/Explanations/Xenia and Weights Explanation.txt",
    "content": "Let us solve this recursively. \n\nTo know if it is possible to do so in x weighings, \n\nall we need to do is keep track of the current move and check if it's possible to do so in x-1 weighings. \n\n-----------------------\n\nLet f(n, last, difference) denote whether or not it is possible to complete the process with n weighings with the difference between left and right pans = difference.\n\n-------------------\n\nFor our next move, we make all legal moves and update the difference accordingly. \n\nint possible(int difference, int current_weigh_no, int no_of_weighs)\n{\n    if(current_weigh_no > no_of_weighs)\n    {\n        return true;\n    }\n\n    int previous_weight = answer[current_weigh_no - 1];\n\n    for(int next_weight = difference + 1; next_weight <= MAX_WEIGHT; next_weight++)\n    {\n        if(available[next_weight] && next_weight != previous_weight)\n        {\n            answer[current_weigh_no] = next_weight;\n\n            if(possible(next_weight - difference, current_weigh_no + 1, no_of_weighs))\n            {\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\n-----------------------------\n"
  },
  {
    "path": "Contests/Div 2 197/Programs/Helpful Maths.cpp",
    "content": "#include <cstdio>\r\n#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string expression;\r\n    cin >> expression;\r\n\r\n    typedef unsigned int u_int;\r\n    vector <char> number;\r\n    for(u_int i = 0; i < expression.size(); i++)\r\n    {\r\n        if(expression[i] != '+')\r\n            number.push_back(expression[i]);\r\n    }\r\n\r\n    sort(all(number));\r\n\r\n    for(u_int i = 0; i < number.size() - 1; i++)\r\n    {\r\n        printf(\"%c+\", number[i]);\r\n    }\r\n    printf(\"%c\\n\", number.back());\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 197/Programs/Xenia and Bit Operations.cpp",
    "content": "#include <cstdio>\r\n\r\nconst int OR = 0, XOR = 1, MAX_SIZE = 1e6;\r\n\r\nint tree[3*MAX_SIZE];\r\nint element[MAX_SIZE];\r\n\r\nint perform(int a, int operation, int b)\r\n{\r\n    switch(operation)\r\n    {\r\n        case OR  :  return (a|b);\r\n        case XOR :  return (a^b);\r\n    }\r\n}\r\n\r\nint other(int operation)\r\n{\r\n    return (operation^1);\r\n}\r\n\r\nvoid build(int node, int start, int end, int operation)\r\n{\r\n    if(start == end)\r\n    {\r\n        tree[node] = element[start];\r\n        return;\r\n    }\r\n\r\n    int mid = (start + end)/2;\r\n\r\n    build(2*node, start, mid, other(operation));\r\n    build(2*node + 1, mid + 1, end, other(operation));\r\n\r\n    tree[node] = perform(tree[2*node], operation, tree[2*node + 1]);\r\n}\r\n\r\nvoid update(int node, int start, int end, int index, int value, int operation)\r\n{\r\n    if(start == end)\r\n    {\r\n        tree[node] = element[index] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (start + end)/2;\r\n\r\n    if(index >= start && index <= mid)\r\n    {\r\n        update(2*node, start, mid, index, value, other(operation));\r\n    }\r\n    else if(index > mid && index <= end)\r\n    {\r\n        update(2*node + 1, mid + 1, end, index, value, other(operation));\r\n    }\r\n\r\n    tree[node] = perform(tree[2*node], operation, tree[2*node + 1]);\r\n}\r\n\r\nint main()\r\n{\r\n    int n, no_of_queries;\r\n    scanf(\"%d %d\", &n, &no_of_queries);\r\n\r\n    int no_of_elements = (1 << n);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    int first_operation = (n%2 == 0 ? XOR : OR);\r\n    build(1, 1, no_of_elements, first_operation);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int index, value;\r\n        scanf(\"%d %d\", &index, &value);\r\n\r\n        update(1, 1, no_of_elements, index, value, first_operation);\r\n        printf(\"%d\\n\", tree[1]);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 197/Programs/Xenia and Ringroad.cpp",
    "content": "#include <cstdio>\r\n\r\nint get_travel_time(int previous, int current, int no_of_houses)\r\n{\r\n    return (previous <= current ? current - previous : no_of_houses - previous + current);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_houses, no_of_tasks;\r\n    scanf(\"%d %d\", &no_of_houses, &no_of_tasks);\r\n\r\n    int previous_house = 1;\r\n    long long total_time = 0;\r\n    while(no_of_tasks--)\r\n    {\r\n        int current_house;\r\n        scanf(\"%d\", &current_house);\r\n\r\n        total_time += get_travel_time(previous_house, current_house, no_of_houses);\r\n\r\n        previous_house = current_house;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 197/Programs/Xenia and Weights.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5, MAX_WEIGHT = 10;\nint answer[MAX_N];\nint available[MAX_WEIGHT + 1];\n\nint possible(int difference, int current_weigh_no, int no_of_weighs)\n{\n    if(current_weigh_no > no_of_weighs)\n    {\n        return true;\n    }\n\n    int previous_weight = answer[current_weigh_no - 1];\n\n    for(int next_weight = difference + 1; next_weight <= MAX_WEIGHT; next_weight++)\n    {\n        if(available[next_weight] && next_weight != previous_weight)\n        {\n            answer[current_weigh_no] = next_weight;\n\n            if(possible(next_weight - difference, current_weigh_no + 1, no_of_weighs))\n            {\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\nint main()\n{\n    int no_of_weighs;\n    string weights;\n    cin >> weights >> no_of_weighs;\n\n    for(int i = 1; i <= MAX_WEIGHT; i++)\n        available[i] = (weights[i - 1] == '1');\n\n    if(possible(0, 1, no_of_weighs))\n    {\n        cout << \"YES\\n\";\n\n        for(int i = 1; i <= no_of_weighs; i++)\n        {\n            cout << answer[i] << \" \";\n        }\n    }\n    else\n    {\n        cout << \"NO\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 205/Explanation/Little Elephant and Cards Explanation.txt",
    "content": "Keep track of the front frequency and back frequency of each colour. \n\nNow if colour c was made the majority colour, \n\nThen, front(c) + back(c) >= half\n\nHow many flips do we make ? \n\nWe greedily make as many flips from the back part as required\n\nThis = max(0, half - front(c))\n\nIf front(c) >= half, then we don't make a flip.\n\nThe tricky case is when a card has the same colour on both sides. \n\nIf c is on the front and back of a card, then only update the front(c)++, don't do anything with back. This is because we will never flip this card. (Flipping will not give us a different colour, so there is no point in flipping.)\n\nI missed this tricky case of what happens when front and back are the same.\n\n-------------------------------------\n\nint main()\n{\n    int no_of_cards;\n    scanf(\"%d\", &no_of_cards);\n\n    map <int, int> present;\n    map <int, int> front_frequency;\n    map <int, int> back_frequency;\n\n    for(int i = 1; i <= no_of_cards; i++)\n    {\n        int front, back;\n        scanf(\"%d %d\", &front, &back);\n\n        front_frequency[front]++;\n\n        if(front != back) //If front and back have the same colour, count only for front.\n            back_frequency[back]++;\n\n        present[front] = true;\n        present[back] = true;\n    }\n\n    int half = no_of_cards/2 + no_of_cards%2;\n    int minimum_moves = no_of_cards + 1;\n\n    for(map <int, int> :: iterator it = present.begin(); it != present.end(); it++)\n    {\n        int colour = it->first;\n\n        if(front_frequency[colour] + back_frequency[colour] >= half)\n        {\n            int moves_for_this_colour = half - front_frequency[colour];\n\n            minimum_moves = min(minimum_moves, max(0, moves_for_this_colour));\n        }\n    }\n\n    printf(\"%d\\n\", minimum_moves > no_of_cards ? -1 : minimum_moves);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 205/Programs/Little Elephant and Cards.cpp",
    "content": "#include <cstdio>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_cards;\n    scanf(\"%d\", &no_of_cards);\n\n    map <int, int> present;\n    map <int, int> front_frequency;\n    map <int, int> back_frequency;\n\n    for(int i = 1; i <= no_of_cards; i++)\n    {\n        int front, back;\n        scanf(\"%d %d\", &front, &back);\n\n        front_frequency[front]++;\n\n        if(front != back) //If front and back have the same colour, count only for front.\n            back_frequency[back]++;\n\n        present[front] = true;\n        present[back] = true;\n    }\n\n    int half = no_of_cards/2 + no_of_cards%2;\n    int minimum_moves = no_of_cards + 1;\n\n    for(map <int, int> :: iterator it = present.begin(); it != present.end(); it++)\n    {\n        int colour = it->first;\n\n        if(front_frequency[colour] + back_frequency[colour] >= half)\n        {\n            int moves_for_this_colour = half - front_frequency[colour];\n\n            minimum_moves = min(minimum_moves, max(0, moves_for_this_colour));\n        }\n    }\n\n    printf(\"%d\\n\", minimum_moves > no_of_cards ? -1 : minimum_moves);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 205/Programs/Little Elephant and Sorting.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%I64d\", &A[i]);\r\n\r\n    long long no_of_additions = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] < A[i - 1])\r\n        {\r\n            no_of_additions += (A[i - 1] - A[i]);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_additions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 205/Programs/Little_Elephant_Rozdil.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read_time_taken_to_each_city(unsigned int,unsigned long *);\r\nvoid find_which_city_elephant_goes_to(unsigned int,unsigned long *, unsigned int *,unsigned int *);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_cities, no_of_minima, city_with_minimum_time;\r\n    scanf(\"%u\",&no_of_cities);\r\n\r\n    unsigned long *time_taken_to_city = malloc(no_of_cities*(sizeof(unsigned long)));\r\n\r\n    read_time_taken_to_each_city(no_of_cities, time_taken_to_city);\r\n    find_which_city_elephant_goes_to(no_of_cities, time_taken_to_city, &city_with_minimum_time, &no_of_minima); //Pass by reference\r\n\r\n    if(no_of_minima > 1) //If there is more than one city with the same minimum time, stay in Rozdil\r\n    {\r\n        printf(\"Still Rozdil\\n\");\r\n    }\r\n    else //Otherwise, tell the number of the city\r\n    {\r\n        printf(\"%u\\n\", city_with_minimum_time);\r\n    }\r\n\r\n    free(time_taken_to_city);\r\n    return 0;\r\n}\r\n\r\nvoid read_time_taken_to_each_city(unsigned int no_of_cities,unsigned long *time_taken_to_city)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_cities; i++)\r\n    {\r\n            scanf(\"%lu\",(time_taken_to_city + i));\r\n    }\r\n}\r\n\r\nvoid find_which_city_elephant_goes_to(unsigned int no_of_cities,unsigned long *time_taken_to_city, unsigned int *city_with_minimum_time,unsigned int *no_of_minima)\r\n{\r\n    unsigned int i;\r\n\r\n    //First element is marked as minima initially\r\n    *city_with_minimum_time = 0;\r\n    *no_of_minima = 1;\r\n\r\n    for(i = 1; i < no_of_cities; i++)\r\n    {\r\n        if( *(time_taken_to_city + i) < *(time_taken_to_city + *(city_with_minimum_time)))//If it is less than minima, change the minima\r\n        {\r\n            *city_with_minimum_time = i;\r\n            *no_of_minima = 1; //Reseting the count of minima\r\n        }\r\n        else if( *(time_taken_to_city + i) == *(time_taken_to_city + *(city_with_minimum_time)))\r\n        {\r\n            *no_of_minima = *no_of_minima + 1;\r\n        }\r\n    }\r\n\r\n    if(*no_of_minima == 1)//If there is only one minima, increment the value of city because we have started counting from 0 rather than 1\r\n    {\r\n        *(city_with_minimum_time) = *(city_with_minimum_time) + 1;\r\n    }\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 261/Explanation/Pashmak and Buses Explanation.txt",
    "content": "Let us represent the activities of each student as a d-tuple. \r\n(b1, b2, ... bd), where bi represents the bus taken on day i.\r\n\r\nEach day you can take k buses. Overall, there are k^d distinct d-tuples. \r\n\r\nIf two tuples are the same, then it means two students take the same bus everyday.\r\n\r\nIf k^d < N, then by the pigeonhole principle there will be two d-tuples that are the same at every spot.\r\n\r\nSo, if k^d < N, then it is not possible. \r\n\r\nint possible(int people, int buses, int days)\r\n{\r\n    //Check if k^d > n\r\n    for(int power = 1, d = 0; d <= days; power *= buses, d++)\r\n    {\r\n        if(power >= people)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n-------------------------------------------------\r\n\r\nOtherwise, let us generate the first N numbers of length d in base k. \r\n\r\n(In other words, we're visiting the d-tuples in lexicographic order.)\r\n\r\n\r\nfor(int p = 0; p < no_of_people; p++)\r\n    {\r\n        for(int d = 0; d < no_of_days; d++)\r\n        {\r\n            arrangement[p][d] = (p == 0 ? 0 : arrangement[p - 1][d]);\r\n        }\r\n\r\n        for(int d = no_of_days - 1; d >= 0; d--)\r\n        {\r\n            arrangement[p][d]++;\r\n            arrangement[p][d] %= no_of_buses;\r\n\r\n            if(arrangement[p][d] != 0)\r\n                break;\r\n        }\r\n    }\r\n\r\n-----------------------------------------\r\n\r\nIt's easy to generate this with respect to d-tuples, but the output must be in n-tuples\r\n\r\nfor(int d = 0; d < no_of_days; d++)\r\n{\r\n        for(int p = 0; p < no_of_people; p++)\r\n\t{\r\n            printf(\"%d \", arrangement[p][d] + 1);\r\n\t}\r\n        printf(\"\\\\n\");\r\n    \r\n}\r\n \r\n"
  },
  {
    "path": "Contests/Div 2 261/Explanation/Pashmak and Buses.cpp",
    "content": "#include <cstdio>\r\n\r\nconst int MAX_N = 1015;\r\nint arrangement[MAX_N][MAX_N];\r\n\r\nint possible(int people, int buses, int days)\r\n{\r\n    //Check if k^d > n\r\n    for(int power = 1, d = 0; d <= days; power *= buses, d++)\r\n    {\r\n        if(power >= people)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_people, no_of_buses, no_of_days;\r\n    scanf(\"%d %d %d\", &no_of_people, &no_of_buses, &no_of_days);\r\n\r\n    if(!possible(no_of_people, no_of_buses, no_of_days))\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    for(int p = 0; p < no_of_people; p++)\r\n    {\r\n        for(int d = 0; d < no_of_days; d++)\r\n        {\r\n            arrangement[p][d] = (p == 0 ? 0 : arrangement[p - 1][d]);\r\n        }\r\n\r\n        for(int d = no_of_days - 1; d >= 0; d--)\r\n        {\r\n            arrangement[p][d]++;\r\n            arrangement[p][d] %= no_of_buses;\r\n\r\n            if(arrangement[p][d] != 0)\r\n                break;\r\n        }\r\n    }\r\n\r\n    for(int d = 0; d < no_of_days; d++)\r\n    {\r\n        for(int p = 0; p < no_of_people; p++)\r\n        {\r\n            printf(\"%d \", arrangement[p][d] + 1);\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 261/Explanation/Pashmak and Flowers - Explanation.txt",
    "content": "Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. \r\nParmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. \r\nShe wants to have those pairs of flowers that their beauty difference is maximal possible!\r\n\r\nYour task is to write a program which calculates two things:\r\n\r\nThe maximum beauty difference of flowers that Pashmak can give to Parmida.\r\nThe number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and \r\nnot chosen in the second way.\r\n\r\n---------------------------------------------------------------------------------------------\r\n\r\nWe need to count the number of maxima and the number of minima and multiply them. I had overlooked overflow at first in multiplication and the case where the \r\nmaxima and minima are equal. In that case, the answer is n(n-1)/2, where n is the number of flowers because all flowers are equally beautiful. Multiplying number of minima \r\nand maxima will not be correct in that case since it will be overcounting pairs.\r\n\r\n    for(i = 1; i <= no_of_flowers; i++)\r\n    {\r\n        scanf(\"%d\",&current_beauty);\r\n\r\n        if(current_beauty == most_beautiful)\r\n            no_of_maxima++;\r\n\r\n        if(current_beauty == least_beautiful)\r\n            no_of_minima++;\r\n\r\n        if(current_beauty < least_beautiful)\r\n            least_beautiful = current_beauty, no_of_minima = 1;\r\n\r\n        if(current_beauty > most_beautiful)\r\n            most_beautiful = current_beauty, no_of_maxima = 1;\r\n    }\r\n\r\n    //If all flowers are equally beautiful, then choices = n(n-1)/2\r\n    no_of_choices = ( most_beautiful == least_beautiful ? (no_of_flowers*1LL*(no_of_flowers - 1) )/2 : no_of_minima*1LL*no_of_maxima );\r\n\r\n    printf(\"%d %I64d\\n\",(most_beautiful - least_beautiful), no_of_choices);\r\n\r\n--------------------------------------------------------------------------------------------------\r\n\r\nNote - type casting by multiplying by 1LL is necessary to avoid overflow, otherwise 32 bit multiplication will be performed."
  },
  {
    "path": "Contests/Div 2 261/Explanation/Pashmak and Garden Explanation.txt",
    "content": "\r\nOkay, if the x1 = x2, then it means we have a side parallel to y-axis.\r\n\r\nx3 = x1 + d, y3 = y1\r\nx4 = x2 + 3, y4 = y2\r\n\r\nSimilar reasoning if y1 = y2, \r\n\r\nnow, what happens if we have two diagonally opposite points ?\r\n\r\nThen, |x1 - x2| = |y1 - y2|\r\n\r\nThis quantity is the same in squares. We are taking absolute values because it might be anti-diagonal as well.\r\n\r\nint main()\r\n{\r\n    int x_1, x_2, y_1, y_2;\r\n    scanf(\"%d %d %d %d\", &x_1, &y_1, &x_2, &y_2);\r\n\r\n    int x_3, y_3, x_4, y_4;\r\n\r\n    if(x_1 == x_2)\r\n    {\r\n        int distance = abs(y_1 - y_2);\r\n\r\n        x_3 = x_1 + distance; y_3 = y_1;\r\n\r\n        x_4 = x_2 + distance; y_4 = y_2;\r\n    }\r\n    else if(y_1 == y_2)\r\n    {\r\n        int distance = abs(x_1 - x_2);\r\n\r\n        y_3 = y_1 + distance; x_3 = x_1;\r\n\r\n        y_4 = y_2 + distance; x_4 = x_2;\r\n    }\r\n    else if(abs(x_1 - x_2) == abs(y_1 - y_2))\r\n    {\r\n        x_3 = x_1; y_3 = y_2;\r\n\r\n        x_4 = x_2; y_4 = y_1;\r\n    }\r\n    else\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n    printf(\"%d %d %d %d\\n\", x_3, y_3, x_4, y_4);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 261/Explanation/Pashmak and Graph Explanation.txt",
    "content": "1. We will keep an empty graph and add the edges one by one in ascending order of weight\n\n2. When we add an edge (u, v) then we will update path[v] = max(1 + path[u], path[v])\n\n3. We have to be careful on handling edges of the same weight\n\nSuppose we have multiple edges ending at u and then at v, we can't use both u and v\n\nSo, we will process all edges of the same weigh together\n\n-----\n\nstruct Edge\n{\n    int source, destination, weight;\n\n    int operator <(const Edge &A)\n    {\n        return (weight < A.weight);\n    }\n};\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\n\n    vector <Edge> edge(no_of_edges + 1);\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        scanf(\"%d %d %d\", &edge[i].source, &edge[i].destination, &edge[i].weight);\n    }\n\n    sort(all(edge));\n\n    vector <int> maximum_ending_at(no_of_vertices + 1, 0);\n\n    vector <int> maximum_with_this_weight(no_of_vertices + 1, 0);\n\n    for(int i = 1; i <= no_of_edges; )\n    {\n        int j = i;\n\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\n        {\n            maximum_with_this_weight[edge[j].destination] = 0;\n        }\n\n        //Process all edges having this weight. Have a different vector so you don't interact with equal weights.\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\n        {\n            maximum_with_this_weight[edge[j].destination] = max(maximum_with_this_weight[edge[j].destination], 1 + maximum_ending_at[edge[j].source]);\n        }\n\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\n        {\n            maximum_ending_at[edge[j].destination] = max(maximum_ending_at[edge[j].destination], maximum_with_this_weight[edge[j].destination]);\n        }\n\n        i = j;\n    }\n\n    int maximum_path = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n        maximum_path = max(maximum_path, maximum_ending_at[i]);\n\n    printf(\"%d\\n\", maximum_path);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 261/Explanation/Pashmak and Parmida's Problem Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpUkU\n\nLet L[i] be frequeny of i in prefix.\nR[i] be frequency of i in suffix.\n\nMaintain an array S, where the index is R[i] and value if frequency of R[i].\n\nProcess the indices from i = N to 1\n\nFor each i, take the sum of [1, L[i] - 1], and then increment S[R[i]] by 1.\n\nThis ensures that whatever we have summed has R < L[i] because we have only taken the range L[i] - 1\n\nAnd j > i, because we are inserting in descending order. If R[j] is already in S, then it means j > i\n\nSo both conditions i < j and L[i] > R[j] are satisfied ! Beautiful Problem !\n\n----------------------------------------------------------------------------------\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\n\n    map <int, int> left_frequency;\n    vector <int> left(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        left_frequency[A[i]]++;\n\n        left[i] = left_frequency[A[i]];\n    }\n\n    map <int, int> right_frequency;\n    vector <int> right(no_of_elements + 1, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        right_frequency[A[i]]++;\n\n        right[i] = right_frequency[A[i]];\n    }\n\n    LL answer = 0;\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        answer += get_sum(1, 1, no_of_elements, 1, left[i] - 1); //Adding all rights that are smaller than left\n\n        update(1, 1, no_of_elements, right[i], 1);\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 261/Programs/Pashmak and Buses.cpp",
    "content": "#include <cstdio>\r\n\r\nconst int MAX_N = 1015;\r\nint arrangement[MAX_N][MAX_N];\r\n\r\nint possible(int people, int buses, int days)\r\n{\r\n    //Check if k^d > n\r\n    for(int power = 1, d = 0; d <= days; power *= buses, d++)\r\n    {\r\n        if(power >= people)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_people, no_of_buses, no_of_days;\r\n    scanf(\"%d %d %d\", &no_of_people, &no_of_buses, &no_of_days);\r\n\r\n    if(!possible(no_of_people, no_of_buses, no_of_days))\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    for(int p = 0; p < no_of_people; p++)\r\n    {\r\n        for(int d = 0; d < no_of_days; d++)\r\n        {\r\n            arrangement[p][d] = (p == 0 ? 0 : arrangement[p - 1][d]);\r\n        }\r\n\r\n        for(int d = no_of_days - 1; d >= 0; d--)\r\n        {\r\n            arrangement[p][d]++;\r\n            arrangement[p][d] %= no_of_buses;\r\n\r\n            if(arrangement[p][d] != 0)\r\n                break;\r\n        }\r\n    }\r\n\r\n    for(int d = 0; d < no_of_days; d++)\r\n    {\r\n        for(int p = 0; p < no_of_people; p++)\r\n        {\r\n            printf(\"%d \", arrangement[p][d] + 1);\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 261/Programs/Pashmak and Garden.cpp",
    "content": "#include <cstdio>\r\n#define abs(x) ( (x) > 0 ? (x) : -(x) )\r\n\r\nint main()\r\n{\r\n    int x_1, x_2, y_1, y_2;\r\n    scanf(\"%d %d %d %d\", &x_1, &y_1, &x_2, &y_2);\r\n\r\n    int x_3, y_3, x_4, y_4;\r\n\r\n    if(x_1 == x_2)\r\n    {\r\n        int distance = abs(y_1 - y_2);\r\n\r\n        x_3 = x_1 + distance; y_3 = y_1;\r\n\r\n        x_4 = x_2 + distance; y_4 = y_2;\r\n    }\r\n    else if(y_1 == y_2)\r\n    {\r\n        int distance = abs(x_1 - x_2);\r\n\r\n        y_3 = y_1 + distance; x_3 = x_1;\r\n\r\n        y_4 = y_2 + distance; x_4 = x_2;\r\n    }\r\n    else if(abs(x_1 - x_2) == abs(y_1 - y_2))\r\n    {\r\n        x_3 = x_1; y_3 = y_2;\r\n\r\n        x_4 = x_2; y_4 = y_1;\r\n    }\r\n    else\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n    printf(\"%d %d %d %d\\n\", x_3, y_3, x_4, y_4);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 261/Programs/Pashmak and Graph.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\nusing namespace std;\r\n\r\nstruct Edge\r\n{\r\n    int source, destination, weight;\r\n\r\n    int operator <(const Edge &A)\r\n    {\r\n        return (weight < A.weight);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    vector <Edge> edge(no_of_edges + 1);\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        scanf(\"%d %d %d\", &edge[i].source, &edge[i].destination, &edge[i].weight);\r\n    }\r\n\r\n    sort(all(edge));\r\n\r\n    vector <int> maximum_ending_at(no_of_vertices + 1, 0);\r\n\r\n    vector <int> maximum_with_this_weight(no_of_vertices + 1, 0);\r\n    \r\n    for(int i = 1; i <= no_of_edges; )\r\n    {\r\n        int j = i;\r\n\r\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\r\n        {\r\n            maximum_with_this_weight[edge[j].destination] = 0;\r\n        }\r\n        \r\n        //Process all edges having this weight. Have a different vector so you don't interact with equal weights.\r\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\r\n        {\r\n            maximum_with_this_weight[edge[j].destination] = max(maximum_with_this_weight[edge[j].destination], 1 + maximum_ending_at[edge[j].source]);\r\n        }\r\n\r\n        for(j = i; j <= no_of_edges && edge[j].weight == edge[i].weight; j++)\r\n        {\r\n            maximum_ending_at[edge[j].destination] = max(maximum_ending_at[edge[j].destination], maximum_with_this_weight[edge[j].destination]);\r\n        }\r\n\r\n        i = j;\r\n    }\r\n\r\n    int maximum_path = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        maximum_path = max(maximum_path, maximum_ending_at[i]);\r\n\r\n    printf(\"%d\\n\", maximum_path);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 261/Programs/Pashmak and Parmida's Problem.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\ntypedef long long LL;\n\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\n\nconst int MAX_N = 1e6;\nLL sum_tree[3*MAX_N];\n\nvoid update(int n, int left, int right, int position, int value)\n{\n    if(right < position || position < left)\n        return;\n\n    if(left == right)\n    {\n        sum_tree[n] += value;\n\n        return;\n    }\n\n    int mid = (left + right) >> 1;\n\n    update(LEFT(n), left, mid, position, value);\n    update(RIGHT(n), mid + 1, right, position, value);\n\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\n}\n\nLL get_sum(int n, int left, int right, int query_left, int query_right)\n{\n    if(right < query_left || query_right < left)\n        return 0;\n\n    if(query_left <= left && right <= query_right)\n        return sum_tree[n];\n\n    int mid = (left + right) >> 1;\n\n    LL left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\n    LL right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\n\n    return (left_sum + right_sum);\n}\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\n\n    map <int, int> left_frequency;\n    vector <int> left(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        left_frequency[A[i]]++;\n\n        left[i] = left_frequency[A[i]];\n    }\n\n    map <int, int> right_frequency;\n    vector <int> right(no_of_elements + 1, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        right_frequency[A[i]]++;\n\n        right[i] = right_frequency[A[i]];\n    }\n\n    LL answer = 0;\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        answer += get_sum(1, 1, no_of_elements, 1, left[i] - 1); //Adding all rights that are smaller than left\n\n        update(1, 1, no_of_elements, right[i], 1);\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 261/Programs/Pashmak_and_Flowers.c",
    "content": "#include <stdio.h>\r\n\r\nint main()\r\n{\r\n    int no_of_minima = 0, no_of_maxima = 0, most_beautiful = 0, least_beautiful = 1e9 + 1, no_of_flowers, current_beauty, i;\r\n    long long no_of_choices;\r\n    scanf(\"%d\", &no_of_flowers);\r\n\r\n    for(i = 1; i <= no_of_flowers; i++)\r\n    {\r\n        scanf(\"%d\",&current_beauty);\r\n\r\n        if(current_beauty == most_beautiful)\r\n            no_of_maxima++;\r\n\r\n        if(current_beauty == least_beautiful)\r\n            no_of_minima++;\r\n\r\n        if(current_beauty < least_beautiful)\r\n            least_beautiful = current_beauty, no_of_minima = 1;\r\n\r\n        if(current_beauty > most_beautiful)\r\n            most_beautiful = current_beauty, no_of_maxima = 1;\r\n    }\r\n\r\n    //If all flowers are equally beautiful, then choices = n(n-1)/2\r\n    no_of_choices = ( most_beautiful == least_beautiful ? (no_of_flowers*1LL*(no_of_flowers - 1) )/2 : no_of_minima*1LL*no_of_maxima );\r\n\r\n    printf(\"%d %I64d\\n\",(most_beautiful - least_beautiful), no_of_choices);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 276/Explanations/Little Girl and Maximum XOR Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTCDS\n\nLet L = 000110011\n\nR = 0001101111\n\nNotice that there must be some position p, where R[p] = 1, and L[p] = 0\n\nand for all i < p, R[p] = L[p]\n\nThe key observation here is that all numbers in between [L, R] will all have the same value for all those bits before p. The XOR of any two numbers will give 0. It doesn’t contribute anything.\n\nNow, the largest possible XOR we can get is a number with p 1’s since all the bits before that will always be 0 in any pair we choose.\n\nNow, I’ll prove it’s always possible to get a number with p 1’s.\n\nLet A match the common prefix of L and R.\n\nA[p] = 0, and let all positions after this = 1\n\nA is smaller than R for sure since R[p] = 1. It is >= L. It can’t be smaller than L because it matches L till position P and from then has all 1’s.\n\nLet B match the common prefix of L and R till p.\n\nB[p] = 1, and then all positions after that have 0.\n\nB is greater than L because B[p] = 1 > L[p]\n\nB is <= R because it matches R till position P and from there has all 0s.\n\n(A xor B) = a string of 1’s.\n\nWe don’t even need to find out what the numbers are ! \n\n----------------------------------------------------------------------------------\n\nint main()\n{\n    long long left, right;\n    scanf(\"%I64d %I64d\", &left, &right);\n\n    if(left == right)\n    {\n        printf(\"0\\n\");\n        return 0;\n    }\n\n    int largest_unequal_bit_position;\n\n    for(int i = 0; left > 0 || right > 0; i++)\n    {\n        if(left%2 != right%2)\n            largest_unequal_bit_position = i;\n\n        left >>= 1;\n        right >>= 1;\n    }\n\n    long long answer = all_ones(largest_unequal_bit_position); //This gives a number consisting of n 1's in binary\n    printf(\"%I64d\\n\", answer);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 276/Programs/Little Girl and Maximum Sum.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    vector <int> element(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <int> no_of_queries_starting_here(no_of_elements + 1, 0);\r\n    vector <int> no_of_queries_ending_here(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        int left_i, right_i;\r\n        scanf(\"%d %d\", &left_i, &right_i);\r\n\r\n        no_of_queries_starting_here[left_i]++;\r\n\r\n        if(right_i + 1 <= no_of_elements)\r\n            no_of_queries_ending_here[right_i + 1]++;\r\n    }\r\n\r\n    int no_of_queries_on_this_index = 0;\r\n    vector <int> no_of_times_index_queried(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        no_of_queries_on_this_index += (no_of_queries_starting_here[i] - no_of_queries_ending_here[i]);\r\n\r\n        no_of_times_index_queried[i] = no_of_queries_on_this_index;\r\n    }\r\n\r\n    sort(all(element));\r\n    sort(all(no_of_times_index_queried));\r\n\r\n    long long maximum_sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        maximum_sum += no_of_times_index_queried[i]*1LL*element[i];\r\n\r\n    printf(\"%I64d\\n\", maximum_sum);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 276/Programs/Little Girl and Maximum XOR.cpp",
    "content": "#include <cstdio>\n\nlong long all_ones(int n)\n{\n    return (1LL << (n + 1)) - 1;\n}\n\nint main()\n{\n    long long left, right;\n    scanf(\"%I64d %I64d\", &left, &right);\n\n    if(left == right)\n    {\n        printf(\"0\\n\");\n        return 0;\n    }\n\n    int largest_unequal_bit_position;\n\n    for(int i = 0; left > 0 || right > 0; i++)\n    {\n        if(left%2 != right%2)\n            largest_unequal_bit_position = i;\n\n        left >>= 1;\n        right >>= 1;\n    }\n\n    long long answer = all_ones(largest_unequal_bit_position); //This gives a number consisting of n 1's in binary\n    printf(\"%I64d\\n\", answer);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 276/Programs/Lunch Rush.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_restaurants, time_limit;\r\n    scanf(\"%d %d\", &no_of_restaurants, &time_limit);\r\n\r\n    const int NEGATIVE_INFINITY = -1e9;\r\n    int maximum_joy = NEGATIVE_INFINITY;\r\n    for(int i = 1; i <= no_of_restaurants; i++)\r\n    {\r\n        int time_i, joy_i;\r\n        scanf(\"%d %d\", &joy_i, &time_i);\r\n\r\n        if(time_i <= time_limit)\r\n        {\r\n            maximum_joy = max(maximum_joy, joy_i);\r\n        }\r\n        else\r\n        {\r\n            maximum_joy = max(maximum_joy, joy_i - (time_i - time_limit));\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", maximum_joy);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 321/Programs/Kefa and Company.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin() + 1, (v).end()\nusing namespace std;\n\nstruct info\n{\n    int money, friendship;\n};\n\nint sort_by_money(const info &A, const info &B)\n{\n    return (A.money < B.money);\n}\n\nint main()\n{\n    int no_of_friends, difference;\n    scanf(\"%d %d\", &no_of_friends, &difference);\n\n    vector <info> friends(no_of_friends + 1);\n    for(int i = 1; i <= no_of_friends; i++)\n        scanf(\"%d %d\", &friends[i].money, &friends[i].friendship);\n\n    sort(all(friends), sort_by_money);\n\n    long long maximum_friendship = 0, current_friendship = 0;\n    int left = 1, right = 1;\n\n    while(right <= no_of_friends)\n    {\n         if(friends[right].money - friends[left].money < difference)\n        {\n            current_friendship += friends[right].friendship;\n            right++;\n        }\n        else\n        {\n            current_friendship -= friends[left].friendship;\n            left++;\n        }\n\n        maximum_friendship = max(maximum_friendship, current_friendship);\n    }\n\n    printf(\"%I64d\\n\", maximum_friendship);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 321/Programs/Kefa and Park.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_VERTICES = 2e5 + 1;\r\nint visited[MAX_VERTICES] = {false};\r\nint has_cat[MAX_VERTICES] = {false};\r\nint no_of_consecutive_cats_till[MAX_VERTICES] = {0};\r\nvector <int> tree[MAX_VERTICES];\r\n\r\nint max_cats;\r\n\r\nvoid dfs(int current_park, int &no_of_paths)\r\n{\r\n    if(tree[current_park].size() == 1 && visited[tree[current_park][0]])\r\n        no_of_paths++;\r\n\r\n    for(int i = 0; i < tree[current_park].size(); i++)\r\n    {\r\n        int next_park = tree[current_park][i];\r\n\r\n        if(!visited[next_park])\r\n        {\r\n            visited[next_park] = true;\r\n\r\n            no_of_consecutive_cats_till[next_park] = (has_cat[next_park] ? no_of_consecutive_cats_till[current_park] + 1 : 0);\r\n\r\n            if(no_of_consecutive_cats_till[next_park] <= max_cats)\r\n                dfs(next_park, no_of_paths);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d %d\", &no_of_vertices, &max_cats);\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        scanf(\"%d\", &has_cat[i]);\r\n\r\n    for(int i = 1; i <= no_of_vertices - 1; i++)\r\n    {\r\n        int x, y;\r\n        scanf(\"%d %d\", &x, &y);\r\n\r\n        tree[x].push_back(y);\r\n        tree[y].push_back(x);\r\n    }\r\n\r\n    no_of_consecutive_cats_till[1] = has_cat[1];\r\n    visited[1] = true;\r\n    int no_of_paths = 0;\r\n\r\n    dfs(1, no_of_paths);\r\n\r\n    printf(\"%d\\n\", no_of_paths);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 321/Programs/Kefa_and_First_Step.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n\r\nvoid read(unsigned long *, unsigned int);\r\nunsigned int find_length_longest_non_decreasing_streak(unsigned long *, unsigned int);\r\nunsigned long max(unsigned long, unsigned long);\r\n\r\nint main()\r\n{\r\n    unsigned int no_of_days, longest_non_decreasing_streak;\r\n\r\n    scanf(\"%u\",&no_of_days);\r\n\r\n    unsigned long *money_made = malloc(no_of_days*sizeof(unsigned long));\r\n    read(money_made, no_of_days);\r\n\r\n    longest_non_decreasing_streak = find_length_longest_non_decreasing_streak(money_made, no_of_days);\r\n    printf(\"%u\\n\",longest_non_decreasing_streak);\r\n    free(money_made);\r\n    return 0;\r\n}\r\n\r\nunsigned int find_length_longest_non_decreasing_streak(unsigned long *money_made, unsigned int no_of_days)\r\n{\r\n    unsigned int i, longest_non_decreasing_streak = 1, current_non_decreasing_streak = 1 ;\r\n\r\n    for(i = 1; i < no_of_days; i++)\r\n    {\r\n        //If A[i] >= A[i-1], current streak increases, else a new streak begins.\r\n        current_non_decreasing_streak = (  ( *(money_made + i) >= *(money_made + i -1) ) ? current_non_decreasing_streak+1 : 1 );\r\n\r\n        longest_non_decreasing_streak = max(longest_non_decreasing_streak, current_non_decreasing_streak);\r\n    }\r\n\r\n    return longest_non_decreasing_streak;\r\n}\r\n\r\nvoid read(unsigned long *money_made, unsigned int no_of_days)\r\n{\r\n    unsigned int i;\r\n\r\n    for(i = 0; i < no_of_days; i++)\r\n    {\r\n        scanf(\"%lu\",(money_made + i));\r\n    }\r\n}\r\n\r\nunsigned long max(unsigned long a, unsigned long b)\r\n{\r\n    return ( (a > b) ? a : b);\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 367/Explanation/Hard Problem Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUT2km\n\n-----------------------------------------\n\nHere's the main idea. \n\nAssume the first i elements of the list are already sorted. How can you place string (i + 1) at the end of this list ?\n\nThere are two options - Either you place it reversed, or un-reversed.\n\nf(i, R) = Minimum cost for the first i strings with last string reversed.\n\nf(i, U) = Minimum cost for the first i strings with last string unreversed.\n\n\nif(s[i] >= s[i - 1]) f(i, U) = f(i - 1, U)\n\nif(s[i] >= R(s[i - 1]) f(i, U) = min{f(i, U), f(i - 1, R)}\n\nif(R(s[i]) >= s[i - 1]) f(i, R) = c[i] + f(i - 1, U)\n\nif(R(s[i]) >= R(s[i - 1])) f(i, R) = min{f(i, R), c[i] + f(i - 1, R)}\n\nAnswer = min{f(N, R), f(N, U)}\n\nCheck if answer >= oo, in which case it's not possible.\n\n------------------------------------------------------------------------------\n\nstring rev(string s)\n{\n    reverse(all(s));\n\n    return s;\n}\n\nint main()\n{\n    int no_of_strings;\n    scanf(\"%d\", &no_of_strings);\n\n    vector <int> cost(no_of_strings + 1);\n    for(int i = 1; i <= no_of_strings; i++)\n        scanf(\"%d\", &cost[i]);\n\n    vector <string> s(no_of_strings + 1);\n    for(int i = 1; i <= no_of_strings; i++)\n        cin >> s[i];\n\n    const long long oo = 1e16;\n    const int WITHOUT_REVERSING = 0, REVERSING = 1;\n    long long minimum_till[no_of_strings + 1][2];\n    minimum_till[0][REVERSING] = minimum_till[0][WITHOUT_REVERSING] = 0;\n\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        minimum_till[i][REVERSING] = minimum_till[i][WITHOUT_REVERSING] = oo;\n\n        if(s[i] >= s[i - 1])\n            minimum_till[i][WITHOUT_REVERSING] = minimum_till[i - 1][WITHOUT_REVERSING];\n\n        if(s[i] >= rev(s[i - 1]))\n            minimum_till[i][WITHOUT_REVERSING] = min(minimum_till[i][WITHOUT_REVERSING], minimum_till[i - 1][REVERSING]);\n\n        if(rev(s[i]) >= s[i - 1])\n            minimum_till[i][REVERSING] = cost[i] + minimum_till[i - 1][WITHOUT_REVERSING];\n\n        if(rev(s[i]) >= rev(s[i - 1]))\n            minimum_till[i][REVERSING] = min(minimum_till[i][REVERSING], cost[i] + minimum_till[i - 1][REVERSING]);\n\n    }\n\n    long long answer = min(minimum_till[no_of_strings][REVERSING], minimum_till[no_of_strings][WITHOUT_REVERSING]);\n\n    printf(\"%I64d\\n\", answer >= oo ? -1 : answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 367/Explanation/Interesting Drink Explanation.txt",
    "content": "Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink \"Beecola\", \r\nwhich can be bought in n different shops in the city. \r\nIt's known that the price of one bottle in the shop i is equal to xi coins.\r\n\r\nVasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. \r\nNow, for each of the days he want to know in how many different shops he can buy a bottle of \"Beecola\".\r\n\r\n-------------------------------------------------\r\n\r\nSort all the drinks in ascending order of price and then use upper bound.\r\n\r\nupper bound returns the rightmost index that is <= key.  It is already one indexed so no need to decrease by 1.  If all the prices are greater, than it will return 0.\r\nIf all are smaller it will return n.\r\n\r\n------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_shops;\r\n    scanf(\"%d\", &no_of_shops);\r\n\r\n    vector <int> price_in_shop(no_of_shops);\r\n    for(int i = 0; i < no_of_shops; i++)\r\n        scanf(\"%d\", &price_in_shop[i]);\r\n\r\n    sort(all(price_in_shop));\r\n\r\n    int no_of_days, budget_day_i;\r\n    scanf(\"%d\", &no_of_days);\r\n\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        scanf(\"%d\", &budget_day_i);\r\n        int no_of_eligible_shops = upper_bound(all(price_in_shop), budget_day_i) - price_in_shop.begin();\r\n\r\n        printf(\"%d\\n\",no_of_eligible_shops); //0 indexed vector so no need to subtract 1.\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 367/Programs/Hard Problem.cpp",
    "content": "#include <cstdio>\n#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nstring rev(string s)\n{\n    reverse(all(s));\n\n    return s;\n}\n\nint main()\n{\n    int no_of_strings;\n    scanf(\"%d\", &no_of_strings);\n\n    vector <int> cost(no_of_strings + 1);\n    for(int i = 1; i <= no_of_strings; i++)\n        scanf(\"%d\", &cost[i]);\n\n    vector <string> s(no_of_strings + 1);\n    for(int i = 1; i <= no_of_strings; i++)\n        cin >> s[i];\n\n    const long long oo = 1e16;\n    const int WITHOUT_REVERSING = 0, REVERSING = 1;\n    long long minimum_till[no_of_strings + 1][2];\n    minimum_till[0][REVERSING] = minimum_till[0][WITHOUT_REVERSING] = 0;\n\n    for(int i = 1; i <= no_of_strings; i++)\n    {\n        minimum_till[i][REVERSING] = minimum_till[i][WITHOUT_REVERSING] = oo;\n\n        if(s[i] >= s[i - 1])\n            minimum_till[i][WITHOUT_REVERSING] = minimum_till[i - 1][WITHOUT_REVERSING];\n\n        if(s[i] >= rev(s[i - 1]))\n            minimum_till[i][WITHOUT_REVERSING] = min(minimum_till[i][WITHOUT_REVERSING], minimum_till[i - 1][REVERSING]);\n\n        if(rev(s[i]) >= s[i - 1])\n            minimum_till[i][REVERSING] = cost[i] + minimum_till[i - 1][WITHOUT_REVERSING];\n\n        if(rev(s[i]) >= rev(s[i - 1]))\n            minimum_till[i][REVERSING] = min(minimum_till[i][REVERSING], cost[i] + minimum_till[i - 1][REVERSING]);\n\n    }\n\n    long long answer = min(minimum_till[no_of_strings][REVERSING], minimum_till[no_of_strings][WITHOUT_REVERSING]);\n\n    printf(\"%I64d\\n\", answer >= oo ? -1 : answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 367/Programs/Interesting Drink.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <iostream>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_shops;\r\n    scanf(\"%d\", &no_of_shops);\r\n\r\n    vector <int> price_in_shop(no_of_shops);\r\n    for(int i = 0; i < no_of_shops; i++)\r\n        scanf(\"%d\", &price_in_shop[i]);\r\n\r\n    sort(all(price_in_shop));\r\n\r\n    int no_of_days, budget_day_i;\r\n    scanf(\"%d\", &no_of_days);\r\n\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        scanf(\"%d\", &budget_day_i);\r\n        int no_of_eligible_shops = upper_bound(all(price_in_shop), budget_day_i) - price_in_shop.begin();\r\n\r\n        printf(\"%d\\n\",no_of_eligible_shops); //0 indexed vector so no need to subtract 1.\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 371/Explanations/Sonya and Queries Explanation.txt",
    "content": "I was thinking of a very complicated solution involving tries, but there's actually a very simple, elegant and beautiful solution to \nthis problem !\n\nMaintain a frequency array. \n\nRather than storing the numbers, store the mask of the number ! We only have about 2^{18} masks !\n\nHere's how you get the mask of an integer - \n\nint get_mask(long long n)\n{\n    int mask = 0;\n\n    for(int bit = 0; n > 0; bit++)\n    {\n        int digit = n%10;\n\n        if(digit%2 == 1)\n            mask |= (1LL << bit);\n\n        n /= 10;\n    }\n\n    return mask;\n}\n\nSet the bit at all the odd digits.\n\n-----------------------------------------------------\n\nFor each query, give the frequency of the mask ! We're done !\n\nwhile(no_of_queries--)\n    {\n        const char INSERTION = '+', DELETION = '-', QUERY = '?';\n        char query_type;\n\n        cin >> query_type;\n\n        if(query_type == INSERTION)\n        {\n            long long n;\n            cin >> n;\n            frequency[get_mask(n)]++;\n        }\n        else if(query_type == DELETION)\n        {\n            long long n;\n            cin >> n;\n            frequency[get_mask(n)]--;\n        }\n        else if(query_type == QUERY)\n        {\n            string mask;\n            cin >> mask;\n            cout << frequency[to_integer(mask)] << \"\\n\";\n        }\n    }\n"
  },
  {
    "path": "Contests/Div 2 371/Programs/Filya_and_Homework.c",
    "content": "#include <stdio.h>\r\n#include <stdlib.h>\r\n#include <string.h>\r\n\r\n#define true 1\r\n#define false 0\r\n\r\nshort count_no_of_distinct_elements(unsigned long *,unsigned long, unsigned long[]);\r\nshort check_if_set_is_in_AP(unsigned long[], short);\r\nvoid get_answer(char[], short);\r\n\r\nint main()\r\n{\r\n    short is_possible = false, distinct_count;\r\n    unsigned long no_of_elements, i, distinct_element[3];\r\n    unsigned long *list_of_numbers = NULL;\r\n    char answer[4];\r\n\r\n    scanf(\"%lu\",&no_of_elements);\r\n    list_of_numbers = malloc(no_of_elements*sizeof(unsigned long));\r\n    for(i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%lu\",(list_of_numbers + i));\r\n    }\r\n\r\n\r\n    distinct_count = count_no_of_distinct_elements(list_of_numbers, no_of_elements, distinct_element);\r\n\r\n    if(distinct_count > 3)\r\n    {\r\n        is_possible = false;\r\n    }\r\n    else\r\n    {\r\n        is_possible = check_if_set_is_in_AP(distinct_element, distinct_count);\r\n    }\r\n    get_answer(answer, is_possible);\r\n\r\n    printf(\"%s\\n\",answer);\r\n    free(list_of_numbers);\r\n    return 0;\r\n}\r\n\r\nshort count_no_of_distinct_elements(unsigned long *list_of_numbers,unsigned long no_of_elements, unsigned long distinct_element[])\r\n{\r\n    short distinct_count = 0, already_counted;\r\n    int i, j;\r\n\r\n    for(i = 0; i < no_of_elements; i++)\r\n    {\r\n        already_counted = false; //For the i=th element,\r\n        for(j = 0; j < distinct_count ; j++)\r\n        {\r\n            if(*(list_of_numbers + i) == distinct_element[j])\r\n            {\r\n                already_counted = true;\r\n                break;\r\n            }\r\n        }\r\n        if(already_counted == false)\r\n        {\r\n            distinct_element[distinct_count] = *(list_of_numbers + i);\r\n            distinct_count++;\r\n            if(distinct_count > 3) //If it exceeds three, just stop. Because it isn't possible for more than three distinct elements.\r\n            {\r\n                break;\r\n            }\r\n        }\r\n    }\r\n    return distinct_count ;\r\n}\r\n\r\nshort check_if_set_is_in_AP(unsigned long distinct_element[], short distinct_count)\r\n{\r\n    short set_is_in_AP = false;\r\n\r\n    if(distinct_count < 3) //Set of 2 or 1 element will always be in AP\r\n    {\r\n        set_is_in_AP = true;\r\n        return set_is_in_AP;\r\n    }\r\n\r\n    unsigned long a = distinct_element[0], b = distinct_element[1], c = distinct_element[2];\r\n\r\n    if( (a + c == 2*b) || (b + c == 2*a) || (b + a == 2*c) )\r\n    {\r\n        set_is_in_AP = true;\r\n    }\r\n    return set_is_in_AP;\r\n}\r\n\r\nvoid get_answer(char answer[], short is_possible)\r\n{\r\n    if(is_possible == true)\r\n    {\r\n        strcpy(answer, \"YES\");\r\n    }\r\n    else\r\n    {\r\n        strcpy(answer, \"NO\");\r\n    }\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 371/Programs/Meeting_of_Old_Friends.c",
    "content": "#include <stdio.h>\r\n\r\n#define max(a,b) (a > b ? a : b)\r\n#define min(a,b) (a < b ? a : b)\r\nint main()\r\n{\r\n    long long sonya_start, sonya_end, filya_start, filya_end, no_of_minutes, prinking_minute, meeting_start, meeting_end;\r\n    scanf(\"%I64d %I64d %I64d %I64d %I64d\",&sonya_start, &sonya_end, &filya_start, &filya_end, &prinking_minute);\r\n\r\n    meeting_start = max(sonya_start, filya_start);\r\n    meeting_end = min(sonya_end, filya_end);\r\n\r\n    no_of_minutes = (meeting_end >= meeting_start) ? (meeting_end - meeting_start + 1) : 0; //Inclusive of starting and ending time\r\n    no_of_minutes -= (prinking_minute >= meeting_start) && (prinking_minute <= meeting_end)? 1 : 0; //Decrement 1 if k is in the meeting time\r\n    printf(\"%I64d\\n\",no_of_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 371/Programs/Sonya and Queries.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint to_integer(string S)\n{\n    int mask = 0;\n\n    for(int i = S.size() - 1, bit = 0; i >= 0; i--, bit++)\n    {\n        if(S[i] == '1')\n            mask |= (1LL << bit);\n    }\n\n    return mask;\n}\n\nint get_mask(long long n)\n{\n    int mask = 0;\n\n    for(int bit = 0; n > 0; bit++)\n    {\n        int digit = n%10;\n\n        if(digit%2 == 1)\n            mask |= (1LL << bit);\n\n        n /= 10;\n    }\n\n    return mask;\n}\n\nint main()\n{\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    map <int, int> frequency;\n    while(no_of_queries--)\n    {\n        const char INSERTION = '+', DELETION = '-', QUERY = '?';\n        char query_type;\n\n        cin >> query_type;\n\n        if(query_type == INSERTION)\n        {\n            long long n;\n            cin >> n;\n            frequency[get_mask(n)]++;\n        }\n        else if(query_type == DELETION)\n        {\n            long long n;\n            cin >> n;\n            frequency[get_mask(n)]--;\n        }\n        else if(query_type == QUERY)\n        {\n            string mask;\n            cin >> mask;\n            cout << frequency[to_integer(mask)] << \"\\n\";\n        }\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 461/Explanations/Cave Paintings Explanation.txt",
    "content": "Let us try to examine the properties of n, if it had a different remainder with every number from 1 to k.\n\nn = 0 (mod 1)\n\nThis means \n\nn = 1 (mod 2) No other option.\n\nSimilarly, \n\nn = 2 (mod 3)\n\nn = 3 (mod 4)\n\nAnd so on. \n\nAt every stage, n = -1 (mod i)\n\nThis means, (n + 1) = 0 (mod i)\n\nThis means that (n + 1) must be divisible by every number from 1 to i.\n\nI made the mistake of thinking that it means (n + 1) should be i!, and then a multiple of i!, but that's incorrect. \n\nIt's a common mistake. If you mark multiples of A and B, multiples of LCM(A, B) will be marked twice, not AB. LCM(A, B) = AB, when they are coprime. \n\nSo, actually (n + 1) should be a multiple of all numbers from 1 to i, means it should be divisibly by LCM(1, ... , i)\n\nI checked how fast the sequence grows and when i = 43, it is > 10^18. So in the contest, I precomputed all LCM's from 1 to 42, and then if k < 43 and (n + 1)%lcm(43) == 0,\n\nAnswer is yes\n\n------------------------------------------------------------------------------\n\n#include <cstdio>\n\nint main()\n{\n    long long n, k;\n    scanf(\"%I64d %I64d\", &n, &k);\n\n    long long lcm_1_till[45];\n    lcm_1_till[1] = 1;\n\n    for(int i = 2; i < 43; i++)\n    {\n        int ii = i;\n        long long extra = 1, lcm_i_minus_1 = lcm_1_till[i - 1];\n\n        for(int j = 2; j <= ii; j++)\n        {\n            while(ii%j == 0)\n            {\n                ii /= j;\n                if(lcm_i_minus_1%j == 0)\n                    lcm_i_minus_1 /= j;\n                else\n                    extra *= j;\n\n            }\n        }\n\n        lcm_1_till[i] = lcm_1_till[i - 1]*extra;\n    }\n\n    printf( k < 43 && (n + 1)%lcm_1_till[k] == 0 ? \"Yes\\n\" : \"No\\n\");\n\n    return 0;\n}\n\n-------------------------------------------------------------------------------\n\nAfter the contest, and reading the editorial, I made it cleaner by realising that no need of precomputing, k < 43, so you can check every number from 1 to 42, provided\n\nk < 43\n\nint main()\n{\n    long long n, k;\n    scanf(\"%I64d %I64d\", &n, &k);\n\n    const int LIMIT = 43;\n    int divisible_by_lcm = true;\n\n    if(k < LIMIT)\n    {\n        for(int i = 1; i <= k; i++)\n        {\n            if( (n + 1)%i != 0)\n            {\n                divisible_by_lcm = false;\n                break;\n            }\n        }\n    }\n\n    printf(k < LIMIT && divisible_by_lcm ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 461/Programs/Cave Paintings.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    long long n, k;\n    scanf(\"%I64d %I64d\", &n, &k);\n\n    const int LIMIT = 43;\n    int divisible_by_lcm_1_till_k = true;\n\n    if(k < LIMIT)\n    {\n        for(int i = 1; i <= k; i++)\n        {\n            if( (n + 1)%i != 0)\n            {\n                divisible_by_lcm_1_till_k = false;\n                break;\n            }\n        }\n    }\n\n    printf(k < LIMIT && divisible_by_lcm_1_till_k ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 464/Programs/Love Triangle.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_planes;\n    scanf(\"%d\", &no_of_planes);\n\n    vector <int> liked_by(no_of_planes + 1);\n    for(int i = 1; i <= no_of_planes; i++)\n        scanf(\"%d\", &liked_by[i]);\n\n    int love_triangle_exists = false;\n    for(int i = 1; i <= no_of_planes; i++)\n    {\n        int a = i;\n        int b = liked_by[a];\n        int c = liked_by[b];\n\n        if(a == liked_by[c])\n        {\n            love_triangle_exists = true;\n        }\n    }\n\n    printf(love_triangle_exists ? \"YES\\n\" : \"NO\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 473/Explanation/Mahmoud and Ehab and Another Array Construction Task Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTAnY\n\nIf all the elements are pairwise coprime, then it means that no prime number occurs in the prime factorisation of two numbers.\n\nLet us keep an array Used[]\n\nUsed[x] = true, if prime factor x occurs in the factorisation of some A[i]. \nUsed[x] = false, otherwise. \n\nNow, we go through each A[i], \n\nIf all of A[i]'s prime factors are unused, then mark all of them and add A[i] to the solution. \n\nIf we get an A[i], which has at least one used prime factor, \n\nThen, x = A[i], \n\nwhile(all_prime_factors_unused(x))\n\tx++\n\nAnd then insert x to the solution. \n\nNow, we have lexicographically larger B. \n\nFrom here, onwards, we must print the smallest numbers that are not used. \n\nThese numbers must be prime. \n\nLet us suppose we have a composite numbe C. We can get a smaller number by replacing C with any of it's prime factors. \n\nSo, here's the overall algorithm.\n\n1. Push as many A[i] as possible. \n2. If an A[i] is not possible, x = A[i] + 1, keep incrementing till x is possible.\n3. After x, print the smallest unused primes. \n\n-----------------------------------------------------------------------------------------------\n\nvoid sieve(vector <int> &is_prime, int LIMIT)\n{\n    is_prime[0] = is_prime[1] = false;\n    for(long long i = 2; i*i <= LIMIT; i++)\n    {\n        if(is_prime[i])\n        {\n            for(long long multiple = i*i; multiple <= LIMIT; multiple += i)\n            {\n                is_prime[multiple] = false;\n            }\n        }\n    }\n}\n\nint all_prime_factors_available(int n, vector <int> &used)\n{\n    for(int p = 2; p*p <= n; p++)\n    {\n        while(n%p == 0)\n        {\n            if(used[p] == true) return false;\n\n            n /= p;\n        }\n    }\n\n    if(n > 1 && used[n]) return false;\n\n    return true;\n}\n\nvoid mark_prime_factors(int n, vector <int> &used)\n{\n    for(int p = 2; p*p <= n; p++)\n    {\n        while(n%p == 0)\n        {\n            used[p] = true;\n\n            n /= p;\n        }\n    }\n\n    if(n > 1)\n        used[n] = true;\n}\n\nint main()\n{\n    const int LIMIT = 2e6;\n    vector <int> is_prime(LIMIT, true);\n    sieve(is_prime, LIMIT);\n\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <int> original(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &original[i]);\n\n    vector <int> solution;\n\n    vector <int> used(LIMIT, false);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        if(all_prime_factors_available(original[i], used))\n        {\n            solution.push_back(original[i]);\n\n            mark_prime_factors(original[i], used);\n        }\n        else\n        {\n            int x = original[i] + 1;\n            while(!all_prime_factors_available(x, used))\n                x++;\n\n            mark_prime_factors(x, used);\n\n            solution.push_back(x);\n            break;\n        }\n    }\n\n    for(int i = 2; i < LIMIT && solution.size() < no_of_elements; i++)\n    {   \n        if(!used[i] && is_prime[i])\n            solution.push_back(i);\n    }\n\n    for(int i = 0; i < no_of_elements; i++) printf(\"%d \", solution[i]);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 473/Explanation/Mahmoud and Ehab and Even Odd Game Explanation.txt",
    "content": "If n is even, then Mahmoud takes n and wins. \r\n\r\nIf n is odd, no matter what even number takes, he leaves an odd number for Ehab. Ehab then takes it and wins. \r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(n%2 == 0 ? \"Mahmoud\\n\" : \"Ehab\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 473/Programs/Mahmoud and Ehab and Another Array Construction Task.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nvoid sieve(vector <int> &is_prime, int LIMIT)\n{\n    is_prime[0] = is_prime[1] = false;\n    for(long long i = 2; i*i <= LIMIT; i++)\n    {\n        if(is_prime[i])\n        {\n            for(long long multiple = i*i; multiple <= LIMIT; multiple += i)\n            {\n                is_prime[multiple] = false;\n            }\n        }\n    }\n}\n\nint all_prime_factors_available(int n, vector <int> &used)\n{\n    for(int p = 2; p*p <= n; p++)\n    {\n        while(n%p == 0)\n        {\n            if(used[p] == true) return false;\n\n            n /= p;\n        }\n    }\n\n    if(n > 1 && used[n]) return false;\n\n    return true;\n}\n\nvoid mark_prime_factors(int n, vector <int> &used)\n{\n    for(int p = 2; p*p <= n; p++)\n    {\n        while(n%p == 0)\n        {\n            used[p] = true;\n\n            n /= p;\n        }\n    }\n\n    if(n > 1)\n        used[n] = true;\n}\n\nint main()\n{\n    const int LIMIT = 2e6;\n    vector <int> is_prime(LIMIT, true);\n    sieve(is_prime, LIMIT);\n\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <int> original(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &original[i]);\n\n    vector <int> solution;\n\n    vector <int> used(LIMIT, false);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        if(all_prime_factors_available(original[i], used))\n        {\n            solution.push_back(original[i]);\n\n            mark_prime_factors(original[i], used);\n        }\n        else\n        {\n            int x = original[i] + 1;\n            while(!all_prime_factors_available(x, used))\n                x++;\n\n            mark_prime_factors(x, used);\n\n            solution.push_back(x);\n            break;\n        }\n    }\n\n    for(int i = 2; i < LIMIT && solution.size() < no_of_elements; i++)\n    {   //printf(\"i = %d, u %d, p %d\\n\", i, used[i], is_prime[i]);\n        if(!used[i] && is_prime[i])\n            solution.push_back(i);\n    }\n\n    for(int i = 0; i < no_of_elements; i++) printf(\"%d \", solution[i]);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 473/Programs/Mahmoud and Ehab and Even Odd Game.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(n%2 == 0 ? \"Mahmoud\\n\" : \"Ehab\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 478/Explanations/Aramic Script Bitmask Solution.txt",
    "content": "Maintain a binary string of length 26. \r\n\r\nConstruct a binary string with each given string as follows :\r\nThe i-th bit is set if the i-th alphabet is present in the string and 0 otherwise. Strings which have the same 'root' have the same mask. \r\n\r\nCount the number of distinct masks. \r\n\r\n------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <int> mask;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        int current_mask = 0;\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            current_mask |= (1 << (word[i] - 'a'));\r\n\r\n        mask.insert(current_mask);\r\n    }\r\n\r\n    cout << mask.size();\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 478/Explanations/Aramic Script Explanation.txt",
    "content": "For each string, keep track of which alphabets were used. \r\n\r\nAnd then make another string X, consisting of exactly one occurence of each of it's alphabets in alphabetical order. \r\n\r\nThis ensures strings which have the same root are mapped to the same X. \r\n\r\nCount the number of distinct X.\r\n\r\n----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <string> distinct_words;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        const int NO_OF_ALPHABETS = 26;\r\n        vector <int> present(NO_OF_ALPHABETS, false);\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            present[word[i] - 'a'] = true;\r\n\r\n        string root;\r\n        for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n            if(present[i])\r\n                root += (char)('a' + i);\r\n\r\n        distinct_words.insert(root);\r\n    }\r\n\r\n    cout << distinct_words.size();\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 478/Explanations/Ghosts Explanation.txt",
    "content": "Unlike most problems, this problems specifically asks us to overcount rather than avoid it. Each collision must be counted two times - once for each ghost. \r\n\r\nNow, the equation for the motion of a ghost = P + VT, where V is velocity, T is time and P is position. We have two dimensions and the equations need to be applied seperately on both. \r\n\r\nNow the trick is in noticing that two ghosts will intersect if the time for their x coordinates to be equal is the same as the Y.\r\n\r\nX1 + Vx1T = X2 + Vx2T\r\nX1 - X2 = T(Vx2 - Vx1)\r\nT = (X1 - X2)/(Vx2 - Vx1)\r\n\r\nAnd Y1 + Vy1T = Y2 + Vy2T\r\n\r\nY1 - Y2 = T(Vy2 - Vy1)\r\n\r\nT = (Y1 - Y2)/(Vy2 - Vy1)\r\n\r\n(X1 - X2)/(Vx2 - Vx1) = (Y1 - Y2)/(Vy2 - Vy1)\r\n\r\n(X1 - X2)/(Vx2 - Vx1) = (aX1 + b - aX2 - b)/(Vy2 - Vy1)\r\n\r\n(X1 - X2)/(Vx2 - Vx1) = a(X1 - X2)/(Vy2 - Vy1)\r\n\r\n1/(Vx2 - Vx1) = a/(Vy2 - Vy1)\r\n\r\nVy2 - Vy1 = aVx2 - aVx1\r\n\r\n-------------------------------\r\n\r\naVx1 - Vy1 = aVx2 - Vy2\r\n\r\nThis shows that ghosts which have the same aVx - Vy intersect at some point.\r\n\r\nHowever, we need to notice that if two ghosts are parallel (V1 = V2) then they never meet. \r\n\r\n---------------------------------\r\n\r\nTake each ghost. That ghost intersects with all ghosts who have aVx - Vy value, but not with those that have the same V. (Parallel)\r\n\r\nA very elegant way to keep track of slopes is to maintain a map of pairs. {Vx, Vy}. \r\n\r\nMaintain another map for {aVx - Vy}\r\n\r\n------------------------------------------\r\n\r\nMultiply the number of collisions by 2 at the end.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_points, a, b;\r\n    scanf(\"%d %d %d\", &no_of_points, &a, &b);\r\n\r\n    long long total_collisions = 0;\r\n    map < pair<int, int>, int > slope_count;\r\n    map <long long, int> intersections;\r\n\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        int x, vx, vy;\r\n        scanf(\"%d %d %d\", &x, &vx, &vy);\r\n\r\n        total_collisions += intersections[a*1LL*vx - vy] - slope_count[make_pair(vx, vy)]; //Parallel points don't meet.\r\n\r\n        slope_count[make_pair(vx, vy)]++;\r\n        intersections[a*1LL*vx - vy]++;\r\n    }\r\n\r\n    total_collisions *= 2;\r\n\r\n    printf(\"%I64d\\n\", total_collisions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 478/Explanations/Mancala Explanation.txt",
    "content": "There are only 14 hold. The problem is small enough to simulate. \r\n\r\nTake each hole. Calculate the answer if this hole was redistributed. And keep track of the best hole. \r\n\r\nHow to calculate the answer if a particular hole is distributed ? \r\n\r\nWell, let's say hole[i] has S stones. \r\n\r\nAnd let S = 14q + r, \r\nq is the quotient, r is the remainder, 0 <= r < 14\r\n\r\nNow, first of all set hole[i] = 0. \r\n\r\nThen all 14 holes will get an additional q stones. \r\n\r\nThen simulate the process of distributing the left out r stones. \r\n(Start from (i + 1) and give one stone to all holes till you run out of stones.)\r\n\r\nAfter this do an O(n) scan to find out the hole with the maximum number of stones. \r\n\r\nThis requires 3 O(n) scans.\r\n\r\nWe do this for all 14 holes. So 42 O(n) scans.\r\n\r\n------------------------------------------------------------\r\n\r\nlong long score_by_distributing(int chosen, vector <long long> stone, int no_of_holes)\r\n{\r\n    int quotient = stone[chosen]/no_of_holes, remainder = stone[chosen]%no_of_holes;\r\n\r\n    stone[chosen] = 0;\r\n\r\n    int current = chosen;\r\n    do\r\n    {\r\n        stone[current] += quotient;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n    while(current != chosen);\r\n\r\n    current = (chosen + 1)%no_of_holes;\r\n    while(remainder > 0)\r\n    {\r\n        stone[current]++;\r\n        remainder--;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n\r\n    long long score = 0;\r\n    for(int i = 0; i < stone.size(); i++)\r\n        if(stone[i]%2 == 0)\r\n            score += stone[i];\r\n\r\n    return score;\r\n}\r\n\r\nint main()\r\n{\r\n    const int NO_OF_HOLES = 14;\r\n    vector <long long> stone(NO_OF_HOLES);\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        cin >> stone[i];\r\n\r\n    long long maximum_score = 0;\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        maximum_score = max(maximum_score, score_by_distributing(i, stone, NO_OF_HOLES));\r\n\r\n    cout << maximum_score;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 478/Explanations/Valhalla Siege Explanation.txt",
    "content": "To kill i soldiers, we need to shoot S[1] + S[2] + ... + S[i] arrows. \n\nMaintain a prefix sum array. \n\nKeep track of the total number of arrows shot so far. If total_arrows >= S[n], then total_arrows = 0\n\nAfter that use binary search and find the smallest position i, such that total_arrows < S[i]. (i - 1) soldiers would have been dead at that time and the remaining N - i are alive. \n\n-----------------------------------------------------------\n\nint main()\n{\n    int no_of_soldiers, no_of_queries;\n    scanf(\"%d %d\", &no_of_soldiers, &no_of_queries);\n\n    vector <long long> strength(no_of_soldiers + 1);\n    for(int i = 1; i <= no_of_soldiers; i++)\n        scanf(\"%I64d\", &strength[i]);\n\n    vector <long long> sum(no_of_soldiers + 1, 0);\n    for(int i = 1; i <= no_of_soldiers; i++)\n        sum[i] = sum[i - 1] + strength[i];\n\n    long long total_arrows = 0;\n    while(no_of_queries--)\n    {\n        long long arrows;\n        scanf(\"%I64d\", &arrows);\n\n        total_arrows += arrows;\n\n        if(total_arrows >= sum[no_of_soldiers])\n            total_arrows = 0;\n\n        int no_of_dead_soldiers = upper_bound(all(sum), total_arrows) - sum.begin() - 1;\n\n        int no_of_alive_soldiers = no_of_soldiers - no_of_dead_soldiers;\n\n        printf(\"%d\\n\", no_of_alive_soldiers);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 478/Programs/Aramic Script Bitmask Solution.cpp",
    "content": "#include <iostream>\r\n#include <set>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <int> mask;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        int current_mask = 0;\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            current_mask |= (1 << (word[i] - 'a'));\r\n\r\n        mask.insert(current_mask);\r\n    }\r\n\r\n    cout << mask.size();\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 478/Programs/Aramic Script.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all (v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <string> distinct_words;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        const int NO_OF_ALPHABETS = 26;\r\n        vector <int> present(NO_OF_ALPHABETS, false);\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            present[word[i] - 'a'] = true;\r\n\r\n        string root;\r\n        for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n            if(present[i])\r\n                root += (char)('a' + i);\r\n\r\n        distinct_words.insert(root);\r\n    }\r\n\r\n    cout << distinct_words.size();\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 478/Programs/Ghosts.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_points, a, b;\r\n    scanf(\"%d %d %d\", &no_of_points, &a, &b);\r\n\r\n    long long total_collisions = 0;\r\n    map < pair<int, int>, int > slope_count;\r\n    map <long long, int> intersections;\r\n\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        int x, vx, vy;\r\n        scanf(\"%d %d %d\", &x, &vx, &vy);\r\n\r\n        total_collisions += intersections[a*1LL*vx - vy] - slope_count[make_pair(vx, vy)]; //Parallel points don't meet.\r\n\r\n        slope_count[make_pair(vx, vy)]++;\r\n        intersections[a*1LL*vx - vy]++;\r\n    }\r\n\r\n    total_collisions *= 2;\r\n\r\n    printf(\"%I64d\\n\", total_collisions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 478/Programs/Mancala.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long score_by_distributing(int chosen, vector <long long> stone, int no_of_holes)\r\n{\r\n    int quotient = stone[chosen]/no_of_holes, remainder = stone[chosen]%no_of_holes;\r\n\r\n    stone[chosen] = 0;\r\n\r\n    int current = chosen;\r\n    do\r\n    {\r\n        stone[current] += quotient;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n    while(current != chosen);\r\n\r\n    current = (chosen + 1)%no_of_holes;\r\n    while(remainder > 0)\r\n    {\r\n        stone[current]++;\r\n        remainder--;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n\r\n    long long score = 0;\r\n    for(int i = 0; i < stone.size(); i++)\r\n        if(stone[i]%2 == 0)\r\n            score += stone[i];\r\n\r\n    return score;\r\n}\r\n\r\nint main()\r\n{\r\n    const int NO_OF_HOLES = 14;\r\n    vector <long long> stone(NO_OF_HOLES);\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        cin >> stone[i];\r\n\r\n    long long maximum_score = 0;\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        maximum_score = max(maximum_score, score_by_distributing(i, stone, NO_OF_HOLES));\r\n\r\n    cout << maximum_score;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 478/Programs/Valhalla Siege.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_soldiers, no_of_queries;\n    scanf(\"%d %d\", &no_of_soldiers, &no_of_queries);\n\n    vector <long long> strength(no_of_soldiers + 1);\n    for(int i = 1; i <= no_of_soldiers; i++)\n        scanf(\"%I64d\", &strength[i]);\n\n    vector <long long> sum(no_of_soldiers + 1, 0);\n    for(int i = 1; i <= no_of_soldiers; i++)\n        sum[i] = sum[i - 1] + strength[i];\n\n    long long total_arrows = 0;\n    while(no_of_queries--)\n    {\n        long long arrows;\n        scanf(\"%I64d\", &arrows);\n\n        total_arrows += arrows;\n\n        if(total_arrows >= sum[no_of_soldiers])\n            total_arrows = 0;\n\n        int no_of_dead_soldiers = upper_bound(all(sum), total_arrows) - sum.begin() - 1;\n\n        int no_of_alive_soldiers = no_of_soldiers - no_of_dead_soldiers;\n\n        printf(\"%d\\n\", no_of_alive_soldiers);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 485/Explanations/AND Graph Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUT6oy\n\nBasically,X&Y = 0, if Y is any submask of X's complement. \n\nSo perform DFS. Start from X\n\nFrom X visit all of the submasks of the complement of Y.\n\nMark N visited if you have visited all of it's submasks.\n\nIf any of the submasks are also present in the array, then visit all the submasks of it's complement as well !\n\nDo this recursively till all integers which can be reached starting from X (in the same component).\n\n------------------------------------------\n\nvoid dfs(int mask, int no_of_bits)\n{\n    if(visited[mask])\n        return;\n\n    visited[mask] = true;\n\n    for(int bit = 0; bit < no_of_bits; bit++)\n    {\n        if(mask&(1LL << bit))\n        {\n            int submask = mask - (1LL << bit);\n            dfs(submask, no_of_bits);\n        }\n    }\n\n    if(is_present[mask])\n        dfs(complement(mask, no_of_bits), no_of_bits);\n}\n\nint main()\n{\n    int no_of_bits, no_of_vertices;\n    scanf(\"%d %d\", &no_of_bits, &no_of_vertices);\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        int x;\n        scanf(\"%d\", &x);\n        is_present[x] = true;\n    }\n\n    int no_of_components = 0;\n    for(int i = 0; i < (1LL << no_of_bits); i++)\n    {\n        if(is_present[i] && !visited[i])\n        {\n            dfs(complement(i, no_of_bits), no_of_bits);\n            no_of_components++;\n        }\n    }\n\n    printf(\"%d\\n\", no_of_components);\n    return 0;\n}\n\n"
  },
  {
    "path": "Contests/Div 2 485/Explanations/Fair Explanation.txt",
    "content": "The number of colours k is quite small (at most 100).\r\n\r\nFor each colour, remember which vertices have that colour. \r\n\r\nThen push all those vertices into a queue, and perform BFS and calculate the minimum distance of that colour for all vertices. \r\n\r\n(You can't necessarily perform DFS as it is a general graph and not always a tree.)\r\n\r\nThen for each vertex you will have the minimum distance to each of the k colours. \r\n\r\nSort them and find the sum of the smallest s of them. \r\n\r\nComplexity = O(k(m + n) + k log k)\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    int no_of_swaps = 0;\r\n    vector <int> visited(n + 1, false);\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            int cycle_size = 0;\r\n\r\n            for(int current = i; !visited[current]; current = permutation[current])\r\n            {\r\n                visited[current] = true;\r\n                cycle_size++;\r\n            }\r\n\r\n            no_of_swaps += cycle_size - 1;\r\n        }\r\n    }\r\n\r\n    printf(no_of_swaps%2 == (3*n)%2 ? \"Petr\" : \"Um_nik\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 485/Explanations/High Schooll Become Human Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTQHH\r\n\r\nYou can either compare the logarithms. \r\n\r\nOr, if x^y > y^x, then \r\n\r\ny log x > x log y\r\n\r\n(log x)/x > (log y)/y\r\n\r\nNow, (log x)/x has a derivative of (1 - log x)/x^2\r\n\r\nThe derivative = 0, at x = e\r\n\r\nDerivative < 0, x > e, which means it is a monotonically decreasing function when x > e\r\n\r\nIf x, y > e\r\n\r\nAnd x < y\r\n\r\nThen, (log x)/x > (log y)/y\r\n\r\nx^y > y^x\r\n\r\n----------------------\r\n\r\nAlso, x^y = y^x, whenever x = y, and x = 2, y = 4\r\n\r\nThe remaining cases can be handled by hand.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long x, y;\r\n    scanf(\"%I64d %I64d\", &x, &y);\r\n\r\n    if(x == y || (min(x, y) == 2 && max(x, y) == 4))\r\n    {\r\n        printf(\"=\");\r\n    }\r\n    else if(min(x, y) == 1)\r\n    {\r\n        printf(x == 1 ? \"<\" : \">\");\r\n    }\r\n    else if(min(x, y) == 2)\r\n    {\r\n        if(x == 2)\r\n        {\r\n            printf(y < 4 ? \"<\" : \">\");\r\n        }\r\n        else if(y == 2)\r\n        {\r\n            printf(x < 4? \">\" : \"<\");\r\n        }\r\n    }\r\n    else if(min(x, y) >= 3) //Both greater than e\r\n    {\r\n        printf(x < y ? \">\" : \"<\");\r\n    }\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 485/Explanations/Infinity Gauntlet Explanation.txt",
    "content": "Have a map of all the colours and their powers. \r\n\r\nAnd then have a map of which colours have been used. \r\n\r\nIf a colour has not been used, then display it.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    map <string, string> power;\r\n    power[\"red\"] = \"Reality\";\r\n    power[\"purple\"] = \"Power\";\r\n    power[\"green\"] = \"Time\";\r\n    power[\"yellow\"] = \"Mind\";\r\n    power[\"orange\"] = \"Soul\";\r\n    power[\"blue\"] = \"Space\";\r\n\r\n    map <string, int> present;\r\n\r\n    int no_of_names;\r\n    cin >> no_of_names;\r\n\r\n    while(no_of_names--)\r\n    {\r\n        string colour;\r\n        cin >> colour;\r\n\r\n        present[colour] = true;\r\n    }\r\n\r\n    vector <string> answer;\r\n    for(map <string, string> :: iterator it = power.begin(); it != power.end(); it++)\r\n    {\r\n        if(!present[it->first])\r\n            answer.push_back(it->second);\r\n    }\r\n\r\n    cout << answer.size() << \"\\n\";\r\n    for(int i = 0; i < answer.size(); i++)\r\n        cout << answer[i] << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 485/Explanations/Petr and Permutations Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTLha\r\n\r\nBasically, notice that 3n and 7n + 1 have different parities ! Find the parity of the number of inversions of the permutation and match it with whichever number of operations has the same parity.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    int no_of_swaps = 0;\r\n    vector <int> visited(n + 1, false);\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            int cycle_size = 0;\r\n\r\n            for(int current = i; !visited[current]; current = permutation[current])\r\n            {\r\n                visited[current] = true;\r\n                cycle_size++;\r\n            }\r\n\r\n            no_of_swaps += cycle_size - 1;\r\n        }\r\n    }\r\n\r\n    printf(no_of_swaps%2 == (3*n)%2 ? \"Petr\" : \"Um_nik\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 485/Explanations/Three Displays Explanation.txt",
    "content": "\r\nThis is the O(n^2) solution. Iterate over all possible middle elements. \r\n\r\nIf A[i] is the middle element, then go from (i + 1) to N. \r\nCheck if S[r] > A[i], if yes then best right[i] = min{best right[i], C[r]}\r\n\r\nDo the same thing towards the left as well. \r\n\r\nBest cost = min{Best cost, best left[i] + A[i] + best right[i]}\r\n\r\nWe perform an O(n) scan for every possible mid element. \r\n\r\nHence, O(n^2)\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <int> text_size(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &text_size[i]);\r\n\r\n    vector <int> cost(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &cost[i]);\r\n\r\n    const long long oo = 1e10;\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n\r\n    long long best_cost = oo;\r\n\r\n    for(int mid = 1; mid <= no_of_displays; mid++)\r\n    {\r\n        for(int right = mid + 1; right <= no_of_displays; right++)\r\n        {\r\n            if(text_size[mid] < text_size[right])\r\n                best_right[mid] = min(best_right[mid], cost[right]);\r\n        }\r\n\r\n        for(int left = 1; left < mid; left++)\r\n        {\r\n            if(text_size[left] < text_size[mid])\r\n                best_left[mid] = min(best_left[mid], cost[left]);\r\n        }\r\n\r\n        best_cost = min(best_cost, best_right[mid] + cost[mid] + best_left[mid]);\r\n    }\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 485/Explanations/Three Displays Segment Tree Solution Explanation.txt",
    "content": "This is actually a beautiful technique. There are plenty of problems where segment trees can make O(n^2) to O(n log n).\r\n\r\nHere's what we do. \r\n\r\nWhile processing element i, ensure that we have already processed all elements which have a smaller font size. Now find the minimum cost in the range [1, Position(i) - 1]. \r\n\r\n(To avoid a clash, ensure that you have not processed elements which have equal font size but who's positions lie to the left of Position(i) because we should not be considering their cost.)\r\n\r\nSo, we sort by font size, \r\nIf font size is equal, then the rightmost element comes first. \r\n\r\nOne by one, we insert the costs into segment tree at Position(i). \r\nAnd then query the minimum in [1, Position(i) - 1].\r\nAs we have ensured rightmost element comes first for equal font sizes, elements with equal font size to the left of an element will not effect it's query as it's not been inserted yet. \r\n\r\nWhile finding the best right, we do the opposite. We insert elements in the reverse order that we did for the left and then find the minimum in the range [Position(i) + 1, N].\r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <info> A(no_of_displays + 1);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        A[i].position = i;\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].font_size);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].cost);\r\n\r\n    sort(A.begin() + 1, A.end(), compare_by_size);\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_left[i] = get_min(1, 1, no_of_displays, 1, A[i].position - 1);\r\n    }\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n    for(int i = no_of_displays; i >= 1; i--)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_right[i] = get_min(1, 1, no_of_displays, A[i].position + 1, no_of_displays);\r\n    }\r\n\r\n    long long best_cost = oo;\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        best_cost = min(best_cost, best_left[i] + A[i].cost + best_right[i]);\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 485/Programs/AND Graph.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = (1LL << 22);\nvector <int> visited(MAX_N, false);\nvector <int> is_present(MAX_N, false);\n\nint complement(int x, int no_of_bits)\n{\n    return ( ( (1LL << no_of_bits) - 1) - x);\n}\n\nvoid dfs(int mask, int no_of_bits)\n{\n    if(visited[mask])\n        return;\n\n    visited[mask] = true;\n\n    for(int bit = 0; bit < no_of_bits; bit++)\n    {\n        if(mask&(1LL << bit))\n        {\n            int submask = mask - (1LL << bit);\n            dfs(submask, no_of_bits);\n        }\n    }\n\n    if(is_present[mask])\n        dfs(complement(mask, no_of_bits), no_of_bits);\n}\n\nint main()\n{\n    int no_of_bits, no_of_vertices;\n    scanf(\"%d %d\", &no_of_bits, &no_of_vertices);\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        int x;\n        scanf(\"%d\", &x);\n        is_present[x] = true;\n    }\n\n    int no_of_components = 0;\n    for(int i = 0; i < (1LL << no_of_bits); i++)\n    {\n        if(is_present[i] && !visited[i])\n        {\n            dfs(complement(i, no_of_bits), no_of_bits);\n            no_of_components++;\n        }\n    }\n\n    printf(\"%d\\n\", no_of_components);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 485/Programs/Fair.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <queue>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(). (v).end()\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e5 + 15, MAX_COLOURS = 105, oo = 1e9;\r\n\r\nvector <int> graph[MAX_N];\r\nvector <int> has_colour[MAX_COLOURS];\r\nint answer[MAX_N][MAX_COLOURS];\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges, no_of_colours, required_colours;\r\n    scanf(\"%d %d %d %d\", &no_of_vertices, &no_of_edges, &no_of_colours, &required_colours);\r\n\r\n    vector <int> colour(no_of_vertices + 1);\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        scanf(\"%d\", &colour[i]);\r\n        has_colour[colour[i]].push_back(i);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    for(int c = 1; c <= no_of_colours; c++)\r\n    {\r\n        queue <int> Q;\r\n        vector <int> distance(no_of_vertices + 1, oo);\r\n\r\n        for(int i = 0; i < has_colour[c].size(); i++)\r\n        {\r\n            int v = has_colour[c][i];\r\n\r\n            distance[v] = 0;\r\n            Q.push(v);\r\n        }\r\n\r\n        while(!Q.empty())\r\n        {\r\n            int v = Q.front();\r\n            Q.pop();\r\n\r\n            for(int i = 0; i < graph[v].size(); i++)\r\n            {\r\n                int child = graph[v][i];\r\n\r\n                if(distance[child] > distance[v] + 1)\r\n                {\r\n                    distance[child] = distance[v] + 1;\r\n                    Q.push(child);\r\n                }\r\n            }\r\n        }\r\n\r\n        for(int v = 1; v <= no_of_vertices; v++)\r\n        {\r\n            answer[v][c] = distance[v];\r\n        }\r\n    }\r\n\r\n    for(int v = 1; v <= no_of_vertices; v++)\r\n    {\r\n        sort(answer[v] + 1, answer[v] + no_of_colours + 1);\r\n\r\n        long long cost = 0;\r\n        for(int c = 1; c <= required_colours; c++)\r\n            cost += answer[v][c];\r\n\r\n        printf(\"%I64d \", cost);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 485/Programs/High School Become Human.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    long long x, y;\r\n    scanf(\"%I64d %I64d\", &x, &y);\r\n\r\n    if(x == y || (min(x, y) == 2 && max(x, y) == 4))\r\n    {\r\n        printf(\"=\");\r\n    }\r\n    else if(min(x, y) == 1)\r\n    {\r\n        printf(x == 1 ? \"<\" : \">\");\r\n    }\r\n    else if(min(x, y) == 2)\r\n    {\r\n        if(x == 2)\r\n        {\r\n            printf(y < 4 ? \"<\" : \">\");\r\n        }\r\n        else if(y == 2)\r\n        {\r\n            printf(x < 4? \">\" : \"<\");\r\n        }\r\n    }\r\n    else if(min(x, y) >= 3) //Both greater than e\r\n    {\r\n        printf(x < y ? \">\" : \"<\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 485/Programs/Infinity Gauntlet.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    map <string, string> power;\r\n    power[\"red\"] = \"Reality\";\r\n    power[\"purple\"] = \"Power\";\r\n    power[\"green\"] = \"Time\";\r\n    power[\"yellow\"] = \"Mind\";\r\n    power[\"orange\"] = \"Soul\";\r\n    power[\"blue\"] = \"Space\";\r\n\r\n    map <string, int> present;\r\n\r\n    int no_of_names;\r\n    cin >> no_of_names;\r\n\r\n    while(no_of_names--)\r\n    {\r\n        string colour;\r\n        cin >> colour;\r\n\r\n        present[colour] = true;\r\n    }\r\n\r\n    vector <string> answer;\r\n    for(map <string, string> :: iterator it = power.begin(); it != power.end(); it++)\r\n    {\r\n        if(!present[it->first])\r\n            answer.push_back(it->second);\r\n    }\r\n\r\n    cout << answer.size() << \"\\n\";\r\n    for(int i = 0; i < answer.size(); i++)\r\n        cout << answer[i] << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 485/Programs/Petr and Permutations.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    int no_of_swaps = 0;\r\n    vector <int> visited(n + 1, false);\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            int cycle_size = 0;\r\n\r\n            for(int current = i; !visited[current]; current = permutation[current])\r\n            {\r\n                visited[current] = true;\r\n                cycle_size++;\r\n            }\r\n\r\n            no_of_swaps += cycle_size - 1;\r\n        }\r\n    }\r\n\r\n    printf(no_of_swaps%2 == (3*n)%2 ? \"Petr\" : \"Um_nik\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 485/Programs/Three Displays Segment Tree Solution.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nconst int MAX_N = 3015;\r\nconst long long oo = 1e10;\r\n\r\nstruct info\r\n{\r\n    int font_size, cost, position;\r\n};\r\n\r\nlong long min_tree[4*MAX_N];\r\nlong long max_tree[4*MAX_N];\r\n\r\nint compare_by_size(const info &A, const info &B)\r\n{\r\n    if(A.font_size == B.font_size)\r\n        return (A.position > B.position);\r\n    else\r\n        return (A.font_size < B.font_size);\r\n}\r\n\r\nvoid build_min_tree(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        min_tree[n] = oo;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build_min_tree(LEFT(n), left, mid);\r\n    build_min_tree(RIGHT(n), mid + 1, right);\r\n\r\n    min_tree[n] = min(min_tree[LEFT(n)], min_tree[RIGHT(n)]);\r\n}\r\n\r\nvoid update_min(int n, int left, int right, int position, int value)\r\n{\r\n    if(position < left || right < position)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        min_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update_min(LEFT(n), left, mid, position, value);\r\n    update_min(RIGHT(n), mid + 1, right, position, value);\r\n\r\n    min_tree[n] = min(min_tree[LEFT(n)], min_tree[RIGHT(n)]);\r\n}\r\n\r\nlong long get_min(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left || query_right < query_left)\r\n        return oo;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return min_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    long long left_min = get_min(LEFT(n), left, mid, query_left, query_right);\r\n    long long right_min = get_min(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return min(left_min, right_min);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <info> A(no_of_displays + 1);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        A[i].position = i;\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].font_size);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].cost);\r\n\r\n    sort(A.begin() + 1, A.end(), compare_by_size);\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_left[i] = get_min(1, 1, no_of_displays, 1, A[i].position - 1);\r\n    }\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n    for(int i = no_of_displays; i >= 1; i--)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_right[i] = get_min(1, 1, no_of_displays, A[i].position + 1, no_of_displays);\r\n    }\r\n\r\n    long long best_cost = oo;\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        best_cost = min(best_cost, best_left[i] + A[i].cost + best_right[i]);\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 485/Programs/Three Displays.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <int> text_size(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &text_size[i]);\r\n\r\n    vector <int> cost(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &cost[i]);\r\n\r\n    const long long oo = 1e10;\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n\r\n    long long best_cost = oo;\r\n\r\n    for(int mid = 1; mid <= no_of_displays; mid++)\r\n    {\r\n        for(int right = mid + 1; right <= no_of_displays; right++)\r\n        {\r\n            if(text_size[mid] < text_size[right])\r\n                best_right[mid] = min(best_right[mid], cost[right]);\r\n        }\r\n\r\n        for(int left = 1; left < mid; left++)\r\n        {\r\n            if(text_size[left] < text_size[mid])\r\n                best_left[mid] = min(best_left[mid], cost[left]);\r\n        }\r\n\r\n        best_cost = min(best_cost, best_right[mid] + cost[mid] + best_left[mid]);\r\n    }\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 489/Explanations/Nastya Studies Informatics Explanation.txt",
    "content": "Let A = pg and B = qg\r\n\r\ng = gcd(A, B)\r\n\r\nThis means gcd(p, q) = 1. Otherwise, gcd(A, B) > g. \r\n\r\nNow, AB = gL, where L = lcm(A, B)\r\n\r\nAB = g (pq)g\r\n\r\nSo, this means that x = g, y = (pq) g\r\n\r\nDivide LCM by GCD ... This gives us pq.\r\n\r\nFind all factors of pq, and then check if gcd(p, q) = 1, and pg and qg lie inside [L, R].\r\n\r\nOne thing to watch out for is that y may not be divisible by x, in which case we have gotten an invalid pair.\r\n\r\n------------------------------------------------\r\n\r\nint good_pairs = 0;\r\n    long long reduced_lcm = lcm/gcd;\r\n    for(int i = 1; i*i <= reduced_lcm; i++)\r\n    {\r\n        if(reduced_lcm%i == 0)\r\n        {\r\n            long long p = i, q = reduced_lcm/i;\r\n\r\n            if(left <= p*gcd && p*gcd <= right && left <= q*gcd && q*gcd <= right && gcd_(p, q) == 1)\r\n            {   \r\n                if(p == q)\r\n                    good_pairs++;\r\n                else\r\n                    good_pairs += 2;\r\n            }\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Div 2 489/Explanations/Nastya and Game Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpezI\r\n\r\nIf there were no ones then it would be easy to have an O(n log max P) solution with two loops. Handle the ones well.\r\n\r\n-------------\r\n\r\nint good_segments = 0;\r\n\r\n    for(int left = 1; left <= no_of_elements; left++)\r\n    {\r\n        LL product = 1;\r\n\r\n        for(int right = left; right <= no_of_elements && !overflow(product, A[right]); right = next_non_1[right])\r\n        {\r\n            LL sum_here = sum[right] - sum[left - 1];\r\n            product *= A[right];\r\n\r\n            LL required_sum = 0;\r\n\r\n            if(product%k == 0) required_sum = product/k;\r\n\r\n            LL ones_in_middle = next_non_1[right] - (right + 1);\r\n\r\n            if(sum_here <= required_sum && required_sum <= sum_here + ones_in_middle)\r\n                good_segments++;\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Div 2 489/Explanations/Nastya and King Shamans Alternate Solution Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpilr\r\n\r\nPlace integers which have the same number of bits in the same bucket. Sort the bucket by index. \r\n\r\nOnly the first two integers of the bucket can have A[i] = S{i - 1]\r\n\r\nThis is because every other integer from the third onwards will have both the first two integers in it's prefix. And when you add two numbers of b bits, the sum has more than b bits. Therefore the number will necessarily be < S[i - 1], if there are more than 2 or more numbers of the same number of bits in it's prefix.\r\n\r\nMaintain a priority queue to sort numbers by index for each bit position and a segment tree to get the sums after every update. \r\n\r\n------------------------------------------\r\n\r\nint get_answer()\r\n{\r\n    for(int bit = 0; bit < MAX_BITS; bit++) //Iterating over the priority queue for each no of bits\r\n    {\r\n        int i = 1;\r\n        for(multiset <info> :: iterator it = S[bit].begin(); it != S[bit].end() && i <= 2; i++, it++)//The first two elements, by index\r\n        {\r\n            int index = it->position;\r\n\r\n            if(get_sum(1, 1, no_of_elements, 1, index - 1) == A[index])\r\n                return index;\r\n        }\r\n    }\r\n\r\n    return NOT_FOUND;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int index, new_value;\r\n    scanf(\"%d %d\", &index, &new_value);\r\n\r\n    info element(A[index], index);\r\n    remove_from_multiset(element, no_of_bits(A[index]));\r\n\r\n    S[no_of_bits(new_value)].insert(info(new_value, index));\r\n\r\n    update(1, 1, no_of_elements, index, new_value);\r\n\r\n    int answer = get_answer();\r\n    printf(\"%d\\n\", answer);\r\n}"
  },
  {
    "path": "Contests/Div 2 489/Explanations/Nastya and King Shamans Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUp5G8\r\n\r\nThe basic idea is that if A[i] = S[i - 1], we are done. Else look for the first index i' > i, such that A[i] >= S[i]. \r\n\r\nAll j, in between, A[j] < S[i] So A[j] < S[j - 1].\r\n\r\nThe sum doubles at every step. \r\n\r\nS[i'] >= A[i'] + S[i] >= S[i] + S[i] >= 2S[i].\r\n\r\nSo, in the given range you will perform at most 32 steps.\r\n\r\n---------------------------------------\r\n\r\nint first_index(int n, int left, int right, int query_left, int query_right, LL minimum)\r\n{\r\n    if(right < query_left || query_right < left || max_tree[n] < minimum)\r\n        return NOT_FOUND;\r\n\r\n    if(left == right)\r\n        return left;\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    int left_answer = first_index(LEFT(n), left, mid, query_left, query_right, minimum);\r\n    if(left_answer != NOT_FOUND) return left_answer;\r\n\r\n    int right_answer = first_index(RIGHT(n), mid + 1, right, query_left, query_right, minimum);\r\n    return right_answer;\r\n}\r\n\r\nYou'll perform O(log max A) such iterations. \r\n\r\n----------------------------------------------------------\r\n\r\nHow do you find the smallest index j in [i + 1, N] with minimum value S ? Maintain a maximum segment tree, reject an interval if it is outside [i + 1, N] or the max < S.\r\n\r\nint first_index(int n, int left, int right, int query_left, int query_right, LL minimum)\r\n{\r\n    if(right < query_left || query_right < left || max_tree[n] < minimum)\r\n        return NOT_FOUND;\r\n\r\n    if(left == right)\r\n        return left;\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    int left_answer = first_index(LEFT(n), left, mid, query_left, query_right, minimum);\r\n    if(left_answer != NOT_FOUND) return left_answer;\r\n\r\n    int right_answer = first_index(RIGHT(n), mid + 1, right, query_left, query_right, minimum);\r\n    return right_answer;\r\n}\r\n\r\n-----------------------------------------------"
  },
  {
    "path": "Contests/Div 2 489/Explanations/Nastya and a Wardrobe Explanation.txt",
    "content": "Claim - After two months the expected value will be 2^k x - (2^k - 1)/2\r\n\r\nLet us see why. \r\n\r\nAfter one month, we will get 2X or 2X - 1. Average = 2x - 1/2\r\n\r\nSimilarly, when this gets doubled we'll have 4x - 1, One may be eaten so 4x - 2\r\n\r\nAverage = 4x - 3/2\r\n\r\nLet us assume it's true for k months and prove it by induction. \r\n\r\nIf after k months we have 2^k X - (2^K - 1)/2\r\n\r\nWhat happens in the (k + 1)th month\r\n\r\n2^{k + 1) X - (2^k - 1) If one gets eaten then 2^{k + 1} X - (2^k)\r\n\r\nSo average = 2^{k + 1} X - (2^k + 2^k)/2 = 2^{k + 1} X - (2^{k + 1} - 1)/2\r\nSo no eating happens in the last month. \r\n\r\nSo we can get rid of the denominator.\r\n\r\nNote - x = 0 is a special case. I missed this. This is because nothing gets eaten. So, it will be 0 only. Not negative !\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long initial, months;\r\n    scanf(\"%I64d %I64d\", &initial, &months);\r\n\r\n    if(initial == 0)\r\n    {\r\n        printf(\"0\\n\");\r\n        return 0;\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    initial %= MOD;\r\n\r\n    long long answer = (initial*power_mod(2, months + 1, MOD))%MOD - power_mod(2, months, MOD) + 1;\r\n    answer = (answer + MOD)%MOD;\r\n\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 489/Explanations/Nastya and an Array Explanation.txt",
    "content": "Count the number of distinct non zero elements.\n\n#include <iostream>\n#include <set>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    set <int> S;\n    while(no_of_elements--)\n    {\n        int element;\n        cin >> element;\n\n        if(element != 0)\n            S.insert(element);\n    }\n\n    cout << S.size();\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 489/Programs/Nastya Studies Informatics.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <set>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <map>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nlong long gcd_(long long p, long long q)\r\n{\r\n    if(min(p, q) == 0)\r\n        return max(p, q);\r\n    else\r\n        return gcd_(min(p, q), max(p, q)%min(p, q));\r\n}\r\n\r\nint main()\r\n{\r\n    long long left, right, gcd, lcm;\r\n    scanf(\"%I64d %I64d %I64d %I64d\", &left, &right, &gcd, &lcm);\r\n\r\n    //search for pg, qg, where pq = l/g\r\n    int good_pairs = 0;\r\n    long long reduced_lcm = lcm/gcd;\r\n    for(int i = 1; i*i <= reduced_lcm; i++)\r\n    {\r\n        if(reduced_lcm%i == 0)\r\n        {\r\n            long long p = i, q = reduced_lcm/i;\r\n\r\n            if(left <= p*gcd && p*gcd <= right && left <= q*gcd && q*gcd <= right && gcd_(p, q) == 1)\r\n            {   //printf(\"p = %d, q = %d\\n\", p, q);\r\n                if(p == q)\r\n                    good_pairs++;\r\n                else\r\n                    good_pairs += 2;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", good_pairs);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 489/Programs/Nastya and Game.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <limits>\r\n\r\nusing namespace std;\r\ntypedef long long LL;\r\n\r\nint overflow(LL a, LL b)\r\n{\r\n    return ( ((a*b)/b) != a);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, k;\r\n    scanf(\"%d %d\", &no_of_elements, &k);\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%I64d\", &A[i]);\r\n\r\n    vector <long long> sum(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum[i] = sum[i - 1] + A[i];\r\n\r\n    vector <int> next_non_1(no_of_elements + 1);\r\n    next_non_1[no_of_elements] = no_of_elements + 1;\r\n    for(int i = no_of_elements - 1; i >= 1; i--)\r\n        next_non_1[i] = (A[i + 1] != 1 ? i + 1 : next_non_1[i + 1]);\r\n\r\n    int good_segments = 0;\r\n\r\n    for(int left = 1; left <= no_of_elements; left++)\r\n    {\r\n        LL product = 1;\r\n\r\n        for(int right = left; right <= no_of_elements && !overflow(product, A[right]); right = next_non_1[right])\r\n        {\r\n            LL sum_here = sum[right] - sum[left - 1];\r\n            product *= A[right];\r\n\r\n            LL required_sum = 0;\r\n\r\n            if(product%k == 0) required_sum = product/k;\r\n\r\n            LL ones_in_middle = next_non_1[right] - (right + 1);\r\n\r\n            if(sum_here <= required_sum && required_sum <= sum_here + ones_in_middle)\r\n                good_segments++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", good_segments);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 489/Programs/Nastya and King-Shamans Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <set>\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\n\r\nstruct info\r\n{\r\n    int value, position;\r\n\r\n    info(int v = 0, int p = 0)\r\n    {\r\n        value = v;\r\n        position = p;\r\n    }\r\n\r\n    int operator<(const info &A) const\r\n    {\r\n        return (position < A.position);\r\n    }\r\n};\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\nconst int MAX_N = 2e5 + 5, NOT_FOUND = -1, MAX_BITS = 32;\r\n\r\nLL sum_tree[3*MAX_N], A[MAX_N];\r\nmultiset <info> S[MAX_BITS];\r\nint no_of_elements;\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nvoid update(int n, int left, int right, int index, int new_value)\r\n{\r\n    if(right < index || index < left)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        A[index] = new_value;\r\n        sum_tree[n] = new_value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update(LEFT(n), left, mid, index, new_value);\r\n    update(RIGHT(n), mid + 1, right, index, new_value);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nLL get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    LL left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    LL right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nint no_of_bits(int n)\r\n{\r\n    int bits = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        n = n >> 1;\r\n        bits++;\r\n    }\r\n\r\n    return bits;\r\n}\r\n\r\nint get_answer()\r\n{\r\n    for(int bit = 0; bit < MAX_BITS; bit++) //Iterating over the priority queue for each no of bits\r\n    {\r\n        int i = 1;\r\n        for(multiset <info> :: iterator it = S[bit].begin(); it != S[bit].end() && i <= 2; i++, it++)//The first two elements, by index\r\n        {\r\n            int index = it->position;\r\n\r\n            if(get_sum(1, 1, no_of_elements, 1, index - 1) == A[index])\r\n                return index;\r\n        }\r\n    }\r\n\r\n    return NOT_FOUND;\r\n}\r\n\r\nvoid remove_from_multiset(info element, int multiset_no)\r\n{\r\n    multiset <info> :: iterator it = S[multiset_no].find(element);\r\n\r\n    if(it != S[multiset_no].end())\r\n        S[multiset_no].erase(it);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int index, new_value;\r\n    scanf(\"%d %d\", &index, &new_value);\r\n\r\n    info element(A[index], index);\r\n    remove_from_multiset(element, no_of_bits(A[index]));\r\n\r\n    S[no_of_bits(new_value)].insert(info(new_value, index));\r\n\r\n    update(1, 1, no_of_elements, index, new_value);\r\n\r\n    int answer = get_answer();\r\n    printf(\"%d\\n\", answer);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64d\", &A[i]);\r\n        S[no_of_bits(A[i])].insert(info(A[i], i));\r\n    }\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 489/Programs/Nastya and King-Shamans.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\nconst int MAX_N = 2e5 + 5, NOT_FOUND = -1;\r\nLL max_tree[4*MAX_N], sum_tree[4*MAX_N], A[MAX_N];\r\nint no_of_elements;\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nvoid update(int n, int left, int right, int index, int new_value)\r\n{\r\n    if(right < index || index < left)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        A[index] = new_value;\r\n        sum_tree[n] = max_tree[n] = new_value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update(LEFT(n), left, mid, index, new_value);\r\n    update(RIGHT(n), mid + 1, right, index, new_value);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nLL get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    LL left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    LL right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nint first_index(int n, int left, int right, int query_left, int query_right, LL minimum)\r\n{\r\n    if(right < query_left || query_right < left || max_tree[n] < minimum)\r\n        return NOT_FOUND;\r\n\r\n    if(left == right)\r\n        return left;\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    int left_answer = first_index(LEFT(n), left, mid, query_left, query_right, minimum);\r\n    if(left_answer != NOT_FOUND) return left_answer;\r\n\r\n    int right_answer = first_index(RIGHT(n), mid + 1, right, query_left, query_right, minimum);\r\n    return right_answer;\r\n}\r\n\r\nint get_answer()\r\n{\r\n    LL prefix_sum;\r\n    int index = 1;\r\n\r\n    while(index != NOT_FOUND)\r\n    {\r\n        prefix_sum = get_sum(1, 1, no_of_elements, 1, index - 1);\r\n\r\n        if(prefix_sum == A[index])\r\n            return index;\r\n\r\n        prefix_sum += A[index];\r\n\r\n        index = first_index(1, 1, no_of_elements, index + 1, no_of_elements, prefix_sum);\r\n    }\r\n\r\n    return index;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int index, new_value;\r\n    scanf(\"%d %d\", &index, &new_value);\r\n\r\n    update(1, 1, no_of_elements, index, new_value);\r\n\r\n    int answer = get_answer();\r\n    printf(\"%d\\n\", answer);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 489/Programs/Nastya and a Wardrobe.cpp",
    "content": "#include <cstdio>\r\n\r\ntypedef long long LL;\r\n\r\nLL power_mod(LL x, LL power, LL MOD)\r\n{\r\n    LL result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%MOD;\r\n\r\n        x = (x*x)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nint main()\r\n{\r\n    long long initial, months;\r\n    scanf(\"%I64d %I64d\", &initial, &months);\r\n\r\n    if(initial == 0)\r\n    {\r\n        printf(\"0\\n\");\r\n        return 0;\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    initial %= MOD;\r\n\r\n    long long answer = (initial*power_mod(2, months + 1, MOD))%MOD - power_mod(2, months, MOD) + 1;\r\n    answer = (answer + MOD)%MOD;\r\n\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 489/Programs/Nastya and an Array.cpp",
    "content": "#include <iostream>\n#include <set>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    set <int> S;\n    while(no_of_elements--)\n    {\n        int element;\n        cin >> element;\n\n        if(element != 0)\n            S.insert(element);\n    }\n\n    cout << S.size();\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 491/Explanations/Bishwock Explanation.txt",
    "content": "We can be greedy. \r\n\r\nIt is never optimal to leave a column blank if a biscwok fits. \r\n\r\n---------------------------------\r\n\r\nint main()\r\n{\r\n    const int NO_OF_ROWS = 2;\r\n    vector <string> S(NO_OF_ROWS);\r\n\r\n    for(int i = 0; i < NO_OF_ROWS; i++)\r\n        cin >> S[i];\r\n\r\n    int no_of_columns = S[0].size();\r\n    int free_spaces = 0, placed_pieces = 0;\r\n    for(int i = 0; i < no_of_columns; i++)\r\n    {\r\n        int column_spaces = (S[0][i] == '0') + (S[1][i] == '0');\r\n\r\n        free_spaces += column_spaces;\r\n\r\n        if(free_spaces >= 3)\r\n        {\r\n            free_spaces -=3;\r\n            placed_pieces++;\r\n        }\r\n        else\r\n        {\r\n            free_spaces = column_spaces;\r\n        }\r\n\r\n    }\r\n\r\n    cout << placed_pieces;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 491/Explanations/Bus Number Explanation.txt",
    "content": "If there are 3 different objects of frequency r1 r2 and r3 respectively. \r\n\r\nThen the number of arrangements of all of them is \r\n\r\n(r1 + r2 + r3)!/r1!r2!r3!\r\n\r\n-----------------------------------\r\n\r\nOne possible way is to have 10 for loops, and then make sure the frequency of each alphabet in S is at least one ...\r\n\r\n-------------------------------------\r\n\r\nAnother way is \r\n\r\n1. Extract every possible subset of N.\r\nSuppose it's 2820.... This part we'll take all subsets out - {2, 8, 0, 280, 80, 220, etc}\r\n\r\nfor(int mask = 0; mask < (1LL << n.size()); mask++)\r\n    {\r\n        string subset_n;\r\n\r\n        for(int i = 0; i < n.size(); i++)\r\n        {\r\n            if(is_bit_set(mask, i))\r\n            {\r\n                subset_n += n[i];\r\n            }\r\n        }\r\n\r\n        answer += solve(subset_n);\r\n    }\r\n\r\n-------------------------------------------------\r\n\r\n2. For every subset, check if every element that occurs once in the set, also occurs at least once in this subset.\r\nFor example {80} is not a legal subset because it doesn't have a 2.\r\n\r\nfor(int i = 0; i < 10; i++)\r\n        if(original_frequency[i] > 0 && frequency[i] == 0)\r\n            return 0;\r\n\r\n-------------------------------------\r\n\r\n3. Check if we've processed a subset before. For instace, 450 and 054 are the same subset. So sort the elements of a subset. Check if it's already been processed.\r\n\r\n(Suppose we have counted permutations of 280, we don't need to count permutations 820. As we'd be overcounting. So map\r\nboth 280 and 820 to 028)\r\n\r\nstring sorted_S;\r\n    for(int i = 0; i < 10; i++)\r\n        for(int j = 1; j <= frequency[i]; j++)\r\n            sorted_S += (char)(i + '0');\r\n\r\n    if(processed.count(sorted_S) == 1)//Already counted\r\n        return 0;\r\n\r\n    processed.insert(sorted_S);\r\n\r\n-------------------------------------------------\r\n\r\n4. Count the number of permutations of this string. Then, count the number of permutations with the first character 0. This means put a 0 in the beginning and then leave the others as it is.\r\n\r\n(Put a 0 at the first character and count the permutations of the remaining n - 1 elements)\r\n\r\nlong long no_of_permutations = get_count(frequency);\r\n\r\n    long long leading_zero_permutations = 0;\r\n\r\n    if(frequency[0] > 0)\r\n    {\r\n        frequency[0]--;\r\n        leading_zero_permutations = get_count(frequency);\r\n    }\r\n\r\n    return (no_of_permutations - leading_zero_permutations);\r\n\r\n---------------------------------------------\r\n\r\n5. Only frequency array is needed to calculate the permutations.\r\n(This is how we get the (r1 + r2 + r3)!/r1!r2!r3!\r\n\r\nlong long get_count(vector <int> &frequency)\r\n{\r\n    int sum = 0;\r\n    long long denominator = 1;\r\n\r\n    for(int i = 0; i < 10; i++)\r\n    {\r\n        sum += frequency[i];\r\n        denominator *= factorial[frequency[i]];\r\n    }\r\n\r\n    long long numerator = factorial[sum];\r\n\r\n    return (numerator/denominator);\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 491/Explanations/Candies Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpOLx\n\nIt's a binary search problem ! \n\n---------------------------------------\n\n#include <cstdio>\n#include <string>\n#include <vector>\n#include <set>\n#include <cstdio>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\ntypedef long long LL;\n\nLL taken_candies(LL total_candies, LL k)\n{\n    LL self_candies = 0;\n\n    while(total_candies > 0)\n    {\n        self_candies += min(k, total_candies);\n\n        total_candies = total_candies - k;\n\n        LL lost_candies = total_candies/10;\n\n        total_candies -= lost_candies;\n    }\n\n    return self_candies;\n}\n\nint main()\n{\n    LL no_of_candies;\n    scanf(\"%I64d\", &no_of_candies);\n\n    LL target_candies = no_of_candies/2 + no_of_candies%2;\n\n    LL left = 1, right = no_of_candies, answer = 1;\n\n    while(left <= right)\n    {\n        LL mid = (left + right) >> 1;\n\n        if(taken_candies(no_of_candies, mid) >= target_candies)\n        {\n            if(mid == 1 || taken_candies(no_of_candies, mid - 1) < target_candies)\n            {\n                answer = mid;\n                break;\n            }\n            else\n            {\n                right = mid - 1;\n            }\n        }\n        else\n        {\n            left = mid + 1;\n        }\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Contests/Div 2 491/Explanations/Getting an A Explanation.txt",
    "content": "Avoid floating point operations. \r\n\r\nRather than make the average 4.5\r\n\r\nMake the 10*sum >= 45*n\r\n\r\nRather than deal with [2, 5], deal with [20, 50]. \r\n\r\nMultiply everything by 10 ! This is a very handy trick to get rid of floating point operations !\r\n\r\nNow, notice that we want the sum to increase as much as possible each time, so we start from the lowest score and greedily make them 50 at each step.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_exams;\r\n    scanf(\"%d\", &no_of_exams);\r\n\r\n    vector <int> grade(no_of_exams);\r\n    for(int i = 0; i < no_of_exams; i++) scanf(\"%d\", &grade[i]);\r\n\r\n    sort(all(grade));\r\n\r\n    int sum = 0;\r\n    for(int i = 0; i < no_of_exams; i++)\r\n    {\r\n        grade[i] *= 10;\r\n        sum += grade[i];\r\n    }\r\n\r\n    int no_of_changes = 0, target = 45; //Rather than 4.5, we aim for 45.\r\n\r\n    for(int i = 0; sum < target*no_of_exams && i < no_of_exams; i++)\r\n    {\r\n        sum += (50 - grade[i]); //Make grade[i] = 50\r\n\r\n        no_of_changes++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_changes);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 491/Explanations/If At First You Don't Succeed Explanation.txt",
    "content": "OKay, so the conditions that contradict the data is if \r\n\r\nC > min(A, B). The number of students who go to both A and B cannot be less than the students who go to both. \r\n\r\nI missed this. \r\n\r\nand if failed < 1. \r\n\r\nNo need of explicitly checking if A + B - C > 0, because that would cause failed to become < 1 anyway.\r\n\r\n(If there are a negative number of students, there are a negative number of failed students too.)\r\n\r\n-----------------------------------------------\r\n\r\n\r\nint main()\r\n{\r\n    int A, B, C, total_students;\r\n    cin >> A >> B >> C >> total_students;\r\n\r\n    int passed = (A + B - C);\r\n    int failed = total_students - passed;\r\n\r\n    cout << (failed < 1 || C > min(A, B) ? -1 : failed);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 491/Programs/Bishwock.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int NO_OF_ROWS = 2;\r\n    vector <string> S(NO_OF_ROWS);\r\n\r\n    for(int i = 0; i < NO_OF_ROWS; i++)\r\n        cin >> S[i];\r\n\r\n    int no_of_columns = S[0].size();\r\n    int free_spaces = 0, placed_pieces = 0;\r\n    for(int i = 0; i < no_of_columns; i++)\r\n    {\r\n        int column_spaces = (S[0][i] == '0') + (S[1][i] == '0');\r\n\r\n        free_spaces += column_spaces;\r\n\r\n        if(free_spaces >= 3)\r\n        {\r\n            free_spaces -=3;\r\n            placed_pieces++;\r\n        }\r\n        else\r\n        {\r\n            free_spaces = column_spaces;\r\n        }\r\n\r\n    }\r\n\r\n    cout << placed_pieces;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 491/Programs/Bus Number.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvector <int> original_frequency(10, 0);\r\nvector <long long> factorial(20, 1);\r\nset <string> processed;\r\n\r\nint is_bit_set(int n, int position)\r\n{\r\n    return ( (n&(1LL << position)) != 0);\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    factorial[0] = 1;\r\n\r\n    for(int i = 1; i < 20; i++)\r\n        factorial[i] = i*factorial[i - 1];\r\n}\r\n\r\nvoid get(string S, vector <int> &frequency)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        frequency[S[i] - '0']++;\r\n    }\r\n}\r\n\r\nlong long get_count(vector <int> &frequency)\r\n{\r\n    int sum = 0;\r\n    long long denominator = 1;\r\n\r\n    for(int i = 0; i < 10; i++)\r\n    {\r\n        sum += frequency[i];\r\n        denominator *= factorial[frequency[i]];\r\n    }\r\n\r\n    long long numerator = factorial[sum];\r\n\r\n    return (numerator/denominator);\r\n}\r\n\r\nlong long solve(string S)\r\n{\r\n    vector <int> frequency(10, 0);\r\n    get(S, frequency);\r\n\r\n    //Not a good string.\r\n    for(int i = 0; i < 10; i++)\r\n        if(original_frequency[i] > 0 && frequency[i] == 0)\r\n            return 0;\r\n\r\n    string sorted_S;\r\n    for(int i = 0; i < 10; i++)\r\n        for(int j = 1; j <= frequency[i]; j++)\r\n            sorted_S += (char)(i + '0');\r\n\r\n    if(processed.count(sorted_S) == 1)//Already counted\r\n        return 0;\r\n\r\n    processed.insert(sorted_S);\r\n\r\n\r\n    long long no_of_permutations = get_count(frequency);\r\n\r\n    long long leading_zero_permutations = 0;\r\n\r\n    if(frequency[0] > 0)\r\n    {\r\n        frequency[0]--;\r\n        leading_zero_permutations = get_count(frequency);\r\n    }\r\n\r\n    return (no_of_permutations - leading_zero_permutations);\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    string n;\r\n    cin >> n;\r\n\r\n    get(n, original_frequency);\r\n\r\n    long long answer = 0;\r\n\r\n    for(int mask = 0; mask < (1LL << n.size()); mask++)\r\n    {\r\n        string subset_n;\r\n\r\n        for(int i = 0; i < n.size(); i++)\r\n        {\r\n            if(is_bit_set(mask, i))\r\n            {\r\n                subset_n += n[i];\r\n            }\r\n        }\r\n\r\n        answer += solve(subset_n);\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 491/Programs/Candies.cpp",
    "content": "#include <cstdio>\n#include <string>\n#include <vector>\n#include <set>\n#include <cstdio>\n#include <algorithm>\n#include <map>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\ntypedef long long LL;\n\nLL taken_candies(LL total_candies, LL k)\n{\n    LL self_candies = 0;\n\n    while(total_candies > 0)\n    {\n        self_candies += min(k, total_candies);\n\n        total_candies = total_candies - k;\n\n        LL lost_candies = total_candies/10;\n\n        total_candies -= lost_candies;\n    }\n\n    return self_candies;\n}\n\nint main()\n{\n    LL no_of_candies;\n    scanf(\"%I64d\", &no_of_candies);\n\n    LL target_candies = no_of_candies/2 + no_of_candies%2;\n\n    LL left = 1, right = no_of_candies, answer = 1;\n\n    while(left <= right)\n    {\n        LL mid = (left + right) >> 1;\n\n        if(taken_candies(no_of_candies, mid) >= target_candies)\n        {\n            if(mid == 1 || taken_candies(no_of_candies, mid - 1) < target_candies)\n            {\n                answer = mid;\n                break;\n            }\n            else\n            {\n                right = mid - 1;\n            }\n        }\n        else\n        {\n            left = mid + 1;\n        }\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Contests/Div 2 491/Programs/Getting an A.cpp",
    "content": "#include <vector>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_exams;\r\n    scanf(\"%d\", &no_of_exams);\r\n\r\n    vector <int> grade(no_of_exams);\r\n    for(int i = 0; i < no_of_exams; i++) scanf(\"%d\", &grade[i]);\r\n\r\n    sort(all(grade));\r\n\r\n    int sum = 0;\r\n    for(int i = 0; i < no_of_exams; i++)\r\n    {\r\n        grade[i] *= 10;\r\n        sum += grade[i];\r\n    }\r\n\r\n    int no_of_changes = 0, target = 45; //Rather than 4.5, we aim for 45.\r\n\r\n    for(int i = 0; sum < target*no_of_exams && i < no_of_exams; i++)\r\n    {\r\n        sum += (50 - grade[i]); //Make grade[i] = 50\r\n\r\n        no_of_changes++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_changes);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 491/Programs/If At First You Don't Succeed.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <set>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <map>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int A, B, C, total_students;\r\n    cin >> A >> B >> C >> total_students;\r\n\r\n    int passed = (A + B - C);\r\n    int failed = total_students - passed;\r\n\r\n    cout << (failed < 1 || C > min(A, B) ? -1 : failed);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 492/Explanation/Game 995 Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpe5F\r\n\r\nExpectation is just the average !\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, no_of_changes;\r\n    scanf(\"%d %d\", &n, &no_of_changes);\r\n\r\n    int no_of_elements = (1LL << n);\r\n    long long sum = 0;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        sum += A[i];\r\n    }\r\n\r\n    double average = (sum*1.0)/no_of_elements;\r\n    printf(\"%.12f\\n\", average);\r\n\r\n    for(int i = 1; i <= no_of_changes; i++)\r\n    {\r\n        int position, new_value;\r\n        scanf(\"%d %d\", &position, &new_value);\r\n\r\n        sum = sum - A[position] + new_value;\r\n        A[position] = new_value;\r\n\r\n        average = (sum*1.0)/(no_of_elements);\r\n        printf(\"%.12f\\n\", average);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 492/Explanation/Hit the Lottery Explanation.txt",
    "content": "Each of 1, 5, 10, 20, 100 is a multiple of the last. So it's always optimal to use a larger denomination when we can. \r\n\r\nIf we don't use a note of value y and use x where y < x, we will k notes where yk = x\r\n\r\nSo it's best to be greedy and use as many high value denominations as possible.\r\n\r\n---------------------------------\r\n\r\nint main()\r\n{\r\n    const int NO_OF_NOTES = 5;\r\n    int denominations[NO_OF_NOTES + 1] = {100, 20, 10, 5, 1};\r\n\r\n    int amount;\r\n    scanf(\"%d\", &amount);\r\n\r\n    int no_of_notes = 0;\r\n    for(int i = 0; i < NO_OF_NOTES; i++)\r\n    {\r\n        if(denominations[i] <= amount)\r\n            no_of_notes += amount/denominations[i];\r\n\r\n        amount %= denominations[i];\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_notes);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 492/Explanation/Leaving the Bar Explanation.txt",
    "content": "Blog link - https://mathprogrammer.quora.com/4253883-1?share=4cf393bf&srid=F7Hz\r\n\r\nTurns out randomly shuffling the vectors and being greedy is a very efficient heuristic !\r\n\r\n------------------------------\r\n\r\n do\r\n    {\r\n        random_shuffle(all(V));\r\n \r\n        P = Point(0, 0);\r\n \r\n        for(int i = 0; i < no_of_points; i++)\r\n        {\r\n            if(square_norm(P + V[i]) <= square_norm(P - V[i]))\r\n            {\r\n                P = P + V[i];\r\n                step[V[i].index] = 1;\r\n            }\r\n            else\r\n            {\r\n                P = P - V[i];\r\n                step[V[i].index] = -1;\r\n            }\r\n        }\r\n    }\r\n    while(square_norm(P) > square(oo));\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 492/Explanation/Suit and Tie Explanation.txt",
    "content": "We can be greedy. \r\n\r\nGo through the array. \r\n\r\nIf A[i] =/= A[i + 1], \r\n\r\nFind the rightmost occurence of A[i] and keep swapping. \r\n\r\nLet us prove that this is optimal. \r\n\r\nnow, if a and a are seperated\r\n\r\nAll other pairs, must be of the form\r\n\r\naa bb\r\n\r\nabab\r\na bb a\r\n\r\nNow in the first kind, our algorithm won't touch it. \r\n\r\nIn the second kind, we need to atleast do one swap. The greedy algorithm does one swap. \r\n\r\nIn the thrid, we need to do at least two, The greedy does two. \r\n\r\nWe see the greedy algorithm does no more swaps than necessary.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_couples;\r\n    scanf(\"%d\", &no_of_couples);\r\n\r\n    vector <int> A(2*no_of_couples + 1);\r\n    for(int i = 1; i <= 2*no_of_couples; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    int no_of_swaps = 0;\r\n    for(int i = 1; i <= 2*no_of_couples; i += 2)\r\n    {\r\n        for(int j = 2*no_of_couples; j > i + 1; j--)\r\n        {\r\n            if(A[j] == A[i])\r\n            {\r\n                swap(A[j], A[j - 1]);\r\n                no_of_swaps++;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_swaps);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 492/Explanation/Tesla Explanation.txt",
    "content": "We will place all cars that we can park in 1 move.\nThen, we will rotate all the cars 1 step.\n\nThis problem is solved by brute force. We will try to park all the cars we can which are one move away from their designated spots.\nThen, we will rotate all the cars by one step and try again.\n\nWe will perform $2n$ rotations and each rotation costs $2n$ moves.\nSo the total number of moves will be $4n^2 + k \\approx 10^5 + 10^2$\n\nWe will perform 2n rotations because after that, they will come back to\nthe same place.\n\nWhile rotating the cars, we will begin at some point where we have a\nfree space to move a car.\n\n-----\n\nstruct Move\n{\n    int index, row, column;\n\n    Move(){};\n\n    Move(int I, int R, int C)\n    {\n        index = I; row = R; column = C;\n    }\n};\n\nvoid park(vector <Move> &Moves, int no_of_columns)\n{\n    for(int column = 1; column <= no_of_columns; column++)\n    {\n        if(parking_lot[2][column] != 0 && parking_lot[2][column] == parking_lot[1][column])\n        {\n            Moves.push_back(Move(parking_lot[2][column], 1, column));\n\n            parking_lot[2][column] = 0;\n        }\n\n        if(parking_lot[3][column] != 0 && parking_lot[3][column] == parking_lot[4][column])\n        {\n            Moves.push_back(Move(parking_lot[3][column], 4, column));\n\n            parking_lot[3][column] = 0;\n        }\n    }\n}\n\nvoid rotate(vector <Move> &Moves, int no_of_columns)\n{\n    int start_row = -1, start_column = -1;\n\n    for(int r = 2; r <= 3 && start_row == -1; r++)\n    {\n        for(int c = 1; c <= no_of_columns; c++)\n        {\n            if(parking_lot[r][c] == 0)\n            {\n                int next_r = r, next_c = c;\n\n                if(r == 2)\n                {\n                    if(c == no_of_columns)\n                    {\n                        next_c = no_of_columns;\n                        next_r = r + 1;\n                    }\n                    else\n                    {\n                        next_c = c + 1;\n                    }\n                }\n                else if(r == 3)\n                {\n                    if(c == 1)\n                    {\n                        next_c = 1;\n                        next_r = r - 1;\n                    }\n                    else\n                    {\n                        next_c = c - 1;\n                    }\n                }\n\n                if(parking_lot[next_r][next_c] != 0)\n                {\n                    start_row = r;\n                    start_column = c;\n                    break;\n                }\n            }\n        }\n    }\n\n    if(start_row == -1 || start_column == -1)\n    {\n        return;\n    }\n\n    int r = start_row, c = start_column;\n\n    while(true)\n    {\n        int next_r = r, next_c = c;\n\n        if(r == 2)\n        {\n            if(c == no_of_columns)\n            {\n                next_c = no_of_columns;\n                next_r = r + 1;\n            }\n            else\n            {\n                next_c = c + 1;\n            }\n        }\n        else if(r == 3)\n        {\n            if(c == 1)\n            {\n                next_c = 1;\n                next_r = r - 1;\n            }\n            else\n            {\n                next_c = c - 1;\n            }\n        }\n\n        if(next_r == start_row && next_c == start_column)\n        {\n            break;\n        }\n\n        if(parking_lot[next_r][next_c] != 0)\n        {\n            Moves.push_back(Move(parking_lot[next_r][next_c], r, c));\n\n            parking_lot[r][c] = parking_lot[next_r][next_c];\n\n            parking_lot[next_r][next_c] = 0;\n        }\n\n        r = next_r; c = next_c;\n    }\n}\n\nint check_empty(int no_of_columns)\n{\n    for(int r = 2; r <= 3; r++)\n    {\n        for(int c = 1; c <= no_of_columns; c++)\n        {\n            if(parking_lot[r][c] != 0)\n            {\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\nvoid print()\n{\n    cout << \"Parking Lot = \\n\";\n\n    for(int i = 1; i <= MAX_ROWS; i++)\n    {\n        for(int j = 1; j <= 4; j++)\n        {\n            cout << parking_lot[i][j] << \" \";\n        }\n\n        cout << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_columns, no_of_cars;\n    cin >> no_of_columns >> no_of_cars;\n\n    for(int i = 1; i <= MAX_ROWS; i++)\n    {\n        for(int j = 1; j <= no_of_columns; j++)\n        {\n            cin >> parking_lot[i][j];\n        }\n    }\n\n    vector <Move> Moves;\n    for(int rotations = 1; rotations <= 2*no_of_columns; rotations++)\n    {\n        park(Moves, no_of_columns);\n\n        //print();\n\n        rotate(Moves, no_of_columns); //print();\n    }\n\n    if(!check_empty(no_of_columns))\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    cout << Moves.size() << \"\\n\";\n    for(int i = 0; i < Moves.size(); i++)\n    {\n        cout << Moves[i].index << \" \" << Moves[i].row << \" \" << Moves[i].column << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 492/Explanation/World Cup Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUGAjY\n\nSuppose you have the numbers A(1), A(2), A(3), ..., A(n)\n\nWhat is the length when you visit them in round 1 ?\n\nA(1) — 0, A(2) — 1, A(3) — 2, A(4) - 3, ..., A(n) — (n - 1)\n\nYou visit queue i when it's size = A(i) — (i - 1) in round 1\n\nAfter that notice if you visit a queue at size t, you also visit it at sizes t - n, t - 2n, t - 3n, ..., 0.\n\nNow, how many visits do you make at a queue when it is 0 ?\n\nThe answer is t / n = (A(i) — (i - 1)) / n\n\nSo, for each queue calculate the time it will take to reach it and keep track of the minimum. \nNow, a small trick here is settign every A[i] to max{A[i] - (i - 1), 0}. It should not be negative. \nMade that mistake the first time. The program will then think it takes 1 round to reach when it actually hits it in the \nfirst round itself.\n\n----------------------------------------------------------------------\n\nvector <int> length(no_of_queues + 1);\n    for(int i = 0; i < no_of_queues; i++)\n        scanf(\"%d\", &length[i]);\n\n    for(int i = 0; i < no_of_queues; i++)\n        length[i] = max(length[i] - i, 0);\n\n    vector <int> rounds_to_arrive_at(no_of_queues);\n    for(int i = 0; i < no_of_queues; i++)\n        rounds_to_arrive_at[i] = ceil(length[i], no_of_queues);\n\n    const int oo = 1e9;\n    int best_queue, minimum_rounds = oo;\n    for(int i = 0; i < no_of_queues; i++)\n        if(rounds_to_arrive_at[i] < minimum_rounds)\n            minimum_rounds = rounds_to_arrive_at[i], best_queue = i + 1;\n\n    printf(\"%d\\n\", best_queue);\n"
  },
  {
    "path": "Contests/Div 2 492/Programs/Game 995D.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n, no_of_changes;\r\n    scanf(\"%d %d\", &n, &no_of_changes);\r\n\r\n    int no_of_elements = (1LL << n);\r\n    long long sum = 0;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        sum += A[i];\r\n    }\r\n\r\n    double average = (sum*1.0)/no_of_elements;\r\n    printf(\"%.12f\\n\", average);\r\n\r\n    for(int i = 1; i <= no_of_changes; i++)\r\n    {\r\n        int position, new_value;\r\n        scanf(\"%d %d\", &position, &new_value);\r\n\r\n        sum = sum - A[position] + new_value;\r\n        A[position] = new_value;\r\n\r\n        average = (sum*1.0)/(no_of_elements);\r\n        printf(\"%.12f\\n\", average);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 492/Programs/Hit the Lottery.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    const int NO_OF_NOTES = 5;\r\n    int denominations[NO_OF_NOTES + 1] = {100, 20, 10, 5, 1};\r\n\r\n    int amount;\r\n    scanf(\"%d\", &amount);\r\n\r\n    int no_of_notes = 0;\r\n    for(int i = 0; i < NO_OF_NOTES; i++)\r\n    {\r\n        if(denominations[i] <= amount)\r\n            no_of_notes += amount/denominations[i];\r\n\r\n        amount %= denominations[i];\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_notes);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 492/Programs/Leaving The Bar.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct Point\r\n{\r\n    int index;\r\n    LL x, y;\r\n\r\n    Point(LL a = 0, LL b = 0, int index = 0)\r\n    {\r\n        x = a, y = b, index = 0;\r\n    }\r\n\r\n    Point operator+(const Point &P)\r\n    {\r\n        return Point(x + P.x, y + P.y);\r\n    }\r\n    Point operator-(const Point &P)\r\n    {\r\n        return Point(x - P.x, y - P.y);\r\n    }\r\n};\r\n\r\nLL square(LL n)\r\n{\r\n    return n*n;\r\n}\r\n\r\nLL square_norm(Point P)\r\n{\r\n    return (P.x*P.x + P.y*P.y);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <Point> V(no_of_points);\r\n    for(int i = 0; i < no_of_points; i++)\r\n    {\r\n        scanf(\"%I64d %I64d\", &V[i].x, &V[i].y);\r\n        V[i].index = i;\r\n    }\r\n\r\n    const LL oo = 1.5e6;\r\n    Point P;\r\n    vector <int> step(no_of_points);\r\n\r\n    do\r\n    {\r\n        random_shuffle(all(V));\r\n\r\n        P = Point(0, 0);\r\n\r\n        for(int i = 0; i < no_of_points; i++)\r\n        {\r\n            if(square_norm(P + V[i]) <= square_norm(P - V[i]))\r\n            {\r\n                P = P + V[i];\r\n                step[V[i].index] = 1;\r\n            }\r\n            else\r\n            {\r\n                P = P - V[i];\r\n                step[V[i].index] = -1;\r\n            }\r\n        }\r\n    }\r\n    while(square_norm(P) > square(oo));\r\n\r\n    for(int i = 0; i < no_of_points; i++)\r\n        printf(\"%d \", step[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 492/Programs/Suit and Tie.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_couples;\r\n    scanf(\"%d\", &no_of_couples);\r\n\r\n    vector <int> A(2*no_of_couples + 1);\r\n    for(int i = 1; i <= 2*no_of_couples; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    int no_of_swaps = 0;\r\n    for(int i = 1; i <= 2*no_of_couples; i += 2)\r\n    {\r\n        for(int j = 2*no_of_couples; j > i + 1; j--)\r\n        {\r\n            if(A[j] == A[i])\r\n            {\r\n                swap(A[j], A[j - 1]);\r\n                no_of_swaps++;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_swaps);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 492/Programs/Tesla.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_ROWS = 4, MAX_COLUMNS = 55, MAX_CARS = 101;\nint parking_lot[MAX_ROWS + 1][MAX_COLUMNS];\n\nstruct Move\n{\n    int index, row, column;\n    \n    Move(){};\n    \n    Move(int I, int R, int C)\n    {\n        index = I; row = R; column = C;\n    }\n};\n\nvoid park(vector <Move> &Moves, int no_of_columns)\n{\n    for(int column = 1; column <= no_of_columns; column++)\n    {\n        if(parking_lot[2][column] != 0 && parking_lot[2][column] == parking_lot[1][column])\n        {\n            Moves.push_back(Move(parking_lot[2][column], 1, column));\n            \n            parking_lot[2][column] = 0;\n        }\n        \n        if(parking_lot[3][column] != 0 && parking_lot[3][column] == parking_lot[4][column])\n        {\n            Moves.push_back(Move(parking_lot[3][column], 4, column));\n            \n            parking_lot[3][column] = 0;\n        }\n    }\n}\n\nvoid rotate(vector <Move> &Moves, int no_of_columns)\n{\n    int start_row = -1, start_column = -1;\n\n    for(int r = 2; r <= 3 && start_row == -1; r++)\n    {\n        for(int c = 1; c <= no_of_columns; c++)\n        {\n            if(parking_lot[r][c] == 0)\n            {\n                int next_r = r, next_c = c;\n                \n                if(r == 2)\n                {\n                    if(c == no_of_columns)\n                    {\n                        next_c = no_of_columns;\n                        next_r = r + 1;\n                    }\n                    else\n                    {\n                        next_c = c + 1;\n                    }\n                }\n                else if(r == 3)\n                {\n                    if(c == 1)\n                    {\n                        next_c = 1;\n                        next_r = r - 1;\n                    }\n                    else\n                    {\n                        next_c = c - 1;\n                    }\n                }\n                \n                if(parking_lot[next_r][next_c] != 0)\n                {\n                    start_row = r;\n                    start_column = c;\n                    break;\n                }\n            }\n        }\n    }\n    \n    if(start_row == -1 || start_column == -1)\n    {\n        return;\n    }\n    \n    int r = start_row, c = start_column;\n    \n    while(true)\n    {\n        int next_r = r, next_c = c;\n        \n        if(r == 2)\n        {\n            if(c == no_of_columns)\n            {\n                next_c = no_of_columns;\n                next_r = r + 1;\n            }\n            else\n            {\n                next_c = c + 1;\n            }\n        }\n        else if(r == 3)\n        {\n            if(c == 1)\n            {\n                next_c = 1;\n                next_r = r - 1;\n            }\n            else\n            {\n                next_c = c - 1;\n            }\n        }\n        \n        if(next_r == start_row && next_c == start_column)\n        {\n            break;\n        }\n        \n        if(parking_lot[next_r][next_c] != 0)\n        {\n            Moves.push_back(Move(parking_lot[next_r][next_c], r, c));\n            \n            parking_lot[r][c] = parking_lot[next_r][next_c];\n            \n            parking_lot[next_r][next_c] = 0;\n        }\n        \n        r = next_r; c = next_c;\n    }\n}\n\nint check_empty(int no_of_columns)\n{\n    for(int r = 2; r <= 3; r++)\n    {\n        for(int c = 1; c <= no_of_columns; c++)\n        {\n            if(parking_lot[r][c] != 0)\n            {\n                return false;\n            }\n        }\n    }\n    \n    return true;\n}\n\nvoid print()\n{\n    cout << \"Parking Lot = \\n\";\n    \n    for(int i = 1; i <= MAX_ROWS; i++)\n    {\n        for(int j = 1; j <= 4; j++)\n        {\n            cout << parking_lot[i][j] << \" \";\n        }\n        \n        cout << \"\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_columns, no_of_cars;\n    cin >> no_of_columns >> no_of_cars;\n    \n    for(int i = 1; i <= MAX_ROWS; i++)\n    {\n        for(int j = 1; j <= no_of_columns; j++)\n        {\n            cin >> parking_lot[i][j];\n        }\n    }\n    \n    vector <Move> Moves;\n    for(int rotations = 1; rotations <= 2*no_of_columns; rotations++)\n    {\n        park(Moves, no_of_columns);\n        \n        //print();\n        \n        rotate(Moves, no_of_columns); //print();\n    }\n    \n    if(!check_empty(no_of_columns))\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    cout << Moves.size() << \"\\n\";\n    for(int i = 0; i < Moves.size(); i++)\n    {\n        cout << Moves[i].index << \" \" << Moves[i].row << \" \" << Moves[i].column << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 492/Programs/World Cup.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint ceil(int numerator, int denominator)\n{\n    int quotient = numerator/denominator;\n    int remainder = numerator%denominator;\n\n    return (quotient + (remainder != 0));\n}\n\nint main()\n{\n    int no_of_queues;\n    scanf(\"%d\", &no_of_queues);\n\n    vector <int> length(no_of_queues + 1);\n    for(int i = 0; i < no_of_queues; i++)\n        scanf(\"%d\", &length[i]);\n\n    for(int i = 0; i < no_of_queues; i++)\n        length[i] = max(length[i] - i, 0);\n\n    vector <int> rounds_to_arrive_at(no_of_queues);\n    for(int i = 0; i < no_of_queues; i++)\n        rounds_to_arrive_at[i] = ceil(length[i], no_of_queues);\n\n    const int oo = 1e9;\n    int best_queue, minimum_rounds = oo;\n    for(int i = 0; i < no_of_queues; i++)\n        if(rounds_to_arrive_at[i] < minimum_rounds)\n            minimum_rounds = rounds_to_arrive_at[i], best_queue = i + 1;\n\n    printf(\"%d\\n\", best_queue);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 497/Explanation/Reorder the Array Explanation.txt",
    "content": "Let us be greedy. \r\n\r\nFor each element x, map it to the smallest element greater than it. \r\n\r\nIt is solved by maintaining two pointers. :)\r\n\r\n--------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int no_of_positions = 0;\r\n\r\n    int available = no_of_elements;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        while(A[available] >= A[i])\r\n            available--;\r\n\r\n        if(available > 0)\r\n            available--, no_of_positions++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_positions);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 497/Explanation/Romaji Explanation.txt",
    "content": "Ensure there are no consecutive vowels and that the last character is not a vowel. \n\n-----------\n\n#include <cstdio>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint is_vowel(char ch)\n{\n    switch(ch)\n    {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u': return true;\n    }\n\n    return false;\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    char last_ch = S[S.size() - 1];\n    int good_string = (!is_vowel(last_ch) && last_ch != 'n' ? false : true);\n\n    for(int i = 0; i + 1 < S.size(); i++)\n    {\n        if(S[i] == 'n') continue;\n\n        if(!is_vowel(S[i]) && !is_vowel(S[i + 1]))\n        {\n            good_string = false;\n        }\n    }\n\n    cout << (good_string ? \"YES\" : \"NO\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 497/Explanation/Turn The Rectangle Explanation.txt",
    "content": "Just go through the array and ensure every rectangle has either minimum or maximum height so far. \r\n\r\n---------\r\n\r\nint main()\r\n{\r\n    int no_of_rectangles;\r\n    scanf(\"%d\", &no_of_rectangles);\r\n\r\n    int possible = true;\r\n    int last_height = 1e9;\r\n    while(no_of_rectangles--)\r\n    {\r\n        int height, width;\r\n        scanf(\"%d %d\", &height, &width);\r\n\r\n        int min_height = min(height, width);\r\n        int max_height = max(height, width);\r\n\r\n        if(max_height <= last_height)\r\n            last_height = max_height;\r\n        else if(min_height <= last_height)\r\n            last_height = min_height;\r\n        else\r\n            possible = false;\r\n    }\r\n\r\n    printf(possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 497/Programs/Reorder the Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int no_of_positions = 0;\r\n\r\n    int available = no_of_elements;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        while(A[available] >= A[i])\r\n            available--;\r\n\r\n        if(available > 0)\r\n            available--, no_of_positions++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_positions);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 497/Programs/Romaji.cpp",
    "content": "#include <cstdio>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\nusing namespace std;\n\nint is_vowel(char ch)\n{\n    switch(ch)\n    {\n        case 'a':\n        case 'e':\n        case 'i':\n        case 'o':\n        case 'u': return true;\n    }\n\n    return false;\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    char last_ch = S[S.size() - 1];\n    int good_string = (!is_vowel(last_ch) && last_ch != 'n' ? false : true);\n\n    for(int i = 0; i + 1 < S.size(); i++)\n    {\n        if(S[i] == 'n') continue;\n\n        if(!is_vowel(S[i]) && !is_vowel(S[i + 1]))\n        {\n            good_string = false;\n        }\n    }\n\n    cout << (good_string ? \"YES\" : \"NO\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 497/Programs/Turn the Rectangle.cpp",
    "content": "#include <cstdio>\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nint main()\r\n{\r\n    int no_of_rectangles;\r\n    scanf(\"%d\", &no_of_rectangles);\r\n\r\n    int possible = true;\r\n    int last_height = 1e9;\r\n    while(no_of_rectangles--)\r\n    {\r\n        int height, width;\r\n        scanf(\"%d %d\", &height, &width);\r\n\r\n        int min_height = min(height, width);\r\n        int max_height = max(height, width);\r\n\r\n        if(max_height <= last_height)\r\n            last_height = max_height;\r\n        else if(min_height <= last_height)\r\n            last_height = min_height;\r\n        else\r\n            possible = false;\r\n    }\r\n\r\n    printf(possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 508/Explanation/Equality Explanation.txt",
    "content": "We want the minimum frequency.\n\n-----------------\n\n#include <cstdio>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int length, no_of_letters;\n    string S;\n    cin >> length >> no_of_letters >> S;\n\n    vector <int> frequency(no_of_letters, 0);\n    for(int i = 0; i < S.size(); i++)\n        frequency[S[i] - 'A']++;\n\n    int minimum_frequency = length + 1;\n    for(int i = 0; i < no_of_letters; i++)\n        minimum_frequency = min(minimum_frequency, frequency[i]);\n\n    int answer = minimum_frequency*no_of_letters;\n    cout << answer;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 508/Explanation/Gambling Explanation.txt",
    "content": "Greedy strategy works. \r\n\r\nIf the largest element in your list, take it. \r\n\r\nElse, block it. \r\n\r\n--------------------------------------------\r\n\r\nsort(all(A));\r\n\r\n    vector <int> B(n);\r\n    for(int i = 0; i < n; i++) cin >> B[i];\r\n\r\n    sort(all(B));\r\n\r\n    long long answer = 0;\r\n\r\n    int a_ptr = n - 1, b_ptr = n - 1;\r\n\r\n    for(int i = 1; i <= 2*n; i++)\r\n    {\r\n        if(i%2 == 1) //A's turn\r\n        {\r\n            if(b_ptr < 0 || (a_ptr >= 0 && A[a_ptr] >= B[b_ptr]))\r\n            {\r\n                answer += A[a_ptr--];\r\n            }\r\n            else\r\n            {\r\n                b_ptr--;\r\n            }\r\n        }\r\n        else if(i%2 == 0) //B's turn\r\n        {\r\n            if(a_ptr < 0 || (b_ptr >= 0 && B[b_ptr] >= A[a_ptr]) )\r\n            {\r\n                answer -= B[b_ptr--];\r\n            }\r\n            else\r\n            {\r\n                a_ptr--;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << answer;"
  },
  {
    "path": "Contests/Div 2 508/Explanation/Non Coprime Partition Explanation.txt",
    "content": "If n = 2, there is no solution. \r\n\r\nElse if n is even. Then (n + 1) divides the remaining sum\r\n\r\nElse n divides the remaining sum.\r\n\r\n-----------------------\r\n\r\n    if(n <= 2)\r\n    {\r\n        cout << \"No\";\r\n    }\r\n    else\r\n    {\r\n        cout << \"Yes\\n\";\r\n\r\n        if(n%2 == 0)\r\n        {\r\n            cout << \"2 1 \" << n;\r\n\r\n            cout << \"\\n\";\r\n\r\n            cout << n - 2 << \" \" ; for(int i = 2; i < n; i++) cout << i << \" \"; // This is (n + 1)(n - 2)/2.  n is even. So it is divisible by n + 1\r\n        }\r\n        else if(n%2 == 1)\r\n        {\r\n            cout << \"1 \" << n;\r\n\r\n            cout << \"\\n\";\r\n\r\n            cout << n - 1 << \" \"; for(int i = 1; i < n; i++) cout << i << \" \"; // This is n(n - 1)/2. n - 1 is even. So divisible by n.\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Div 2 508/Programs/Equality.cpp",
    "content": "#include <cstdio>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int length, no_of_letters;\n    string S;\n    cin >> length >> no_of_letters >> S;\n\n    vector <int> frequency(no_of_letters, 0);\n    for(int i = 0; i < S.size(); i++)\n        frequency[S[i] - 'A']++;\n\n    int minimum_frequency = length + 1;\n    for(int i = 0; i < no_of_letters; i++)\n        minimum_frequency = min(minimum_frequency, frequency[i]);\n\n    int answer = minimum_frequency*no_of_letters;\n    cout << answer;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 508/Programs/Gambling.cpp",
    "content": "#include <cstdio>\n#include <string>\n#include <algorithm>\n#include <vector>\n#include <iostream>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    vector <int> A(n);\n    for(int i = 0; i < n; i++) cin >> A[i];\n\n    sort(all(A));\n\n    vector <int> B(n);\n    for(int i = 0; i < n; i++) cin >> B[i];\n\n    sort(all(B));\n\n    long long answer = 0;\n\n    int a_ptr = n - 1, b_ptr = n - 1;\n\n    for(int i = 1; i <= 2*n; i++)\n    {\n        if(i%2 == 1) //A's turn\n        {\n            if(b_ptr < 0 || (a_ptr >= 0 && A[a_ptr] >= B[b_ptr]))\n            {\n                answer += A[a_ptr--];\n            }\n            else\n            {\n                b_ptr--;\n            }\n        }\n        else if(i%2 == 0) //B's turn\n        {\n            if(a_ptr < 0 || (b_ptr >= 0 && B[b_ptr] >= A[a_ptr]) )\n            {\n                answer -= B[b_ptr--];\n            }\n            else\n            {\n                a_ptr--;\n            }\n        }\n    }\n\n    cout << answer;\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Contests/Div 2 508/Programs/Non Coprime Partition.cpp",
    "content": "#include <cstdio>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <iostream>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    if(n <= 2)\r\n    {\r\n        cout << \"No\";\r\n    }\r\n    else\r\n    {\r\n        cout << \"Yes\\n\";\r\n\r\n        if(n%2 == 0)\r\n        {\r\n            cout << \"2\"; cout << \" 1 \" << n;\r\n\r\n            cout << \"\\n\";\r\n\r\n            cout << n - 2 << \" \" ; for(int i = 2; i < n; i++) cout << i << \" \"; // This is (n + 1)(n - 2)/2.  n is even. So it is divisible by n + 1\r\n        }\r\n        else if(n%2 == 1)\r\n        {\r\n            cout << \"1 \" << n;\r\n\r\n            cout << \"\\n\";\r\n\r\n            cout << n - 1 << \" \"; for(int i = 1; i < n; i++) cout << i << \" \"; // This is n(n - 1)/2. n - 1 is even. So divisible by n.\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 511/Explanation/Enlarge GCD Explanation.txt",
    "content": "Every integer is divisible by the gcd - g. \r\n\r\nWe want to look for the largest set of integers which have an additional common factor. Suppose it is x. Then all numbers are divisible by g and by x.\r\n\r\nIf all numbers are divisible by some common factor x, then they all must have some common prime factor p. \r\n\r\n\r\nWe look for the largest set of integers which are divisible by (gp), for some prime p. \r\n\r\nNow, we can't just look for a prime p which has the largest number of multiples as it is ... Because p might be a factor of g. \r\n\r\n--------------\r\n\r\nStep 1 - Divide all integers by their gcd g. \r\n\r\nint array_gcd = 0;\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n\r\n        array_gcd = gcd(array_gcd, A[i]);\r\n    }\r\n\r\n------------------\r\n\r\nStep 2 - Now you have N coprime numbers. Look for the largest set of integers which have some common prime factor - p.\r\n\r\nWe can't factorise every integer. \r\n\r\nGo through every prime, and find out the number of multiples it has. \r\n\r\nThe prime which has the largest number of multiples in the set is the one we want. \r\n\r\nint max_set_with_same_gcd = 0;\r\n    vector <int> is_prime(MAX_NUM + 1, true);\r\n    for(int i = 2; i <= MAX_NUM; i++)\r\n    {\r\n        if(!is_prime[i]) continue;\r\n\r\n        int no_of_i_multiples = 0;\r\n\r\n        for(int multiple = i; multiple <= MAX_NUM; multiple += i)\r\n        {\r\n            no_of_i_multiples += frequency[multiple];\r\n\r\n            is_prime[multiple] = false;\r\n        }\r\n\r\n        max_set_with_same_gcd = max(max_set_with_same_gcd, no_of_i_multiples);\r\n    }"
  },
  {
    "path": "Contests/Div 2 511/Explanation/Little C Loves 3 I Explanation.txt",
    "content": "(1, 1, n - 2) satisfies the given condition unless n = 2 (mod 3)\n\nSo if n = 2 (mod 3)\n\nWe will give (1, 2, n - 3)\n\n----------------------\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n\n    if(n%3 == 2)\n    {\n        printf(\"%d %d %d\\n\", 1, 2, n - 3);\n    }\n    else\n    {\n        printf(\"%d %d %d\\n\", 1, 1, n - 2);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 511/Programs/Little C Loves 3 I.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n\n    if(n%3 == 2)\n    {\n        printf(\"%d %d %d\\n\", 1, 2, n - 3);\n    }\n    else\n    {\n        printf(\"%d %d %d\\n\", 1, 1, n - 2);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 533/Explanations/Ayoub and Lost Array Explanation.txt",
    "content": "Let f(i, r) be the number of ways of filling first i elements such that they sum upto r. \n\nThen the last element l can be either 0, 1, or 2. \n\nLet F(r) denote the frequency of r = {0, 1, 2}\n\nNow, we can fix the last element. \n\nSuppose last element is 0. \n\nThen f(i + 1, (0 + 0)) += F(0)f(i, 0)\n\nf(i + 1, (0 + 1)) += F(0)f(i, 1)\n\nf(i + 1, (0 + 2)) += F(0)f(i, 2)\n\n-----\n\nThese would be the transitions. The last can be l. The previous can be p = {0, 1, 2}\n\n---\n\nint get_count(int limit, int remainder)\n{\n    if(remainder == 0)\n        return limit/3;\n    else\n        return (limit/3 + (limit%3 >= remainder));\n}\n\n--------\n\nAccordingly, we update the DP like this - \n\nA total_remainder is made by combination of {last, previous}.\n\nSo, f(i, total) += F(last)f(i - 1, previous)\n\nFor example, \n\nf(i, 0) = F(0)f(i - 1, 0) + F(1)f(i - 1, 2) + F(2)f(i - 1, 1)\n\n---\n\n    no_of_ways[0][0] = 1;\n    no_of_ways[0][1] = no_of_ways[0][2] = 0;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int last = 0; last < 3; last++)\n        {\n            for(int previous = 0; previous < 3; previous++)\n            {\n                int total_remainder = (previous + last)%3;\n\n                no_of_ways[i][total_remainder] += (frequency[last]*no_of_ways[i - 1][previous])%MOD;\n\n                no_of_ways[i][total_remainder] %= MOD;\n            }\n        }\n\n    }\n"
  },
  {
    "path": "Contests/Div 2 533/Explanations/Ayoub and Lost Array Matrix Exponentiation Explanation.txt",
    "content": "This one uses the approach of the previous solution but uses matrix exponentiation. \r\n\r\nLet us write down the recurrence - \r\n\r\nf(i, 0) = F[0]f(i - 1, 0) + F[2]f(i - 1, 1) + F[1]f(i - 1, 2);\r\nf(i, 1) = F[1]f(i - 1, 0) + F[0]f(i - 1, 1) + F[2]f(i - 1, 2);\r\nf(i, 2) = F[2]f(i - 1, 0) + F[1]f(i - 1, 1) + F[0]f(i - 1, 2);\r\n\r\nLet A = [f(i, 0) f(i, 1) f(i 2)]\r\n\r\nLet F = | F[0] F[1] F[2] |\r\n        | F[2] F[0] F[1] |\r\n        | F[1] F[2] F[0] |\r\n\r\nThen A^N = A^{N - 1} F = A^0 F^N\r\n\r\n------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, left, right;\r\n    scanf(\"%d %d %d\", &no_of_elements, &left, &right);\r\n\r\n    vector <long long> frequency(3, 0);\r\n\r\n    for(int i = 0; i < 3; i++)\r\n    {\r\n        frequency[i] = get_count(right, i) - get_count(left - 1, i);\r\n    }\r\n\r\n    int no_of_ways_sum_0_from_0_elements = 1, no_of_ways_sum_1_from_0_elements = 0, no_of_ways_sum_2_from_0_elements = 0;\r\n\r\n  /*f(i, 0) = F[0]f(i - 1, 0) + F[2]f(i - 1, 1) + F[1]f(i - 1, 2);\r\n    f(i, 1) = F[1]f(i - 1, 0) + F[0]f(i - 1, 1) + F[2]f(i - 1, 2);\r\n    f(i, 2) = F[2]f(i - 1, 0) + F[1]f(i - 1, 1) + F[0]f(i - 1, 2);*/\r\n\r\n    long long A[SIZE][SIZE] = {{no_of_ways_sum_0_from_0_elements, no_of_ways_sum_1_from_0_elements, no_of_ways_sum_2_from_0_elements}};\r\n\r\n    long long F[SIZE][SIZE] = { {frequency[0], frequency[1], frequency[2]},\r\n                                {frequency[2], frequency[0], frequency[1]},\r\n                                {frequency[1], frequency[2], frequency[0]} };\r\n\r\n    //A^n = A^{n - 1}F = A^1 F^{n-1}\r\n\r\n    power(F, no_of_elements);\r\n\r\n    multiply(A, F);\r\n\r\n    printf(\"%I64d\\n\", A[0][0]);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 533/Explanations/Salem and Sticks Explanation.txt",
    "content": "It is a unimodal function. (Not monotonic). \r\nSo we can apply ternary search instead of binary search !\r\n\r\n------------\r\n\r\nint calculate_cost(vector <int> &A, int t)\r\n{\r\n    int cost = 0;\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if(A[i] < t) cost += ((t - 1) - A[i]);\r\n        if(A[i] > t) cost += (A[i] - (t + 1));\r\n    }\r\n\r\n    return cost;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    const int MAX = 100;\r\n    int left = 1, right = MAX;\r\n\r\n    while(left < right)\r\n    {\r\n        int mid_1 = (2*left + right)/3;\r\n        int mid_2 = (left + 2*right)/3;\r\n\r\n        if(calculate_cost(A, mid_1) <= calculate_cost(A, mid_2))\r\n        {\r\n            right = mid_2;\r\n        }\r\n        else\r\n        {\r\n            left = mid_1 + 1;\r\n        }\r\n    }\r\n\r\n    int answer = (calculate_cost(A, left) < calculate_cost(A,  right) ? left : right);\r\n\r\n    cout << answer << \" \" << calculate_cost(A, answer);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 533/Explanations/Zuhair and Strings Explanation.txt",
    "content": "Let us call a substring of same characters a 'block'.\r\n\r\nLet us call a substring of same characters a 'chunk' if it is of size = k\r\n\r\nIf we have a block of size >= k, we will divide it into chunks of size k. \r\n\r\nThe 'level' of a string is the number of chunks we can make with any one alphabet. \r\n\r\nSo, we will calculate the number of 'chunks' we can make with each alphabet and then find which alphabet has the highest number of 'chunks'.\r\n\r\n----\r\n\r\nLet f(i) denote the length of the 'block' size ending at i.\r\n\r\nIf position i is the end of a 'block', Then we can have [f(i)/k] 'chunks' from this 'block'. \r\n\r\nWe will keep track of the number of 'chunks' we can have of each alphabet and then find the maximum.\r\n\r\n----\r\n\r\nSuppose we have aaabaaaa\r\n\r\nThen f(i) would be {1 2 3 1 1 2 3 4}\r\n\r\nIf k = 2, \r\n\r\nThen the first block aaa, can be divided into one substring of length 2. So, we get one chunk from the first block.\r\n\r\nThe second block aaaa, can be divided into two substrings of length 2. So, we get two chunks from the second block.\r\n\r\nWe get 3 chunks of a\r\nWe do not have any chunks of b as there is only one block of b, who's size is 1 so we cannot divide it into chunks of a.\r\n\r\n----\r\n\r\nWe calculate f(i) with a simple DP. \r\n\r\nvector <int> longest_block_till(length, 0);\r\n    longest_block_till[0] = 1;\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        longest_block_till[i] = (S[i] == S[i - 1] ? longest_block_till[i - 1] + 1 : 1);\r\n    }\r\n\r\n---\r\n\r\nAnd then we use f(i). We know a block ends if it is either the end of the string or a position such that S[i] != S[i + 1]. \r\n\r\nAt this position we will find the number of new blocks of the letter S[i] that are possible\r\n\r\nconst int NO_OF_ALPHABETS = 26;\r\n    vector <int> no_of_k_sequences(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(i == length - 1 || S[i] != S[i + 1])//Reached the end of a block\r\n        {\r\n            no_of_k_sequences[S[i] - 'a'] += longest_block_till[i]/k;\r\n        }\r\n    }\r\n\r\n---\r\n\r\nAfter this, we will find out which alphabet has the highest number of blocks. \r\n\r\nint answer = 0;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n        answer = max(answer, no_of_k_sequences[i]);"
  },
  {
    "path": "Contests/Div 2 533/Programs/Ayoub and Lost Array Matrix Exponentiation.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MOD = 1e9 + 7, SIZE = 3;\r\n\r\nvoid load_identity(long long I[][SIZE])\r\n{\r\n    for(int i = 0; i < SIZE; i++)\r\n        for(int j = 0; j < SIZE; j++)\r\n            I[i][j] = (i == j ? 1 : 0);\r\n}\r\n\r\nvoid copy(long long source[][SIZE], long long target[][SIZE])\r\n{\r\n    for(int i = 0; i < SIZE; i++)\r\n        for(int j = 0; j < SIZE; j++)\r\n            target[i][j] = source[i][j];\r\n}\r\n\r\nvoid multiply(long long A[][SIZE], long long B[][SIZE])\r\n{\r\n    long long product[SIZE][SIZE];\r\n\r\n    for(int i = 0; i < SIZE; i++)\r\n    {\r\n        for(int j = 0; j < SIZE; j++)\r\n        {\r\n            product[i][j] = 0;\r\n\r\n            for(int k = 0; k < SIZE; k++)\r\n            {\r\n                product[i][j] += (A[i][k]*B[k][j])%MOD;\r\n            }\r\n\r\n            product[i][j] %= MOD;\r\n        }\r\n    }\r\n\r\n    copy(product, A);\r\n}\r\n\r\nvoid power(long long X[][SIZE], long long power)\r\n{\r\n    long long result[SIZE][SIZE];\r\n    load_identity(result);\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            multiply(result, X);\r\n\r\n        multiply(X, X);\r\n        power = power >> 1;\r\n    }\r\n\r\n    copy(result, X);\r\n}\r\n\r\nint get_count(int limit, int remainder)\r\n{\r\n    if(remainder == 0)\r\n        return limit/3;\r\n    else\r\n        return (limit/3 + (limit%3 >= remainder));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, left, right;\r\n    scanf(\"%d %d %d\", &no_of_elements, &left, &right);\r\n\r\n    vector <long long> frequency(3, 0);\r\n\r\n    for(int i = 0; i < 3; i++)\r\n    {\r\n        frequency[i] = get_count(right, i) - get_count(left - 1, i);\r\n    }\r\n\r\n    int no_of_ways_sum_0_from_0_elements = 1, no_of_ways_sum_1_from_0_elements = 0, no_of_ways_sum_2_from_0_elements = 0;\r\n\r\n  /*f(i, 0) = F[0]f(i - 1, 0) + F[2]f(i - 1, 1) + F[1]f(i - 1, 2);\r\n    f(i, 1) = F[1]f(i - 1, 0) + F[0]f(i - 1, 1) + F[2]f(i - 1, 2);\r\n    f(i, 2) = F[2]f(i - 1, 0) + F[1]f(i - 1, 1) + F[0]f(i - 1, 2);*/\r\n\r\n    long long A[SIZE][SIZE] = {{no_of_ways_sum_0_from_0_elements, no_of_ways_sum_1_from_0_elements, no_of_ways_sum_2_from_0_elements}};\r\n\r\n    long long F[SIZE][SIZE] = { {frequency[0], frequency[1], frequency[2]},\r\n                                {frequency[2], frequency[0], frequency[1]},\r\n                                {frequency[1], frequency[2], frequency[0]} };\r\n\r\n    //A^n = A^{n - 1}F = A^0 F^n\r\n\r\n    power(F, no_of_elements);\r\n\r\n    multiply(A, F);\r\n\r\n    printf(\"%I64d\\n\", A[0][0]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 533/Programs/Ayoub and Lost Array.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nconst int MOD = 1e9 + 7, MAX_N = 2e5 + 5;\nlong long no_of_ways[MAX_N][3];\n\nint get_count(int limit, int remainder)\n{\n    if(remainder == 0)\n        return limit/3;\n    else\n        return (limit/3 + (limit%3 >= remainder));\n}\n\nint main()\n{\n    int no_of_elements, left, right;\n    scanf(\"%d %d %d\", &no_of_elements, &left, &right);\n\n    vector <long long> frequency(3, 0);\n\n    for(int i = 0; i < 3; i++)\n    {\n        frequency[i] = get_count(right, i) - get_count(left - 1, i);\n    }\n\n    no_of_ways[0][0] = 1;\n    no_of_ways[0][1] = no_of_ways[0][2] = 0;\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int last = 0; last < 3; last++)\n        {\n            for(int previous = 0; previous < 3; previous++)\n            {\n                int total_remainder = (previous + last)%3;\n\n                no_of_ways[i][total_remainder] += (frequency[last]*no_of_ways[i - 1][previous])%MOD;\n\n                no_of_ways[i][total_remainder] %= MOD;\n            }\n        }\n\n    }\n\n    printf(\"%I64d\\n\", no_of_ways[no_of_elements][0]);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 533/Programs/Salem and Sticks.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint calculate_cost(vector <int> &A, int t)\r\n{\r\n    int cost = 0;\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if(A[i] < t) cost += ((t - 1) - A[i]);\r\n        if(A[i] > t) cost += (A[i] - (t + 1));\r\n    }\r\n\r\n    return cost;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    const int MAX = 100;\r\n    int left = 1, right = MAX;\r\n\r\n    while(left < right)\r\n    {\r\n        int mid_1 = (2*left + right)/3;\r\n        int mid_2 = (left + 2*right)/3;\r\n\r\n        if(calculate_cost(A, mid_1) <= calculate_cost(A, mid_2))\r\n        {\r\n            right = mid_2;\r\n        }\r\n        else\r\n        {\r\n            left = mid_1 + 1;\r\n        }\r\n    }\r\n\r\n    int answer = (calculate_cost(A, left) < calculate_cost(A,  right) ? left : right);\r\n\r\n    cout << answer << \" \" << calculate_cost(A, answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 533/Programs/Zuhair and Strings.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, k;\r\n    cin >> length >> k;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    vector <int> longest_block_till(length, 0);\r\n    longest_block_till[0] = 1;\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        longest_block_till[i] = (S[i] == S[i - 1] ? longest_block_till[i - 1] + 1 : 1);\r\n    }\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> no_of_k_sequences(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(i == length - 1 || S[i] != S[i + 1])//Reached the end of a block\r\n        {\r\n            no_of_k_sequences[S[i] - 'a'] += longest_block_till[i]/k;\r\n        }\r\n    }\r\n\r\n    int answer = 0;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n        answer = max(answer, no_of_k_sequences[i]);\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Explanations/Arithmetic Progression Explanation.txt.txt",
    "content": "- Use queries of the first kind to find the maximum element using binary search.\r\n- Find random indices and get the values  and sort them\r\n    - The difference between any two consecutive elements will be a multiple of $g$\r\n    - If we choose them randomly enough, there will two that are coprime, for example $3g$ and $5g$ so their GCD will give us $g$\r\n\r\nThe probability of failing to find 2 coprime differences among a sequence of n elements among k is of the order 10^{-9}\r\n------\r\n\r\n\r\nmt19937 rng(time(NULL));\r\n\r\nint find_maximum(int &queries)\r\n{\r\n    int left = 0, right = 1e9 + 5;\r\n\r\n    //Always L < Max <= R\r\n    while(right - left > 1)\r\n    {\r\n        int has_higher;\r\n        int mid = (left + right)/2;\r\n\r\n        queries--;\r\n\r\n        cout << \"> \" << mid << \"\\n\"; cout.flush();\r\n\r\n        cin >> has_higher;\r\n\r\n        if(has_higher)\r\n            left = mid;\r\n        else\r\n            right = mid;\r\n    }\r\n\r\n    return right;\r\n}\r\n\r\nint find_difference(int &queries, int greatest, int no_of_elements)\r\n{\r\n    int remaining_range = no_of_elements - 1;\r\n    vector <int> A;\r\n\r\n    vector <int> asked(no_of_elements + 1, false);\r\n\r\n    while(queries > 0 && remaining_range > 0)\r\n    {\r\n        int question_index = uniform_int_distribution<int>(1, no_of_elements)(rng);\r\n\r\n        if(asked[question_index])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        cout << \"? \" << question_index << \"\\n\"; cout.flush();\r\n\r\n        asked[question_index] = true;\r\n\r\n        int answer;\r\n        cin >> answer;\r\n        A.push_back(answer);\r\n\r\n        queries--;\r\n        remaining_range--;\r\n    }\r\n\r\n    sort(all(A));\r\n\r\n    if(A[A.size() - 1] != greatest)\r\n        A.push_back(greatest);\r\n\r\n    int difference = A[1] - A[0];\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n        difference = __gcd(difference, A[i] - A[i - 1]);\r\n\r\n    return difference;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    const int MAX_QUERIES = 60;\r\n    int queries = MAX_QUERIES;\r\n\r\n    int maximum = find_maximum(queries);\r\n    int difference = find_difference(queries, maximum, no_of_elements);\r\n\r\n    int minimum = maximum - difference*(no_of_elements - 1);\r\n\r\n    cout << \"! \" << minimum << \" \" << difference << \"\\n\"; cout.flush();\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 538/Explanations/Flood Fill Explanation.txt",
    "content": "Fact - If a segment [L, R] is of one colour, then it is either A[L] or A[R] regardless of the starting square. \r\n\r\nProof - In the last move of making the segment the same colour, we must absorb one of the ends - L or R (or both). \r\n\r\nWhen we absorb an end we must cover the entire segment with one colour. \r\n\r\n---------------\r\n\r\nLet f(L, R, 0) represent the minimum number of moves to make the segment [L, R] in one colour if the colour is A[L].\r\n\r\nLet f(L, R, 1) represent the minimum number of moves to make the segment [L, R] in one colour if the color is A[R]. \r\n\r\nHow do we build [L, R] from smaller states ? \r\n\r\nSuppose we want to find out f(L, R, 0) ... Then it means we are using the colour of A[L]. \r\n\r\nSo we need to know the minimum number of moves to make [L + 1, R] the same colour.\r\n\r\n-----\r\n\r\nThere are 2 cases - \r\n\r\nCase 1 - Either [L - 1, R] is the same colour as A[L]. \r\n\r\nThen the number of moves is given by f(L - 1, R, 0) and the colour is A[L]. \r\n\r\nCase 2 - [L - 1, R] is the same colour as A[R]. \r\n\r\nThe the number of moves is given by f(L - 1, R, 1) and the colour is A[R].\r\n\r\n-------"
  },
  {
    "path": "Contests/Div 2 538/Explanations/Got Any Grapes Explanation.txt",
    "content": "We will see if there are enough grapes of the first kind and give the excess to the second. \r\n\r\nThen, we will see if there are enough grapes of the second kind and give the excess to the third.\r\n\r\n------------\r\n\r\nint main()\r\n{\r\n    int green_want, black_want, purple_want;\r\n    cin >> green_want >> black_want >> purple_want;\r\n\r\n    int green_have, black_have, purple_have;\r\n    cin >> green_have >> black_have >> purple_have;\r\n\r\n    if(green_have > green_want)\r\n    {\r\n        int excess = green_have - green_want;\r\n\r\n        green_have -= excess;\r\n        black_have += excess;\r\n    }\r\n\r\n    if(black_have > black_want)\r\n    {\r\n        int excess = black_have - black_want;\r\n\r\n        black_have -= excess;\r\n        purple_have += excess;\r\n    }\r\n\r\n    cout << (green_want <= green_have && black_want <= black_have && purple_want <= purple_have ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 538/Explanations/Please Another Queries on Array Explanation.txt",
    "content": "Let N = p1^k1 p2^k2 ... pm^k\r\nphi(N) = p1^(k1 - 1)(p1 - 1) p2^(k2 - 1)(p2 - 1) ... pm^(km - 1)(pm - 1)\r\n\r\n= p1^K1 p2^k2 ... pm^km {(p1 - 1)(p2 - 1) ... (pm - 1)}/(p1 p2 ... pm)\r\n\r\nThe reason this form of phi(N) is important is because it is independent of exponents of primes. \r\n\r\n-----------\r\n\r\nTo answer a range query, we need two informations - \r\n\r\n1. The product of the range\r\n2. The list of all primes having factors in the range. \r\n\r\nWe can get the product of a range very easily by maintaining a segment tree. \r\n\r\n--------------\r\n\r\nHow do we keep the list of all primes having factors ? \r\n\r\nNote that Ai < 300. There are less than 64 (62 to be exact) primes from [2, 300].\r\n\r\nWe will represent each integer x, by a bitmask where the i-th bit will be set if the i-th prime divides x\r\n\r\nFor example, if x = 24, then bitmask will have 00000 ... 0011\r\n\r\nThe first two bits set since it is divisible by 2 and 3. \r\n\r\nHere is how we precompute the masks - \r\n\r\nvoid precompute_mask()\r\n{\r\n    for(int i = 1; i < MAX_N; i++)\r\n    {\r\n        mask[i] = 0;\r\n\r\n        for(int bit = 0; bit < primes.size(); bit++)\r\n        {\r\n            if(i%primes[bit] == 0)\r\n            {\r\n                set_bit(mask[i], bit);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n---------------\r\n\r\nNow, how do we find out the mask of a range of numbers ? \r\n\r\nIt is simple. We want the i-th bit set, if the i-th prime divides any of the integers in the range. \r\n\r\nIn other words, if any of the masks in the range have the i-th bit set, then the mask of the range should have the i-th bit set. \r\n\r\nAll we need to do is find the OR of the masks of the segment !\r\n\r\nWhen we are multiplying a number x with every integer in the range, we need to perform OR(x, ) with every integer in the range. \r\n\r\nIt will be too slow to perform each update in O(n) time so we will maintain a segment tree that performs the OR operation !\r\n\r\n----------------\r\n\r\nHere is how we answer each query - \r\n\r\nvoid solve()\r\n{\r\n    string query;\r\n    int left, right;\r\n    cin >> query >> left >> right;\r\n\r\n    if(query == \"MULTIPLY\")\r\n    {\r\n        int x;\r\n        cin >> x;\r\n\r\n        product_tree.update(1, 1, no_of_elements, left, right, x);\r\n        OR_tree.update(1, 1, no_of_elements, left, right, mask[x]);\r\n    }\r\n    else if(query == \"TOTIENT\")\r\n    {\r\n        LL totient = product_tree.get_product(1, 1, no_of_elements, left, right);\r\n\r\n        LL segment_mask = OR_tree.get_mask(1, 1, no_of_elements, left, right);\r\n\r\n        for(int bit = 0; bit < primes.size(); bit++)\r\n        {\r\n            if(!is_bit_set(segment_mask, bit))\r\n                continue;\r\n\r\n            totient = (totient*(primes[bit] - 1))%MOD;\r\n            totient = (totient*prime_inverse[bit])%MOD;\r\n        }\r\n\r\n        cout << totient << \"\\n\";\r\n    }\r\n}\r\n\r\n---------\r\n\r\nWe cannot divide since we are dealing with a MOD so we will need to multiply by the inverse of the prime. It is better to precompute the inverses as well using Fermat's Little Theorem. \r\n\r\nI had a lot of bugs in implementation of segment tree such as - \r\n\r\n1. The Lazy Function of Product Segment Tree should multiply tree[n] by x^r, where r is the size of the range under n, not just by x. \r\n2. The OR Tree should allow long long masks and the tree should be long long. And the value of MAX_N should be properly set to 300.\r\n3. The set bit function had a mistake\r\n4. The prime sieve should start from 2, not 1 or 0.\r\n5. The base case of the product function should have an OR condition, not AND, which will cause an infinite loop."
  },
  {
    "path": "Contests/Div 2 538/Explanations/Trailing Loves Explanation.txt",
    "content": "The number of 0s in n! is equal to the exponent of b in (n!)\r\n\r\nLet us look at the prime factorisation of b.\r\n\r\nb = p1^k1 p2^k2 .... pm^km\r\n\r\n--------------\r\n\r\nThe exponent of a prime number p in n! is \r\n(n/p) + (n/p^2) + (n/p^3) + ... \r\n\r\nThe exponent of p^k in n! is e/k, where e is the exponent of p in n! (which can be calculated by the method given above).\r\n\r\nLL get_exponent_sum(LL n, LL p, int e)\r\n{\r\n    LL sum = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        sum += n/p;\r\n\r\n        n /= p;\r\n    }\r\n\r\n    return (sum/e);\r\n}\r\n\r\n-------------\r\n\r\nThe exponent of b in (n!) is \r\n\r\nmin{exp(p1^k1), exp(p2^k2), ... , (exp(pm^km))} in n!\r\n\r\nint main()\r\n{\r\n    LL n, base;\r\n    cin >> n >> base;\r\n\r\n    vector <LL> prime_factors;\r\n    vector <int> exponents;\r\n    factorise(prime_factors, exponents, base);\r\n\r\n    const LL oo = 1e18;\r\n    LL trailing_zeroes = oo;\r\n    for(int i = 0; i < prime_factors.size(); i++)\r\n    {\r\n        trailing_zeroes = min(trailing_zeroes, get_exponent_sum(n, prime_factors[i], exponents[i]));\r\n    }\r\n\r\n    cout << trailing_zeroes;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 538/Explanations/Yet Another Subarray Alternate Solution Explanation.txt",
    "content": "This is exactly like the previous solution. \r\n\r\nBut, rather than marking which indices belong to the greatest mk elements. \r\n\r\nHere we push those mk indices into a vector and sort it. \r\n\r\nAnd then we print every m-th index of this vector.\r\n\r\n--------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, min_size, no_of_subarrays;\r\n    cin >> no_of_elements >> min_size >> no_of_subarrays;\r\n\r\n    vector <info> A;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        int element;\r\n\r\n        cin >> element;\r\n\r\n        A.push_back(info(i, element));\r\n    }\r\n\r\n    sort(all(A));\r\n    reverse(all(A));\r\n\r\n    int greatest_elements = min_size*no_of_subarrays;\r\n    long long total_sum = 0;\r\n    vector <int> special_index(greatest_elements);\r\n    for(int i = 0; i < greatest_elements; i++)\r\n    {\r\n        total_sum += A[i].value;\r\n\r\n        special_index[i] = A[i].index + 1;\r\n    }\r\n\r\n    sort(all(special_index));\r\n\r\n    vector <int> partition_points(no_of_subarrays);\r\n    for(int i = 0; i < no_of_subarrays; i++)\r\n    {\r\n        partition_points[i] = special_index[(i + 1)*min_size - 1];\r\n    }\r\n\r\n    cout << total_sum << \"\\n\";\r\n    for(int i = 0; i < no_of_subarrays - 1; i++)\r\n        cout << partition_points[i] << \" \";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 538/Explanations/Yet Another Subarray Explanation.txt",
    "content": "Let us look at the greatest mk elements. \n\nWe will divide the arrays in such a way that each subarray has exactly m of these mk elements. \n\nThis is always possible since mk <= n. \n\nWe will mark all the indices which belong to the greatest mk elements. \n\nThen we will do a linear sweep through the array. Whenever the current segment has m of these indices, we will end the segment and begin a new one. \n\n-----------------------\n\nint main()\n{\n    int no_of_elements, min_size, no_of_subarrays;\n    cin >> no_of_elements >> min_size >> no_of_subarrays;\n\n    vector <info> A;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        int element;\n\n        cin >> element;\n\n        A.push_back(info(i, element));\n    }\n\n    sort(all(A));\n    reverse(all(A));\n\n    int greatest_elements = min_size*no_of_subarrays;\n    long long total_sum = 0;\n    vector <int> is_special(no_of_elements, false);\n    for(int i = 0; i < greatest_elements; i++)\n    {\n        is_special[A[i].index] = true;\n\n        total_sum += A[i].value;\n    }\n\n    int no_of_subarrays_made = 0, current_subarray_special_elements = 0;\n    vector <int> partition_points;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        current_subarray_special_elements += (is_special[i]);\n\n        if(current_subarray_special_elements == min_size)\n        {\n            partition_points.push_back(i + 1);\n\n            no_of_subarrays_made++;\n\n            current_subarray_special_elements = 0;\n        }\n    }\n\n    cout << total_sum << \"\\n\";\n    for(int i = 0; i < no_of_subarrays_made - 1; i++)\n        cout << partition_points[i] << \" \";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Arithmetic Progression.cpp",
    "content": "#include <iostream>\r\n#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <bits/stdc++.h>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nmt19937 rng(time(NULL));\r\n\r\nint find_maximum(int &queries)\r\n{\r\n    int left = 0, right = 1e9 + 5;\r\n\r\n    //Always L < Max <= R\r\n    while(right - left > 1)\r\n    {\r\n        int has_higher;\r\n        int mid = (left + right)/2;\r\n\r\n        queries--;\r\n\r\n        cout << \"> \" << mid << \"\\n\"; cout.flush();\r\n\r\n        cin >> has_higher;\r\n\r\n        if(has_higher)\r\n            left = mid;\r\n        else\r\n            right = mid;\r\n    }\r\n\r\n    return right;\r\n}\r\n\r\nint find_difference(int &queries, int greatest, int no_of_elements)\r\n{\r\n    int remaining_range = no_of_elements - 1;\r\n    vector <int> A;\r\n\r\n    vector <int> asked(no_of_elements + 1, false);\r\n\r\n    while(queries > 0 && remaining_range > 0)\r\n    {\r\n        int question_index = uniform_int_distribution<int>(1, no_of_elements)(rng);\r\n\r\n        if(asked[question_index])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        cout << \"? \" << question_index << \"\\n\"; cout.flush();\r\n\r\n        asked[question_index] = true;\r\n\r\n        int answer;\r\n        cin >> answer;\r\n        A.push_back(answer);\r\n\r\n        queries--;\r\n        remaining_range--;\r\n    }\r\n\r\n    sort(all(A));\r\n\r\n    if(A[A.size() - 1] != greatest)\r\n        A.push_back(greatest);\r\n\r\n    int difference = A[1] - A[0];\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n        difference = __gcd(difference, A[i] - A[i - 1]);\r\n\r\n    return difference;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    const int MAX_QUERIES = 60;\r\n    int queries = MAX_QUERIES;\r\n\r\n    int maximum = find_maximum(queries);\r\n    int difference = find_difference(queries, maximum, no_of_elements);\r\n\r\n    int minimum = maximum - difference*(no_of_elements - 1);\r\n\r\n    cout << \"! \" << minimum << \" \" << difference << \"\\n\"; cout.flush();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Flood Fill.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\nconst int MAX_N = 5005, oo = 5005, LEFT_COLOUR = 0, RIGHT_COLOUR = 1, NO_OF_ENDS = 2;\r\nint minimum_moves[MAX_N][MAX_N][NO_OF_ENDS];\r\n\r\nint main()\r\n{\r\n    int no_of_squares;\r\n    cin >> no_of_squares;\r\n\r\n    vector <int> A(no_of_squares + 1);\r\n    for(int i = 1; i <= no_of_squares; i++)\r\n        cin >> A[i];\r\n\r\n    for(int i = 1; i <= no_of_squares; i++)\r\n    {\r\n        minimum_moves[i][i][LEFT_COLOUR] = minimum_moves[i][i][RIGHT_COLOUR] = 0;\r\n    }\r\n\r\n    for(int length = 2; length <= no_of_squares; length++)\r\n    {\r\n        for(int left = 1, right = left + length - 1; right <= no_of_squares; left++, right++)\r\n        {\r\n            minimum_moves[left][right][LEFT_COLOUR] = min(minimum_moves[left + 1][right][LEFT_COLOUR] + (A[left] != A[left + 1]),\r\n                                                          minimum_moves[left + 1][right][RIGHT_COLOUR] + (A[left] != A[right]));\r\n\r\n            minimum_moves[left][right][RIGHT_COLOUR] = min(minimum_moves[left][right - 1][LEFT_COLOUR] + (A[left] != A[right]),\r\n                                                           minimum_moves[left][right - 1][RIGHT_COLOUR] + (A[right - 1] != A[right]));\r\n        }\r\n    }\r\n\r\n    LL answer = min(minimum_moves[1][no_of_squares][LEFT_COLOUR], minimum_moves[1][no_of_squares][RIGHT_COLOUR]);\r\n    cout << answer;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Got Any Grapes.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int green_want, black_want, purple_want;\r\n    cin >> green_want >> black_want >> purple_want;\r\n\r\n    int green_have, black_have, purple_have;\r\n    cin >> green_have >> black_have >> purple_have;\r\n\r\n    if(green_have > green_want)\r\n    {\r\n        int excess = green_have - green_want;\r\n\r\n        green_have -= excess;\r\n        black_have += excess;\r\n    }\r\n\r\n    if(black_have > black_want)\r\n    {\r\n        int excess = black_have - black_want;\r\n\r\n        black_have -= excess;\r\n        purple_have += excess;\r\n    }\r\n\r\n    cout << (green_want <= green_have && black_want <= black_have && purple_want <= purple_have ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Please Another Queries on Array.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\n#define LEFT(n) (2*n)\r\n#define RIGHT(n) (2*n + 1)\r\nusing namespace std;\r\n\r\nconst int MOD = 1e9 + 7, MAX_N = 305;\r\n\r\ntypedef long long LL;\r\n\r\nvector <LL> primes;\r\nvector <LL> prime_inverse;\r\nvector <LL> mask(MAX_N, 0);\r\n\r\n\r\nint is_bit_set(LL n, int position)\r\n{\r\n    return ( (n&(1LL << position)) != 0);\r\n}\r\n\r\nvoid set_bit(LL &n, int position)\r\n{\r\n    n |= (1LL << position);\r\n}\r\n\r\nLL fast_power(LL base, LL power)\r\n{\r\n    LL result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*base)%MOD;\r\n\r\n        base = (base*base)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nvoid precompute_primes()\r\n{\r\n    vector <int> is_prime(MAX_N, true);\r\n\r\n    for(int i = 2; i < MAX_N; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] < MAX_N; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n}\r\n\r\nvoid precompute_prime_inverse()\r\n{\r\n    for(int i = 0; i < primes.size(); i++)\r\n    {\r\n        LL inverse = fast_power(primes[i], MOD - 2);\r\n\r\n        prime_inverse.push_back(inverse);\r\n    }\r\n}\r\n\r\nvoid precompute_mask()\r\n{\r\n    for(int i = 1; i < MAX_N; i++)\r\n    {\r\n        mask[i] = 0;\r\n\r\n        for(int bit = 0; bit < primes.size(); bit++)\r\n        {\r\n            if(i%primes[bit] == 0)\r\n            {\r\n                set_bit(mask[i], bit);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nstruct Product_Tree\r\n{\r\n    vector <LL> tree, lazy;\r\n\r\n    Product_Tree(){}\r\n\r\n    Product_Tree(int n)\r\n    {\r\n        tree.resize(4*n, 1);\r\n        lazy.resize(4*n, 1);\r\n    }\r\n\r\n    void propagate(int n, int left, int right)\r\n    {\r\n        LL range = right - (left - 1);\r\n        tree[n] = (tree[n]*fast_power(lazy[n], range))%MOD;\r\n\r\n        if(left != right)\r\n        {\r\n            lazy[LEFT(n)] = (lazy[LEFT(n)]*lazy[n])%MOD;\r\n            lazy[RIGHT(n)] = (lazy[RIGHT(n)]*lazy[n])%MOD;\r\n        }\r\n\r\n        lazy[n] = 1;\r\n    }\r\n\r\n    void update(int n, int left, int right, int query_left, int query_right, int value)\r\n    {\r\n        if(lazy[n] > 1)\r\n        {\r\n            propagate(n, left, right);\r\n        }\r\n\r\n        if(right < query_left || query_right < left)\r\n        {\r\n            return;\r\n        }\r\n\r\n        if(query_left <= left && right <= query_right)\r\n        {\r\n            lazy[n] = (lazy[n]*value)%MOD;\r\n\r\n            propagate(n, left, right);\r\n\r\n            return;\r\n        }\r\n\r\n        int mid = (left + right)/2;\r\n\r\n        update(LEFT(n), left, mid, query_left, query_right, value);\r\n        update(RIGHT(n), mid + 1, right, query_left, query_right, value);\r\n\r\n        tree[n] = (tree[LEFT(n)]*tree[RIGHT(n)])%MOD;\r\n    }\r\n\r\n    LL get_product(int n, int left, int right, int query_left, int query_right)\r\n    {\r\n        if(lazy[n] > 1)\r\n        {\r\n            propagate(n, left, right);\r\n        }\r\n\r\n        if(right < query_left || query_right < left)\r\n        {\r\n            return 1LL;\r\n        }\r\n\r\n        if(query_left <= left && right <= query_right)\r\n        {\r\n            return tree[n];\r\n        }\r\n\r\n        int mid = (left + right)/2;\r\n\r\n        LL left_product = get_product(LEFT(n), left, mid, query_left, query_right);\r\n        LL right_product = get_product(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n        LL product = (left_product*right_product)%MOD;\r\n\r\n        return product;\r\n    }\r\n};\r\n\r\nstruct OR_Tree\r\n{\r\n    vector <LL> tree, lazy;\r\n\r\n    OR_Tree(){}\r\n\r\n    OR_Tree(int n)\r\n    {\r\n        tree.resize(4*n, 0);\r\n        lazy.resize(4*n, 0);\r\n    }\r\n\r\n    void propagate(int n, int left, int right)\r\n    {\r\n        tree[n] |= lazy[n];\r\n\r\n        if(left != right)\r\n        {\r\n            lazy[LEFT(n)]  |= lazy[n];\r\n            lazy[RIGHT(n)] |= lazy[n];\r\n        }\r\n\r\n        lazy[n] = 0;\r\n    }\r\n\r\n    void update(int n, int left, int right, int query_left, int query_right, LL value)\r\n    {\r\n        if(lazy[n])\r\n        {\r\n            propagate(n, left, right);\r\n        }\r\n\r\n        if(right < query_left || query_right < left)\r\n        {\r\n            return;\r\n        }\r\n\r\n        if(query_left <= left && right <= query_right)\r\n        {\r\n            lazy[n] |= value;\r\n\r\n            propagate(n, left, right);\r\n\r\n            return;\r\n        }\r\n\r\n        int mid = (left + right)/2;\r\n\r\n        update(LEFT(n), left, mid, query_left, query_right, value);\r\n        update(RIGHT(n), mid + 1, right, query_left, query_right, value);\r\n\r\n        tree[n] = (tree[LEFT(n)]|tree[RIGHT(n)]);\r\n    }\r\n\r\n    LL get_mask(int n, int left, int right, int query_left, int query_right)\r\n    {\r\n        if(lazy[n])\r\n        {\r\n            propagate(n, left, right);\r\n        }\r\n\r\n        if(right < query_left || query_right < left)\r\n        {\r\n            return 0;\r\n        }\r\n\r\n        if(query_left <= left && right <= query_right)\r\n        {\r\n            return tree[n];\r\n        }\r\n\r\n        int mid = (left + right)/2;\r\n        LL left_mask = get_mask(LEFT(n), left, mid, query_left, query_right);\r\n        LL right_mask = get_mask(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n        LL mask = (left_mask|right_mask);\r\n        return mask;\r\n    }\r\n};\r\n\r\nProduct_Tree product_tree;\r\nOR_Tree OR_tree;\r\nint no_of_elements, no_of_queries;\r\n\r\nvoid read_input()\r\n{\r\n    cin >> no_of_elements >> no_of_queries;\r\n\r\n    product_tree = Product_Tree(no_of_elements);\r\n    OR_tree = OR_Tree(no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        product_tree.update(1, 1, no_of_elements, i, i, element);\r\n        OR_tree.update(1, 1, no_of_elements, i, i, mask[element]);\r\n    }\r\n}\r\n\r\nvoid solve()\r\n{\r\n    string query;\r\n    int left, right;\r\n    cin >> query >> left >> right;\r\n\r\n    if(query == \"MULTIPLY\")\r\n    {\r\n        int x;\r\n        cin >> x;\r\n\r\n        product_tree.update(1, 1, no_of_elements, left, right, x);\r\n        OR_tree.update(1, 1, no_of_elements, left, right, mask[x]);\r\n    }\r\n    else if(query == \"TOTIENT\")\r\n    {\r\n        LL totient = product_tree.get_product(1, 1, no_of_elements, left, right);\r\n\r\n        LL segment_mask = OR_tree.get_mask(1, 1, no_of_elements, left, right);\r\n\r\n        for(int bit = 0; bit < primes.size(); bit++)\r\n        {\r\n            if(!is_bit_set(segment_mask, bit))\r\n                continue;\r\n\r\n            totient = (totient*(primes[bit] - 1))%MOD;\r\n            totient = (totient*prime_inverse[bit])%MOD;\r\n        }\r\n\r\n        cout << totient << \"\\n\";\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_primes();\r\n    precompute_prime_inverse();\r\n    precompute_mask();\r\n\r\n    read_input();\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Trailing Loves.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nvoid factorise(vector <LL> &F, vector <int> &E, LL n)\r\n{\r\n    for(LL i = 2; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            int exponent = 0;\r\n\r\n            while(n%i == 0)\r\n            {\r\n                n /= i;\r\n\r\n                exponent++;\r\n            }\r\n\r\n            F.push_back(i);\r\n            E.push_back(exponent);\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n    {\r\n        F.push_back(n);\r\n        E.push_back(1);\r\n    }\r\n}\r\n\r\nLL get_exponent_sum(LL n, LL p, int e)\r\n{\r\n    LL sum = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        sum += n/p;\r\n\r\n        n /= p;\r\n    }\r\n\r\n    return (sum/e);\r\n}\r\n\r\nint main()\r\n{\r\n    LL n, base;\r\n    cin >> n >> base;\r\n\r\n    vector <LL> prime_factors;\r\n    vector <int> exponents;\r\n    factorise(prime_factors, exponents, base);\r\n\r\n    const LL oo = 1e18;\r\n    LL trailing_zeroes = oo;\r\n    for(int i = 0; i < prime_factors.size(); i++)\r\n    {\r\n        trailing_zeroes = min(trailing_zeroes, get_exponent_sum(n, prime_factors[i], exponents[i]));\r\n    }\r\n\r\n    cout << trailing_zeroes;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Yet Another Subarray Problem Alternate Solution.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct info\r\n{\r\n    int index, value;\r\n\r\n    info(int i, int v)\r\n    {\r\n        index = i; value = v;\r\n    }\r\n\r\n    const int operator<(const info &X)\r\n    {\r\n        return (value < X.value);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_elements, min_size, no_of_subarrays;\r\n    cin >> no_of_elements >> min_size >> no_of_subarrays;\r\n\r\n    vector <info> A;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        int element;\r\n\r\n        cin >> element;\r\n\r\n        A.push_back(info(i, element));\r\n    }\r\n\r\n    sort(all(A));\r\n    reverse(all(A));\r\n\r\n    int greatest_elements = min_size*no_of_subarrays;\r\n    long long total_sum = 0;\r\n    vector <int> special_index(greatest_elements);\r\n    for(int i = 0; i < greatest_elements; i++)\r\n    {\r\n        total_sum += A[i].value;\r\n\r\n        special_index[i] = A[i].index + 1;\r\n    }\r\n\r\n    sort(all(special_index));\r\n\r\n    vector <int> partition_points(no_of_subarrays);\r\n    for(int i = 0; i < no_of_subarrays; i++)\r\n    {\r\n        partition_points[i] = special_index[(i + 1)*min_size - 1];\r\n    }\r\n\r\n    cout << total_sum << \"\\n\";\r\n    for(int i = 0; i < no_of_subarrays - 1; i++)\r\n        cout << partition_points[i] << \" \";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 538/Programs/Yet Another Subarray Problem.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct info\r\n{\r\n    int index, value;\r\n\r\n    info(int i, int v)\r\n    {\r\n        index = i; value = v;\r\n    }\r\n\r\n    const int operator<(const info &X)\r\n    {\r\n        return (value < X.value);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_elements, min_size, no_of_subarrays;\r\n    cin >> no_of_elements >> min_size >> no_of_subarrays;\r\n\r\n    vector <info> A;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        int element;\r\n\r\n        cin >> element;\r\n\r\n        A.push_back(info(i, element));\r\n    }\r\n\r\n    sort(all(A));\r\n    reverse(all(A));\r\n\r\n    int greatest_elements = min_size*no_of_subarrays;\r\n    long long total_sum = 0;\r\n    vector <int> is_special(no_of_elements, false);\r\n    for(int i = 0; i < greatest_elements; i++)\r\n    {\r\n        is_special[A[i].index] = true;\r\n\r\n        total_sum += A[i].value;\r\n    }\r\n\r\n    int no_of_subarrays_made = 0, current_subarray_special_elements = 0;\r\n    vector <int> partition_points;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        current_subarray_special_elements += (is_special[i]);\r\n\r\n        if(current_subarray_special_elements == min_size)\r\n        {\r\n            partition_points.push_back(i + 1);\r\n\r\n            no_of_subarrays_made++;\r\n\r\n            current_subarray_special_elements = 0;\r\n        }\r\n    }\r\n\r\n    cout << total_sum << \"\\n\";\r\n    for(int i = 0; i < no_of_subarrays_made - 1; i++)\r\n        cout << partition_points[i] << \" \";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 539/Explanations/Sasha and A Bit of Relax Explanation.txt",
    "content": "I thought of approaching this question by treating each bit independently, like most bitwise questions. I couldn't find a way to combine answers for different bits. I read the editorial used the insight that the XOR of the segment is 0 and then I immediately understood how to use prefix XOR to solve this problem.\r\n\r\n-------------\r\n\r\nWe keep track of the frequency of every prefix_xor and each parity. \r\n\r\nIf XOR[L, ... , R] = 0, then \r\n\r\nPrefix[R] = Prefix[L - 1]\r\n\r\nFor every i, let f(i, 0) be the frequency of prefix XOR i in even positions and \r\nf(i, 1) be the frequency of prefix XOR i in odd positions.\r\n\r\nWe will go through the array and for each i, we will add f(Prefix[i], i%2) to the answer and then update f(Prefix[i], i%2). \r\n\r\nRemember to set f(0, 0) = 1. That represents the empty array.\r\n\r\n-------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    int prefix_xor = 0;\r\n    long long good_subarrays = 0;\r\n    memset(frequency, 0, sizeof(frequency));\r\n\r\n    frequency[0][0] = 1;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        prefix_xor ^= element;\r\n\r\n        good_subarrays += (frequency[prefix_xor][i%2]);\r\n\r\n        frequency[prefix_xor][i%2]++;\r\n    }\r\n\r\n    cout << good_subarrays;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 539/Explanations/Sasha and His Trip Explanation.txt",
    "content": "It is always better to buy the liter as early as possible as we will pay more for the same amount as time goes on. \r\n\r\nWe will be greedy. We will first buy v literes in first city\r\n\r\nThen, we will go to each city and buy only one liter, and make sure the capacity is full. \r\n\r\nWe will not refill, if the remaining journey x, is smaller than the the fuel we have v.\r\n\r\n\r\n-------------------\r\n\r\nOf course, if we capacity is more than the number of cities, then we will only refuel n - 1 times.\r\n\r\n-------------------\r\n\r\nint main()\r\n{\r\n    int no_of_cities, capacity;\r\n    cin >> no_of_cities >> capacity;\r\n\r\n    int fuel;\r\n    if(capacity >= no_of_cities - 1)\r\n    {\r\n        fuel = no_of_cities - 1;\r\n    }\r\n    else\r\n    {\r\n        fuel = capacity - 1;\r\n\r\n        for(int i = 1; i <= no_of_cities - capacity; i++)\r\n            fuel += i;\r\n    }\r\n\r\n    cout << fuel;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 539/Explanations/Sasha and Magnetic Machine Explanation.txt",
    "content": "The number we multiply with will always be the minimum integer. \n\nSo, we will iterate from 1 to 100. \n\nFor each number x from the minimum till 100, we will iterate over all of x's factors and examine the change in the sum if we multiply the minimum with x and divide x by it's factor.\n\n---------\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    const int MAX = 105;\n    vector <int> frequency(MAX, 0);\n\n    int sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int element;\n        cin >> element;\n\n        frequency[element]++;\n        sum += element;\n    }\n\n    int minimum;\n    for(int i = 1; i < MAX; i++)\n    {\n        if(frequency[i] > 0)\n        {\n            minimum = i;\n            break;\n        }\n    }\n\n    int answer = sum;\n    for(int i = minimum; i < MAX; i++)\n    {\n        if(frequency[i] == 0)\n            continue;\n\n        if(i == minimum && frequency[i] == 1)\n            continue;\n\n        for(int p = 2; p <= i; p++)\n        {\n            if(i%p == 0)\n            {\n                int increase = minimum*(p - 1);\n                int decrease = i - i/p;\n\n                answer = min(answer, sum + increase - decrease);\n            }\n        }\n    }\n\n    cout << answer;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 539/Explanations/Sasha and One More Name Explanation.txt",
    "content": "Given a palindrome string S, we must cut it into some k parts and then rearrange them to get a string R, such that \r\n\r\nR is a palindrome and R is not equal to S.\r\n\r\nWe want to find the minimum such k.\r\n\r\n-------\r\n\r\nSuppose - S has only one character, then only one palindromic string is possible. \r\nIf S is odd palindrome, and has n - 1 same characters and one different character (central character), even then only one palindrome is possible. \r\n\r\nIn these situations it is impossible to get a palindrome R =/= S. \r\n\r\nint is_cut_impossible(string &S)\r\n{\r\n    int same = 0, length = S.size();\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        same += (S[i] == S[0]);\r\n    }\r\n\r\n    int not_possible = ( (length%2 == 0 && same == length ) || (length%2 == 1 && same >= length - 1) );\r\n\r\n    return not_possible;\r\n}\r\n\r\n---------\r\n\r\nLet us suppose this is not the case.\r\n\r\nFirstly, let us check if it is possible with one cut. \r\n\r\nIf we make only one cut, S[1, 2, ... i] S[i + 1, ... , n]\r\n\r\nAnd if we put the second part first, then it is like a cyclic rotations of S. \r\n\r\nWe will check all cyclic rotations of S and check if any of those rotations yield a string R that is not equal to S and is also a palindrome. \r\n\r\n(Don't physically rotate the string. Just maintain two pointers.)\r\n\r\nfor(int start = 1; start < S.size(); start++)\r\n    {\r\n        if(!is_equal(S, start) && is_palindrome(S, start))\r\n        {\r\n            cout << \"1\\n\";\r\n            return 0;\r\n        }\r\n    }\r\n\r\n------------\r\n\r\nIf this is also not the case, then we will show that it is always possible with 2 cuts and 3 pieces.\r\n\r\nLet p be the smallest length prefix such that there are at least 2 distinct characters. \r\n\r\nThis prefix will be of the form - xxxxxxxxxxA\r\n\r\nLet us look at the suffix of the same length p. \r\n\r\nIt will be of the form Axxxxxxxxx.\r\n\r\nClearly p =/= reverse(p) because\r\n\r\nand p = reverse( reverse(p) )\r\n\r\nSo we will interchange the prefix and suffix. The middle part is unchanged. The string R is a palindrome and R is not equal to S.\r\n"
  },
  {
    "path": "Contests/Div 2 539/Programs/Sasha and A Bit of Relax.cpp",
    "content": "#include <iostream>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = (1 << 21), PARITY = 2;\r\nint frequency[MAX_N][PARITY];\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    int prefix_xor = 0;\r\n    long long good_subarrays = 0;\r\n    memset(frequency, 0, sizeof(frequency));\r\n\r\n    frequency[0][0] = 1;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        prefix_xor ^= element;\r\n\r\n        good_subarrays += (frequency[prefix_xor][i%2]);\r\n\r\n        frequency[prefix_xor][i%2]++;\r\n    }\r\n\r\n    cout << good_subarrays;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 539/Programs/Sasha and His Trip.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_cities, capacity;\r\n    cin >> no_of_cities >> capacity;\r\n\r\n    int fuel;\r\n    if(capacity >= no_of_cities - 1)\r\n    {\r\n        fuel = no_of_cities - 1;\r\n    }\r\n    else\r\n    {\r\n        fuel = capacity - 1;\r\n\r\n        for(int i = 1; i <= no_of_cities - capacity; i++)\r\n            fuel += i;\r\n    }\r\n\r\n    cout << fuel;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 539/Programs/Sasha and Magnetic Machine.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    const int MAX = 105;\n    vector <int> frequency(MAX, 0);\n\n    int sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int element;\n        cin >> element;\n\n        frequency[element]++;\n        sum += element;\n    }\n\n    int minimum;\n    for(int i = 1; i < MAX; i++)\n    {\n        if(frequency[i] > 0)\n        {\n            minimum = i;\n            break;\n        }\n    }\n\n    int answer = sum;\n    for(int i = minimum; i < MAX; i++)\n    {\n        if(frequency[i] == 0)\n            continue;\n\n        if(i == minimum && frequency[i] == 1)\n            continue;\n\n        for(int p = 2; p <= i; p++)\n        {\n            if(i%p == 0)\n            {\n                int increase = minimum*(p - 1);\n                int decrease = i - i/p;\n\n                answer = min(answer, sum + increase - decrease);\n            }\n        }\n    }\n\n    cout << answer;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 539/Programs/Sasha and One More Name.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid increment(int &i, int n)\r\n{\r\n    i = (i + 1)%n;\r\n}\r\n\r\nvoid decrement(int &i, int n)\r\n{\r\n    i = (i - 1 + n)%n;\r\n}\r\n\r\nint is_palindrome(string &S, int left)\r\n{\r\n    int length = S.size();\r\n\r\n    int right = (left - 1);\r\n\r\n    for(int forward_i = left, backward_i = right; forward_i != right; increment(forward_i, length), decrement(backward_i, length))\r\n    {\r\n        if(S[forward_i] != S[backward_i])\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint is_equal(string &S, int start)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] != S[(i + start)%S.size()])\r\n        {\r\n            return false;\r\n        }\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint is_cut_impossible(string &S)\r\n{\r\n    int same = 0, length = S.size();\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        same += (S[i] == S[0]);\r\n    }\r\n\r\n    int not_possible = ( (length%2 == 0 && same == length ) || (length%2 == 1 && same >= length - 1) );\r\n\r\n    return not_possible;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    if(is_cut_impossible(S))\r\n    {\r\n        cout << \"Impossible\\n\";\r\n        return 0;\r\n    }\r\n\r\n    for(int start = 1; start < S.size(); start++)\r\n    {\r\n        if(!is_equal(S, start) && is_palindrome(S, start))\r\n        {\r\n            cout << \"1\\n\";\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    cout << \"2\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 546/Explanations/Nastya  is Playing Computer Games Explanation.txt",
    "content": "Here is what is optimal. At the first hole, we will throw the stone into the neighbouring hole. Then go to the neighbouring hole and throw back to the first stone \r\nAfter this, whenever we visit any hole, throw the stones into the first hole. Rather than simulate the entire movement, there is a clean solution.\r\n\r\nLet us notice that we must visit each and every hole. The number of movements = Min{k - 1, n - k} + N - 1\r\n\r\nWe will throw a stone at every hole except the second hole where we throw 2 stones. Total stones thrown = N + 1\r\n\r\nTotal coins picked up = N\r\n\r\nThe total number of moves is the sum of all 3. \r\n\r\n---------\r\n\r\nint main()\r\n{\r\n\tint no_of_holes, position;\r\n\tcin >> no_of_holes >> position;\r\n\r\n\tint movement = min(position - 1, no_of_holes - position) + no_of_holes - 1;\r\n\tint stones_thrown = no_of_holes + 1;\r\n\tint coins_picked = no_of_holes;\r\n\r\n\tint total_moves = movement + stones_thrown + coins_picked;\r\n\tcout << total_moves;\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 546/Explanations/Nastya is Transposing Matrices Explanation.txt",
    "content": "Each element only moves across it's anti-diagonal. It never moves out of it. \n\nWe can always make A = B if each of their anti-diagonals are equal. \n\nIn a given anti-diagonal, (x + y) is invariant.\n\n--------\n\nint main()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    int max_diagonals = rows + columns;\n    vector <int> A_diagonals[max_diagonals + 5];\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int x;\n            cin >> x;\n\n            int diagonal_no = i + j;\n            A_diagonals[diagonal_no].push_back(x);\n        }\n    }\n\n    vector <int> B_diagonals[max_diagonals + 5];\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int x;\n            cin >> x;\n\n            int diagonal_no = i + j;\n            B_diagonals[diagonal_no].push_back(x);\n        }\n    }\n\n    int possible = true;\n    for(int i = 1; i <= max_diagonals; i++)\n    {\n        sort(all(A_diagonals[i]));\n        sort(all(B_diagonals[i]));\n\n        if(A_diagonals[i] != B_diagonals[i])\n        {\n            possible = false;\n            break;\n        }\n    }\n\n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 546/Programs/Nastya is Playing Computer Games.cpp",
    "content": "#include <iostream>\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n\tint no_of_holes, position;\r\n\tcin >> no_of_holes >> position;\r\n\r\n\tint movement = min(position - 1, no_of_holes - position) + no_of_holes - 1;\r\n\tint stones_thrown = no_of_holes + 1;\r\n\tint coins_picked = no_of_holes;\r\n\r\n\tint total_moves = movement + stones_thrown + coins_picked;\r\n\tcout << total_moves;\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 546/Programs/Nastya is Transposing Matrices.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    int max_diagonals = rows + columns;\n    vector <int> A_diagonals[max_diagonals + 5];\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int x;\n            cin >> x;\n\n            int diagonal_no = i + j;\n            A_diagonals[diagonal_no].push_back(x);\n        }\n    }\n\n    vector <int> B_diagonals[max_diagonals + 5];\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            int x;\n            cin >> x;\n\n            int diagonal_no = i + j;\n            B_diagonals[diagonal_no].push_back(x);\n        }\n    }\n\n    int possible = true;\n    for(int i = 1; i <= max_diagonals; i++)\n    {\n        sort(all(A_diagonals[i]));\n        sort(all(B_diagonals[i]));\n\n        if(A_diagonals[i] != B_diagonals[i])\n        {\n            possible = false;\n            break;\n        }\n    }\n\n    cout << (possible ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 554/Explanations/Neko Does Math Explanation.txt",
    "content": "We want to minimize LCM(a + k, b + k) given a and b.\n\nLCM(a + k, b + k) = (a + k).(b + k)/gcd(a + k, b + k)\n\n= (a + k).(b + k)/gcd(b - a, b + k)\n\nLet us iterate over all divisors of (b - a)\n\n1. Suppose d is a divisor of (b - a). We will find the smallest k, such that d = gcd(b - a, b + k)\nd also needs to be the gcd(a + k, b + k). \nSo a = b (mod d) has to be satisfied\n\n2. Then, we will find the LCM.\n\n3. The key is iterating over the divisors of (b - a)\n\n-----\n\nThere is a special case when a = b. \n\n(b - a) will have no factors.\n\nk = 0 here\n\n-----\n\nint main()\n{\n    LL a, b;\n    cin >> a >> b;\n\n    vector <int> factors;\n    factorise(abs(b - a), factors);\n\n    const LL oo = 1e18;\n    LL minimum_lcm = (a == b ? a : oo), k = (a == b ? 0 : oo);\n\n    for(int i = 0; i < factors.size(); i++)\n    {\n        int f = factors[i];\n\n        if(a%f != b%f)\n            continue;\n\n        LL to_add = (a%f == 0 ? 0 : f - a%f);\n        LL lcm = ((a + to_add)*(b + to_add))/__gcd(a + to_add, b + to_add);\n\n        if(a%f == 0)\n        {\n            if(lcm <= minimum_lcm)\n            {\n                minimum_lcm = lcm;\n                k = to_add;\n            }\n        }\n        else\n        {\n            if(lcm < minimum_lcm)\n            {\n                minimum_lcm = lcm;\n                k = to_add;\n            }\n        }\n    }\n\n    cout << k;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 554/Programs/Neko Does Math.cpp",
    "content": "#include <iostream>\n#include <algorithm>\n#include <vector>\n\nusing namespace std;\n\ntypedef long long LL;\n\nLL lcm(LL a, LL b)\n{\n    return (a*b)/__gcd(a, b);\n}\n\nvoid factorise(LL n, vector <int> &F)\n{\n    for(int i = 1; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            F.push_back(i);\n\n            if(i*i != n)\n                F.push_back(n/i);\n        }\n    }\n}\n\nint main()\n{\n    LL a, b;\n    cin >> a >> b;\n\n    vector <int> factors;\n    factorise(abs(b - a), factors);\n\n    const LL oo = 1e18;\n    LL minimum_lcm = (a == b ? a : oo), k = (a == b ? 0 : oo);\n\n    for(int i = 0; i < factors.size(); i++)\n    {\n        int f = factors[i];\n\n        if(a%f != b%f)\n            continue;\n\n        LL to_add = (a%f == 0 ? 0 : f - a%f);\n        LL lcm = ((a + to_add)*(b + to_add))/__gcd(a + to_add, b + to_add);\n\n        if(a%f == 0)\n        {\n            if(lcm <= minimum_lcm)\n            {\n                minimum_lcm = lcm;\n                k = to_add;\n            }\n        }\n        else\n        {\n            if(lcm < minimum_lcm)\n            {\n                minimum_lcm = lcm;\n                k = to_add;\n            }\n        }\n    }\n\n    cout << k;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 562/Explanations/Good Triple Explanation.txt",
    "content": "We only need to check segments of length 9.\n\nhttps://www.cut-the-knot.org/proofs/2ColorsOnLine.shtml#solution\n\n-----\n\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint is_good(string &S)\n{\n    for(int x = 0; x < S.size(); x++)\n    {\n        for(int k = 1; x + 2*k < S.size(); k++)\n        {\n            if(S[x] == S[x + k] && S[x + k] == S[x + 2*k])\n            {\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    long long answer = 0;\n    for(int left = 0; left < S.size(); left++)\n    {\n        for(int length = 2; length <= 9 && left + length - 1 < S.size(); length++)\n        {\n            string substring = S.substr(left, length);\n\n            if(is_good(substring))\n            {\n                int right = left + length - 1;\n\n                //cout << \"L = \" << left << \" R = \" << right << \" S = \" << substring << \"\\n\";\n\n                answer += (S.size() - 1) - (right - 1);\n\n                break;\n            }\n        }\n    }\n\n    cout << answer;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 562/Explanations/Pairs Explanation.txt",
    "content": "Let us take the first pair (x, y)\n\nOne of these must be x and the other must be y\n\n-----\n\nLet us fix one of these as x and collect all pairs which don't have x\n\nNow the problem is\n\nGiven a graph, check if there 1 vertex that is connected to every other vertex\n\n-----\n\nWe can do this by checking the degree of each vertex. One of the degrees must be equal to the number of pairs\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint range, no_of_pairs;\nvector <int> x, y;\n\nint check_for_x(int n)\n{\n    int no_of_remaining_pairs = 0;\n    vector <int> degree(range + 1, 0);\n    for(int i = 1; i <= no_of_pairs; i++)\n    {\n        if(x[i] == n || y[i] == n)\n        {\n            continue;\n        }\n\n        degree[x[i]]++;\n        degree[y[i]]++;\n\n        no_of_remaining_pairs++;\n    }\n\n    for(int i = 1; i <= range; i++)\n    {\n        if(degree[i] == no_of_remaining_pairs)\n        {\n            return true;\n        }\n    }\n\n    return false;\n}\n\nint main()\n{\n    cin >> range >> no_of_pairs;\n\n    x.resize(no_of_pairs + 1);\n    y.resize(no_of_pairs + 1);\n    for(int i = 1; i <= no_of_pairs; i++)\n    {\n        cin >> x[i] >> y[i];\n    }\n\n    cout << (check_for_x(x[1]) || check_for_x(y[1]) ? \"YES\\n\" : \"NO\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 562/Programs/Good Triple.cpp",
    "content": "#include <iostream>\n#include <string>\n\nusing namespace std;\n\nint is_good(string &S)\n{\n    for(int x = 0; x < S.size(); x++)\n    {\n        for(int k = 1; x + 2*k < S.size(); k++)\n        {\n            if(S[x] == S[x + k] && S[x + k] == S[x + 2*k])\n            {\n                return true;\n            }\n        }\n    }\n\n    return false;\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    long long answer = 0;\n    for(int left = 0; left < S.size(); left++)\n    {\n        for(int length = 2; length <= 9 && left + length - 1 < S.size(); length++)\n        {\n            string substring = S.substr(left, length);\n\n            if(is_good(substring))\n            {\n                int right = left + length - 1;\n\n                answer += (S.size() - 1) - (right - 1);\n\n                break;\n            }\n        }\n    }\n\n    cout << answer;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 562/Programs/Increasing by Modulo.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint possible(int operations, int m, vector <int> &A)\r\n{\r\n    int minimum = 0;\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if( (A[i] <= minimum && A[i] + operations >= minimum) || (A[i] > minimum && A[i] + operations - m >= minimum) )\r\n            continue;\r\n\r\n        if(A[i] < minimum)\r\n            return false;\r\n\r\n        minimum = A[i];\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, m;\r\n    cin >> no_of_elements >> m;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    int left = -1, right = m;\r\n    while(right - left > 1)\r\n    {\r\n        int mid = (left + right)/2;\r\n\r\n        if(possible(mid, m, A))\r\n            right = mid;\r\n        else\r\n            left = mid;\r\n    }\r\n\r\n    cout << right;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 562/Programs/Pairs.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint range, no_of_pairs;\nvector <int> x, y;\n\nint check_for_x(int n)\n{\n    int no_of_remaining_pairs = 0;\n    vector <int> degree(range + 1, 0);\n    for(int i = 1; i <= no_of_pairs; i++)\n    {\n        if(x[i] == n || y[i] == n)\n        {\n            continue;\n        }\n        \n        degree[x[i]]++;\n        degree[y[i]]++;\n        \n        no_of_remaining_pairs++;\n    }\n    \n    for(int i = 1; i <= range; i++)\n    {\n        if(degree[i] == no_of_remaining_pairs)\n        {\n            return true;\n        }\n    }\n    \n    return false;\n}\n\nint main()\n{\n    cin >> range >> no_of_pairs;\n    \n    x.resize(no_of_pairs + 1);\n    y.resize(no_of_pairs + 1);\n    for(int i = 1; i <= no_of_pairs; i++)\n    {\n        cin >> x[i] >> y[i];\n    }\n    \n    cout << (check_for_x(x[1]) || check_for_x(y[1]) ? \"YES\\n\" : \"NO\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 562/Rough Notes Link",
    "content": "https://1drv.ms/b/s!AoiWcyvzkQXVhzYKKX7Jt0H-xG4_\n"
  },
  {
    "path": "Contests/Div 2 566/Explanations/Filing Shapes Explanation.txt",
    "content": "A 2x3 block can be tiled in two ways. \n\n2 2     2 2\n1 2 and 2 1\n1 1     1 1\n\nIn whatever way we place the first block, the second block will have to be placed in the way above. \nThis shows that we will always be filing blocks of 2x3 at a time. If n is odd, then nx3 cannot be tiled. \n\nIf it is 3xn, then there are n/2 blocks of 2 if n is even. \n\nSo the number of tilings is 2^{n/2}\n\n----\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    long long no_of_fillings  = (n%2 == 1 ? 0 : (1LL << (n/2)) );\n    cout << no_of_fillings;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 566/Explanations/Plus From Picture Explanation.txt",
    "content": "Let us precompute d(i, j), u(i, j), l(i, j) and r(i, j) which holds the number of consecutive stars from (i, j)\nin the down, up, left and right directions respectively. \n\nNow, a square is the center of a plus if it has at least 2 consecutive stars in each direction.\n\nCase 1 - No of Plus Centers is not 1\n\nIf the gird has more than 1 plus center or 0 plus center, then the answer is NO. \n\n----\n\nCase 2 - Nof Plus Centers is exactly 1\n\nWe need to check every single star on the grid. Let us say a star lies on (X, Y) and the center is on (Cx, Cy)\n\n----\n\n  Case 2a - Cx = X or Cx = y\n\n  That means (X, Y) lies on the same line as (Cx, Cy). We just need to check if it lies on the same plus sign.\n  For this, there has to be an uninterrupted streak of stars in between (X, Y) and (Cx, Cy)\n\n  Then, we will need to first find the direction of (X, Y) from (Cx, Cy) [Left, Up, Right, Down].\n\n  Suppose (X, Y) is to the left of (Cx, Cy), then we must check if X + left(Cx) - 1 <= Cx\n\n---\n\n  Case 2b - Cx != X and Cx != Y\n\n  This means (X, Y) is not in the same line as (Cx, Cy) and the answer is no, regardless of the distance between them.\n  \n  \n  ---\n  \n  #include <cstdio>\n#include <cstring>\n\nconst int MAX_N = 505;\nconst char STAR = '*', EMPTY = '.';\nchar grid[MAX_N][MAX_N];\nint up[MAX_N][MAX_N], down[MAX_N][MAX_N], left[MAX_N][MAX_N], right[MAX_N][MAX_N];\n\nint main()\n{\n    int height, width;\n    scanf(\"%d %d\", &height, &width);\n\n    for(int i = 1; i <= height; i++)\n    {\n        scanf(\"%s\", grid[i] + 1);\n    }\n\n    memset(up, 0, sizeof(up));\n    memset(left, 0, sizeof(left));\n    for(int i = 1; i <= height; i++)\n    {\n        for(int j = 1; j <= width; j++)\n        {\n            up[i][j] = (grid[i][j] == STAR ? 1 + up[i - 1][j] : 0);\n            left[i][j] = (grid[i][j] == STAR ? 1 + left[i][j - 1] : 0);\n        }\n    }\n\n    memset(down, 0, sizeof(down));\n    memset(right, 0, sizeof(right));\n    for(int i = height; i >= 1; i--)\n    {\n        for(int j = width; j >= 1; j--)\n        {\n            down[i][j] = (grid[i][j] == STAR ? 1 + down[i + 1][j] : 0);\n            right[i][j] = (grid[i][j] == STAR ? 1 + right[i][j + 1] : 0);\n        }\n    }\n\n    int no_of_plus_centers = 0, center_i = 0, center_j = 0;\n    for(int i = 1; i <= height; i++)\n    {\n        for(int j = 1; j <= width; j++)\n        {\n            if(down[i][j] >= 2 && right[i][j] >= 2 && up[i][j] >= 2 && left[i][j] >= 2)\n            {\n                no_of_plus_centers++;\n\n                center_i = i, center_j = j;\n            }\n        }\n    }\n\n    int possible = true;\n\n    if(no_of_plus_centers != 1)\n    {\n        possible = false;\n    }\n\n    for(int i = 1; i <= height; i++)\n    {\n        for(int j = 1; j <= width; j++)\n        {\n            if(grid[i][j] == EMPTY) continue;\n\n            if(i != center_i && j != center_j)\n            {\n                possible = false;\n            }\n\n            if(i < center_i && i + up[center_i][center_j]  - 1 < center_i)\n            {\n                possible = false;\n            }\n            if(center_i < i && center_i + down[center_i][center_j] - 1 < i)\n            {\n                possible = false;\n            }\n            if(j < center_j && j + left[center_i][center_j] - 1 < center_j)\n            {\n                possible = false;\n            }\n            if(center_j < j && center_j + right[center_i][center_j] - 1 < j)\n            {\n                possible = false;\n            }\n        }\n    }\n\n    printf(\"%s\", (possible ? \"YES\\n\" : \"NO\\n\"));\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 566/Programs/Filing Shapes.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    long long no_of_fillings  = (n%2 == 1 ? 0 : (1LL << (n/2)) );\n    cout << no_of_fillings;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 566/Programs/Plus From Picture.cpp",
    "content": "#include <cstdio>\n#include <cstring>\n\nconst int MAX_N = 505;\nconst char STAR = '*', EMPTY = '.';\nchar grid[MAX_N][MAX_N];\nint up[MAX_N][MAX_N], down[MAX_N][MAX_N], left[MAX_N][MAX_N], right[MAX_N][MAX_N];\n\nint main()\n{\n    int height, width;\n    scanf(\"%d %d\", &height, &width);\n\n    for(int i = 1; i <= height; i++)\n    {\n        scanf(\"%s\", grid[i] + 1);\n    }\n\n    memset(up, 0, sizeof(up));\n    memset(left, 0, sizeof(left));\n    for(int i = 1; i <= height; i++)\n    {\n        for(int j = 1; j <= width; j++)\n        {\n            up[i][j] = (grid[i][j] == STAR ? 1 + up[i - 1][j] : 0);\n            left[i][j] = (grid[i][j] == STAR ? 1 + left[i][j - 1] : 0);\n        }\n    }\n\n    memset(down, 0, sizeof(down));\n    memset(right, 0, sizeof(right));\n    for(int i = height; i >= 1; i--)\n    {\n        for(int j = width; j >= 1; j--)\n        {\n            down[i][j] = (grid[i][j] == STAR ? 1 + down[i + 1][j] : 0);\n            right[i][j] = (grid[i][j] == STAR ? 1 + right[i][j + 1] : 0);\n        }\n    }\n\n    int no_of_plus_centers = 0, center_i = 0, center_j = 0;\n    for(int i = 1; i <= height; i++)\n    {\n        for(int j = 1; j <= width; j++)\n        {\n            if(down[i][j] >= 2 && right[i][j] >= 2 && up[i][j] >= 2 && left[i][j] >= 2)\n            {\n                no_of_plus_centers++;\n\n                center_i = i, center_j = j;\n            }\n        }\n    }\n\n    int possible = true;\n\n    if(no_of_plus_centers != 1)\n    {\n        possible = false;\n    }\n\n    for(int i = 1; i <= height; i++)\n    {\n        for(int j = 1; j <= width; j++)\n        {\n            if(grid[i][j] == EMPTY) continue;\n\n            if(i != center_i && j != center_j)\n            {\n                possible = false;\n            }\n\n            if(i < center_i && i + up[center_i][center_j]  - 1 < center_i)\n            {\n                possible = false;\n            }\n            if(center_i < i && center_i + down[center_i][center_j] - 1 < i)\n            {\n                possible = false;\n            }\n            if(j < center_j && j + left[center_i][center_j] - 1 < center_j)\n            {\n                possible = false;\n            }\n            if(center_j < j && center_j + right[center_i][center_j] - 1 < j)\n            {\n                possible = false;\n            }\n        }\n    }\n\n    printf(\"%s\", (possible ? \"YES\\n\" : \"NO\\n\"));\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 566/Rough Notes Link",
    "content": "https://1drv.ms/b/s!AoiWcyvzkQXVh1hzrJWSS_3VPtDD?e=ck92iL\n"
  },
  {
    "path": "Contests/Div 2 585/Explanations/Swap Letters Explanation.txt",
    "content": "Now, let us get the impossibility criteria clear. When is it not possible ? \r\n\r\nIf the strings S and T are equal, it means whenever there is an A, it occurs twice and whenever there is a B, it occurs twice.\r\n\r\nIf the number of As or number of Bs is odd, then there is no solution. \r\n\r\n-----\r\n\r\nNow let us suppose that both the As and Bs are even. \r\n\r\nWe will ignore all the positions (A, A) and (B, B) since they are already equal. \r\n\r\nLet us look at (A, B)\r\n\r\nIf we have two (A, B) and (A, B). One operation can make both pairs equal. \r\n\r\nIf we have two (B, A) and (B, A). One operation can also make both pairs equal. \r\n\r\n----\r\n\r\nCase 1 - The number of pairs (A, B) and (B, A) is even. \r\n\r\nThen we will pair up pairs of (A, B) and pairs of (B, A) and get our solution. \r\n\r\n----\r\n\r\nCase 2 - The number of pairs (A, B) and (B, A) is both odd. \r\n\r\nWe will match as above until we have only one pair of (A, B) and (B, A) left. \r\n\r\nWhen we have only one left, we will do one swap on the same position on (B, A). Now, it becomes (A, B)\r\n\r\nNow we have two (A, B) pairs and we will do one operation to make the pairs equal !\r\n\r\n---\r\n\r\nCase 3 - One of the number of pairs (A, B) and (B,A) is odd. \r\n\r\nThis will not happen since it means that A and B occur an odd number of times. We have already checked this condition when we were doing the impossibility check\r\n\r\n----\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S, T;\r\n    cin >> length >> S >> T;\r\n\r\n    const int NO_OF_ALPHABETS = 2, A = 0, B = 1;\r\n    vector <int> frequency(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        frequency[S[i] - 'a']++;\r\n    }\r\n\r\n    for(int i = 0; i < T.size(); i++)\r\n    {\r\n        frequency[T[i] - 'a']++;\r\n    }\r\n\r\n    if(frequency[A]%2 == 1 || frequency[B]%2 == 1)\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    vector <int> ABs;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == 'a' && T[i] == 'b')\r\n        {\r\n            ABs.push_back(i + 1);\r\n        }\r\n    }\r\n\r\n    vector <int> BAs;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == 'b' && T[i] == 'a')\r\n        {\r\n            BAs.push_back(i + 1);\r\n        }\r\n    }\r\n\r\n    int no_of_operations = 0;\r\n\r\n    if(ABs.size()%2 == 1 && BAs.size()%2 == 1)\r\n    {\r\n        no_of_operations = ABs.size()/2 + BAs.size()/2 + 2;\r\n    }\r\n    else if(ABs.size()%2 == 0 && BAs.size()%2 == 0)\r\n    {\r\n        no_of_operations = ABs.size()/2 + BAs.size()/2;\r\n    }\r\n    else //Redundant but just to be safe\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    cout << no_of_operations << \"\\n\";\r\n    for(int i = 0; i + 1 < ABs.size(); i += 2)\r\n    {\r\n        cout << ABs[i] << \" \" << ABs[i + 1] << \"\\n\";\r\n    }\r\n\r\n    for(int i = 0; i + 1 < BAs.size(); i += 2)\r\n    {\r\n        cout << BAs[i] << \" \" << BAs[i + 1] << \"\\n\";\r\n    }\r\n\r\n    if(ABs.size()%2 == 1 && BAs.size()%2 == 1)\r\n    {\r\n        int last_AB = ABs.size() - 1, last_BA = BAs.size() - 1;\r\n\r\n        cout << ABs[last_AB] << \" \" << ABs[last_AB] << \"\\n\";\r\n        cout << ABs[last_AB] << \" \" << BAs[last_BA] << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 585/Explanations/The Number of Products Explanation.txt",
    "content": "Let us use an elegant idea for this. \r\n\r\nNotice that the actual values of the elements do not matter - only the signs. \r\n\r\nLet us replace the positive numbers by 0 and the negative numbers by 1. \r\n\r\nThen let us maintain an array Sum, where Sum[i] holds the sum of the first i elements (mod 2). \r\n\r\n-----\r\n\r\nIf Sum[L - 1] = Sum[R], then it means that (Sum[R] - Sum[L - 1] = 0), which means that negative numbers occur an even number of times in the range. \r\n\r\nEvery time in the sum vector, there are two elements which have the same value, they correspond to (L - 1, R) which gives us a segment(L, R) which has a positive product.\r\n\r\n------\r\n\r\nWe want to count the ranges of the first x elements too so we will make Sum[0] = 0, even though A[0] does not exist. \r\n\r\nNow the number of segments that have positive products is simply\r\n\r\nC(zeros, 2) + C(ones, 2) - The number of ways to choose 2 zeroes and the number of ways to choose 2 ones in the sum vector. \r\n\r\n----\r\n\r\nThe number of segments that give negative products is simply the total number of segments - positive product segments\r\n\r\nThe total number of segments is C(N, 2) + N - Because we want to include singleton segments as well. \r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> sign(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int x;\r\n        cin >> x;\r\n\r\n        sign[i] = (x > 0 ? 0 : 1);\r\n    }\r\n\r\n    vector <int> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i] = (sum_till[i - 1] + sign[i])%2;\r\n    }\r\n\r\n    long long no_of_zeroes = 0, no_of_ones = 0;\r\n    for(int i = 0; i <= no_of_elements; i++)\r\n    {\r\n        if(sum_till[i] == 0)\r\n        {\r\n            no_of_zeroes++;\r\n        }\r\n        else\r\n        {\r\n            no_of_ones++;\r\n        }\r\n    }\r\n\r\n    long long no_of_positive_products = choose_2(no_of_zeroes) + choose_2(no_of_ones);\r\n    long long no_of_negative_prodcuts = choose_2(no_of_elements) + no_of_elements - no_of_positive_products;\r\n\r\n    cout << no_of_negative_prodcuts << \" \" << no_of_positive_products << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 585/Explanations/Yellow Cards Explanation",
    "content": "How do we minimise the number of eliminations ? \n\nWe will try to use out as many cards as possible without eliminating a single player. This means we will first give every player\n1 card less than the number of cards he is allowed. This is\n\na1(k1 - 1) + a2(k2 - 1)\n\nIf the number of yellow cards is lesser than this, we will not have a single elimination. \n\nIf it is more than this, we will have one elimination for every card that we cross from this threshold. \n\nOf course, the number cannot be greater than (k1 + k2) as that is the total number of people. \n\n-------\n\nint total_people = team_1 + team_2;\nint max_cards_without_elimination = team_1*(yellow_1 - 1) + team_2*(yellow_2 - 1);\n\nint minimum_eliminations, maximum_eliminations;\n\nif(max_cards_without_elimination >= yellow)\n{\n    minimum_eliminations = 0;\n}\nelse\n{\n    minimum_eliminations = min(total_people, (yellow - max_cards_without_elimination));\n}\n\n------\n\nNow, let us try to maximise the number of eliminations. \n\nFirst, let us assume without loss of generality that k1 < k2. (If not, we just swap (k1, k2) and (a1, a2))\n\n----\n\nWe will give as many yellow cards as possible to the players of team 1. \n\nThis is K/k1. Of course, this number cannot be greater than a1. \n\nK = K - K/k1\n\nThen, we will give as many yellow cards as possible to the second team. \nThis number is also K/k2 and cannot be greater than a2. \n\n-----\n\nmaximum_eliminations = min(team_1, yellow/yellow_1);\n\nyellow -= maximum_eliminations*yellow_1;\n\nmaximum_eliminations += min(team_2, yellow/yellow_2);\n"
  },
  {
    "path": "Contests/Div 2 585/Programs/Swap Letters.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S, T;\r\n    cin >> length >> S >> T;\r\n\r\n    const int NO_OF_ALPHABETS = 2, A = 0, B = 1;\r\n    vector <int> frequency(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        frequency[S[i] - 'a']++;\r\n    }\r\n\r\n    for(int i = 0; i < T.size(); i++)\r\n    {\r\n        frequency[T[i] - 'a']++;\r\n    }\r\n\r\n    if(frequency[A]%2 == 1 || frequency[B]%2 == 1)\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    vector <int> ABs;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == 'a' && T[i] == 'b')\r\n        {\r\n            ABs.push_back(i + 1);\r\n        }\r\n    }\r\n\r\n    vector <int> BAs;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == 'b' && T[i] == 'a')\r\n        {\r\n            BAs.push_back(i + 1);\r\n        }\r\n    }\r\n\r\n    int no_of_operations = 0;\r\n\r\n    if(ABs.size()%2 == 1 && BAs.size()%2 == 1)\r\n    {\r\n        no_of_operations = ABs.size()/2 + BAs.size()/2 + 2;\r\n    }\r\n    else if(ABs.size()%2 == 0 && BAs.size()%2 == 0)\r\n    {\r\n        no_of_operations = ABs.size()/2 + BAs.size()/2;\r\n    }\r\n    else //Redundant but just to be safe\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    cout << no_of_operations << \"\\n\";\r\n    for(int i = 0; i + 1 < ABs.size(); i += 2)\r\n    {\r\n        cout << ABs[i] << \" \" << ABs[i + 1] << \"\\n\";\r\n    }\r\n\r\n    for(int i = 0; i + 1 < BAs.size(); i += 2)\r\n    {\r\n        cout << BAs[i] << \" \" << BAs[i + 1] << \"\\n\";\r\n    }\r\n\r\n    if(ABs.size()%2 == 1 && BAs.size()%2 == 1)\r\n    {\r\n        int last_AB = ABs.size() - 1, last_BA = BAs.size() - 1;\r\n\r\n        cout << ABs[last_AB] << \" \" << ABs[last_AB] << \"\\n\";\r\n        cout << ABs[last_AB] << \" \" << BAs[last_BA] << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 585/Programs/The Number of Products.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long choose_2(long long n)\r\n{\r\n    return (n*(n - 1))/2;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> sign(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int x;\r\n        cin >> x;\r\n\r\n        sign[i] = (x > 0 ? 0 : 1);\r\n    }\r\n\r\n    vector <int> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i] = (sum_till[i - 1] + sign[i])%2;\r\n    }\r\n\r\n    long long no_of_zeroes = 0, no_of_ones = 0;\r\n    for(int i = 0; i <= no_of_elements; i++)\r\n    {\r\n        if(sum_till[i] == 0)\r\n        {\r\n            no_of_zeroes++;\r\n        }\r\n        else\r\n        {\r\n            no_of_ones++;\r\n        }\r\n    }\r\n\r\n    long long no_of_positive_products = choose_2(no_of_zeroes) + choose_2(no_of_ones);\r\n    long long no_of_negative_prodcuts = choose_2(no_of_elements) + no_of_elements - no_of_positive_products;\r\n\r\n    cout << no_of_negative_prodcuts << \" \" << no_of_positive_products << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 585/Programs/Yellow Cards.cpp",
    "content": "#include <iostream>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int team_1, yellow_1, team_2, yellow_2, yellow;\n    cin >> team_1 >> team_2 >> yellow_1 >> yellow_2 >> yellow;\n\n    int total_people = team_1 + team_2;\n    int max_cards_without_elimination = team_1*(yellow_1 - 1) + team_2*(yellow_2 - 1);\n\n    int minimum_eliminations, maximum_eliminations;\n\n    if(max_cards_without_elimination >= yellow)\n    {\n        minimum_eliminations = 0;\n    }\n    else\n    {\n        minimum_eliminations = min(total_people, (yellow - max_cards_without_elimination));\n    }\n\n\n    if(yellow_2 < yellow_1)\n    {\n        swap(yellow_1, yellow_2);\n\n        swap(team_1, team_2);\n    }\n\n    maximum_eliminations = min(team_1, yellow/yellow_1);\n\n    yellow -= maximum_eliminations*yellow_1;\n\n    maximum_eliminations += min(team_2, yellow/yellow_2);\n\n    cout << minimum_eliminations << \" \" << maximum_eliminations << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 585/Rough Notes",
    "content": "https://1drv.ms/b/s!AoiWcyvzkQXViGyGD7z-k0Yo5Rij?e=UMzxCH\n"
  },
  {
    "path": "Contests/Div 2 588/Explanations/Anadi and Domino Explanation.txt",
    "content": "1. I didn't notice that there are only 7 vertices. \r\n\r\n2. If there are < 7 vertices, then it is always possible. \r\n\r\n3. If there are 7 vertices, then 2 vertices will have the same number. We will iterate over all pairs and calculate the number of lost edges in each case. \r\n\r\n\r\nIt is better to use an adjacency matrix in this question rather than an adjacency vector. \r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    vector <vector <int> > has_edge(no_of_vertices + 1, vector <int> (no_of_vertices + 1, false));\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        has_edge[u][v] = true;\r\n        has_edge[v][u] = true;\r\n    }\r\n\r\n    int answer = 0;\r\n    if(no_of_vertices < 7)\r\n    {\r\n        answer = no_of_edges;\r\n    }\r\n    else if(no_of_vertices == 7)\r\n    {\r\n        for(int i = 1; i <= no_of_vertices; i++)\r\n        {\r\n            for(int j = i + 1; j <= no_of_vertices; j++)\r\n            {\r\n                int lost_edges = 0;\r\n\r\n                for(int k = 1; k <= no_of_vertices; k++)\r\n                {\r\n                    if(has_edge[i][k] && has_edge[j][k])\r\n                    {\r\n                        lost_edges++;\r\n                    }\r\n                }\r\n\r\n                answer = max(answer, no_of_edges - lost_edges);\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 588/Explanations/Ania and Minimizing Explanation.txt",
    "content": "If it is a single digit number, then make it 0. \r\n\r\nIn all other cases, leading 0s are not allowed. Make the first digit 1.\r\n\r\nMake as many 0s as possible starting from the leftmost position. \r\n\r\n----\r\n\r\nint main()\r\n{\r\n    int length, no_of_steps;\r\n    cin >> length >> no_of_steps;\r\n\r\n    string N;\r\n    cin >> N;\r\n\r\n    for(int i = 0; i < length && no_of_steps > 0; i++)\r\n    {\r\n        if(i == 0)\r\n        {\r\n            if(length == 1)\r\n            {\r\n                if(N[i] != '0')\r\n                {\r\n                    N[i] = '0';\r\n                    no_of_steps--;\r\n                }\r\n\r\n                continue;\r\n            }\r\n\r\n            if(N[i] != '1')\r\n            {\r\n                N[i] = '1';\r\n                no_of_steps--;\r\n            }\r\n\r\n            continue;\r\n        }\r\n\r\n        if(N[i] == '0')\r\n        {\r\n            continue;\r\n        }\r\n\r\n        N[i] = '0';\r\n        no_of_steps--;\r\n    }\r\n\r\n    cout << N << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 588/Explanations/Dawid and Bags of Candies Explanation.txt",
    "content": "Just check all possibilities. \r\n\r\nWe could also check if there is any sequence which sums upto S/2. \r\n\r\n----\r\n\r\nint main()\r\n{\r\n    const int NO_OF_CANDIES = 4;\r\n    vector <int> A(NO_OF_CANDIES + 1, 0);\r\n    for(int i = 1; i <= NO_OF_CANDIES; i++)\r\n        cin >> A[i];\r\n\r\n    cout << ( ( (A[1] + A[2] == A[3] + A[4]) || (A[1] + A[3] == A[2] + A[4]) || (A[1] + A[4] == A[2] + A[3])\r\n               || (A[1] == A[2] + A[3] + A[4]) || (A[2] == A[1] + A[3] + A[4]) || (A[3] == A[1] + A[2] + A[4]) || (A[4] == A[1] + A[2] + A[3]) ) ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 588/Explanations/Kamil and Making a Stream Explanation.txt",
    "content": "Now, let us notice one thing. \r\n\r\nGCD[1, p] is the gcd of [1, p]\r\n\r\nGCD[1, v] is the gcd of [1, v] where p is the parent of v. \r\n\r\nGCD[1, v] = gcd(GCD[1, P], A[v])\r\n\r\nThis means that the GCD of the child must divide the GCD of the parent. \r\n\r\nAlthough the value of A[i] is huge, this means that the distinct values of GCD in each vertex will not be many. \r\n\r\nThere can be at most log(10^12) ~ 40 different values of GCD at each node. \r\n\r\n----\r\n\r\n1. For each node, we will keep track of the frequency of all it's GCDs\r\n\r\n2. We will get the answer by multiplying the value with the frequency. \r\n\r\n3. Then, we will traverse to the child node. \r\n\r\n-----\r\n\r\nvoid dfs(int v, map <long long, int> frequency)\r\n{\r\n    visited[v] = true;\r\n\r\n    map <long long, int> new_frequency;\r\n\r\n    for(map <long long, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        new_frequency[gcd(value[v], it->first)] += it->second;\r\n    }\r\n\r\n    new_frequency[value[v]]++;\r\n\r\n    for(map <long long, int> :: iterator it = new_frequency.begin(); it != new_frequency.end(); it++)\r\n    {\r\n        answer += (it->first)*(it->second);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    for(int i = 0; i < tree[v].size(); i++)\r\n    {\r\n        int child = tree[v][i];\r\n\r\n        if(visited[child])\r\n        {\r\n           continue;\r\n        }\r\n\r\n        dfs(child, new_frequency);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> value[i];\r\n    }\r\n\r\n    int no_of_edges = no_of_vertices - 1;\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        tree[u].push_back(v);\r\n        tree[v].push_back(u);\r\n    }\r\n\r\n    map <long long, int> frequency;\r\n    dfs(1, frequency);\r\n\r\n    cout << answer << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 588/Explanations/Konrad and Company Evaluation Explanation.txt",
    "content": "In any counting question, it is always a good idea to iterate over the middle\nto count triplets.\n\nWe want to count the number of vertices (u, v, w) that are connected.\n\nLet us iterate over the middle vertex v and count the number of incoming and outgoing edges.\n\nThe total count is the sum of (indegree[v]*outdegree[v]) over all v.\n\n-----\n\nWe will draw a graph where u->v, if u < v\n\nHow do we process updates when v becomes the largest vertex in the graph ?\nAlthough the question says salary increases by (n + i), ignore it.\n\nWhen v becomes the largest element in the graph, we need to reverse the direction of\nall edges going out of v and make them come into v.\n\nWe have to correspondingly update the indegree and outdegree of v and all it's neighbours.\n\n-----\n\nHow do we do this in time ?\n\nAt first, I maintained an adjacency set and for each neighbour of v,\nI erased it from v's adjacency set and inserted v into the adjacency set of it's neighbour.\n\nHowever, this adds an additional log factor.\n\nIt is more efficient to simply use Adjacency Lists !\nWe will first insert v into the adjacency lists of all it's neighbours.\nInstead of erasing the elements of v one by one, we will just clear v's adjacency list\nall at once when we are done.\nv will anyway be empty and become a sink after we are done, so we can do this !\n\nBefore updating the edge, indegree and outdegree of a vertex,\nwe will remove it's contribution from the sum and then add it's new contribution to the sum.\nIt is easier to do this than to try to count the amount it's contribution has changed.\n\n-----\n\nlong long contribution(int v)\n{\n    return indegree[v]*outdegree[v];\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        if(u > v)\n        {\n            swap(u, v);\n        }\n\n        graph[u].push_back(v);\n\n        //Reverse\n        indegree[v]++;\n        outdegree[u]++;\n    }\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    long long no_of_paths = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        no_of_paths += contribution(i);\n    }\n\n    cout << no_of_paths << \"\\n\";\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int v;\n        cin >> v;\n\n        no_of_paths -= contribution(v);\n\n        for(auto child_v : graph[v])\n        {   //cout << \"u = \" << u << \"\\n\";\n            no_of_paths -= contribution(child_v); //cout << \"Old Contribution = \" << contribution(u) << \"\\n\";\n\n            indegree[child_v]--;\n            outdegree[v]--;\n\n            graph[child_v].push_back(v);\n            indegree[v]++;\n            outdegree[child_v]++;\n\n            no_of_paths += contribution(child_v); //cout << \"New Contribution = \" << contribution(u) << \"\\n\";\n        }\n\n        graph[v].clear();\n\n        no_of_paths += contribution(v);\n\n        cout << no_of_paths << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 588/Explanations/Marcin and Training Camp Explanation.txt",
    "content": "Fact - Every mask chosen M, either has frequency(M) > 1 or is a submask of another mask M' such that frequency(M') > 1\n\n---\n\nProof - \n\nLet us say we have chosen bitmask M1 in our set. \n\nEither the frequency[M1] > 1 or there is another mask M2 such that M1 is a submask of M2. \n\nThen either frequency[M2] > 1 or there is another mask M3 such that M2 is a submask of M3.\n\nAnd so on. \n\nThe number of masks chosen is finite so this cannot go on indefinitely. \n\nWe will finally end up at mask Mk, such that frequency(Mk) > 1\n\nM1 -> M2 -> .... -> Mk\n\nAll the masks before Mk are submasks of Mk\n\n----\n\nHow do we use this idea ? \n\nFirst, we will add all masks into our set, if the frequency(mask) > 1\n\n---\n\n    vector <long long> distinct_masks;\n    map <long long, int> selected;\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        if(mask_frequency[mask[i]] > 1 && !selected[mask[i]])\n        {\n            distinct_masks.push_back(mask[i]);\n\n            selected[mask[i]] = true;\n        }\n    }\n\n----\n\nCall the masks who's frequency > 1 'Master' masks.\n\nNow, we will go over the remaining masks. If there is any mask such that it is a submask of one of the 'Master' masks, then we will include it in our set as well. \n\nIf there is some mask M1, such that it is not a submask of any of the 'Master' Masks, then it can't be included in our set. \nSuppose we choose M1, we have to choose M2 such that M1 is a submask of M2, and then M3 and so on. \nWe will eventually end up at a mask Mk, such that there is no mask M(k + 1) such that Mk is a submask of M(k + 1). \nAlso, M(k) has frequency = 1. Since, M1 is not a submask of any of the 'Master' masks.\n\nSo, we cannot choose the entire sequence.\n\nThe only masks we can choose are the masks which are submasks of the 'Master' Masks\n\n-----\n\nfor(int i = 1; i <= no_of_students; i++)\n    {\n        if(selected[mask[i]])\n        {\n            continue;\n        }\n\n        for(int j = 0; j < distinct_masks.size(); j++)\n        {\n            if(is_submask(distinct_masks[j], mask[i]))\n            {\n                selected[mask[i]] = true;\n\n                break;\n            }\n        }\n    }\n\n----\n\nThen, we just add up the skills of all the players\n\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        if(selected[mask[i]])\n        {\n            continue;\n        }\n\n        for(int j = 0; j < distinct_masks.size(); j++)\n        {\n            if(is_submask(distinct_masks[j], mask[i]))\n            {\n                selected[mask[i]] = true;\n\n                break;\n            }\n        }\n    }\n"
  },
  {
    "path": "Contests/Div 2 588/Programs/Anadi and Domino.cpp",
    "content": "\r\n#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    vector <vector <int> > has_edge(no_of_vertices + 1, vector <int> (no_of_vertices + 1, false));\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        has_edge[u][v] = true;\r\n        has_edge[v][u] = true;\r\n    }\r\n\r\n    int answer = 0;\r\n    if(no_of_vertices < 7)\r\n    {\r\n        answer = no_of_edges;\r\n    }\r\n    else if(no_of_vertices == 7)\r\n    {\r\n        for(int i = 1; i <= no_of_vertices; i++)\r\n        {\r\n            for(int j = i + 1; j <= no_of_vertices; j++)\r\n            {\r\n                int lost_edges = 0;\r\n\r\n                for(int k = 1; k <= no_of_vertices; k++)\r\n                {\r\n                    if(has_edge[i][k] && has_edge[j][k])\r\n                    {\r\n                        lost_edges++;\r\n                    }\r\n                }\r\n\r\n                answer = max(answer, no_of_edges - lost_edges);\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 588/Programs/Ania and Minimizing.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, no_of_steps;\r\n    cin >> length >> no_of_steps;\r\n\r\n    string N;\r\n    cin >> N;\r\n\r\n    for(int i = 0; i < length && no_of_steps > 0; i++)\r\n    {\r\n        if(i == 0)\r\n        {\r\n            if(length == 1)\r\n            {\r\n                if(N[i] != '0')\r\n                {\r\n                    N[i] = '0';\r\n                    no_of_steps--;\r\n                }\r\n\r\n                continue;\r\n            }\r\n\r\n            if(N[i] != '1')\r\n            {\r\n                N[i] = '1';\r\n                no_of_steps--;\r\n            }\r\n\r\n            continue;\r\n        }\r\n\r\n        if(N[i] == '0')\r\n        {\r\n            continue;\r\n        }\r\n\r\n        N[i] = '0';\r\n        no_of_steps--;\r\n    }\r\n\r\n    cout << N << \"\\n\";\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 588/Programs/Dawid and Bags of Candies.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    const int NO_OF_CANDIES = 4;\r\n    vector <int> A(NO_OF_CANDIES + 1, 0);\r\n    for(int i = 1; i <= NO_OF_CANDIES; i++)\r\n        cin >> A[i];\r\n\r\n    cout << ( ( (A[1] + A[2] == A[3] + A[4]) || (A[1] + A[3] == A[2] + A[4]) || (A[1] + A[4] == A[2] + A[3])\r\n               || (A[1] == A[2] + A[3] + A[4]) || (A[2] == A[1] + A[3] + A[4]) || (A[3] == A[1] + A[2] + A[4]) || (A[4] == A[1] + A[2] + A[3]) ) ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 588/Programs/Kamil and Making a Stream.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\nconst int MAX_N = 1e5 + 5, MOD = 1e9 + 7;\r\n\r\nlong long answer;\r\nvector <int> tree[MAX_N];\r\nvector <int> visited(MAX_N, 0);\r\nvector <long long> value(MAX_N, 0);\r\n\r\nlong long gcd(long long x, long long y)\r\n{\r\n    if(min(x, y) == 0)\r\n        return max(x, y);\r\n    else\r\n        return gcd(max(x, y)%min(x, y), min(x,y));\r\n}\r\n\r\nvoid dfs(int v, map <long long, int> frequency)\r\n{\r\n    visited[v] = true;\r\n\r\n    map <long long, int> new_frequency;\r\n\r\n    for(map <long long, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        new_frequency[gcd(value[v], it->first)] += it->second;\r\n    }\r\n\r\n    new_frequency[value[v]]++;\r\n\r\n    for(map <long long, int> :: iterator it = new_frequency.begin(); it != new_frequency.end(); it++)\r\n    {\r\n        answer += (it->first)*(it->second);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    for(int i = 0; i < tree[v].size(); i++)\r\n    {\r\n        int child = tree[v][i];\r\n\r\n        if(visited[child])\r\n        {\r\n           continue;\r\n        }\r\n\r\n        dfs(child, new_frequency);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    cin >> no_of_vertices;\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        cin >> value[i];\r\n    }\r\n\r\n    int no_of_edges = no_of_vertices - 1;\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        tree[u].push_back(v);\r\n        tree[v].push_back(u);\r\n    }\r\n\r\n    map <long long, int> frequency;\r\n    dfs(1, frequency);\r\n\r\n    cout << answer << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 588/Programs/Konrad and Company Evaluation.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nconst int MAX_N = 1e5 + 5;\nvector <long long> indegree(MAX_N, 0), outdegree(MAX_N, 0);\nvector <int> graph[MAX_N], transpose_graph[MAX_N];\n\nlong long contribution(int v)\n{\n    return indegree[v]*outdegree[v];\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n    \n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        if(u > v)\n        {\n            swap(u, v);\n        }\n        \n        graph[u].push_back(v);\n        \n        //Reverse\n        indegree[v]++;\n        outdegree[u]++;\n    }\n    \n    int no_of_queries;\n    cin >> no_of_queries;\n    \n    long long no_of_paths = 0;\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        no_of_paths += contribution(i);\n    }\n    \n    cout << no_of_paths << \"\\n\";\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int v;\n        cin >> v;\n        \n        no_of_paths -= contribution(v);\n        \n        for(auto child_v : graph[v])\n        {   //cout << \"u = \" << u << \"\\n\";\n            no_of_paths -= contribution(child_v); //cout << \"Old Contribution = \" << contribution(u) << \"\\n\";\n            \n            indegree[child_v]--;\n            outdegree[v]--;\n            \n            graph[child_v].push_back(v);\n            indegree[v]++;\n            outdegree[child_v]++;\n            \n            no_of_paths += contribution(child_v); //cout << \"New Contribution = \" << contribution(u) << \"\\n\";\n        }\n        \n        graph[v].clear();\n        \n        no_of_paths += contribution(v);\n        \n        cout << no_of_paths << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 588/Programs/Marcin and Training Camp.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <cstdlib>\n#include <algorithm>\n#include <ctime>\n\nusing namespace std;\n\nint is_submask(long long mask, long long submask)\n{\n    return ((mask&submask) == submask);\n}\n\nint main()\n{\n    int no_of_students;\n    cin >> no_of_students;\n\n    map <long long, int> mask_frequency;\n    vector <long long> mask(no_of_students + 1);\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cin >> mask[i];\n\n        mask_frequency[mask[i]]++;\n    }\n\n    vector <long long> skill_level(no_of_students + 1, 0);\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        cin >> skill_level[i];\n    }\n\n    vector <long long> distinct_masks;\n    map <long long, int> selected;\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        if(mask_frequency[mask[i]] > 1 && !selected[mask[i]])\n        {\n            distinct_masks.push_back(mask[i]);\n\n            selected[mask[i]] = true;\n        }\n    }\n\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        if(selected[mask[i]])\n        {\n            continue;\n        }\n\n        for(int j = 0; j < distinct_masks.size(); j++)\n        {\n            if(is_submask(distinct_masks[j], mask[i]))\n            {\n                selected[mask[i]] = true;\n\n                break;\n            }\n        }\n    }\n\n    long long best_max_skill = 0;\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        if(selected[mask[i]])\n        {\n            best_max_skill += skill_level[i];\n        }\n    }\n\n    cout << best_max_skill << \"\\n\";\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Contests/Div 2 589/Explanations/Complete Tripartite Explanation.txt",
    "content": "Two vertices in the same group do not have any edge.\n\nLet us pick a vertex and put all vertices that don't share an edge with it in 1 group\n\nWe will try to make 3 groups like this\n\n1. We have to ensure that there are exactly 3 groups, no more and no less\n2. We have to ensure that for each vertex v, all it's neighbours are in different groups\n3. For each vertex v, the number of it's neighbours must be equal to the size of the other 2 groups\nThis ensures that v has an edge with every vertex in the other two groups\n\n------\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n\n    set <int> graph[no_of_vertices + 1];\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        graph[u].insert(v);\n        graph[v].insert(u);\n    }\n\n    const int NO_OF_GROUPS = 3;\n    vector <int> group(no_of_vertices + 1, 0);\n    vector <int> group_sizes(NO_OF_GROUPS + 1, 0);\n    for(int g = 1; g <= NO_OF_GROUPS; g++)\n    {\n        int first = 0;\n\n        for(first = 1; first <= no_of_vertices && group[first] != 0; first++);\n\n        if(first == no_of_vertices + 1)\n        {\n            cout << \"-1\\n\";\n\n            return 0;\n        }\n\n        group[first] = g;\n        for(int second = 1; second <= no_of_vertices; second++)\n        {\n            if(graph[first].find(second) == graph[first].end())\n            {\n                group[second] = g;\n                group_sizes[g]++;\n            }\n        }\n    }\n\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        if(group[v] == 0)\n        {\n            cout << \"-1\\n\";\n\n            return 0;\n        }\n    }\n\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        for(auto it = graph[v].begin(); it != graph[v].end(); it++)\n        {\n            int u = *it;\n\n            if(group[u] == group[v])\n            {\n                cout << \"-1\\n\";\n\n                return 0;\n            }\n        }\n    }\n\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        int other_groups = group_sizes[1] + group_sizes[2] + group_sizes[3]\n                            - group_sizes[group[v]];\n\n        if(graph[v].size() != other_groups)\n        {\n            cout << \"-1\\n\";\n\n            return 0;\n        }\n    }\n\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        cout << group[v] << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 589/Explanations/Distinct Digits Explanation.txt",
    "content": "We can iterate over every integer in between L and R and check if each integer has distinct digits. \r\n\r\nWe will never have to go too far to find an integer with all distinct digits or find that it doesn't exist.\r\n\r\nWe can check if N is made up of all distinct digits by capturing the frequency of all it's digits and checking if each of their frequencies is <= 1\r\n\r\n\r\n-----\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint distinct_digits(int n)\r\n{\r\n   vector <int> frequency(10, 0);\r\n\r\n   while(n > 0)\r\n   {\r\n       if(frequency[n%10] > 0)\r\n            return false;\r\n\r\n       frequency[n%10]++;\r\n\r\n       n /= 10;\r\n   }\r\n\r\n   return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int left, right;\r\n    cin >> left >> right;\r\n\r\n    for(int i = left; i <= right; i++)\r\n    {\r\n        if(distinct_digits(i))\r\n        {\r\n            cout << i << endl;\r\n\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    cout << \"-1\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 589/Explanations/Filing the Grid Explanation.txt",
    "content": "How do we check if a tiling is not possible ? \n\nSuppose R[i] = x and it means that the first x-columns of the i-th row must be black and the (x + 1)-th column must be white. \n\nWe will check if C[x + 1] >= i, \nIf this is the case, then in the (x + 1)-th column, we have to make more than i-rows black. \n\nThis causes a contradiction. \n\nWe will check this condition for every row and every column\n\n\n-------\n\n\nfor(int i = 1; i <= rows; i++)\n    {\n        int first_empty_column = blocked_cells_row[i] + 1;\n\n        if(blocked_cells_column[first_empty_column] >= i)\n        {\n            cout << \"0\\n\";\n\n            return 0;\n        }\n    }\n\n    for(int j = 1; j <= columns; j++)\n    {\n        int first_empty_row = blocked_cells_column[j] + 1;\n\n        if(blocked_cells_row[first_empty_row] >= j)\n        {\n            cout << \"0\\n\";\n\n            return 0;\n        }\n    }\n\n-----\n\nA question that might arise here is that if R[i] = x, we are checking if the (x + 1)-th cell is allowed to be white (as it should). \n\nBut what if we are forced to make one of the first x columns of the i-th row white ? \n\nWell, if the y-th column of the i-th row must be white, then it means that \n\nC[y] = i - 1, \n\nWe will encounter this case, when we are checking the columns. \n\n------\n\n1. For every row R[i] = X, we will check if we can colour the cell(i, X + 1), white. \n  1a. This is possible if C[X + 1] < i\n  \n2. For every column C[j] = Y, we will check if we can colour the cell(Y + 1, j) white\n  2a. This is possible if R[Y + 1] < j\n\n-----\n\nA cell(i, j) is blocked if we are forced to colour it either black or white and we do not have a choice in colouring it. \n\nIf R[j] = x, then the first X rows of column j must be black and the (X + 1)-th row of column j must be white. These (X + 1) cells are forced. \n\nIf C[i] = y, then the first Y rows of column i must be black and the (Y + 1)-th column of row i must be white. These (Y + 1) cells are forced.\n\n-----\n\nThen, we will visit each cell and check if it is 'free' or 'forced'. \n\nCell (i, j) is forced if \n\nR[j] + 1 >= i \n\n or if \n\nC[i] + 1 >= j\n\n-----\n\nLL free_cells = 0;\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(i <= blocked_cells_column[j] + 1 || j <= blocked_cells_row[i] + 1)\n            {\n                continue;\n            }\n            else\n            {\n                free_cells++;\n            }\n        }\n    }\n\n-----\n\nSuppose, there are F free cells. The answer is 2^F because each of the F free cells can be either black or white.\n\nWe must calculate 2^F using binary exponentiation.\n\n"
  },
  {
    "path": "Contests/Div 2 589/Explanations/Primes and Multiplication Explanation.txt",
    "content": "Whenever we are asked to calculate a long sum or product, we must try to group the summands and try to calculate the contribution of each prime factor \r\n\r\n----\r\n\r\nWhat is the contribution of prime factor P ? \r\n\r\nWe will encounter P as many times as [N/P]\r\n\r\nWe will encounter P^2 as many times as [N/P^2]\r\n\r\nWe will encounter P^3 as many times as [N/P^3] \r\n\r\nand so on\r\n\r\nThe exponent of P is [N/P] + [N/P^2] + ... \r\n\r\nWe basically want to find the number of 0s in n! in base p. \r\nThis is a famous problem.\r\n\r\n----\r\n\r\nWe can factor the number in O(root(n)) time into it's prime factors. \r\n\r\nvoid factorise(LL n, vector <LL> &P)\r\n{\r\n    for(LL i = 2; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            P.push_back(i);\r\n\r\n            while(n%i == 0)\r\n            {\r\n                n /= i;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n    {\r\n        P.push_back(n);\r\n    }\r\n}\r\n\r\n----\r\n\r\nFor each of it's prime factors, we will calculate the exponent to which it is raised. \r\n\r\nWe need to be careful with how we evaluate this. We need to avoid overflow. \r\n\r\nSo, the number of multiples of p till n = n/p\r\n\r\nThe number of multiples of p^2 till n =  n/p^2\r\n\r\nWe might not be able to square p if it's too large. Instead, we will divide and bring down n. \r\nWe will make n = n/p\r\n\r\n----\r\n\r\nLL get_exponent(LL n, LL p)\r\n{\r\n    LL exponent = 0;\r\n    LL temp_p = p;\r\n\r\n    while(n > 0)\r\n    {\r\n        exponent += n/p;\r\n\r\n        n /= p;\r\n    }\r\n\r\n    return exponent;\r\n}\r\n\r\n----\r\n\r\nThen, we will simply multiply all of them in the answer\r\n\r\nint main()\r\n{\r\n    LL x, n;\r\n    cin >> x >> n;\r\n\r\n    vector <LL> prime_factors;\r\n    factorise(x, prime_factors);\r\n\r\n    const LL MOD = 1e9 + 7;\r\n    LL answer = 1;\r\n    for(int i = 0; i < prime_factors.size(); i++)\r\n    {\r\n        LL exponent = get_exponent(n, prime_factors[i]);\r\n\r\n        answer *= power_mod(prime_factors[i], exponent, MOD);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 589/Programs/Complete Tripartite.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    cin >> no_of_vertices >> no_of_edges;\n    \n    set <int> graph[no_of_vertices + 1];\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        graph[u].insert(v);\n        graph[v].insert(u);\n    }\n    \n    const int NO_OF_GROUPS = 3;\n    vector <int> group(no_of_vertices + 1, 0);\n    vector <int> group_sizes(NO_OF_GROUPS + 1, 0);\n    for(int g = 1; g <= NO_OF_GROUPS; g++)\n    {\n        int first = 0;\n        \n        for(first = 1; first <= no_of_vertices && group[first] != 0; first++);\n        \n        if(first == no_of_vertices + 1)\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n        \n        group[first] = g;\n        for(int second = 1; second <= no_of_vertices; second++)\n        {\n            if(graph[first].find(second) == graph[first].end())\n            {\n                group[second] = g;\n                group_sizes[g]++;\n            }\n        }\n    }\n    \n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        if(group[v] == 0)\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n    }\n    \n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        for(auto it = graph[v].begin(); it != graph[v].end(); it++)\n        {\n            int u = *it;\n            \n            if(group[u] == group[v])\n            {\n                cout << \"-1\\n\";\n                \n                return 0;\n            }\n        }\n    }\n    \n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        int other_groups = group_sizes[1] + group_sizes[2] + group_sizes[3]\n                            - group_sizes[group[v]];\n        \n        if(graph[v].size() != other_groups)\n        {\n            cout << \"-1\\n\";\n            \n            return 0;\n        }\n    }\n    \n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        cout << group[v] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 589/Programs/Distinct Digits.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint distinct_digits(int n)\r\n{\r\n   vector <int> frequency(10, 0);\r\n\r\n   while(n > 0)\r\n   {\r\n       if(frequency[n%10] > 0)\r\n            return false;\r\n\r\n       frequency[n%10]++;\r\n\r\n       n /= 10;\r\n   }\r\n\r\n   return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int left, right;\r\n    cin >> left >> right;\r\n\r\n    for(int i = left; i <= right; i++)\r\n    {\r\n        if(distinct_digits(i))\r\n        {\r\n            cout << i << endl;\r\n\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    cout << \"-1\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 589/Programs/Filing the Grid.cpp",
    "content": "#include <iostream>\n#include <vector>\n\ntypedef long long LL;\n\nusing namespace std;\n\nLL power_mod(LL n, LL power, LL mod)\n{\n    LL result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*n)%mod;\n\n        n = (n*n)%mod;\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nint main()\n{\n    int rows, columns;\n    cin >> rows >> columns;\n\n    vector <int> blocked_cells_row(rows + 3, 0);\n    for(int i = 1; i <= rows; i++)\n        cin >> blocked_cells_row[i];\n\n    vector <int> blocked_cells_column(columns + 3, 0);\n    for(int i = 1; i <= columns; i++)\n        cin >> blocked_cells_column[i];\n\n    for(int i = 1; i <= rows; i++)\n    {\n        int first_empty_column = blocked_cells_row[i] + 1;\n\n        if(blocked_cells_column[first_empty_column] >= i)\n        {\n            cout << \"0\\n\";\n\n            return 0;\n        }\n    }\n\n    for(int j = 1; j <= columns; j++)\n    {\n        int first_empty_row = blocked_cells_column[j] + 1;\n\n        if(blocked_cells_row[first_empty_row] >= j)\n        {\n            cout << \"0\\n\";\n\n            return 0;\n        }\n    }\n\n    LL free_cells = 0;\n    for(int i = 1; i <= rows; i++)\n    {\n        for(int j = 1; j <= columns; j++)\n        {\n            if(i <= blocked_cells_column[j] + 1 || j <= blocked_cells_row[i] + 1)\n            {\n                continue;\n            }\n            else\n            {\n                free_cells++;\n            }\n        }\n    }\n\n    const LL MOD = 1e9 + 7;\n    LL answer = power_mod(2, free_cells, MOD);\n    cout << answer << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 589/Programs/Primes and Multiplication.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\ntypedef long long LL;\r\n\r\nusing namespace std;\r\n\r\nLL get_exponent(LL n, LL p)\r\n{\r\n    LL exponent = 0;\r\n    LL temp_p = p;\r\n\r\n    while(n > 0)\r\n    {\r\n        exponent += n/p;\r\n\r\n        n /= p;\r\n    }\r\n\r\n    return exponent;\r\n}\r\n\r\nvoid factorise(LL n, vector <LL> &P)\r\n{\r\n    for(LL i = 2; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            P.push_back(i);\r\n\r\n            while(n%i == 0)\r\n            {\r\n                n /= i;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n    {\r\n        P.push_back(n);\r\n    }\r\n}\r\n\r\nLL power_mod(LL n, LL power, LL mod)\r\n{\r\n    LL result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*n)%mod;\r\n\r\n        n = (n*n)%mod;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nint main()\r\n{\r\n    LL x, n;\r\n    cin >> x >> n;\r\n\r\n    vector <LL> prime_factors;\r\n    factorise(x, prime_factors);\r\n\r\n    const LL MOD = 1e9 + 7;\r\n    LL answer = 1;\r\n    for(int i = 0; i < prime_factors.size(); i++)\r\n    {\r\n        LL exponent = get_exponent(n, prime_factors[i]);\r\n\r\n        answer *= power_mod(prime_factors[i], exponent, MOD);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 592/Explanations/Minimizing Difference Explanation.txt",
    "content": "Quora Editorial - https://qr.ae/TWoHA1\n\nLet us consider the sorted array. \n\nThe difference between the minimum and maximum element is initially (A[n] - A[1]).\n\n---\n\nIn order to reduce this difference, we have to make some prefix of length i equal and some suffix of length j equal. \n\nFor example, suppose we want to make the difference = (A[j] - A[i]). \n\nThen, we need to make the entire prefix of length i = A[i]\n\nThis takes (i*A[i] - Sum_till[i]) operations. \n\nWe also want to make the suffix of length j = A[j]\n\nThis takes (Sum_from[j] - (n - j + 1)*A[j])\n\n---\n\nNow, we have to somehow iterate over all possible values of the prefix = L and all possible values of the suffix = R, provided that the number of operations we use is <= K.\n\nKey Observation - If the prefix = L and the Suffix = R, then one of {L, R} will be from the array. \n\nProof -\n\n1. Suppose we have more elements in the prefix than in the suffix, then we can get [L - 1, R - 1], with the same (or lesser) number of operations. \nWe can also get [L - 2, R - 2] and so on till L or R (or both) becomes equal to some array element A[i]. \n\n2. Suppose we have more elements in the suffix than in the prefix, then we can get [L + 1, R + 1], with the same (or lesser) number of operations. \nSimilarly, we can get [L + 2, R + 2] and so on till L or R becomes equal to some array element in A. \n\n----\n\nThis is a very important observation as it simplifies our job greatly. \n\nHere, is what we will do. \n\n1. Iterate i = 1 to n, and make the prefix = A[i]\n\n2. This will make us use (i*A[i] - Sum_till[i]) operations.  \n\n3. With our remaining operations, we need to find the best value of R (which may be from the array or not).\n\n4. The maximum value of R is A[n] and the minimum value of R is A[i]. \n\nWe will binary search for the best possible value of R. \n\n-----\n\nLet us maintain the invariant that it is not possible to make the suffix of the array = L1 and \nit is always possible to make the suffix of the array = R1. \n\nWe will do binary search and get Mid = (L1 + R1)/2. \n\nHow many operations do we need to make the suffix of the array = Mid ? \n\nLet A[k] be the first element in A that is >= Mid. \n\nThen, the number of operations used is (Sum_from[k] - (n - k + 1)*Mid)\n\nIf these number of operations are allowed, then we will set R2 = Mid \nIf these number of operations are not allowed, then we will set L2 = Mid\n\nWe will continue doing this till (R2 - L2) > 1\nWhen R2 - L2 = 1, then R2 is the number we want as it is the first integer such that we can make some suffix = R2\n\n----\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long operations_used_in_prefix = i*A[i] - sum_till[i];\n\n        if(operations_used_in_prefix > no_of_operations)\n        {\n            continue;\n        }\n\n        //Maintain the invariant that it is always possible to make the suffix of the array = Right\n        long long left = A[i], right = A[no_of_elements];\n        while(right - left > 1)\n        {\n            long long mid = (right + left)/2;\n\n            int pos = upper_bound(A.begin(), A.end(), mid - 1) - A.begin(); //Make suffix = mid\n\n            long long operations_used_in_suffix = sum_from[pos] - (no_of_elements - pos + 1)*mid;\n\n            if(operations_used_in_prefix + operations_used_in_suffix <= no_of_operations)\n            {\n                right = mid;\n            }\n            else\n            {\n                left = mid;\n            }\n        }\n\n        best_minimum = min(best_minimum, right - A[i]);\n    }\n    \n-----\n\nNow, this is not enough. \n\nWe have to do the same thing in the other direction as well. \n\n1. Iterate from i = n to i = 1\n\n2. Make the entire suffix of the array = A[i]\n\n3. Then, binary search the best value of L such that some prefix of the array can be = L using the remaining operations.\n\nWe will use a similar binary search idea as mentioned above. \n\n---\n\nfor(int i = no_of_elements; i >= 1; i--)\n    {\n        long long operations_used_in_suffix = sum_from[i] - (no_of_elements - i + 1)*A[i];\n\n        if(operations_used_in_suffix > no_of_operations)\n        {\n            continue;\n        }\n\n        //Maintain the invariant that it is always possible to make the prefix of array = Left\n        long long left = A[1], right = A[i];\n        while(right - left > 1)\n        {\n            long long mid = (left + right)/2;\n\n            int pos = upper_bound(A.begin(), A.end(), mid) - A.begin() - 1; //Make Prefix = Mid\n\n            long long operations_used_in_prefix = pos*mid - sum_till[pos];\n\n            if(operations_used_in_suffix + operations_used_in_prefix <= no_of_operations)\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n\n        best_minimum = min(best_minimum, A[i] - left);\n    }\n    \n-----\n\nOf course, we need to check if it is possible to make the entire array = x,\n\nIf this is possible it is always better to make x from some element from the array. \n\n----\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(i*A[i] - sum_till[i] + sum_from[i + 1] - (no_of_elements - i)*A[i] <= no_of_operations)\n        {\n            best_minimum = 0;\n            break;\n        }\n    }\n    \n-----\n"
  },
  {
    "path": "Contests/Div 2 592/Explanations/Pens and Pencils Explanation.txt",
    "content": "We can calculate the number of pens and pencils required and see if it fits into the bag. \r\n\r\nThe number of pens is ceil(a/c) and the number of pencils is ceil(b/d). \r\n\r\n---\r\n\r\nint ceil(int n, int d)\r\n{\r\n    return (n/d + (n%d != 0));\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int lectures, practicals, pen_limit, pencil_limit, bag_capacity;\r\n    cin >> lectures >> practicals >> pen_limit >> pencil_limit >> bag_capacity;\r\n\r\n    int pens_required = ceil(lectures, pen_limit);\r\n    int pencils_required = ceil(practicals, pencil_limit);\r\n\r\n    if(pens_required + pencils_required <= bag_capacity)\r\n    {\r\n        cout << pens_required << \" \" << pencils_required << \"\\n\";\r\n    }\r\n    else\r\n    {\r\n        cout << \"-1\\n\";\r\n    }\r\n}"
  },
  {
    "path": "Contests/Div 2 592/Explanations/Rooms and Staircases Explanation.txt",
    "content": "If there is a 1, then we can switch over and travel all the rooms all over again. \r\n\r\nIt is 2*max(i, N - i + 1)\r\n\r\nWe will choose the best ladder.\r\n\r\n---\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int no_of_rooms = length;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] == '1')\r\n        {\r\n            no_of_rooms = max(no_of_rooms, 2*max(i + 1, length - i));\r\n        }\r\n    }\r\n\r\n    cout << no_of_rooms << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Div 2 592/Explanations/The Football Season Explanation.txt",
    "content": "Let us suppose that the number of wins, draws and losses is w, d and l and the number of points in each case is W, D and 0 respectively. \r\n\r\nWe know that, \r\n\r\nw + d + l = N\r\nw.W + d.D = P\r\n\r\n----\r\n\r\nWe have 2 equations. \r\n\r\nFrom the second equation, we can iterate over the value of w and determine d and from w and d, we can determine l. \r\n\r\nMy first approach was to brute force w from 1 to 10^6 and then to brute force d from 1 to 10^6. \r\n\r\nIf it is not possible in either case, then declare it is never possible. \r\n\r\nThis limit 10^6 was arbitrarily chosen. \r\n\r\nHowever, this solution was accepted. \r\n\r\n---\r\n\r\nA couple of crucial observations - \r\n\r\nw(D) = d(W)\r\n\r\nThis observation is simple but extremely elegant and powerful. \r\n\r\nIf we win D matches, it is the same as drawing W matches. \r\n\r\n---\r\n\r\nSecond Observation - Wins and Draws are NOT symmetric. \r\n\r\nD < W always\r\n\r\n----\r\n\r\nSuppose we have drawn more than W matches\r\n\r\nThen, we can reduce the number of draws by W and increase the number of wins by D. \r\n\r\nThe number of 'total matches drawn or won' changes by (D - W). \r\n\r\nThis is negative. \r\n\r\nThis reduces the number of matches. \r\n\r\n----\r\n\r\nSince, we have a sum bound on w and d i.e. \r\n\r\nw + d + l = N, \r\n\r\nLet us try to minimise the sum of (w + d)\r\n\r\nIf d >= W, then reduce d by W and increase w by D. \r\n\r\nThis reduces the total number of matches, keeping the points the same. \r\n\r\n---\r\n\r\nThis proves that if a solution is possible, then it is possible with the number of draws in [0, W - 1].\r\n\r\n---\r\n\r\nWe will iterate over the number of draws in this range. \r\n\r\nFor each i in this range, we will check if a triplet is possible.\r\n\r\n---\r\n\r\nSuppose we reduce the number of wins by D and increase the number of draws by W. Then the number of matches increases by (W - D). Since W > D, this increases the number of matches. \r\nSuppose we reduce the number of draws by W and increase the number of wins by D, then the number of matches decreases by (D - W). Since W > D, this decreases the number of matches. \r\n\r\nWe want to minimise the number of matches. So, we will always increase the wins by D and reduce the draws by W. If there is some solution, there will also be a solution where the number of draws is < W. This is the crucial insight. \r\n\r\nAfter that, we just have to iterate over the number of draws in [0, W - 1]\r\n\r\n---\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long no_of_games, points, win_point, draw_point;\r\n    cin >> no_of_games >> points >> win_point >> draw_point;\r\n\r\n    int limit = win_point - 1;\r\n    for(int draws = 0; points >= draws*draw_point && draws <= limit; draws++)\r\n    {\r\n        if( (points - draws*draw_point)%win_point == 0)\r\n        {\r\n            long long wins = (points - draws*draw_point)/win_point;\r\n\r\n            long long losses = no_of_games - wins - draws;\r\n\r\n            if(losses >= 0)\r\n            {\r\n                cout << wins << \" \" << draws << \" \" << losses;\r\n\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n    cout << \"-1\\n\";\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 592/Programs/Minimizing Difference.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    long long no_of_operations;\n    cin >> no_of_elements >> no_of_operations;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    vector <long long> sum_till(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + A[i];\n    }\n\n    vector <long long> sum_from(no_of_elements + 2, 0);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        sum_from[i] = sum_from[i + 1] + A[i];\n    }\n\n    long long best_minimum = A[no_of_elements] - A[1];\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(i*A[i] - sum_till[i] + sum_from[i + 1] - (no_of_elements - i)*A[i] <= no_of_operations)\n        {\n            best_minimum = 0;\n            break;\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long operations_used_in_prefix = i*A[i] - sum_till[i];\n\n        if(operations_used_in_prefix > no_of_operations)\n        {\n            continue;\n        }\n\n        //Maintain the invariant that it is always possible to make the suffix of the array = Right\n        long long left = A[i], right = A[no_of_elements];\n        while(right - left > 1)\n        {\n            long long mid = (right + left)/2;\n\n            int pos = upper_bound(A.begin(), A.end(), mid - 1) - A.begin(); //Make suffix = mid\n\n            long long operations_used_in_suffix = sum_from[pos] - (no_of_elements - pos + 1)*mid;\n\n            if(operations_used_in_prefix + operations_used_in_suffix <= no_of_operations)\n            {\n                right = mid;\n            }\n            else\n            {\n                left = mid;\n            }\n        }\n\n        best_minimum = min(best_minimum, right - A[i]);\n    }\n\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        long long operations_used_in_suffix = sum_from[i] - (no_of_elements - i + 1)*A[i];\n\n        if(operations_used_in_suffix > no_of_operations)\n        {\n            continue;\n        }\n\n        //Maintain the invariant that it is always possible to make the prefix of array = Left\n        long long left = A[1], right = A[i];\n        while(right - left > 1)\n        {\n            long long mid = (left + right)/2;\n\n            int pos = upper_bound(A.begin(), A.end(), mid) - A.begin() - 1; //Make Prefix = Mid\n\n            long long operations_used_in_prefix = pos*mid - sum_till[pos];\n\n            if(operations_used_in_suffix + operations_used_in_prefix <= no_of_operations)\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n\n        best_minimum = min(best_minimum, A[i] - left);\n    }\n\n    cout << best_minimum << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 592/Programs/Pens and Pencils.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint ceil(int n, int d)\r\n{\r\n    return (n/d + (n%d != 0));\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int lectures, practicals, pen_limit, pencil_limit, bag_capacity;\r\n    cin >> lectures >> practicals >> pen_limit >> pencil_limit >> bag_capacity;\r\n\r\n    int pens_required = ceil(lectures, pen_limit);\r\n    int pencils_required = ceil(practicals, pencil_limit);\r\n\r\n    if(pens_required + pencils_required <= bag_capacity)\r\n    {\r\n        cout << pens_required << \" \" << pencils_required << \"\\n\";\r\n    }\r\n    else\r\n    {\r\n        cout << \"-1\\n\";\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 592/Programs/Rooms and Staircases.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int no_of_rooms = length;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] == '1')\r\n        {\r\n            no_of_rooms = max(no_of_rooms, 2*max(i + 1, length - i));\r\n        }\r\n    }\r\n\r\n    cout << no_of_rooms << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 592/Programs/The Football Season.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long no_of_games, points, win_point, draw_point;\r\n    cin >> no_of_games >> points >> win_point >> draw_point;\r\n\r\n    int limit = win_point - 1;\r\n    for(int draws = 0; points >= draws*draw_point && draws <= limit; draws++)\r\n    {\r\n        if( (points - draws*draw_point)%win_point == 0)\r\n        {\r\n            long long wins = (points - draws*draw_point)/win_point;\r\n\r\n            long long losses = no_of_games - wins - draws;\r\n\r\n            if(losses >= 0)\r\n            {\r\n                cout << wins << \" \" << draws << \" \" << losses;\r\n\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n    cout << \"-1\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 596/Explanations/Forgetting Things Explanation.txt",
    "content": "If the prefixes are same, then we can just put 1 and 2. \r\n\r\nIf the prefixes differ by 1, then we can put 9 and 0. \r\n\r\nIf one prefix is 9 and the oether is 1, then we can put 9 and 00\r\n\r\n---\r\n\r\nint main()\r\n{\r\n    int old_left, new_left;\r\n    cin >> old_left >> new_left;\r\n\r\n    if(old_left == new_left)\r\n    {\r\n        cout << old_left << \"1 \" << new_left << \"2\\n\";\r\n    }\r\n    else if(old_left + 1 == new_left)\r\n    {\r\n        cout << old_left << \"9 \" << new_left << \"0\\n\";\r\n    }\r\n    else if(old_left == 9 && new_left == 1)\r\n    {\r\n        cout << old_left << \"9 \" << new_left << \"00\\n\";\r\n    }\r\n    else\r\n    {\r\n        cout << \"-1\\n\";\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 596/Explanations/P Binary Explanation.txt",
    "content": "To check if it is possible to write n in i bits,\n\n(n - ip) must have exactly i bits set in it's binary representation.\n\n-----\n\n(n - ip) will not be more than a 32 bit number in the given range so we only need to check from 1 to 32.\n\nIf it is possible for any value of i, it is the minimum.\n\nIf it is not possible for any i in [0, 32], it's not possible.\n\n-----\n\nint main()\n{\n    long long n, p;\n    cin >> n >> p;\n\n    int answer = 100;\n    for(int i = 0; i < 32; i++)\n    {\n        if(__builtin_popcount(n - i*p) > i || (n - i*p) < i)\n        {\n            continue;\n        }\n\n        answer = i;\n\n        break;\n    }\n\n    cout << (answer == 100 ? -1 : answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 596/Explanations/Power Products Explanation.txt",
    "content": "Let us look at N in terms of it's prime factorisation. \n\nSuppose N = p1^a1 p2^a2 ... pk^ak\n\nTo make it a perfect power of M, all the exponents have to be a multiple of M. \n\nLet us define the 'complement' of an integer N as an integer C such that N.C is a perfect power of M. \n\n\n---\n\nFor Example, \n\nN = 2^3 3^2 5^1\n\nAnd we want to make it a perfect 3rd power, then the complement \n\nC = 3 5^2\n\n---\n\nWe will replace each exponent by it's remainder (mod M) as that is all that matters. \n\nSuppose, we had N = 2^5 3^2 5^3, then we will replace N = 2^2 3\n\n---\n\nWe will perform a scan through the array. \n\nFor each integer A[i], we will replace all it's exponent. \n\nThen, we will add the frequency of it's complement to the left and add it to our answer.\n\n---\n\nint main()\n{\n    sieve();\n\n    int no_of_elements, power;\n    scanf(\"%d %d\", &no_of_elements, &power);\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%I64d\", &A[i]);\n\n        vector <pair <int, int> > factors;\n\n        get_factors(factors, A[i]);\n\n        for(int f = 0; f < factors.size(); f++)\n        {\n            int p = factors[f].first;\n            int exponent = (factors[f].second)%power;\n\n            for(int e = 1; e <= exponent; e++)\n            {\n                A[i] *= p;\n            }\n        }\n    }\n\n    long long answer = 0;\n    map <long long, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long complement = get_complement(A[i], power);\n\n        answer += frequency[complement];\n\n        frequency[A[i]]++;\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 596/Explanations/TV Subscriptions Explanation.txt",
    "content": "We only need to keep track of the leftmost occurence of each element. \r\n\r\nWe will maintain two pointers - L and R to keep a sliding window. \r\n\r\nWhen we increment R, we will check if the leftmost occurence of A[R] is < L, This would mean that A[R] is a distinct element in the current segment [L, R]. Otherwise, it would not. \r\n\r\nAlthough there are 2 for loops, the time complexity is O(n) since each of the N elements is visited at most twice by each of the pointers. \r\n\r\nWe will find out the minimum number of distinct elements of all segments of length K.\r\n\r\n---\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, no_of_distinct_elements, segment_length;\r\n    cin >> no_of_elements >> no_of_distinct_elements >> segment_length;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int distinct_elements = 0;\r\n    map <int, int> last_occurence;\r\n    for(int i = 1; i <= segment_length; i++)\r\n    {\r\n        if(last_occurence[A[i]] == 0)\r\n        {\r\n            distinct_elements++; \r\n        }\r\n\r\n        last_occurence[A[i]] = i;\r\n    }\r\n\r\n    int minimum_distinct_elements = distinct_elements;\r\n    for(int i = segment_length + 1; i <= no_of_elements; i++)\r\n    {\r\n        int left = i - segment_length, right = i;\r\n        int left_element = A[left], right_element = A[right];\r\n\r\n        if(last_occurence[left_element] == left)\r\n        {\r\n            distinct_elements--;\r\n        }\r\n\r\n        if(last_occurence[right_element] <= left)\r\n        {\r\n            distinct_elements++;\r\n        }\r\n\r\n        last_occurence[right_element] = i;\r\n\r\n        minimum_distinct_elements = min(minimum_distinct_elements, distinct_elements);\r\n    }\r\n\r\n    cout << minimum_distinct_elements << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Div 2 596/Programs/Forgetting Things.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int old_left, new_left;\r\n    cin >> old_left >> new_left;\r\n\r\n    if(old_left == new_left)\r\n    {\r\n        cout << old_left << \"1 \" << new_left << \"2\\n\";\r\n    }\r\n    else if(old_left + 1 == new_left)\r\n    {\r\n        cout << old_left << \"9 \" << new_left << \"0\\n\";\r\n    }\r\n    else if(old_left == 9 && new_left == 1)\r\n    {\r\n        cout << old_left << \"9 \" << new_left << \"00\\n\";\r\n    }\r\n    else\r\n    {\r\n        cout << \"-1\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 596/Programs/P-Binary.cpp",
    "content": "#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long n, p;\r\n    cin >> n >> p;\r\n\r\n    int answer = 100;\r\n    for(int i = 0; i < 32; i++)\r\n    {\r\n        if(__builtin_popcount(n - i*p) > i || (n - i*p) < i)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        answer = i;\r\n\r\n        break;\r\n    }\r\n\r\n    cout << (answer == 100 ? -1 : answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 596/Programs/Power Products.cpp",
    "content": "#include <iostream>\n#include <cstdio>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nconst int N = 1e5 + 5;\nconst long long oo = 1e10;\nvector <long long> primes;\n\nvoid sieve()\n{\n    vector <int> is_prime(N + 1, true);\n    is_prime[0] = is_prime[1] = false;\n\n    for(int i = 2; i < N; i++)\n    {\n        if(is_prime[i])\n        {\n            primes.push_back(i);\n        }\n\n        for(int j = 0; j < primes.size() && i*primes[j] < N; j++)\n        {\n            is_prime[i*primes[j]] = false;\n\n            if(primes[j]%i == 0)\n            {\n                break;\n            }\n        }\n    }\n}\n\nvoid get_factors(vector <pair <int, int> > &F, long long &n)\n{\n    for(int i = 0; n > 1 && i < primes.size(); i++)\n    {\n        if(n%primes[i] != 0)\n        {\n            continue;\n        }\n\n        int exponent = 0;\n\n        while(n%primes[i] == 0)\n        {\n            n /= primes[i];\n\n            exponent++;\n        }\n\n        F.push_back(make_pair(primes[i], exponent));\n    }\n\n    if(n > 1)\n    {\n        F.push_back(make_pair(n, 1));\n\n        n /= n;\n    }\n}\n\nlong long get_complement(long long n, long long power)\n{\n    long long complement = 1;\n\n    for(int i = 0; n > 1 && i < primes.size(); i++)\n    {\n        if(primes[i]*primes[i] > n)\n        {\n            break;\n        }\n\n        if(n%primes[i] != 0)\n        {\n            continue;\n        }\n\n        int exponent = 0;\n\n        while(n%primes[i] == 0)\n        {\n            n /= primes[i];\n\n            exponent++;\n        }\n\n        while(exponent%power != 0)\n        {\n            exponent++;\n\n            if(complement > oo/primes[i])\n            {\n                complement = -1;\n\n                return -1;\n            }\n            else\n            {\n                complement *= primes[i];\n            }\n        }\n    }\n\n    if(n == 1)\n    {\n        return complement;\n    }\n\n    int exponent = 1;\n\n    while(exponent%power != 0)\n    {\n        exponent++;\n\n        if(complement > oo/n)\n        {\n            complement = -1;\n\n            return -1;\n        }\n        else\n        {\n            complement *= n;\n        }\n    }\n\n    return complement;\n}\n\nint main()\n{\n    sieve();\n\n    int no_of_elements, power;\n    scanf(\"%d %d\", &no_of_elements, &power);\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%I64d\", &A[i]);\n\n        vector <pair <int, int> > factors;\n\n        get_factors(factors, A[i]);\n\n        for(int f = 0; f < factors.size(); f++)\n        {\n            int p = factors[f].first;\n            int exponent = (factors[f].second)%power;\n\n            for(int e = 1; e <= exponent; e++)\n            {\n                A[i] *= p;\n            }\n        }\n    }\n\n    long long answer = 0;\n    map <long long, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long complement = get_complement(A[i], power);\n\n        answer += frequency[complement];\n\n        frequency[A[i]]++;\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 596/Programs/TV Subscriptions.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, no_of_distinct_elements, segment_length;\r\n    cin >> no_of_elements >> no_of_distinct_elements >> segment_length;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int distinct_elements = 0;\r\n    map <int, int> last_occurence;\r\n    for(int i = 1; i <= segment_length; i++)\r\n    {\r\n        if(last_occurence[A[i]] == 0)\r\n        {\r\n            distinct_elements++;\r\n        }\r\n\r\n        last_occurence[A[i]] = i;\r\n    }\r\n\r\n    int minimum_distinct_elements = distinct_elements;\r\n    for(int i = segment_length + 1; i <= no_of_elements; i++)\r\n    {\r\n        int left = i - segment_length, right = i;\r\n        int left_element = A[left], right_element = A[right];\r\n\r\n        if(last_occurence[left_element] == left)\r\n        {\r\n            distinct_elements--;\r\n        }\r\n\r\n        if(last_occurence[right_element] <= left)\r\n        {\r\n            distinct_elements++;\r\n        }\r\n\r\n        last_occurence[right_element] = i;\r\n\r\n        minimum_distinct_elements = min(minimum_distinct_elements, distinct_elements);\r\n    }\r\n\r\n    cout << minimum_distinct_elements << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_tests;\r\n    cin >> no_of_tests;\r\n\r\n    while(no_of_tests--)\r\n    {\r\n        solve();\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 597/Explanations/Constanze's Machine Explanation.txt",
    "content": "If the string contains any 'w' or 'm', then the answer is 0. \n\nOtherwise, Let f(i) be the number of ways of making the first i letters.\n\nIf, S[i, i - 1] = 'nn', then f(i) = f(i - 1) + f(i - 2) since the last letter can either be 'n' and appended at the end of a string of length (i - 1) \n\nor it can be 'm' and appended at the end of a string of length (i - 2)\n\nIf we treat it like 'n', then we can get f(i - 1) strings of length (i - 1) and put an 'n' at the end. \n\nIf we treat it like 'm', then we can get f(i - 2) strings of length(i - 2) and put an 'm' at the end. \n\nHence, f(i) = f(i - 1) + f(i - 2)\n\n---\n\nSimilarly, if S[i, i - 1] = 'uu', then f(i) = f(i - 1) + f(i - 2)\n\n---\n\nOtherwise, f(i) = f(i - 1), as there is only one choice for the last letter and it can be appended at the end of a string of length (i - 1) letters. \n\n---\n\nThe answer is f(N)\n\n---\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == 'm' || S[i] == 'w')\n        {\n            cout << \"0\\n\";\n\n            return 0;\n        }\n    }\n\n    const int MOD = 1e9 + 7;\n\n    vector <int> no_of_strings_till(S.size() + 1, 0);\n    no_of_strings_till[0] = 1;\n\n    for(int i = 1; i < S.size(); i++)\n    {\n        if(S[i] == 'n' && S[i - 1] == 'n')\n        {\n            if(i == 1)\n            {\n                no_of_strings_till[i] = 2;\n                continue;\n            }\n\n            no_of_strings_till[i] = (no_of_strings_till[i - 1] + no_of_strings_till[i - 2])%MOD;\n        }\n        else if(S[i] == 'u' && S[i - 1] == 'u')\n        {\n            if(i == 1)\n            {\n                no_of_strings_till[i] = 2;\n                continue;\n            }\n\n            no_of_strings_till[i] = (no_of_strings_till[i - 1] + no_of_strings_till[i - 2])%MOD;\n        }\n        else\n        {\n            no_of_strings_till[i] = no_of_strings_till[i - 1];\n        }\n    }\n\n    cout << no_of_strings_till[S.size() - 1];\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 597/Explanations/Good Ol Number Colouring Explanation.txt",
    "content": "Essentially an integer n is coloured white if it is possible to write n = Xa + Yb, where x and Y are any positive integers. \r\n\r\nIf gcd(a, b) = 1, then there is always a positive integer L, such that it is possible to reach all integers >= L by a linear combination of a and b. \r\n\r\nIf (a, b) are coprime, then the number of integers not coloured white is finite. \r\n\r\nOtherwise, it is infinite. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int a, b;\r\n    cin >> a >> b;\r\n\r\n    cout << (__gcd(a, b) == 1 ? \"Finite\\n\" : \"Infinite\\n\");\r\n}"
  },
  {
    "path": "Contests/Div 2 597/Explanations/Restricted RPS Explanation.txt",
    "content": "We will do linear passes over the string. \r\n\r\nPass 1 - We will try to be greedy. \r\n\r\nWhatever move is played, we will try to make the winning move. If not, we will mark it as 'X'. \r\n\r\nFor example, if the 5th move is 'Rocks', then we will try to play a 'Paper'. If we have no Paper, we will put 'X'. \r\n\r\n\r\nThis maximises the number of wins as every move has been made for a win. \r\n\r\n-----\r\n\r\nPass 2 - Now, we will fill up the 'X's with any available move. It doesn't really matter\r\n\r\n-----\r\n\r\nWe need to check if the total number of wins is the number desired. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int total, papers, scissors, rocks;\r\n    cin >> total >> rocks >> papers >> scissors;\r\n\r\n    string moves;\r\n    cin >> moves;\r\n\r\n    int wins = 0;\r\n    string answer;\r\n\r\n    for(int i = 0; i < moves.size(); i++)\r\n    {\r\n        switch(moves[i])\r\n        {\r\n            case 'R':{\r\n                         if(papers > 0)\r\n                         {\r\n                             wins++;\r\n                             papers--;\r\n                             answer += 'P';\r\n                             break;\r\n                         }\r\n                         else\r\n                         {\r\n                             answer += 'X';\r\n                             break;\r\n                         }\r\n                     }\r\n            case 'P':{\r\n                        if(scissors > 0)\r\n                        {\r\n                            wins++;\r\n                            scissors--;\r\n                            answer += 'S';\r\n                            break;\r\n                        }\r\n                        else\r\n                        {\r\n                            answer += 'X';\r\n                            break;\r\n                        }\r\n                     }\r\n            case 'S':{\r\n                        if(rocks > 0)\r\n                        {\r\n                            wins++;\r\n                            rocks--;\r\n                            answer += 'R';\r\n                            break;\r\n                        }\r\n                        else\r\n                        {\r\n                            answer += 'X';\r\n                            break;\r\n                        }\r\n                     }\r\n        }\r\n    }\r\n\r\n    if(2*wins < total)\r\n    {\r\n        cout << \"No\\n\";\r\n        return;\r\n    }\r\n\r\n    for(int i = 0; i < answer.size(); i++)\r\n    {\r\n        if(answer[i] != 'X')\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(rocks > 0)\r\n        {\r\n            answer[i] = 'R';\r\n            rocks--;\r\n            continue;\r\n        }\r\n\r\n        if(papers > 0)\r\n        {\r\n            answer[i] = 'P';\r\n            papers--;\r\n            continue;\r\n        }\r\n\r\n        if(scissors > 0)\r\n        {\r\n            answer[i] = 'S';\r\n            scissors--;\r\n            continue;\r\n        }\r\n    }\r\n\r\n    cout << \"Yes\\n\";\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Div 2 597/Programs/Constanze's Machine.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <string>\n\nusing namespace std;\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == 'm' || S[i] == 'w')\n        {\n            cout << \"0\\n\";\n\n            return 0;\n        }\n    }\n\n    const int MOD = 1e9 + 7;\n\n    vector <int> no_of_strings_till(S.size() + 1, 0);\n    no_of_strings_till[0] = 1;\n\n    for(int i = 1; i < S.size(); i++)\n    {\n        if(S[i] == 'n' && S[i - 1] == 'n')\n        {\n            if(i == 1)\n            {\n                no_of_strings_till[i] = 2;\n                continue;\n            }\n\n            no_of_strings_till[i] = (no_of_strings_till[i - 1] + no_of_strings_till[i - 2])%MOD;\n        }\n        else if(S[i] == 'u' && S[i - 1] == 'u')\n        {\n            if(i == 1)\n            {\n                no_of_strings_till[i] = 2;\n                continue;\n            }\n\n            no_of_strings_till[i] = (no_of_strings_till[i - 1] + no_of_strings_till[i - 2])%MOD;\n        }\n        else\n        {\n            no_of_strings_till[i] = no_of_strings_till[i - 1];\n        }\n    }\n\n    cout << no_of_strings_till[S.size() - 1];\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 597/Programs/Good Ol Number Colouring.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int a, b;\r\n    cin >> a >> b;\r\n\r\n    cout << (__gcd(a, b) == 1 ? \"Finite\\n\" : \"Infinite\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 597/Programs/Restricted RPS.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int total, papers, scissors, rocks;\r\n    cin >> total >> rocks >> papers >> scissors;\r\n\r\n    string moves;\r\n    cin >> moves;\r\n\r\n    int wins = 0;\r\n    string answer;\r\n\r\n    for(int i = 0; i < moves.size(); i++)\r\n    {\r\n        switch(moves[i])\r\n        {\r\n            case 'R':{\r\n                         if(papers > 0)\r\n                         {\r\n                             wins++;\r\n                             papers--;\r\n                             answer += 'P';\r\n                             break;\r\n                         }\r\n                         else\r\n                         {\r\n                             answer += 'X';\r\n                             break;\r\n                         }\r\n                     }\r\n            case 'P':{\r\n                        if(scissors > 0)\r\n                        {\r\n                            wins++;\r\n                            scissors--;\r\n                            answer += 'S';\r\n                            break;\r\n                        }\r\n                        else\r\n                        {\r\n                            answer += 'X';\r\n                            break;\r\n                        }\r\n                     }\r\n            case 'S':{\r\n                        if(rocks > 0)\r\n                        {\r\n                            wins++;\r\n                            rocks--;\r\n                            answer += 'R';\r\n                            break;\r\n                        }\r\n                        else\r\n                        {\r\n                            answer += 'X';\r\n                            break;\r\n                        }\r\n                     }\r\n        }\r\n    }\r\n\r\n    if(2*wins < total)\r\n    {\r\n        cout << \"No\\n\";\r\n        return;\r\n    }\r\n\r\n    for(int i = 0; i < answer.size(); i++)\r\n    {\r\n        if(answer[i] != 'X')\r\n        {\r\n            continue;\r\n        }\r\n\r\n        if(rocks > 0)\r\n        {\r\n            answer[i] = 'R';\r\n            rocks--;\r\n            continue;\r\n        }\r\n\r\n        if(papers > 0)\r\n        {\r\n            answer[i] = 'P';\r\n            papers--;\r\n            continue;\r\n        }\r\n\r\n        if(scissors > 0)\r\n        {\r\n            answer[i] = 'S';\r\n            scissors--;\r\n            continue;\r\n        }\r\n    }\r\n\r\n    cout << \"Yes\\n\";\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 599/Explanations/Character Swap Explanation.txt",
    "content": "If the frequency of any alphabet in both S and T is not even, then it is not possible. The reason is that the same character should appear twice - Once at S[i], and then at T[i]. \r\n\r\nOne important realisation is that we are allowed to swap (S[i] with T[i] also) - A swap of (i, i) is allowed. I did not realise this till I read the editorial. \r\n\r\nNow, let us try to solve it in O(N^2). \r\n\r\n-----\r\n\r\nWhenever we find a pair (S[i], T[i]) that are not equal, we will look for a (j > i) such that either \r\n\r\n1. S[i] = S[j]\r\n\r\n\tThen, swap (S[j], T[i]). This will ensure i has the correct position.\r\n\r\n2. S[i] = T[j]\r\n\r\n\tThen, swap (S[j], T[j]) first. \r\n\r\n\tThen, we get Case 1 above with S[i] = S[j]. One more swap suffices. \r\n\r\n----\r\n\r\nWe will use at most 2 swaps for every position and it can always be done in 2n steps :)\r\n\r\n---\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    string S, T;\r\n    cin >> S >> T;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> frequency(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        frequency[S[i] - 'a']++;\r\n        frequency[T[i] - 'a']++;\r\n    }\r\n\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(frequency[i]%2 == 1)\r\n        {\r\n            cout << \"No\\n\";\r\n\r\n            return;\r\n        }\r\n    }\r\n\r\n    vector <pair <int, int> > swaps;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == T[i])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        for(int j = i + 1; j < length; j++)\r\n        {\r\n            if(S[j] == T[j])\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if(S[i] == T[j])\r\n            {\r\n                swap(S[j], T[j]);\r\n\r\n                swaps.push_back(make_pair(j, j));\r\n            }\r\n\r\n            if(S[i] == S[j])\r\n            {\r\n                swap(S[j], T[i]);\r\n\r\n                swaps.push_back(make_pair(j, i));\r\n\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"Yes\\n\";\r\n\r\n    cout << swaps.size() << \"\\n\";\r\n\r\n    for(int i = 0; i < swaps.size(); i++)\r\n    {\r\n        cout << swaps[i].first + 1 << \" \" << swaps[i].second + 1 << \"\\n\";\r\n    }\r\n}"
  },
  {
    "path": "Contests/Div 2 599/Explanations/Maximum Square Explanation.txt",
    "content": "I did this in O(n^2) time. \r\n\r\nSuppose we want to check if it is possible to make a square of length L. Then, we need at least L planks of height >= L\r\n\r\n---\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int max_length = 0;\r\n    for(int l = 1; l <= no_of_elements; l++)\r\n    {\r\n        int planks = 0;\r\n        for(int i = 1; i <= no_of_elements; i++)\r\n        {\r\n            planks += (A[i] >= l);\r\n        }\r\n\r\n        if(planks >= l)\r\n            max_length = max(max_length, l);\r\n    }\r\n\r\n    cout << max_length << \"\\n\";\r\n}\r\n\r\n---\r\n\r\nNow, we can also do this in O(N Log N) time. We can solve this by binary search. \r\n\r\nIf we can get a square of length L, then we can also get (L - 1). \r\n\r\nIf we can't get L, we can't get (L + 1). \r\n\r\nThis is a monotonic function and can be binary searched.\r\n\r\n---\r\n\r\nWe can also do this in O(N Log N) time by sorting the list in descending order. \r\n\r\nThe answer is = min{A[i], i} at each step. \r\nFor the first i values, A[i] is the minimum so far. \r\n\r\nIf A[i] > i, then we can make a square of length i since all the planks so far are >= A[i] > i\r\n\r\nIf i > A[i], then we can make a square of length A[i] since all the planks are height >= A[i] and we have already seen i > A[i] planks. So, a square of length A[i] is possible.\r\n\r\nWe need the maximum of all these values. \r\n\r\nfor(int i = 1; i <= N; i++)\r\n{\r\n\tanswer = max(answer, min(A[i], i));\r\n}\r\n\r\n---"
  },
  {
    "path": "Contests/Div 2 599/Explanations/Tile Painting Explanation.txt",
    "content": "Bezout's Identity tells us that there are always two integers (A, B) such that \n\nAx + By = gcd(x, y)\n\nWe can reach any multiple of G as well. \n\nTo reach, KG, we need to multiply A and B by K. \n\n---\n\nIn general, if we are given a set S of integers - {A_1, A_2, ... , A_k}\n\nThen, we can reach any multiple of gcd(S)\n\nWhatever colour we choose for x, we have to choose the same colour for (x + G) too\n\n---\n\nNow, coming to our specific question. \n\nLet N = p1^a1 p2^a2 ... pk^ak\n\nNow, the gcd of any two primes is (p1, p2) = 1\n\nSo, if N has at least 2 primes in it's prime factorisation, then we can reach every integer as (Ap1 + Bp2)\n\nOtherwise, N has only 1 prime factor p. \n\nWe can choose colours for [1, p] \n\n(p + 1) has to be the same colour as 1, (p + 2) as 2 and so on\n\nSo there are p colours totally. \n\nWe need to handle the special case of N = 1 seperately.\n\n---\n\nvoid factorise(long long n, vector <long long> &F)\n{\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            F.push_back(i);\n\n            while(n%i == 0)\n            {\n                n /= i;\n            }\n        }\n    }\n\n    if(n > 1)\n    {\n        F.push_back(n);\n    }\n}\n\nint main()\n{\n    long long n;\n    cin >> n;\n\n    vector <long long> prime_divisors;\n    factorise(n, prime_divisors);\n\n    cout << (prime_divisors.size() > 1 || n == 1 ? 1 : prime_divisors[0]) << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 599/Programs/Character Swap.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    string S, T;\r\n    cin >> S >> T;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> frequency(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        frequency[S[i] - 'a']++;\r\n        frequency[T[i] - 'a']++;\r\n    }\r\n\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(frequency[i]%2 == 1)\r\n        {\r\n            cout << \"No\\n\";\r\n\r\n            return;\r\n        }\r\n    }\r\n\r\n    vector <pair <int, int> > swaps;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == T[i])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        for(int j = i + 1; j < length; j++)\r\n        {\r\n            if(S[j] == T[j])\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if(S[i] == T[j])\r\n            {\r\n                swap(S[j], T[j]);\r\n\r\n                swaps.push_back(make_pair(j, j));\r\n            }\r\n\r\n            if(S[i] == S[j])\r\n            {\r\n                swap(S[j], T[i]);\r\n\r\n                swaps.push_back(make_pair(j, i));\r\n\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"Yes\\n\";\r\n\r\n    cout << swaps.size() << \"\\n\";\r\n\r\n    for(int i = 0; i < swaps.size(); i++)\r\n    {\r\n        cout << swaps[i].first + 1 << \" \" << swaps[i].second + 1 << \"\\n\";\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 599/Programs/Maximum Square.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int max_length = 0;\r\n    for(int l = 1; l <= no_of_elements; l++)\r\n    {\r\n        int planks = 0;\r\n        for(int i = 1; i <= no_of_elements; i++)\r\n        {\r\n            planks += (A[i] >= l);\r\n        }\r\n\r\n        if(planks >= l)\r\n            max_length = max(max_length, l);\r\n    }\r\n\r\n    cout << max_length << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 599/Programs/Tile Painting.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid factorise(long long n, vector <long long> &F)\n{\n    for(long long i = 2; i*i <= n; i++)\n    {\n        if(n%i == 0)\n        {\n            F.push_back(i);\n\n            while(n%i == 0)\n            {\n                n /= i;\n            }\n        }\n    }\n\n    if(n > 1)\n    {\n        F.push_back(n);\n    }\n}\n\nint main()\n{\n    long long n;\n    cin >> n;\n\n    vector <long long> prime_divisors;\n    factorise(n, prime_divisors);\n\n    cout << (prime_divisors.size() > 1 || n == 1 ? 1 : prime_divisors[0]) << \"\\n\";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 600/Explanations/Antenna Coverage Explanation.txt.txt",
    "content": "Let f(i) be the minimum antennas needed to cover [0, i] \r\n\r\nFor each antenna, find the range [L, R] where it is active\r\n\r\nFor each antenna, calculate the cost of extending it to it's right so that it covers the point i. \r\n\r\nBe careful to only cover extensions to the right. \r\n\r\nWe could extend an antenna to it's left and add f(i - 1), but it is never optimal.\r\n\r\n------\r\n\r\n#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, range;\r\n    cin >> no_of_elements >> range;\r\n    \r\n    vector <pair <int, int> > A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        cin >> A[i].first >> A[i].second;\r\n    }\r\n    \r\n    vector <int> minimum_cost(range + 1);\r\n    for(int i = 0; i <= range; i++)\r\n    {\r\n        minimum_cost[i] = (i);\r\n        \r\n        for(int j = 0; j < no_of_elements; j++)\r\n        {\r\n            int left = max(0, A[j].first - A[j].second), right = min(range, A[j].first + A[j].second);\r\n            \r\n            if(left <= i && i <= right)\r\n            {\r\n                minimum_cost[i] = (i == 0 ? 0 : minimum_cost[i - 1]);\r\n                break;\r\n            }\r\n            \r\n            if(right < i)\r\n            {\r\n                int additional_cost = i - right;\r\n                int previous_antenna = max(0, left - additional_cost - 1);\r\n                \r\n                minimum_cost[i] = min(minimum_cost[i], additional_cost + minimum_cost[previous_antenna]);\r\n            }\r\n        }\r\n        \r\n    }\r\n    \r\n    cout << minimum_cost[range] << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 600/Explanations/Harmonious Graph Explanation.txt",
    "content": "1. Let us look at each Connected Component seperately. \r\n\r\n2. For each connected component, let us look at the minimum L and the maximum R. \r\n\r\n3. Now, we have x segments - [L, R]. \r\n\r\n4. We will sort these segments by their Left Borders and keep track of the right most point we have met so far. If L_i < R, then it means we need to make another connection. \r\n\r\n5. We have to update R = max(R, R_i) at every step. \r\n\r\nIf R is the rightmost point we have had so far and L_i < R, then it means L_i should be reachable from wherever we were able to reach R. \r\n\r\nThis is the reason we will make 1 connection per component where L_i < R. Now the entire component [L_i, R_i] is reachable to the current segment. \r\n\r\n------\r\n\r\nstruct component\r\n{\r\n    int minimum, maximum;\r\n\r\n    component()\r\n    {\r\n        minimum = oo, maximum = 0;\r\n    };\r\n\r\n    component(int Min, int Max)\r\n    {\r\n        minimum = Min, maximum = Max;\r\n    }\r\n};\r\n\r\nvoid dfs(int v, component &C)\r\n{\r\n    if(visited[v])\r\n    {\r\n        return;\r\n    }\r\n\r\n    visited[v] = true;\r\n\r\n    C.minimum = min(C.minimum, v);\r\n    C.maximum = max(C.maximum, v);\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        dfs(child, C);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    vector <component> components;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            component this_component;\r\n\r\n            dfs(i, this_component);\r\n\r\n            components.push_back(this_component);\r\n        }\r\n    }\r\n\r\n    //Components are already sorted by their Lefts\r\n\r\n    int right_most_point = 0;\r\n    int no_of_connections = 0;\r\n    for(int i = 0; i < components.size(); i++)\r\n    {\r\n        if(components[i].minimum < right_most_point)\r\n        {\r\n            no_of_connections++;\r\n        }\r\n\r\n        right_most_point = max(right_most_point, components[i].maximum);\r\n    }\r\n\r\n    cout << no_of_connections << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 600/Explanations/Silly Mistakes Explanation.txt",
    "content": "This problem has a lot of implementation. Let us maximise the number of partitions even though it is not required as it is the easiest thing to do. \r\n\r\nWe will keep track of the following things in segment [L, R] - \r\n\r\n1. The number of people in \r\n2. The state of the people there - (Entry/Exit)\r\n3. The exact people who made an appearance in the day - This is required to ensure that nobody enters, exits and then enters again on the same day. \r\n\r\nWe will end a day as soon as the number of people becomes 0. \r\nAt the end of the day, we will clear the vector containing the exact people who came in that day. \r\nThen, we will set the flag that indicates the list of people who came on that day to 0 again. \r\n\r\n(We need to do this. We can't set all the flags of everyone to 0 everyday as that would be O(n^2))\r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    const int MAX_N = 1e6 + 5;\r\n    int possible = true;\r\n\r\n    int no_of_people = 0;\r\n    vector <int> no_of_entries_today(MAX_N, 0);\r\n    vector <int> people_today;\r\n\r\n    vector <int> has_entered(1e6 + 5, 0);\r\n    vector <int> day_events;\r\n    for(int left = 1, right = 1; right <= no_of_elements; right++)\r\n    {\r\n        if(A[right] > 0)\r\n        {\r\n            has_entered[A[right]] = true;\r\n            no_of_people++;\r\n\r\n            people_today.push_back(A[right]);\r\n\r\n            no_of_entries_today[A[right]]++;\r\n\r\n            if(no_of_entries_today[A[right]] > 1)\r\n            {\r\n                possible = false;\r\n\r\n                break;\r\n            }\r\n        }\r\n        else if(A[right] < 0)\r\n        {\r\n            if(!has_entered[-A[right]])\r\n            {\r\n                possible = false;\r\n\r\n                break;\r\n            }\r\n\r\n            has_entered[-A[right]] = false;\r\n\r\n            no_of_people--;\r\n        }\r\n\r\n        if(no_of_people == 0)\r\n        {\r\n            day_events.push_back(right - (left - 1));\r\n\r\n            left = right + 1;\r\n\r\n            for(int p = 0; p < people_today.size(); p++)\r\n            {\r\n                no_of_entries_today[people_today[p]] = 0;\r\n            }\r\n\r\n            people_today.clear();\r\n        }\r\n    }\r\n\r\n    if(no_of_people > 0)\r\n    {\r\n        possible = false;\r\n    }\r\n\r\n    if(!possible)\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    cout << day_events.size() << \"\\n\";\r\n    for(int i = 0; i < day_events.size(); i++)\r\n    {\r\n        cout << day_events[i] << \" \";\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 600/Explanations/Single Push Explanation.txt",
    "content": "Let us keep track of the number of segments we have to change. \n\nLet (k[i] = B[i] - A[i])\n\nIf (k[i] != k[i - 1]), then it means that we must begin a new segment starting at i. \n\nAlso, A[0] = B[0] = 0 for convenience. \n\nWe also need to ensure that k is never negative. \n\n------\n\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    int segments = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] == B[i])\n        {\n            continue;\n        }\n\n        if(A[i] > B[i])\n        {\n            segments = 100000000;\n            break;\n        }\n\n        if(B[i] - A[i] != B[i - 1] - A[i - 1])\n        {\n            segments++;\n        }\n    }\n\n    cout << (segments > 1 ? \"No\\n\" : \"Yes\\n\");\n}\n"
  },
  {
    "path": "Contests/Div 2 600/Explanations/Sweets Eating Explanation.txt",
    "content": "Here is the strategy -\n\nIf we eat the first i sweets, we want to minimise the penalty against each sweet.\n\nSo, we will eat the sweets with the highest penalty first -\n\nWe will eat the sweets in descending order.\n\nNow, suppose f(i) is the penalty of eating the first i sweets.\n\nWe will eat sweets [i, i - k] on day 1.\n\nAll sweets [1, i - k - 1] will get pushed back by 1 day.\nThis means that the penalty against sweet j becomes (d + 1)*p(j) from d*p(j).\n\nThe total penalty increases by sum [i - k].\n\nSo, f(i) = (Sum[i] - Sum[i - k]) + f(i - k) + Sum[i - k]\n\nWe need to handle the base case of i <= k i.e. - When there is only one day seperately.\n\n\n------\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, max_per_day;\n    cin >> no_of_elements >> max_per_day;\n\n    vector <int> A(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    sort(all(A));\n\n    vector <long long> sum_till(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        sum_till[i] = sum_till[i - 1] + A[i];\n    }\n\n    vector <long long> penalty(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        long long day_1 = 0, remaining_days = 0;\n\n        if(i <= max_per_day)\n        {\n            day_1 = sum_till[i];\n        }\n        else\n        {\n            day_1 = sum_till[i] - sum_till[i - max_per_day];\n\n            remaining_days = penalty[i - max_per_day] + sum_till[i - max_per_day];\n        }\n\n        penalty[i] = day_1 + remaining_days;\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cout << penalty[i] << \" \";\n    }\n\n    return 0;\n}\n \n"
  },
  {
    "path": "Contests/Div 2 600/Programs/Antenna Coverage.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, range;\n    cin >> no_of_elements >> range;\n    \n    vector <pair <int, int> > A(no_of_elements);\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        cin >> A[i].first >> A[i].second;\n    }\n    \n    vector <int> minimum_cost(range + 1);\n    for(int i = 0; i <= range; i++)\n    {\n        minimum_cost[i] = (i);\n        \n        for(int j = 0; j < no_of_elements; j++)\n        {\n            int left = max(0, A[j].first - A[j].second), right = min(range, A[j].first + A[j].second);\n            \n            if(left <= i && i <= right)\n            {\n                minimum_cost[i] = (i == 0 ? 0 : minimum_cost[i - 1]);\n                break;\n            }\n            \n            if(right < i)\n            {\n                int additional_cost = i - right;\n                int previous_antenna = max(0, left - additional_cost - 1);\n                \n                minimum_cost[i] = min(minimum_cost[i], additional_cost + minimum_cost[previous_antenna]);\n            }\n        }\n        \n    }\n    \n    cout << minimum_cost[range] << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 600/Programs/Harmonious Graph.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 5, oo = 1e9;\r\nvector <int> graph[MAX_N];\r\nvector <int> visited(MAX_N, false);\r\n\r\nstruct component\r\n{\r\n    int minimum, maximum;\r\n\r\n    component()\r\n    {\r\n        minimum = oo, maximum = 0;\r\n    };\r\n\r\n    component(int Min, int Max)\r\n    {\r\n        minimum = Min, maximum = Max;\r\n    }\r\n};\r\n\r\nvoid dfs(int v, component &C)\r\n{\r\n    if(visited[v])\r\n    {\r\n        return;\r\n    }\r\n\r\n    visited[v] = true;\r\n\r\n    C.minimum = min(C.minimum, v);\r\n    C.maximum = max(C.maximum, v);\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        dfs(child, C);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    cin >> no_of_vertices >> no_of_edges;\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        cin >> u >> v;\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    vector <component> components;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            component this_component;\r\n\r\n            dfs(i, this_component);\r\n\r\n            components.push_back(this_component);\r\n        }\r\n    }\r\n\r\n    //Components are already sorted by their Lefts\r\n\r\n    int right_most_point = 0;\r\n    int no_of_connections = 0;\r\n    for(int i = 0; i < components.size(); i++)\r\n    {\r\n        if(components[i].minimum < right_most_point)\r\n        {\r\n            no_of_connections++;\r\n        }\r\n\r\n        right_most_point = max(right_most_point, components[i].maximum);\r\n    }\r\n\r\n    cout << no_of_connections << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 600/Programs/Silly Mistakes.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    const int MAX_N = 1e6 + 5;\r\n    int possible = true;\r\n\r\n    int no_of_people = 0;\r\n    vector <int> no_of_entries_today(MAX_N, 0);\r\n    vector <int> people_today;\r\n\r\n    vector <int> has_entered(1e6 + 5, 0);\r\n    vector <int> day_events;\r\n    for(int left = 1, right = 1; right <= no_of_elements; right++)\r\n    {\r\n        if(A[right] > 0)\r\n        {\r\n            has_entered[A[right]] = true;\r\n            no_of_people++;\r\n\r\n            people_today.push_back(A[right]);\r\n\r\n            no_of_entries_today[A[right]]++;\r\n\r\n            if(no_of_entries_today[A[right]] > 1)\r\n            {\r\n                possible = false;\r\n\r\n                break;\r\n            }\r\n        }\r\n        else if(A[right] < 0)\r\n        {\r\n            if(!has_entered[-A[right]])\r\n            {\r\n                possible = false;\r\n\r\n                break;\r\n            }\r\n\r\n            has_entered[-A[right]] = false;\r\n\r\n            no_of_people--;\r\n        }\r\n\r\n        if(no_of_people == 0)\r\n        {\r\n            day_events.push_back(right - (left - 1));\r\n\r\n            left = right + 1;\r\n\r\n            for(int p = 0; p < people_today.size(); p++)\r\n            {\r\n                no_of_entries_today[people_today[p]] = 0;\r\n            }\r\n\r\n            people_today.clear();\r\n        }\r\n    }\r\n\r\n    if(no_of_people > 0)\r\n    {\r\n        possible = false;\r\n    }\r\n\r\n    if(!possible)\r\n    {\r\n        cout << \"-1\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    cout << day_events.size() << \"\\n\";\r\n    for(int i = 0; i < day_events.size(); i++)\r\n    {\r\n        cout << day_events[i] << \" \";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 600/Programs/Single Push.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> B(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> B[i];\n    }\n\n    int segments = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] == B[i])\n        {\n            continue;\n        }\n\n        if(A[i] > B[i])\n        {\n            segments = 100;\n            break;\n        }\n\n        if(B[i] - A[i] != B[i - 1] - A[i - 1])\n        {\n            segments++;\n        }\n    }\n\n    cout << (segments > 1 ? \"No\\n\" : \"Yes\\n\");\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 600/Programs/Sweets Eating.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, max_per_day;\r\n    cin >> no_of_elements >> max_per_day;\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    sort(all(A));\r\n\r\n    vector <long long> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i] = sum_till[i - 1] + A[i];\r\n    }\r\n\r\n    vector <long long> penalty(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long day_1 = 0, remaining_days = 0;\r\n        \r\n        if(i <= max_per_day)\r\n        {\r\n            day_1 = sum_till[i];\r\n        }\r\n        else\r\n        {\r\n            day_1 = sum_till[i] - sum_till[i - max_per_day];\r\n            \r\n            remaining_days = penalty[i - max_per_day] + sum_till[i - max_per_day];\r\n        }\r\n        \r\n        penalty[i] = day_1 + remaining_days;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << penalty[i] << \" \";\r\n    }\r\n\r\n    return 0;\r\n}\r\n \r\n"
  },
  {
    "path": "Contests/Div 2 608/Programs/Shwarma Tent.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint max_3(int a, int b, int c)\n{\n    return max(a, max(b, c));\n}\n\nint main()\n{\n    const int oo = 1e9;\n    \n    int no_of_students, school_x, school_y;\n    cin >> no_of_students >> school_x >> school_y;\n    \n    vector <int> X(no_of_students + 1);\n    vector <int> Y(no_of_students + 1);\n    \n    int up = 0, right = 0, down = 0, left = 0;\n    for(int i = 1; i <= no_of_students; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n        \n        up += (y > school_y);\n        down += (y < school_y);\n        left += (x < school_x);\n        right += (x > school_x);\n    }\n    \n    if(up >= max_3(left, right, down))\n    {\n        cout << up << \"\\n\";\n        cout << school_x << \" \" << school_y + 1 << \"\\n\";\n    }\n    else if(left >= max_3(up, down, right))\n    {\n        cout << left << \"\\n\";\n        cout << school_x - 1 << \" \" << school_y << \"\\n\";\n    }\n    else if(right >= max_3(up, down, left))\n    {\n        cout << right << \"\\n\";\n        cout << school_x + 1 << \" \" << school_y << \"\\n\";\n    }\n    else if(down >= max_3(left, right, up))\n    {\n        cout << down << \"\\n\";\n        cout << school_x << \" \" << school_y - 1 << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 85/Explanation/Petya and Divisors Explanation.txt",
    "content": "The main insight of this question is to use an array,\n\nlast_index_multiple(d) = i, \n\nif the index of the last multiple of d is i. \n\nI remember a similar idea used where I had to find the lexicographically smallest array such that it was all pairwise coprime. \n\nEven there, the idea was to factorise and check if it was used. \n\nHere we take in every number n, factorise it. And check if the last index of any factor is >= i - y. If yes, then we don't count it. Else we do.\n\n---------------------------------------------------\n\n#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_queries;\n    scanf(\"%d\", &no_of_queries);\n\n    const int MAX_N = 1e5 + 15;\n    vector <int> last_multiple_index(MAX_N, 0);\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int number, y;\n        scanf(\"%d %d\", &number, &y);\n\n        int last_index = i - y;\n        int divisors = 0, bad_divisors = 0;\n\n        for(int d = 1; d*d <= number; d++)\n        {\n            if(number%d == 0)\n            {\n                divisors += (d*d == number ? 1 : 2);\n\n                if(last_multiple_index[d] >= last_index)\n                {\n                    bad_divisors++;\n                }\n\n                if(d*d != number && last_multiple_index[number/d] >= last_index)\n                {\n                    bad_divisors++;\n                }\n\n                last_multiple_index[d] = last_multiple_index[number/d] = i;\n            }\n        }\n\n        int good_divisors = divisors - bad_divisors;\n\n        printf(\"%d\\n\", good_divisors);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 85/Explanation/Petya and Inequiations Explanation.txt",
    "content": "\r\nTry to find the maximum value of the sum of squares - \r\n\r\nTurns out this happens when all the elements except one = 1, and the last element = Y - (n - 1)\r\n\r\nLet us say there is another arrangement where we have at most (n - 2) ones. I will show that you can always do better by making it (n - 1) 1's \r\n\r\nChoose the largest and second largest element - Let it be a and b. Without loss of generality, a < b, and a > b > 1\r\n\r\nSum of squares = a^2 + b^2 = X\r\n\r\nNow, let us make the two numbers 1, (b + a - 1)\r\n\r\nKeeping the sum invariant.\r\n\r\nLet us examine the sum of squares now\r\n\r\n1^2 + (b + a - 1)^2\r\n\r\n= 1 + a^2 + b^2 + 1 - 2a - 2b + 2ab\r\n\r\n= (a^2 + b^2) + 2(1 + ab - a - b)\r\n\r\n= X + 2( 1  + ab - a - b)\r\n\r\nNow, all I have to do is show that (1 + ab - a - b) is positive\r\n\r\nWhen a and b are two positive integers > 1, their product is always greater than their sum.\r\n\r\nxy - x - y + 1 = x(y - 1) - y + 1 = (x - 1)(y - 1), both terms are positive, so (x - 1)(y - 1) > 0\r\n\r\nThis completes the proof ---------\r\n\r\nNow, get the maximum possible sum of squares for a given sum = 1^2 + 1^2 + ... + (Y - (N - 1))^2\r\n\r\nTest cases I missed - What happens when N > Y.\r\n\r\n--------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, sum_limit;\r\n    long long square_sum_lower_bound;\r\n    scanf(\"%d %I64d %d\", &n, &square_sum_lower_bound, &sum_limit);\r\n\r\n    long long largest_element = sum_limit - (n - 1);\r\n    long long max_square_sum = (n - 1) + largest_element*largest_element;\r\n\r\n    if(max_square_sum < square_sum_lower_bound || n > sum_limit)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n        printf(\"%I64d\\n\", (i == n ? largest_element : 1));\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 2 85/Explanation/Petya and Strings Explanation.txt",
    "content": "Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. \r\nNow Petya wants to compare those two strings lexicographically. The letters' case does not matter, \r\nthat is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.\r\n\r\n-------------------------------------------------------\r\n\r\nMaybe if I had more time, I would make both strings lower character and then use strcmp so that there's no abrupt end ... But I wanted to finish this as soon as possible.\r\n\r\n#define tolower(c) (c < 'a' ? (c + 'a' - 'A') : c)\r\n\r\nint main()\r\n{\r\n    char string_1[MAX_LENGTH], string_2[MAX_LENGTH];\r\n    scanf(\"%s %s\", string_1, string_2);\r\n\r\n    for(int i = 0; string_1[i] != '\\0'; i++)\r\n    {\r\n        if(tolower(string_1[i]) > tolower(string_2[i]) )\r\n        {\r\n            printf(\"1\\n\");\r\n            return 0;\r\n        }\r\n        else if(tolower(string_1[i]) < tolower(string_2[i]) )\r\n        {\r\n            printf(\"-1\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    printf(\"0\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 2 85/Programs/Petya and Divisors.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_queries;\n    scanf(\"%d\", &no_of_queries);\n\n    const int MAX_N = 1e5 + 15;\n    vector <int> last_multiple_index(MAX_N, 0);\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int number, y;\n        scanf(\"%d %d\", &number, &y);\n\n        int last_index = i - y;\n        int divisors = 0, bad_divisors = 0;\n\n        for(int d = 1; d*d <= number; d++)\n        {\n            if(number%d == 0)\n            {\n                divisors += (d*d == number ? 1 : 2);\n\n                if(last_multiple_index[d] >= last_index)\n                {\n                    bad_divisors++;\n                }\n\n                if(d*d != number && last_multiple_index[number/d] >= last_index)\n                {\n                    bad_divisors++;\n                }\n\n                last_multiple_index[d] = last_multiple_index[number/d] = i;\n            }\n        }\n\n        int good_divisors = divisors - bad_divisors;\n\n        printf(\"%d\\n\", good_divisors);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 2 85/Programs/Petya and Inequiations.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, sum_limit;\r\n    long long square_sum_lower_bound;\r\n    scanf(\"%d %I64d %d\", &n, &square_sum_lower_bound, &sum_limit);\r\n\r\n    long long largest_element = sum_limit - (n - 1);\r\n    long long max_square_sum = (n - 1) + largest_element*largest_element;\r\n\r\n    if(max_square_sum < square_sum_lower_bound || n > sum_limit)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n        printf(\"%I64d\\n\", (i == n ? largest_element : 1));\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 2 85/Programs/Petya and Strings.cpp",
    "content": "#include <cstdio>\r\n#include <string.h>\r\n\r\n#define MAX_LENGTH 100 + 1\r\n#define tolower(c) (c < 'a' ? (c + 'a' - 'A') : c)\r\n\r\nint main()\r\n{\r\n    char string_1[MAX_LENGTH], string_2[MAX_LENGTH];\r\n    scanf(\"%s %s\", string_1, string_2);\r\n\r\n    for(int i = 0; string_1[i] != '\\0'; i++)\r\n    {\r\n        if(tolower(string_1[i]) > tolower(string_2[i]) )\r\n        {\r\n            printf(\"1\\n\");\r\n            return 0;\r\n        }\r\n        else if(tolower(string_1[i]) < tolower(string_2[i]) )\r\n        {\r\n            printf(\"-1\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    printf(\"0\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Consecutive Subsequences Explanation.txt",
    "content": "Let f(A[i]) denote the longest sequence ending at A[i]. \r\n\r\nNow, A[i] is appended to the sequence ending at A[i] - 1\r\n\r\nSo, f(A[i]) = 1 + f(A[i] - 1)\r\n\r\nAs n is large use maps. Don't use unordered maps as unordered maps have worst case complexity O(n) so the algorithm degrades to O(n^2) and causes TLE.\r\n\r\n------------------------------\r\n\r\nI've solved two problems seperately. First, find the longest sequence length and the last element. \r\n\r\nThen collect the indices. \r\n\r\nIf I know the longest sequence has length L, and last element X\r\n\r\nThen I need to store the index of (X - L + 1) (X - L + 2) ... (X -1) (X)\r\n\r\nAt first the index list is empty. I store the index of element (X - L + 1). Then, after that store the index of i, where\r\nA[i] = A[index.back()] + 1\r\n\r\nBecause we know that i must be the index of the element that is one more than the last element in the list.\r\n\r\n----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int last_element, longest_sequence = 0;\r\n\r\n    map <int, int> answer_with_last_element;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n       answer_with_last_element[A[i]] = 1 + answer_with_last_element[A[i] - 1];\r\n\r\n\r\n        if(answer_with_last_element[A[i]] > longest_sequence)\r\n        {\r\n            longest_sequence = answer_with_last_element[A[i]];\r\n            last_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <int> index;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(index.size() == 0)\r\n        {\r\n            if(A[i] == last_element - longest_sequence + 1)\r\n                index.push_back(i);\r\n        }\r\n        else if(A[i] == A[index.back()] + 1)\r\n        {\r\n            index.push_back(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_sequence);\r\n    for(int i = 0; i < longest_sequence; i++) printf(\"%d \", index[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Cyclic Components Explanation.txt",
    "content": "Store each component in a seperate vector. \r\n\r\nIn the contest, I used a more complicated solution. But there's an easier solution with an observation - \r\n\r\nA component is a cycle if each vertex has degree 2. \r\n\r\nThis can be proven through induction. \r\n\r\n---------------------------------------------------------\r\n\r\nvoid dfs_and_mark_component(int v, int no)\r\n{\r\n    component[no].push_back(v);\r\n    component_no[v] = no;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(component_no[child] == UNMARKED)\r\n            dfs_and_mark_component(child, no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    memset(component_no, UNMARKED, sizeof(component_no));\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(component_no[i] == UNMARKED)\r\n            dfs_and_mark_component(i, no_of_components++);\r\n    }\r\n\r\n    int no_of_cycles = 0;\r\n\r\n    for(int i = 0; i < no_of_components; i++)\r\n    {\r\n        int is_cycle = true;\r\n\r\n        for(int j = 0; j < component[i].size(); j++)\r\n        {\r\n            int v = component[i][j];\r\n\r\n            if(graph[v].size() != 2)\r\n            {\r\n                is_cycle = false;\r\n            }\r\n        }\r\n\r\n        no_of_cycles += (is_cycle == true);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_cycles);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Divide by Three Multiply by Two Alternate Solution Explanation.txt",
    "content": "http://qr.ae/TUTyWZ\r\n\r\nFor any x, we cannot have both (2x and x/3) in the array. \r\n\r\nThis is because from x, we can go either to 2x or to x/3. \r\n\r\nIf we go to 2x, we can never reach x/3 as we can never divide by 2. \r\nSimilar reasoning for x/3. \r\n\r\nFor any element A[i], the chain from A[i] is uniquely determined. \r\n\r\nAll we need to do is find the first element. \r\n\r\nThis is the element x, for which x/2 and 3x are both absent from the array. \r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    map <ULL, int> present;\r\n    vector <ULL> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64u\", &A[i]);\r\n        present[A[i]] = true;\r\n    }\r\n\r\n    ULL first_element;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int comes_from_multiplication = (A[i]%2 == 0 && present[A[i]/2]);\r\n        int comes_from_division = (A[i] <= 1e18 && present[3*A[i]]);\r\n\r\n        if(!comes_from_multiplication && !comes_from_division)\r\n        {\r\n            first_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <ULL> solution;\r\n    solution.push_back(first_element);\r\n    while(solution.size() < no_of_elements)\r\n    {\r\n        ULL last_element = solution.back();\r\n        if(last_element%3 == 0 && present[last_element/3])\r\n        {\r\n               solution.push_back(last_element/3);\r\n        }\r\n        else\r\n        {\r\n            solution.push_back(2*last_element);\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", solution[i]);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Divide by Three, Multiply by Two Explanation.txt",
    "content": "http://qr.ae/TUTyWZ\r\n\r\nNotice that Exp(3) only decreases from left to right. \r\n\r\nExp(2) only increases. \r\n\r\n-Exp(3) only increases. \r\n\r\nThis means Exp(2) - Exp(3) increases from left to right. \r\n\r\nIn going from one element to another, only one of these values changes by 1. \r\n\r\nSO, the quantity Exp(2) - Exp(3) is a monotonic and increases by 1 for each element. \r\n\r\nThe beautiful solution is to simply sort the array according to (Exp(2) - Exp(3))\r\n\r\n-------------------------------------\r\n\r\nstruct info\r\n{\r\n    int two, three;\r\n    unsigned long long number;\r\n};\r\n\r\nint compare(const info &A, const info &B)\r\n{\r\n    if(A.two - A.three < B.two - B.three)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <info> A(no_of_elements);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        unsigned long long element;\r\n        scanf(\"%I64u\", &element);\r\n\r\n        A[i].number = element;\r\n        A[i].two = 0, A[i].three = 0;\r\n\r\n        while(element%2 == 0) A[i].two++, element /= 2;\r\n        while(element%3 == 0) A[i].three++, element /= 3;\r\n    }\r\n\r\n    sort(all(A), compare);\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", A[i].number);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Less or Equal Explanation.txt",
    "content": "Let us sort the array. \r\n\r\nThe question is asking for any number in the range [A[k], A[k + 1] - 1]\r\n\r\nThis is not possible when A[k] = A[k + 1]\r\n\r\nOtherwise, just output A[k]\r\n\r\nThe special case is k = 0, when we must output a number smaller than all the elements of the array.\r\n\r\nIf A[1] = 1, then we cannot output any number as we must output a number that is at least 1. \r\nElse, we simply output 1.\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, position;\r\n    scanf(\"%d %d\", &no_of_elements, &position);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int answer;\r\n    if(position == 0)\r\n    {\r\n        answer = (A[1] > 1 ? 1 : -1);\r\n    }\r\n    else\r\n    {\r\n        answer = (position < no_of_elements && A[position] == A[position + 1] ? -1 : A[position]);\r\n    }\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Two Gram Explanation.txt",
    "content": "There are only (n - 1) two-grams. \r\n\r\nKeep track of the frequency of each two-gram. \r\n\r\nThe most frequent two-gram is the answer.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    map <string, int> frequency;\r\n    int max_frequency = 0;\r\n    string answer;\r\n\r\n    for(int i = 0; i + 1 < length; i++)\r\n    {\r\n        string two_gram = S.substr(i, 2);\r\n        frequency[two_gram]++;\r\n\r\n        if(frequency[two_gram] > max_frequency)\r\n            max_frequency = frequency[two_gram], answer = two_gram;\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 479/Explanations/Wrong Subtraction Explanation.txt",
    "content": "\nThe process is simple enough to simulate. \n\n----------------------------------\n\n#include <cstdio>\n\nint main()\n{\n    int n, no_of_operations;\n    scanf(\"%d %d\", &n, &no_of_operations);\n\n    while(no_of_operations--)\n    {\n        n = (n%10 == 0 ? n/10 : n - 1);\n    }\n\n    printf(\"%d\\n\", n);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Consecutive Subsequences.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int last_element, longest_sequence = 0;\r\n\r\n    map <int, int> answer_with_last_element;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer_with_last_element[A[i]] = 1 + answer_with_last_element[A[i] - 1];\r\n\r\n        if(answer_with_last_element[A[i]] > longest_sequence)\r\n        {\r\n            longest_sequence = answer_with_last_element[A[i]];\r\n            last_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <int> index;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(index.size() == 0)\r\n        {\r\n            if(A[i] == last_element - longest_sequence + 1)\r\n                index.push_back(i);\r\n        }\r\n        else if(A[i] == A[index.back()] + 1)\r\n        {\r\n            index.push_back(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_sequence);\r\n    for(int i = 0; i < longest_sequence; i++) printf(\"%d \", index[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Cyclic Components.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <cstring>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 15, UNMARKED = -1;\r\nvector <int> graph[MAX_N];\r\nvector <int> component[MAX_N];\r\nint component_no[MAX_N];\r\n\r\nvoid dfs_and_mark_component(int v, int no)\r\n{\r\n    component[no].push_back(v);\r\n    component_no[v] = no;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(component_no[child] == UNMARKED)\r\n            dfs_and_mark_component(child, no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    memset(component_no, UNMARKED, sizeof(component_no));\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(component_no[i] == UNMARKED)\r\n            dfs_and_mark_component(i, no_of_components++);\r\n    }\r\n\r\n    int no_of_cycles = 0;\r\n\r\n    for(int i = 0; i < no_of_components; i++)\r\n    {\r\n        int is_cycle = true;\r\n\r\n        for(int j = 0; j < component[i].size(); j++)\r\n        {\r\n            int v = component[i][j];\r\n\r\n            if(graph[v].size() != 2)\r\n            {\r\n                is_cycle = false;\r\n            }\r\n        }\r\n\r\n        no_of_cycles += (is_cycle == true);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_cycles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Divide by Three, Multiply by Two Alternate Solution.cpp",
    "content": "#include <cstdio>\r\n#include <map>\r\n#include <vector>\r\n\r\ntypedef unsigned long long ULL;\r\nusing namespace std;\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    map <ULL, int> present;\r\n    vector <ULL> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64u\", &A[i]);\r\n        present[A[i]] = true;\r\n    }\r\n\r\n    ULL first_element;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int comes_from_multiplication = (A[i]%2 == 0 && present[A[i]/2]);\r\n        int comes_from_division = (A[i] <= 1e18 && present[3*A[i]]);\r\n\r\n        if(!comes_from_multiplication && !comes_from_division)\r\n        {\r\n            first_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <ULL> solution;\r\n    solution.push_back(first_element);\r\n    while(solution.size() < no_of_elements)\r\n    {\r\n        ULL last_element = solution.back();\r\n        if(last_element%3 == 0 && present[last_element/3])\r\n        {\r\n               solution.push_back(last_element/3);\r\n        }\r\n        else\r\n        {\r\n            solution.push_back(2*last_element);\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", solution[i]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Divide by Three, Multiply by Two.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct info\r\n{\r\n    int two, three;\r\n    unsigned long long number;\r\n};\r\n\r\nint compare(const info &A, const info &B)\r\n{\r\n    if(A.two - A.three < B.two - B.three)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <info> A(no_of_elements);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        unsigned long long element;\r\n        scanf(\"%I64u\", &element);\r\n\r\n        A[i].number = element;\r\n        A[i].two = 0, A[i].three = 0;\r\n\r\n        while(element%2 == 0) A[i].two++, element /= 2;\r\n        while(element%3 == 0) A[i].three++, element /= 3;\r\n    }\r\n\r\n    sort(all(A), compare);\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", A[i].number);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Less or Equal.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <set>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, position;\r\n    scanf(\"%d %d\", &no_of_elements, &position);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int answer;\r\n    if(position == 0)\r\n    {\r\n        answer = (A[1] > 1 ? 1 : -1);\r\n    }\r\n    else\r\n    {\r\n        answer = (position < no_of_elements && A[position] == A[position + 1] ? -1 : A[position]);\r\n    }\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Two Gram.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    map <string, int> frequency;\r\n    int max_frequency = 0;\r\n    string answer;\r\n\r\n    for(int i = 0; i + 1 < length; i++)\r\n    {\r\n        string two_gram = S.substr(i, 2);\r\n        frequency[two_gram]++;\r\n\r\n        if(frequency[two_gram] > max_frequency)\r\n            max_frequency = frequency[two_gram], answer = two_gram;\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 479/Programs/Wrong Subtraction.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    int n, no_of_operations;\n    scanf(\"%d %d\", &n, &no_of_operations);\n\n    while(no_of_operations--)\n    {\n        n = (n%10 == 0 ? n/10 : n - 1);\n    }\n\n    printf(\"%d\\n\", n);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 481/Explanations/Almost Arithmetic Progression Explanation.txt",
    "content": "Any AP is uniquely determined by it's first two elements. \r\n\r\nLet us check all possible first two elements\r\n\r\nA[0] +/- 1 \r\nA[1] +/- 1\r\n\r\nFor each of the 9 possible first two terms, check if an AP with that difference is possible with only adding or subtracting one to each element. \r\n\r\nIf it's possible, then |term1 + k*d - A[k]| <= 1\r\n\r\nIf it is greater then it is not possible. \r\n\r\nIf |term1 + k*d - A[k]| = 1, no of operations++\r\n\r\nKeep track of the total no of operations and minimum total in all 9 configurations.\r\n\r\nIn my program, if it's not possible, I set the number of operations to oo.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    const int oo = 1e7;\r\n    int add[3] = {-1, 0, 1}, min_operations = oo;\r\n\r\n    for(int i = 0; i < 3; i++)\r\n    {\r\n        int term_1 = A[0] + add[i];\r\n\r\n        for(int j = 0; j < 3; j++)\r\n        {\r\n            int term_2 = A[1] + add[j];\r\n\r\n            int difference = term_2 - term_1;\r\n\r\n            int no_of_operations = (term_1 != A[0]) + (term_2 != A[1]);\r\n\r\n            for(int k = 2; k < no_of_elements; k++)\r\n            {\r\n                if(abs(term_1 + k*difference - A[k]) == 1)\r\n                {\r\n                    no_of_operations++;\r\n                }\r\n                else if(abs(term_1 + k*difference - A[k]) > 1)\r\n                {\r\n                    no_of_operations = oo;\r\n                }\r\n            }\r\n\r\n            min_operations = min(min_operations, no_of_operations);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", min_operations >= oo ? -1 : min_operations);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 481/Explanations/File Name Explanation.txt",
    "content": "For every character i, check if the previous two characters were x, if it was, then remove it. \r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int removable_characters = 0;\r\n    for(int i = 2; i < length; i++)\r\n       removable_characters += (S[i] == 'x' && S[i - 1] == 'x' && S[i - 2] == 'x');\r\n\r\n    cout << removable_characters;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 481/Explanations/Letters Explanation.txt",
    "content": "Maintain a prefix sum array of the array. \r\n\r\nThen do binary search to find the first i, such that S[i] >= x and S[i - 1] < x\r\n\r\ni is the dorm no\r\nAnd x - S[i - 1] is the room no\r\n\r\nI used upper bound here quite clearly. upper bound(x) returns the first element which is GREATER than x. So upper bound(x - 1) does the trick quite nicely !\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    vector <long long > sum_till(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64d\", &A[i]);\r\n        sum_till[i] = sum_till[i - 1] + A[i];\r\n    }\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        long long x;\r\n        scanf(\"%I64d\", &x);\r\n\r\n        int dorm_no = upper_bound(all(sum_till), x - 1) - sum_till.begin();\r\n        long long room_no = x - sum_till[dorm_no - 1];\r\n\r\n        printf(\"%d %I64d\\n\", dorm_no, room_no);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 481/Explanations/Mentors Explanation.txt",
    "content": "Here's what you do. SOrt the skills. The no of juniors = no of people less skilled. This can be gotten with binary search. \n\nThen read in the pairs of quarrels one by one. \n\nIf Skill[x] > Skill[y], then juniors[x]--\nAnd vice versa. \n\nAt the end, simply print the juniors.\n\n-----------------------------------------------\n\nint main()\n{\n    int no_of_programmers, no_of_pairs;\n    scanf(\"%d %d\", &no_of_programmers, &no_of_pairs);\n\n    vector <int> skill(no_of_programmers + 1, 0);\n    for(int i = 1; i <= no_of_programmers; i++)\n        scanf(\"%d\", &skill[i]);\n\n    vector <int> sorted_skill(no_of_programmers + 1, 0);\n    for(int i = 1; i <= no_of_programmers; i++) sorted_skill[i] = skill[i];\n\n    sort(all(sorted_skill));\n\n    vector <int> no_of_juniors(no_of_programmers + 1);\n    for(int i = 1; i <= no_of_programmers; i++)\n    {\n        no_of_juniors[i] = upper_bound(all(sorted_skill), skill[i] - 1) - sorted_skill.begin() - 1;\n    }\n\n    for(int i = 1; i <= no_of_pairs; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        if(skill[u] > skill[v])\n        {\n            no_of_juniors[u]--;\n        }\n        else if(skill[v] - skill[u])\n        {\n            no_of_juniors[v]--;\n        }\n    }\n\n    for(int i = 1; i <= no_of_programmers; i++) printf(\"%d \", no_of_juniors[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 481/Explanations/Remove Duplicates Explanation.txt",
    "content": "Read the integers right to left and keep track of what has been used so far. \r\n\r\nPut that into the solution and then print the solution in reverse. \r\n\r\n----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    const int MAX = 1015;\r\n    vector <int> used(MAX, false);\r\n    vector <int> ans;\r\n\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        if(!used[A[i]])\r\n        {\r\n            used[A[i]] = true;\r\n            ans.push_back(A[i]);\r\n        }\r\n    }\r\n\r\n    reverse(all(ans));\r\n\r\n    printf(\"%d\\n\", ans.size());\r\n    for(int i = 0; i < ans.size(); i++) printf(\"%d \", ans[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 481/Programs/Almost Arithmetic Progression.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    const int oo = 1e7;\r\n    int add[3] = {-1, 0, 1}, min_operations = oo;\r\n\r\n    for(int i = 0; i < 3; i++)\r\n    {\r\n        int term_1 = A[0] + add[i];\r\n\r\n        for(int j = 0; j < 3; j++)\r\n        {\r\n            int term_2 = A[1] + add[j];\r\n\r\n            int difference = term_2 - term_1;\r\n\r\n            int no_of_operations = (term_1 != A[0]) + (term_2 != A[1]);\r\n\r\n            for(int k = 2; k < no_of_elements; k++)\r\n            {\r\n                if(abs(term_1 + k*difference - A[k]) == 1)\r\n                {\r\n                    no_of_operations++;\r\n                }\r\n                else if(abs(term_1 + k*difference - A[k]) > 1)\r\n                {\r\n                    no_of_operations = oo;\r\n                }\r\n            }\r\n\r\n            min_operations = min(min_operations, no_of_operations);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", min_operations >= oo ? -1 : min_operations);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 481/Programs/File Name.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int removable_characters = 0;\r\n    for(int i = 2; i < length; i++)\r\n       removable_characters += (S[i] == 'x' && S[i - 1] == 'x' && S[i - 2] == 'x');\r\n\r\n    cout << removable_characters;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 481/Programs/Letters.cpp",
    "content": "#include <vector>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    vector <long long > sum_till(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64d\", &A[i]);\r\n        sum_till[i] = sum_till[i - 1] + A[i];\r\n    }\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        long long x;\r\n        scanf(\"%I64d\", &x);\r\n\r\n        int dorm_no = upper_bound(all(sum_till), x - 1) - sum_till.begin();\r\n        long long room_no = x - sum_till[dorm_no - 1];\r\n\r\n        printf(\"%d %I64d\\n\", dorm_no, room_no);\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 481/Programs/Mentors.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_programmers, no_of_pairs;\n    scanf(\"%d %d\", &no_of_programmers, &no_of_pairs);\n\n    vector <int> skill(no_of_programmers + 1, 0);\n    for(int i = 1; i <= no_of_programmers; i++)\n        scanf(\"%d\", &skill[i]);\n\n    vector <int> sorted_skill(no_of_programmers + 1, 0);\n    for(int i = 1; i <= no_of_programmers; i++) sorted_skill[i] = skill[i];\n\n    sort(all(sorted_skill));\n\n    vector <int> no_of_juniors(no_of_programmers + 1);\n    for(int i = 1; i <= no_of_programmers; i++)\n    {\n        no_of_juniors[i] = upper_bound(all(sorted_skill), skill[i] - 1) - sorted_skill.begin() - 1;\n    }\n\n    for(int i = 1; i <= no_of_pairs; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        if(skill[u] > skill[v])\n        {\n            no_of_juniors[u]--;\n        }\n        else if(skill[v] - skill[u])\n        {\n            no_of_juniors[v]--;\n        }\n    }\n\n    for(int i = 1; i <= no_of_programmers; i++) printf(\"%d \", no_of_juniors[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 481/Programs/Remove Duplicates.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <set>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    const int MAX = 1015;\r\n    vector <int> used(MAX, false);\r\n    vector <int> ans;\r\n\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        if(!used[A[i]])\r\n        {\r\n            used[A[i]] = true;\r\n            ans.push_back(A[i]);\r\n        }\r\n    }\r\n\r\n    reverse(all(ans));\r\n\r\n    printf(\"%d\\n\", ans.size());\r\n    for(int i = 0; i < ans.size(); i++) printf(\"%d \", ans[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 486/Explanation/Diverse Team Explanation.txt",
    "content": "It's pretty simple. Keep track of distinct ratings and compare it with the required team size. \r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_students, team_size;\r\n    scanf(\"%d %d\", &no_of_students, &team_size);\r\n\r\n    const int MAX_RATING = 115;\r\n    vector <int> team;\r\n    vector <int> rating_used(MAX_RATING, false);\r\n\r\n    for(int i = 1; i <= no_of_students; i++)\r\n    {\r\n        int rating_i;\r\n        scanf(\"%d\", &rating_i);\r\n\r\n        if(!rating_used[rating_i])\r\n            team.push_back(i);\r\n\r\n        rating_used[rating_i] = true;\r\n    }\r\n\r\n    if(team.size() >= team_size)\r\n    {\r\n        printf(\"YES\\n\");\r\n        for(int i = 0; i < team_size; i++)\r\n            printf(\"%d \", team[i]);\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 486/Explanation/Divisibility by 25 Explanation.txt",
    "content": "Check if it's possible to get all four suffixes. \n\nNow, whether it is possible to get a given suffix can be done in better time complexity but it will cost more complexity in the code. \n\nHere's what I did - \n\n1. Iterate over every pair of digits and simulate making this pair the last two digits. \n\n2. Check if the first digit is 0. If so, keep swapping it till the first digit becomes non-zero. \n\n3. If the last two digits are the suffix we desire, then keep track of the number of moves we have used. We want the minimum number. \n\n----\n\nint min_moves_for_suffix(string S, string suffix)\n{\n    int moves = oo;\n\n    for(int first = 0; first < S.size(); first++)\n    {\n        for(int second = 0; second < S.size(); second++)\n        {\n            if(first == second)\n                continue;\n\n            string N = S;\n            int moves_here = 0;\n\n            for(int i = first; i < N.size() - 1.; i++)\n            {\n                swap(N[i], N[i + 1]);\n                moves_here++;\n            }\n\n            //Second may have been disturbed by first\n            for(int i = second - (second > first); i < N.size() - 2; i++)\n            {\n                swap(N[i], N[i + 1]);\n                moves_here++;\n            }\n\n            int first_non_zero = 0;\n            while(N[first_non_zero] == '0')\n                first_non_zero++;\n\n            for(int i = first_non_zero; i > 0; i--)\n            {\n                swap(N[i], N[i - 1]);\n                moves_here++;\n            }\n\n            if(N[N.size() - 2] == suffix[0] && N[N.size() - 1] == suffix[1])\n                moves = min(moves, moves_here);\n        }\n    }\n\n    return moves;\n}\n\n-----------------------\n\nNow for a number to be a multiple of 25, it must have 1 of 4 suffixes.\n\nint main()\n{\n    string N;\n    cin >> N;\n\n    int minimum_moves = oo;\n\n    minimum_moves = min( min(min_moves_for_suffix(N, \"25\"), min_moves_for_suffix(N, \"50\")),\n                         min(min_moves_for_suffix(N, \"75\"), min_moves_for_suffix(N, \"00\")) );\n\n    cout << (minimum_moves >= oo ? -1 : minimum_moves);\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Contests/Div 3 486/Explanation/Equal Sums Explanation.txt",
    "content": "Firstly, keep an array called used, which contains all the sums [S - A[i]], where S is the sum of the entire array for each i.\r\n\r\nThen go through the array and check for each i, if [S - A[i]] is present in used.\r\n\r\nBe careful to check that used [S - A[i]] is present in some index other than i. \r\n\r\n----------------\r\n\r\nint main()\r\n{\r\n    int no_of_sequences;\r\n    scanf(\"%d\", &no_of_sequences);\r\n\r\n    map <long long, pair<int, int> > used;\r\n\r\n    for(int i = 1; i <= no_of_sequences; i++)\r\n    {\r\n        int length_i;\r\n        scanf(\"%d\", &length_i);\r\n\r\n        vector <int> A(length_i + 1);\r\n\r\n        for(int j = 1; j <= length_i; j++)\r\n            scanf(\"%d\", &A[j]);\r\n\r\n        long long sum = 0;\r\n        for(int j = 1; j <= length_i; j++)\r\n            sum += A[j];\r\n\r\n        for(int j = 1; j <= length_i; j++)\r\n        {\r\n            long long remaining_sum = sum - A[j];\r\n\r\n            if(used.find(remaining_sum) != used.end() && used[remaining_sum].first != i)\r\n            {\r\n                printf(\"YES\\n\");\r\n                printf(\"%d %d\\n\", used[remaining_sum].first, used[remaining_sum].second);\r\n                printf(\"%d %d\\n\", i, j);\r\n                return 0;\r\n            }\r\n            else\r\n            {\r\n                used[remaining_sum] = make_pair(i, j);\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"NO\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 486/Explanation/Points and Powers of Two Explanation.txt",
    "content": "Fact - This is only possible for at most 3 points. \r\n\r\nLet P[1] < P[2] < P[3]. \r\n\r\nLet us suppose distance between P[1] and P[2] is x. \r\n\r\nAnd distance between P[2] and P[3] is x, then distance between P[1] and P[3] is 2x. \r\n\r\nIf the distance between P[2] and P[3] is anything other than x, (say y). \r\n\r\nThen P[2] - P[1] = x, P[3] - P[2] = y\r\n\r\nP[3] - P[1] = x + y,\r\n\r\nx, y and x + y cannot all be powers of 2 unless x = y.\r\n\r\nNow if we introduce a 4th point P[4]. P[4] - P[3] = x, But then P[4] - P[1] = 3x, which is not a power of 2. \r\n\r\nThis completes our proof. \r\n\r\n------------------------\r\n\r\nNow for each number and for each power of 2, we will do binary search to check if (A[i] + 2^p) is present in the array. \r\n\r\nWe will first look for a triplet. \r\n\r\nIf not there, we will look for a pair. \r\n\r\nIf not there, we will print any one element of the array.\r\n\r\n---------\r\n\r\nint answer_i = -1, answer_j = -1;\r\n\r\n    for(int i = 0; i < number_of_points; i++)\r\n    {\r\n        for(long long power = 1; power <= 1e12; power *= 2)\r\n        {\r\n            int j = upper_bound(all(P), P[i] + power - 1) - P.begin();\r\n\r\n            if(P[j] - P[i] == power)\r\n            {\r\n                int k = upper_bound(all(P), P[j] + power - 1) - P.begin();\r\n\r\n                if(P[k] - P[j] == power)//Answer can't be more than 3\r\n                {\r\n                    printf(\"3\\n\");\r\n                    printf(\"%I64d %I64d %I64d\\n\", P[i], P[j], P[k]);\r\n                    return 0;\r\n                }\r\n                else\r\n                {\r\n                    answer_i = i, answer_j = j;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    if(answer_i != -1 && answer_j != -1)\r\n    {\r\n        printf(\"2\\n\");\r\n        printf(\"%I64d %I64d\\n\", P[answer_i], P[answer_j]);\r\n    }\r\n    else\r\n    {\r\n        printf(\"1\\n\");\r\n        printf(\"%I64d\\n\", P[0]);\r\n    }\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 486/Explanation/Substring Sort Explanation.txt",
    "content": "1. Write a custom sort function that sorts strings by length. \r\n\r\nint sort_by_length(const string &A, const string &B)\r\n{\r\n    return (A.size() < B.size());\r\n}\r\n\r\n--------\r\n\r\n2. If any S[i] is not a substring of S[i + 1], then we don't have a desireable order. \r\n\r\nLet us suppose there is some j such that j > i + 1\r\n\r\nand S[i] is a substring of S[j] but not of S[i + 1].\r\n\r\nThen we have to put S[j] after S[i] and S[i + 1] after S[j]. Either way S[j] cannot be a substring of S[i + 1] because S[j] is longer. (If they are the same length, they are clearly not equal.)\r\n\r\n------------\r\n\r\nIf every S[i] is a substring of S[i + 1], then the sorted order is the order we want. \r\n\r\nint main()\r\n{\r\n    int no_of_strings;\r\n    cin >> no_of_strings;\r\n\r\n    vector <string> S(no_of_strings);\r\n    for(int i = 0; i < no_of_strings; i++)\r\n        cin >> S[i];\r\n\r\n    sort(all(S), sort_by_length);\r\n\r\n    for(int i = 1; i < no_of_strings; i++)\r\n    {\r\n        if(!substring_of(S[i], S[i - 1]))\r\n        {\r\n            cout << \"NO\\n\";\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    for(int i = 0; i < no_of_strings; i++)\r\n        cout << S[i] << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 486/Programs/Diverse Team.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <set>\r\n#include <cstdio>\r\n#include <algorithm>\r\n#include <map>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_students, team_size;\r\n    scanf(\"%d %d\", &no_of_students, &team_size);\r\n\r\n    const int MAX_RATING = 115;\r\n    vector <int> team;\r\n    vector <int> rating_used(MAX_RATING, false);\r\n\r\n    for(int i = 1; i <= no_of_students; i++)\r\n    {\r\n        int rating_i;\r\n        scanf(\"%d\", &rating_i);\r\n\r\n        if(!rating_used[rating_i])\r\n            team.push_back(i);\r\n\r\n        rating_used[rating_i] = true;\r\n    }\r\n\r\n    if(team.size() >= team_size)\r\n    {\r\n        printf(\"YES\\n\");\r\n        for(int i = 0; i < team_size; i++)\r\n            printf(\"%d \", team[i]);\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 486/Programs/Divisibility by 25.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nconst int oo = 100;\r\n\r\nint min_moves_for_suffix(string S, string suffix)\r\n{\r\n    int moves = oo;\r\n\r\n    for(int first = 0; first < S.size(); first++)\r\n    {\r\n        for(int second = 0; second < S.size(); second++)\r\n        {\r\n            if(first == second)\r\n                continue;\r\n\r\n            string N = S;\r\n            int moves_here = 0;\r\n\r\n            for(int i = first; i < N.size() - 1.; i++)\r\n            {\r\n                swap(N[i], N[i + 1]);\r\n                moves_here++;\r\n            }\r\n\r\n            //Second may have been disturbed by first\r\n            for(int i = second - (second > first); i < N.size() - 2; i++)\r\n            {\r\n                swap(N[i], N[i + 1]);\r\n                moves_here++;\r\n            }\r\n\r\n            int first_non_zero = 0;\r\n            while(N[first_non_zero] == '0')\r\n                first_non_zero++;\r\n\r\n            for(int i = first_non_zero; i > 0; i--)\r\n            {\r\n                swap(N[i], N[i - 1]);\r\n                moves_here++;\r\n            }\r\n\r\n            if(N[N.size() - 2] == suffix[0] && N[N.size() - 1] == suffix[1])\r\n                moves = min(moves, moves_here);\r\n        }\r\n    }\r\n\r\n    return moves;\r\n}\r\n\r\nint main()\r\n{\r\n    string N;\r\n    cin >> N;\r\n\r\n    int minimum_moves = oo;\r\n\r\n    minimum_moves = min( min(min_moves_for_suffix(N, \"25\"), min_moves_for_suffix(N, \"50\")),\r\n                         min(min_moves_for_suffix(N, \"75\"), min_moves_for_suffix(N, \"00\")) );\r\n\r\n    cout << (minimum_moves >= oo ? -1 : minimum_moves);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 486/Programs/Equal Sums.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_sequences;\r\n    scanf(\"%d\", &no_of_sequences);\r\n\r\n    map <long long, pair<int, int> > used;\r\n\r\n    for(int i = 1; i <= no_of_sequences; i++)\r\n    {\r\n        int length_i;\r\n        scanf(\"%d\", &length_i);\r\n\r\n        vector <int> A(length_i + 1);\r\n\r\n        for(int j = 1; j <= length_i; j++)\r\n            scanf(\"%d\", &A[j]);\r\n\r\n        long long sum = 0;\r\n        for(int j = 1; j <= length_i; j++)\r\n            sum += A[j];\r\n\r\n        for(int j = 1; j <= length_i; j++)\r\n        {\r\n            long long remaining_sum = sum - A[j];\r\n\r\n            if(used.find(remaining_sum) != used.end() && used[remaining_sum].first != i)\r\n            {\r\n                printf(\"YES\\n\");\r\n                printf(\"%d %d\\n\", used[remaining_sum].first, used[remaining_sum].second);\r\n                printf(\"%d %d\\n\", i, j);\r\n                return 0;\r\n            }\r\n            else\r\n            {\r\n                used[remaining_sum] = make_pair(i, j);\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 486/Programs/Points and Powers of Two.cpp",
    "content": "#include <cstdio>\n#include <map>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int number_of_points;\n    scanf(\"%d\", &number_of_points);\n\n    vector <long long> P(number_of_points);\n    for(int i = 0; i < number_of_points; i++)\n        scanf(\"%I64d\", &P[i]);\n\n    sort(all(P));\n\n    int answer_i = -1, answer_j = -1;\n\n    for(int i = 0; i < number_of_points; i++)\n    {\n        for(long long power = 1; power <= 1e12; power *= 2)\n        {\n            int j = upper_bound(all(P), P[i] + power - 1) - P.begin();\n\n            if(P[j] - P[i] == power)\n            {\n                int k = upper_bound(all(P), P[j] + power - 1) - P.begin();\n\n                if(P[k] - P[j] == power)//Answer can't be more than 3\n                {\n                    printf(\"3\\n\");\n                    printf(\"%I64d %I64d %I64d\\n\", P[i], P[j], P[k]);\n                    return 0;\n                }\n                else\n                {\n                    answer_i = i, answer_j = j;\n                }\n            }\n        }\n    }\n\n    if(answer_i != -1 && answer_j != -1)\n    {\n        printf(\"2\\n\");\n        printf(\"%I64d %I64d\\n\", P[answer_i], P[answer_j]);\n    }\n    else\n    {\n        printf(\"1\\n\");\n        printf(\"%I64d\\n\", P[0]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 486/Programs/Substring Sort.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint sort_by_length(const string &A, const string &B)\r\n{\r\n    return (A.size() < B.size());\r\n}\r\n\r\nint substring_of(string S, string sub_S)\r\n{\r\n    for(int i = 0; i + sub_S.size() - 1 < S.size(); i++)\r\n    {\r\n        int substring = true;\r\n\r\n        for(int j = 0; j < sub_S.size(); j++)\r\n        {\r\n            if(S[i + j] != sub_S[j])\r\n            {\r\n                substring = false;\r\n            }\r\n        }\r\n\r\n        if(substring)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_strings;\r\n    cin >> no_of_strings;\r\n\r\n    vector <string> S(no_of_strings);\r\n    for(int i = 0; i < no_of_strings; i++)\r\n        cin >> S[i];\r\n\r\n    sort(all(S), sort_by_length);\r\n\r\n    for(int i = 1; i < no_of_strings; i++)\r\n    {\r\n        if(!substring_of(S[i], S[i - 1]))\r\n        {\r\n            cout << \"NO\\n\";\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    for(int i = 0; i < no_of_strings; i++)\r\n        cout << S[i] << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 490/Explanations/Alphabetic Removals Explanation.txt",
    "content": "Keep track of the frequency of each alphabet. \r\n\r\nIf the frequency[a] >= k, then ban the alphabet a. Reduce k by frequency[a].\r\n\r\nif there is a situation when frequency[x] < k, then do an O(n) scan on the array and ban specific positions of the string. \r\n\r\nIn the end print a character in the string, if both it's position and alphabet aren't bad.\r\n\r\n------------------------------\r\n\r\nvector <int> frequency(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < S.size(); i++)\r\n        frequency[S[i] - 'a']++;\r\n\r\n    vector <int> is_allowed(length, true);\r\n    vector <int> banned(NO_OF_ALPHABETS, false);\r\n\r\n    for(int alphabet = 0; alphabet < NO_OF_ALPHABETS && k > 0; alphabet++)\r\n    {\r\n        if(frequency[alphabet] <= k)\r\n        {\r\n            banned[alphabet] = true;\r\n            k -= frequency[alphabet];\r\n        }\r\n        else if(frequency[alphabet] > k)\r\n        {\r\n            for(int i = 0; i < length && k > 0; i++)\r\n            {\r\n                if(S[i] == 'a' + alphabet)\r\n                {\r\n                    k--;\r\n                    is_allowed[i] = false;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < length; i++)\r\n        if(is_allowed[i] && !banned[S[i] - 'a'])\r\n            cout << S[i];"
  },
  {
    "path": "Contests/Div 3 490/Explanations/Equalise the Remainders Explanation.txt",
    "content": "Firstly, we need to print the modified array not just print the number of changes required. \r\n\r\nSo, we will keep track of the positions of each index of modulus. \r\n\r\nThat is we will know the indices of all the A[i]%m = x, \r\n\r\n---------------------\r\n\r\nNow, we will make a pass from i = 0 to m - 1\r\n\r\nIf any modulus occurs more than N/m times, then we will remove the excess indices and put them in 'extra'\r\n\r\nIf any modulus occurs less than N/m times, we will remove from extra from the end [Since the ones in the end will be closer to the current modulus.] and put it here. \r\n\r\nWe need to do two passes, not one. (This is an unusual feature of this problem.)\r\n\r\nBecause The first element might be deficient and the last may be in excess.\r\n\r\n-----------------------------\r\nlong long no_of_changes = 0;\r\n    vector <int> extra;\r\n\r\n    for(int runs = 1; runs <= 2; runs++)\r\n    {\r\n        for(int i = 0; i < m; i++)\r\n        {\r\n            while(position[i].size() > target)\r\n            {\r\n                int index = position[i].back();\r\n\r\n                extra.push_back(index);\r\n\r\n                position[i].pop_back();\r\n            }\r\n\r\n            while(position[i].size() < target && extra.size() > 0)\r\n            {\r\n                int index = extra.back();\r\n\r\n                no_of_changes += (A[index]%m < i ? i - A[index]%m : m - A[index]%m + i);\r\n\r\n                A[index] += (A[index]%m < i ? i - A[index]%m : m - A[index]%m + i);\r\n\r\n                position[i].push_back(index);\r\n\r\n                extra.pop_back();\r\n            }\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Div 3 490/Explanations/Mishika and Contests Explanation.txt",
    "content": "Have two pointers - One at the front, one at the back and move whichever pointer is allowed. \n\n#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_problems, skill;\n    scanf(\"%d %d\", &no_of_problems, &skill);\n\n    vector <int> difficulty(no_of_problems + 1);\n    for(int i = 1; i <= no_of_problems; i++) scanf(\"%d\", &difficulty[i]);\n\n    int solvable = 0;\n    int left = 1, right = no_of_problems;\n    while( (difficulty[left] <= skill || difficulty[right] <= skill) && left <= right)\n    {\n        if(difficulty[left] <= skill)\n            left++, solvable++;\n        else if(difficulty[right] <= skill)\n            right--, solvable++;\n    }\n\n    printf(\"%d\\n\", solvable);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 490/Explanations/Reachability from Capital Explanation.txt",
    "content": "1. If the graph were not directed,\nit would be equivalent to counting the number of components in the graph.\n\n2. As the graph is directed,\nlet us condense each strongly connected component to a single vertex and\ndraw an edge between two vertices if any vertex of one component\nhas an edge with any component of the other\n\n3. The number of components in this 'component' graph is\nthe number of vertices we must connect.\n\n4. How to get strongly connected components ?\nFirst, we will perform DFS on the tree.\nThen, we will perform DFS on the reverse tree\n\n-----\n\n#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 5015;\nvector <int> graph[MAX_N];\nvector <int> visited(MAX_N, false);\nvector <int> visit_order;\n\nvector <int> reverse_graph[MAX_N];\nvector <int> component(MAX_N, 0);\n\nvector <int> component_graph[MAX_N];\nvector <int> reachable_component(MAX_N, false);\n\nvoid dfs(int v)\n{\n    visited[v] = true;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n\n        if(!visited[child])\n            dfs(child);\n    }\n\n    visit_order.push_back(v);\n}\n\nvoid reverse_dfs(int v, int c)\n{\n    component[v] = c;\n\n    for(int i = 0; i < reverse_graph[v].size(); i++)\n    {\n        int child = reverse_graph[v][i];\n\n        if(component[child] == 0)\n            reverse_dfs(child, c);\n    }\n}\n\nvoid component_dfs(int v)\n{\n    reachable_component[v] = true;\n\n    for(int i = 0; i < component_graph[v].size(); i++)\n    {\n        int child_v = component_graph[v][i];\n\n        if(!reachable_component[child_v])\n            dfs(child_v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges, source;\n    scanf(\"%d %d %d\", &no_of_vertices, &no_of_edges, &source);\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        graph[u].push_back(v);\n        reverse_graph[v].push_back(u);\n    }\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(!visited[i])\n        {\n            dfs(i);\n        }\n    }\n\n    int no_of_components = 0;\n    reverse(all(visit_order));\n    for(int i = 0; i < no_of_vertices; i++)\n    {\n        int v = visit_order[i];\n        if(component[v] == 0)\n        {\n            reverse_dfs(v, ++no_of_components);\n        }\n    }\n\n    vector <int> incoming(no_of_components + 1);\n\n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        for(int i = 0; i < graph[v].size(); i++)\n        {\n            int child = graph[v][i];\n\n            if(component[v] != component[child])\n            {\n                component_graph[component[v]].push_back(component[child]);\n                incoming[component[child]]++;\n            }\n        }\n    }\n\n    component_dfs(component[source]);\n\n    int new_edges = 0;\n    for(int i = 1; i <= no_of_components; i++)\n    {\n        if(!reachable_component[i] && incoming[i] == 0)\n        {\n            new_edges++;\n        }\n    }\n\n    printf(\"%d\\n\", new_edges);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 490/Explanations/Reversing Encryption Explanation.txt",
    "content": "Perform the reverses in increasing order of the divisors of n !\r\n\r\nThis undoes all the reverses done in the encryption preserving order !\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    vector <int> divisors;\r\n    get_divisors(divisors, length);\r\n    sort(divisors.begin(), divisors.end());\r\n\r\n    for(int i = 0; i < divisors.size(); i++)\r\n    {\r\n        reverse(S.begin(), S.begin() + divisors[i]);\r\n    }\r\n\r\n    cout << S;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 490/Programs/Alphabetic Removals.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length, k;\r\n    string S;\r\n    cin >> length >> k >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> frequency(NO_OF_ALPHABETS, 0);\r\n    for(int i = 0; i < S.size(); i++)\r\n        frequency[S[i] - 'a']++;\r\n\r\n    vector <int> is_allowed(length, true);\r\n    vector <int> banned(NO_OF_ALPHABETS, false);\r\n\r\n    for(int alphabet = 0; alphabet < NO_OF_ALPHABETS && k > 0; alphabet++)\r\n    {\r\n        if(frequency[alphabet] <= k)\r\n        {\r\n            banned[alphabet] = true;\r\n            k -= frequency[alphabet];\r\n        }\r\n        else if(frequency[alphabet] > k)\r\n        {\r\n            for(int i = 0; i < length && k > 0; i++)\r\n            {\r\n                if(S[i] == 'a' + alphabet)\r\n                {\r\n                    k--;\r\n                    is_allowed[i] = false;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < length; i++)\r\n        if(is_allowed[i] && !banned[S[i] - 'a'])\r\n            cout << S[i];\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 490/Programs/Equalise the Remainders.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 2e5 + 5;\r\nvector <int> position[MAX_N];\r\n\r\nint main()\r\n{\r\n    typedef long long LL;\r\n    int no_of_elements, m;\r\n    scanf(\"%d %d\", &no_of_elements, &m);\r\n\r\n    vector <LL> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    int target = no_of_elements/m;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        position[A[i]%m].push_back(i);\r\n    }\r\n\r\n    long long no_of_changes = 0;\r\n    vector <int> extra;\r\n\r\n    for(int runs = 1; runs <= 2; runs++)\r\n    {\r\n        for(int i = 0; i < m; i++)\r\n        {\r\n            while(position[i].size() > target)\r\n            {\r\n                int index = position[i].back();\r\n\r\n                extra.push_back(index);\r\n\r\n                position[i].pop_back();\r\n            }\r\n\r\n            while(position[i].size() < target && extra.size() > 0)\r\n            {\r\n                int index = extra.back();\r\n\r\n                no_of_changes += (A[index]%m < i ? i - A[index]%m : m - A[index]%m + i);\r\n\r\n                A[index] += (A[index]%m < i ? i - A[index]%m : m - A[index]%m + i);\r\n\r\n                position[i].push_back(index);\r\n\r\n                extra.pop_back();\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_changes);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        printf(\"%I64d \", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 490/Programs/Mishika and Contests.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_problems, skill;\n    scanf(\"%d %d\", &no_of_problems, &skill);\n\n    vector <int> difficulty(no_of_problems + 1);\n    for(int i = 1; i <= no_of_problems; i++) scanf(\"%d\", &difficulty[i]);\n\n    int solvable = 0;\n    int left = 1, right = no_of_problems;\n    while( (difficulty[left] <= skill || difficulty[right] <= skill) && left <= right)\n    {\n        if(difficulty[left] <= skill)\n            left++, solvable++;\n        else if(difficulty[right] <= skill)\n            right--, solvable++;\n    }\n\n    printf(\"%d\\n\", solvable);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 490/Programs/Reachability from Capital.cpp",
    "content": "#include <cstdio>\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 5015;\nvector <int> graph[MAX_N];\nvector <int> visited(MAX_N, false);\nvector <int> visit_order;\n\nvector <int> reverse_graph[MAX_N];\nvector <int> component(MAX_N, 0);\n\nvector <int> component_graph[MAX_N];\nvector <int> reachable_component(MAX_N, false);\n\nvoid dfs(int v)\n{\n    visited[v] = true;\n\n    for(int i = 0; i < graph[v].size(); i++)\n    {\n        int child = graph[v][i];\n\n        if(!visited[child])\n            dfs(child);\n    }\n    \n    visit_order.push_back(v);\n}\n\nvoid reverse_dfs(int v, int c)\n{\n    component[v] = c;\n    \n    for(int i = 0; i < reverse_graph[v].size(); i++)\n    {\n        int child = reverse_graph[v][i];\n        \n        if(component[child] == 0)\n            reverse_dfs(child, c);\n    }\n}\n\nvoid component_dfs(int v)\n{\n    reachable_component[v] = true;\n    \n    for(int i = 0; i < component_graph[v].size(); i++)\n    {\n        int child_v = component_graph[v][i];\n        \n        if(!reachable_component[child_v])\n            dfs(child_v);\n    }\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges, source;\n    scanf(\"%d %d %d\", &no_of_vertices, &no_of_edges, &source);\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        graph[u].push_back(v);\n        reverse_graph[v].push_back(u);\n    }\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(!visited[i])\n        {\n            dfs(i);\n        }\n    }\n\n    int no_of_components = 0;\n    reverse(all(visit_order));\n    for(int i = 0; i < no_of_vertices; i++)\n    {\n        int v = visit_order[i];\n        if(component[v] == 0)\n        {\n            reverse_dfs(v, ++no_of_components);\n        }\n    }\n    \n    vector <int> incoming(no_of_components + 1);\n    \n    for(int v = 1; v <= no_of_vertices; v++)\n    {\n        for(int i = 0; i < graph[v].size(); i++)\n        {\n            int child = graph[v][i];\n            \n            if(component[v] != component[child])\n            {\n                component_graph[component[v]].push_back(component[child]);\n                incoming[component[child]]++;\n            }\n        }\n    }\n    \n    component_dfs(component[source]);\n    \n    int new_edges = 0;\n    for(int i = 1; i <= no_of_components; i++)\n    {\n        if(!reachable_component[i] && incoming[i] == 0)\n        {\n            new_edges++;\n        }\n    }\n    \n    printf(\"%d\\n\", new_edges);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 490/Programs/Reversing Encryption.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid get_divisors(vector <int> &divisors, int n)\r\n{\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            divisors.push_back(i);\r\n\r\n            if(i*i != n)\r\n                divisors.push_back(n/i);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    vector <int> divisors;\r\n    get_divisors(divisors, length);\r\n    sort(divisors.begin(), divisors.end());\r\n\r\n    for(int i = 0; i < divisors.size(); i++)\r\n    {\r\n        reverse(S.begin(), S.begin() + divisors[i]);\r\n    }\r\n\r\n    cout << S;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 494/Explanations/Binary String Constructing Explanation.txt",
    "content": "Let us be greedy and construct exactly x different positions and then put all the remaining characters together. We are guaranteed that it is always possible. \r\n\r\n--------------------------\r\n\r\nint main()\r\n{\r\n    int ones, zeroes, differences;\r\n    cin >> zeroes >> ones >> differences;\r\n\r\n    string answer;\r\n\r\n    if(ones > zeroes)\r\n    {\r\n        answer += '1';\r\n        ones--;\r\n    }\r\n    else\r\n    {\r\n        answer += '0';\r\n        zeroes--;\r\n    }\r\n\r\n    for(int i = 1; i <= differences; i++)\r\n    {\r\n        int len = answer.size();\r\n\r\n        if(answer[len - 1] == '0')\r\n        {\r\n            answer += '1';\r\n            ones--;\r\n        }\r\n        else\r\n        {\r\n            answer += '0';\r\n            zeroes--;\r\n        }\r\n    }\r\n\r\n    string S;\r\n    for(int i = 0; i < answer.size(); i++)\r\n    {\r\n        S += answer[i];\r\n\r\n        if(answer[i] == '1' && ones > 0)\r\n        {\r\n            while(ones--)\r\n                S += '1';\r\n        }\r\n\r\n        if(answer[i] == '0' && zeroes > 0)\r\n        {\r\n            while(zeroes--)\r\n                S += '0';\r\n        }\r\n    }\r\n\r\n    cout << S;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 494/Explanations/Coins and Queries Explanation.txt",
    "content": "It is always optimal to use the largest coin size we have at the current moment. \n\nSuppose we don't use coin x, we will have to use more coins of size y < x ... Since y is a divisor of x.\n\nSo, let us be greedy and do it in O(N log N) time. \n\n-------------------\n\nvoid solve(map <int, int> &frequency)\n{\n    int target;\n    scanf(\"%d\", &target);\n\n    int coins_used = 0;\n\n    for(int bit = 30; bit >= 0; bit--)\n    {\n        if(frequency[1 << bit] == 0) continue;\n\n        int coins_used_here = min(frequency[(1 << bit)], target/(1 << bit));\n\n        target = target - coins_used_here*(1 << bit);\n\n        coins_used += coins_used_here;\n    }\n\n    printf(\"%d\\n\", target > 0 ? -1 : coins_used);\n}\n"
  },
  {
    "path": "Contests/Div 3 494/Explanations/Intense Heat Explanation.txt",
    "content": "First, we will compute prefix sums so we can find the mean of a subarray [L, R] in O(1) time. \r\n\r\nNow, we shall visit all subarrays in O(n^2) time.\r\n\r\n---------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_days, k;\r\n    scanf(\"%d %d\", &no_of_days, &k);\r\n\r\n    vector <int> temperature(no_of_days + 1);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        scanf(\"%d\", &temperature[i]);\r\n\r\n    vector <long long> sum_till(no_of_days + 1, 0);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        sum_till[i] = sum_till[i - 1] + temperature[i];\r\n\r\n    double best = 0;\r\n    for(int length = k; length <= no_of_days; length++)\r\n    {\r\n        for(int left = 1, right = left + length - 1; right <= no_of_days; left++, right++)\r\n        {\r\n            double average_here = (1.0*(sum_till[right] - sum_till[left - 1]))/(1.0*length);\r\n\r\n            best = max(best, average_here);\r\n        }\r\n    }\r\n\r\n    printf(\"%.12f\\n\", best);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 494/Explanations/Polycarp's Pockets Explanation.txt",
    "content": "We want the element which has the highest frequency.\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int MAX_N = 115;\r\n    vector <int> frequency(MAX_N, 0);\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n        frequency[element]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(int i = 0; i < MAX_N; i++)\r\n        max_frequency = max(max_frequency, frequency[i]);\r\n\r\n    printf(\"%d\\n\", max_frequency);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 494/Programs/Binary String Constructing.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int ones, zeroes, differences;\r\n    cin >> zeroes >> ones >> differences;\r\n\r\n    string answer;\r\n\r\n    if(ones > zeroes)\r\n    {\r\n        answer += '1';\r\n        ones--;\r\n    }\r\n    else\r\n    {\r\n        answer += '0';\r\n        zeroes--;\r\n    }\r\n\r\n    for(int i = 1; i <= differences; i++)\r\n    {\r\n        int len = answer.size();\r\n\r\n        if(answer[len - 1] == '0')\r\n        {\r\n            answer += '1';\r\n            ones--;\r\n        }\r\n        else\r\n        {\r\n            answer += '0';\r\n            zeroes--;\r\n        }\r\n    }\r\n\r\n    string S;\r\n    for(int i = 0; i < answer.size(); i++)\r\n    {\r\n        S += answer[i];\r\n\r\n        if(answer[i] == '1' && ones > 0)\r\n        {\r\n            while(ones--)\r\n                S += '1';\r\n        }\r\n\r\n        if(answer[i] == '0' && zeroes > 0)\r\n        {\r\n            while(zeroes--)\r\n                S += '0';\r\n        }\r\n    }\r\n\r\n    cout << S;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 494/Programs/Coins and Queries.cpp",
    "content": "#include <cstdio>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve(map <int, int> &frequency)\n{\n    int target;\n    scanf(\"%d\", &target);\n\n    int coins_used = 0;\n\n    for(int bit = 30; bit >= 0; bit--)\n    {\n        if(frequency[1 << bit] == 0) continue;\n\n        int coins_used_here = min(frequency[(1 << bit)], target/(1 << bit));\n\n        target = target - coins_used_here*(1 << bit);\n\n        coins_used += coins_used_here;\n    }\n\n    printf(\"%d\\n\", target > 0 ? -1 : coins_used);\n}\n\nint main()\n{\n    map <int, int> frequency;\n    int no_of_coins, no_of_queries;\n    scanf(\"%d %d\", &no_of_coins, &no_of_queries);\n\n    while(no_of_coins--)\n    {\n        int value;\n        scanf(\"%d\", &value);\n        frequency[value]++;\n    }\n\n    while(no_of_queries--)\n        solve(frequency);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 494/Programs/Intense Heat.cpp",
    "content": "#include <vector>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_days, k;\r\n    scanf(\"%d %d\", &no_of_days, &k);\r\n\r\n    vector <int> temperature(no_of_days + 1);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        scanf(\"%d\", &temperature[i]);\r\n\r\n    vector <long long> sum_till(no_of_days + 1, 0);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        sum_till[i] = sum_till[i - 1] + temperature[i];\r\n\r\n    double best = 0;\r\n    for(int length = k; length <= no_of_days; length++)\r\n    {\r\n        for(int left = 1, right = left + length - 1; right <= no_of_days; left++, right++)\r\n        {\r\n            double average_here = (1.0*(sum_till[right] - sum_till[left - 1]))/(1.0*length);\r\n\r\n            best = max(best, average_here);\r\n        }\r\n    }\r\n\r\n    printf(\"%.12f\\n\", best);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 494/Programs/Polycarp's Pockets.cpp",
    "content": "#include <cstdio>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int MAX_N = 115;\r\n    vector <int> frequency(MAX_N, 0);\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n        frequency[element]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(int i = 0; i < MAX_N; i++)\r\n        max_frequency = max(max_frequency, frequency[i]);\r\n\r\n    printf(\"%d\\n\", max_frequency);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 521/Explanations/Cutting Out Explanation.txt",
    "content": "Let us binary search on the number of arrays we can have.\n\nSuppose we have to check if X arrays are possible.\n\nHow do we do it ?\n\nFor every element A[i] in the array, we will try to distribute it as evenly as possible\nin the array B.\n\nEach array will have (frequency[A[i]]/x) copies of A[i]\n\nAt the end, we will say if we have managed to put k elements in B\n\nIf Yes, then we can can create X copies of B\n\n-----\n\nint possible(int no_of_arrays, int length, vector <int> &answer)\n{\n    vector <int> filled;\n\n    for(auto it = frequency.begin(); it != frequency.end() && filled.size() < length; it++)\n    {\n        int required_frequency = (it->second)/no_of_arrays;\n\n        for(int i = 1; i <= required_frequency; i++)\n        {\n            filled.push_back(it->first);\n        }\n    }\n\n    if(filled.size() >= length)\n    {\n        answer = filled;\n    }\n\n    return (filled.size() >= length);\n}\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n\n    A.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n\n    //L is always possible, R is always not possible\n    vector <int> answer;\n    int left = 0, right = no_of_elements + 1;\n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n\n        if(possible(mid, k, answer))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n\n    for(int i = 0; i < k; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 521/Explanations/Disturbed People.txt",
    "content": "We solve the problem by being greedy.\r\n\r\nWhenever we find a triplet - \"1 0 1\"\r\n\r\nwe switch off the rightmost 1. \r\n\r\nWe could also switch off all the leftmost 1s. The two solutions are equivalent. \r\n\r\nNow every triplet 1 0 1 needs one of the border 1s to be switched off. So, we always switch off rightmost switches.\r\n\r\n------------\r\n\r\nint main()\r\n{\r\n    int no_of_houses;\r\n    cin >> no_of_houses;\r\n\r\n    vector <int> light_on(no_of_houses + 1);\r\n    for(int i = 1; i <= no_of_houses; i++)\r\n        cin >> light_on[i];\r\n\r\n    int excess_houses = 0;\r\n    for(int i = 2; i < no_of_houses; i++)\r\n    {\r\n        if(light_on[i - 1] && !light_on[i] && light_on[i + 1])\r\n        {\r\n            light_on[i + 1] = false;\r\n            excess_houses++;\r\n        }\r\n    }\r\n\r\n    cout << excess_houses << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 521/Explanations/Frog Jumping.txt",
    "content": "The total displacement towards right is positive, and left is negative. \n\nThe answer is their difference.\n\nAll we need to do is calculate the number of jumps in either direction and then the displacement in both directions.\n\n\nvoid solve()\n{\n    long long left_jump, right_jump, total_jumps;\n    cin >> right_jump >> left_jump >> total_jumps;\n\n    long long no_of_right_jumps = total_jumps/2 + total_jumps%2;\n    long long no_of_left_jumps = total_jumps/2;\n\n    long long right_distance = no_of_right_jumps*right_jump;\n    long long left_distance = no_of_left_jumps*left_jump;\n\n    long long distance = right_distance - left_distance;\n    cout << distance << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/Div 3 521/Explanations/Good Array.txt",
    "content": "Suppose the sum is S. \r\n\r\nIf we remove A[i] from the array, the sum is S - A[i].\r\n\r\nNow if i is a nice index, there is some index j, j =/= i such that A[j] = (S - A[i])/2\r\n\r\nWe simply keep track of the frequency of each element and solve this problem. \r\n\r\n----------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    const int MAX = 1e6 + 5;\r\n    vector <int> frequency(MAX, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        frequency[A[i]]++;\r\n\r\n    long long sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum += A[i];\r\n\r\n    vector <int> nice_indices;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long remaining_sum = sum - A[i];\r\n        long long target = remaining_sum/2;\r\n\r\n        if(target < MAX && remaining_sum%2 == 0 && frequency[target] > 0 &&\r\n           !(frequency[target] == 1 and A[i] == target))\r\n        {\r\n            nice_indices.push_back(i);\r\n        }\r\n    }\r\n\r\n    cout << nice_indices.size() << \"\\n\";\r\n    for(int i = 0; i < nice_indices.size(); i++)\r\n        cout << nice_indices[i] << \" \";\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 521/Explanations/Thematic Contests Explanation.txt",
    "content": "We will keep track of the frequency of each topic.\n\n-----\n\nLet us try to fix the end of the segment.\n\nIf the last contest has X problems, then the second last problem has X/2 problems.\n\nWe will continue like this till either X is odd or there is no topic which has X problems\n\n-----\n\nint get_count_ending(int ending, vector <int> &A)\n{\n    int count = 0;\n\n    for(int i = A.size() - 1, current = ending; i >= 0 && A[i] >= current; i--)\n    {\n        count += current;\n\n        if(current%2 == 1)\n        {\n            break;\n        }\n\n        current /= 2;\n    }\n\n    return count;\n}\n\n\n-----\n\nNow, we will iterate over the possible end.\n\nIt can be at most A[end]\n\n-----\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    map <int, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n\n    vector <int> frequencies;\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\n    {\n        frequencies.push_back(it->second);\n    }\n\n    sort(all(frequencies));\n\n    int maximum = 0;\n    for(int i = 0; i <= frequencies.back(); i++)\n    {\n        maximum = max(maximum, get_count_ending(i, frequencies));\n    }\n\n    cout << maximum << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 521/Programs/Cutting Out.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n\nusing namespace std;\n\nmap <int, int> frequency;\nvector <int> A;\n\nint possible(int no_of_arrays, int length, vector <int> &answer)\n{\n    vector <int> filled;\n    \n    for(auto it = frequency.begin(); it != frequency.end() && filled.size() < length; it++)\n    {\n        int required_frequency = (it->second)/no_of_arrays;\n        \n        for(int i = 1; i <= required_frequency; i++)\n        {\n            filled.push_back(it->first);\n        }\n    }\n    \n    if(filled.size() >= length)\n    {\n        answer = filled;\n    }\n    \n    return (filled.size() >= length);\n}\n\nint main()\n{\n    int no_of_elements, k;\n    cin >> no_of_elements >> k;\n    \n    A.resize(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n     \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n    \n    //L is always possible, R is always not possible\n    vector <int> answer;\n    int left = 0, right = no_of_elements + 1;\n    while(right - left > 1)\n    {\n        int mid = (left + right)/2;\n        \n        if(possible(mid, k, answer))\n        {\n            left = mid;\n        }\n        else\n        {\n            right = mid;\n        }\n    }\n        \n    for(int i = 0; i < k; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 521/Programs/Disturbed People.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_houses;\r\n    cin >> no_of_houses;\r\n\r\n    vector <int> light_on(no_of_houses + 1);\r\n    for(int i = 1; i <= no_of_houses; i++)\r\n        cin >> light_on[i];\r\n\r\n    int excess_houses = 0;\r\n    for(int i = 2; i < no_of_houses; i++)\r\n    {\r\n        if(light_on[i - 1] && !light_on[i] && light_on[i + 1])\r\n        {\r\n            light_on[i + 1] = false;\r\n            excess_houses++;\r\n        }\r\n    }\r\n\r\n    cout << excess_houses << \"\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 521/Programs/Frog Jumping.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long left_jump, right_jump, total_jumps;\n    cin >> right_jump >> left_jump >> total_jumps;\n\n    long long no_of_right_jumps = total_jumps/2 + total_jumps%2;\n    long long no_of_left_jumps = total_jumps/2;\n\n    long long right_distance = no_of_right_jumps*right_jump;\n    long long left_distance = no_of_left_jumps*left_jump;\n\n    long long distance = right_distance - left_distance;\n    cout << distance << \"\\n\";\n}\n\nint main()\n{\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 521/Programs/Good Array.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    const int MAX = 1e6 + 5;\r\n    vector <int> frequency(MAX, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        frequency[A[i]]++;\r\n\r\n    long long sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum += A[i];\r\n\r\n    vector <int> nice_indices;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long remaining_sum = sum - A[i];\r\n        long long target = remaining_sum/2;\r\n\r\n        if(target < MAX && remaining_sum%2 == 0 && frequency[target] > 0 &&\r\n           !(frequency[target] == 1 and A[i] == target))\r\n        {\r\n            nice_indices.push_back(i);\r\n        }\r\n    }\r\n\r\n    cout << nice_indices.size() << \"\\n\";\r\n    for(int i = 0; i < nice_indices.size(); i++)\r\n        cout << nice_indices[i] << \" \";\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 521/Programs/Pictures with Kittens (Easy Version).cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, segment, total;\n    cin >> no_of_elements >> segment >> total;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    const int oo = 1e9;\n    vector <vector <long long> > max_till(no_of_elements + 1, vector <long long> (total + 1, -oo));\n    max_till[0][total] = 0;\n    \n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int remaining = total - 1; remaining >= 0; remaining--)\n        {\n            if(remaining == total)\n            {\n                max_till[i][remaining] = 0;\n                continue;\n            }\n            \n            for(int last = i - 1; last >= 0 && last >= i - segment; last--)\n            {\n                if(max_till[last][remaining + 1] != -oo)\n                {\n                    max_till[i][remaining] = max(max_till[i][remaining], A[i] + max_till[last][remaining + 1]);\n                }\n            }\n            \n            //cout << \"F(\" << i << \",\" << remaining << \") = \" << max_till[i][remaining] << \"\\n\";\n        }\n    }\n    \n    long long answer = -oo;\n    for(int i = no_of_elements - segment + 1; i <= no_of_elements; i++)\n    {\n        answer = max(answer, max_till[i][0]);\n    }\n    \n    cout << (answer == -oo ? -1 : answer) << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 521/Programs/Thematic Contests.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <map>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint get_count_ending(int ending, vector <int> &A)\n{\n    int count = 0;\n    \n    for(int i = A.size() - 1, current = ending; i >= 0 && A[i] >= current; i--)\n    {\n        count += current;\n        \n        if(current%2 == 1)\n        {\n            break;\n        }\n        \n        current /= 2;\n    }\n    \n    return count;\n}\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    map <int, int> frequency;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        frequency[A[i]]++;\n    }\n    \n    vector <int> frequencies;\n    for(auto it = frequency.begin(); it != frequency.end(); it++)\n    {\n        frequencies.push_back(it->second);\n    }\n    \n    sort(all(frequencies));\n    \n    int maximum = 0;\n    for(int i = 0; i <= frequencies.back(); i++)\n    {\n        maximum = max(maximum, get_count_ending(i, frequencies));\n    }\n    \n    cout << maximum << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 531/Explanations/Array K Colouring Explanation.txt",
    "content": "We have to ensure that for all elements of a given value x, we use all k colours. \r\n\r\nSo, let us sort the array by value. \r\nWe will colour the first element in colour 1, second in colour 2 and so on. When we go to colour k + 1, we will check if that colour has already been used on such a colour. \r\n\r\nThis approach works because - \r\n\r\n1. We are using colours 1 by 1, so guaranteed each colour will be used once. \r\n\r\n2. For a given value, we are using all k colours before using the same again. This greedy strategy helps us. \r\n\r\n--------\r\n\r\nint main()\r\n{\r\n\tint no_of_elements, no_of_colours;\r\n\tcin >> no_of_elements >> no_of_colours;\r\n\r\n\tvector <bricks> A(no_of_elements);\r\n\tfor(int i=0; i < no_of_elements ;i++)\r\n\t{\r\n\t\tcin >> A[i].value;\r\n\t\tA[i].position=i;\r\n\t}\r\n\r\n\tsort(all(A));\r\n\r\n\tvector <int> last_brick_of_colour(no_of_colours + 1, 0);\r\n    vector <int> colour(no_of_elements + 1);\r\n\r\n    for(int c = 0, i = 0; i < no_of_elements; i++, c = (c + 1)%no_of_colours)\r\n    {\r\n        if(last_brick_of_colour[c] == A[i].value)\r\n        {\r\n            cout << \"NO\\n\";\r\n            return 0;\r\n        }\r\n\r\n        colour[A[i].position] = c;\r\n        last_brick_of_colour[c] = A[i].value;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        cout << colour[i] + 1 << \" \";\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 531/Explanations/Balanced Ternary String Explanation.txt",
    "content": "We will do four operations at the end of which the string will be the lexicographically smallest balanced string. \n\n1. The number of 0s is < N/3. \n\nGo through the string from beginning to end. Replace A[i] with 0 if frequency(A[i]) > N/3. \n\nThis is because it is always better to put the new 0s in the leftmost positions rather than the rightmost ones. \n\nAfter we have finished this, we are guaranteed that the number of 0s is >= N/3.\n\n-------------\n\n2. The number of 2s is < N/3\n\nGo through the string from end to beginning. Replace A[i] with 2 if frequency(A[i]) > N/3\n\nIt is always better to put 2s in the end rather than the beginning.\n\nAfter we have finished this, we are sure that the number of 2s is >= N/3.\n\n-------\n\nNow, after these two operations, the number of 1s is <= N/3. \n\nIf the number of 1s is > N/3, then one among the 0s and 2s have to be less than N/3 which is not possible. \n\n----\n\nSo, all we need to do is place the remaining 1s. \n\nThe excess 2s need to be replaced with 1. \n\n3. We need to replace the rightmost 0s. Because it is always better. to post a 1 instead of a 0 in the end rather than in the beginning. \n\n4. We need to replace the leftmost 2s. \n\nAfter we are done, the number of 1s is = N/3. \nThe number of 2s and 0s are both >= N/3, which is only possible if both are = N/3. \n\n--------\n\nSo here are the four operations - \n\n1. If the number of 0s is < N/3, place them as early as possible. \n2. If the number of 2s is < N/3, place the 2s as late as possible. \n3. If the 0s are in excess now, replace the latest 0s with 1s. \n4. If the 2s are in excess now, replace the earliest 2s with 1s.\n"
  },
  {
    "path": "Contests/Div 3 531/Programs/Array K Colouring.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nstruct bricks\r\n{\r\n\tint value, position;\r\n\r\n\tint operator<(const bricks &b) const\r\n\t{\r\n\t\treturn (value < b.value);\r\n\t}\r\n};\r\n\r\nint main()\r\n{\r\n\tint no_of_elements, no_of_colours;\r\n\tcin >> no_of_elements >> no_of_colours;\r\n\r\n\tvector <bricks> A(no_of_elements);\r\n\tfor(int i=0; i < no_of_elements ;i++)\r\n\t{\r\n\t\tcin >> A[i].value;\r\n\t\tA[i].position=i;\r\n\t}\r\n\r\n\tsort(all(A));\r\n\r\n\tvector <int> last_brick_of_colour(no_of_colours + 1, 0);\r\n    vector <int> colour(no_of_elements + 1);\r\n\r\n    for(int c = 0, i = 0; i < no_of_elements; i++, c = (c + 1)%no_of_colours)\r\n    {\r\n        if(last_brick_of_colour[c] == A[i].value)\r\n        {\r\n            cout << \"NO\\n\";\r\n            return 0;\r\n        }\r\n\r\n        colour[A[i].position] = c;\r\n        last_brick_of_colour[c] = A[i].value;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        cout << colour[i] + 1 << \" \";\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 531/Programs/Balanced Ternary String.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    const int MAX = 3;\n    vector <int> frequency(MAX, 0);\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%1d\", &A[i]);\n        frequency[A[i]]++;\n    }\n\n    for(int i = 1; i <= no_of_elements && frequency[0] < no_of_elements/3; i++)\n    {\n        if(A[i] != 0 && frequency[A[i]] > no_of_elements/3)\n        {\n            frequency[A[i]]--;\n            frequency[0]++;\n\n            A[i] = 0;\n        }\n    }\n\n    for(int i = no_of_elements; i >= 1 && frequency[2] < no_of_elements/3; i--)\n    {\n        if(A[i] != 2 && frequency[A[i]] > no_of_elements/3)\n        {\n            frequency[A[i]]--;\n            frequency[2]++;\n\n            A[i] = 2;\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements && frequency[1] < no_of_elements/3 && frequency[2] > no_of_elements/3; i++)\n    {\n        if(A[i] == 2)\n        {\n            frequency[2]--;\n            frequency[1]++;\n\n            A[i] = 1;\n        }\n    }\n\n    for(int i = no_of_elements; i >= 1 && frequency[1] < no_of_elements/3 && frequency[0] > no_of_elements/3; i--)\n    {\n        if(A[i] == 0)\n        {\n            frequency[0]--;\n            frequency[1]++;\n\n            A[i] = 1;\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        printf(\"%d\", A[i]);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Colored Boots Explanation.txt",
    "content": "We can be greedy. First, we will match alphabets to each other. \r\n\r\nThen we will map alphabets to question marks. \r\n\r\nAnd lastly, we will map the question marks to each other. \r\n\r\nIt is important to map question marks to each other only after we have mapped question marks to alphabets. \r\n\r\nWhen we map question marks to alphabets, we get one pair for each question mark we have used. \r\nBut, if we map question marks to each other first, then we will be left with at most one question mark in the end. \r\n\r\nWe must map alphabets to each other first because we don't want to map any alphabet to a question mark if we can map it to another alphabet. \r\nMapping alphabets to each other rather than to question marks does not reduce the number of pairs and generally increases it.\r\n\r\n-------\r\n\r\nvoid match(char a, char b)\r\n{\r\n    int common_elements = min(A_indices[a].size(), B_indices[b].size());\r\n\r\n    while(common_elements > 0)\r\n    {\r\n        pair <int, int> current_pair = make_pair(A_indices[a].back(), B_indices[b].back());\r\n        answer.push_back(current_pair);\r\n\r\n        A_indices[a].pop_back();\r\n        B_indices[b].pop_back();\r\n\r\n        common_elements--;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string A, B;\r\n    cin >> length >> A >> B;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        A_indices[A[i]].push_back(i);\r\n\r\n        B_indices[B[i]].push_back(i);\r\n    }\r\n\r\n    for(char ch = 'a'; ch <= 'z'; ch++)\r\n        match(ch, ch);\r\n\r\n    for(char ch = 'a'; ch <= 'z'; ch++)\r\n        match('?', ch);\r\n\r\n    for(char ch = 'a'; ch <= 'z'; ch++)\r\n        match(ch, '?');\r\n\r\n    match('?', '?');\r\n\r\n    cout << answer.size() << \"\\n\";\r\n    for(int i = 0; i < answer.size(); i++)\r\n    {\r\n        cout << answer[i].first + 1 << \" \" << answer[i].second + 1 << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Game 23 Explanation.txt",
    "content": "We will make the power of 2 and 3 equal in m and n. \r\n\r\nIf m and n are not equal after that, then it is impossible.\r\n\r\nElse, we are done.\r\n\r\n---\r\n\r\nint main()\r\n{\r\n    ULL target, source;\r\n    cin >> source >> target;\r\n\r\n    int target_power_of_2 = exponent(target, 2);\r\n    int target_power_of_3 = exponent(target, 3);\r\n\r\n    int source_power_of_2 = exponent(source, 2);\r\n    int source_power_of_3 = exponent(source, 3);\r\n\r\n    int no_of_moves = 0;\r\n\r\n    for(int i = source_power_of_2 + 1; i <= target_power_of_2; i++)\r\n    {\r\n        if(source <= target/2)\r\n        {\r\n            source *= 2;\r\n\r\n            no_of_moves++;\r\n        }\r\n    }\r\n\r\n    for(int i = source_power_of_3 + 1; i <= target_power_of_3; i++)\r\n    {\r\n        if(source <= target/3)\r\n        {\r\n            source *= 3;\r\n\r\n            no_of_moves++;\r\n        }\r\n    }\r\n\r\n    const int IMPOSSIBLE = -1;\r\n    cout << (source == target ? no_of_moves : IMPOSSIBLE);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Maximal Continuous Rest Explanation.txt",
    "content": "We will use the normal DP to keep track of the largest substring. \r\n\r\nWe also need to check the sum of the prefix and suffix. \r\n\r\nEnsure that the length of the substring is not greater than the length of the string !\r\n\r\n---\r\n\r\nint main()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    vector <int> A(length + 1);\r\n    for(int i = 1; i <= length; i++)\r\n        cin >> A[i];\r\n\r\n    int maximum_1s_till_here = 0, maximum_1s = 0;\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        maximum_1s_till_here = (A[i] == 1 ? maximum_1s_till_here + 1 : 0);\r\n\r\n        maximum_1s = max(maximum_1s, maximum_1s_till_here);\r\n    }\r\n\r\n    int prefix = 0;\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        if(A[i] != 1)\r\n            break;\r\n\r\n        prefix++;\r\n    }\r\n\r\n    int suffix = 0;\r\n    for(int i = length; i >= 1; i--)\r\n    {\r\n        if(A[i] != 1)\r\n            break;\r\n\r\n        suffix++;\r\n    }\r\n\r\n    maximum_1s = max(maximum_1s, prefix + suffix);\r\n    maximum_1s = min(maximum_1s, length);\r\n\r\n    cout << maximum_1s;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Polycarp Restores Permutation Explanation.txt",
    "content": "Let us notice that \n\n1. The first element of the permutation uniquely determines the permutation. \n\n2. If we can reach [p1, p2, ... , pn], then we can also reach [p1 + x, p2 + x, ... , pn + x]. \nAlso note that we cannot reach any other permutation.\n\nSo we will set p1 = 1 and generate a permutation P. \nThen, we will check if P is a block of n consecutive integers. \n\nThen we will have [1, p2, p3, ... , pn]. \n\nWe can reach [1 + x, p2 + x, ... , pn + x]. \n\nWe cannot reach any other permutation.\n\n---\n\nTo check if it is a block of n consecutive integers, we will first find the smallest element x in P. \n\n1. If x <= 0, then we will add |x| + 1 to every element in P. \n\n2. Let the maximum element in P be x. If x > n, then we will subtract |x - n| from every element in P. \n\n-------\n\nAfter doing these two operations, P should be a permutation of [1, n]. \n\nSuppose P is a permutation, then we are done. \n\nIf P is not a permutation, then it can be because of 2 reasons - \n\n1. P has duplicates. This property will always hold. \n2. P has some element that is not in [1, n]. This property will also always be true regardless of the first element.\n\n----\nint main()\n{\n    int length;\n    cin >> length;\n\n    vector <int> difference(length);\n    for(int i = 1; i <= length - 1; i++)\n        cin >> difference[i];\n\n    vector <int> permutation(length + 1);\n    permutation[1] = 1;\n    int minimum = 1, maximum = 1;\n    for(int i = 2; i <= length; i++)\n    {\n        permutation[i] = permutation[i - 1] + difference[i - 1];\n\n        minimum = min(minimum, permutation[i]);\n        maximum = max(maximum, permutation[i]);\n    }\n\n    if(minimum < 1)\n    {\n        for(int i = 1; i <= length; i++)\n            permutation[i] += abs(minimum) + 1;\n    }\n\n    if(maximum > length)\n    {\n        for(int i = 1; i <= length; i++)\n            permutation[i] -= (maximum - length);\n    }\n\n    int is_permutation = true;\n    vector <int> frequency(length + 1, 0);\n    for(int i = 1; i <= length; i++)\n    {\n        if(permutation[i] < 1 || permutation[i] > length)\n        {\n            is_permutation = false;\n            continue;\n        }\n\n        frequency[permutation[i]]++;\n    }\n\n    for(int i = 1; i <= length; i++)\n    {\n        if(frequency[i] != 1)\n            is_permutation = false;\n    }\n\n    if(!is_permutation)\n    {\n        cout << \"-1\\n\";\n        return 0;\n    }\n\n    for(int i = 1; i <= length; i++)\n        cout << permutation[i] << \" \";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Privatization of Roads in Berland Explanation.txt",
    "content": "Let us make an observation -\n\nIf we colour the edges with D colours,\nthen every vertex with more than D edges will have 2 edges of the same colour\n\nLet us keep track of the degree of each vertex.\nWe will make a suffix sum array over the array of frequencies of every degree.\n\nLet us look at the rightmost i, such that Suffix Sum[i] > k,\n\nIf we paint the graph in (i - 1) colours,\nthen all of the Suffix Sum[i] vertices will have 2 monochromatic edges, which is more than k\n\nSo that means (i - 1) or fewer colours is not possible.\n\nThen, i is the answer.\n\n-----\n\nNow, we will see how we will colour the edges in exactly i colours\n\nWe will do a DFS and keep track of which colour the edge {Parent[v], v} was painted in\n\nSuppose it was painted in colour c, then we will paint the first edge of v\n\n(c + 1) mod k, then the next edge\n(c + 2) mod k, and so on\n\nThis ensures that only those vertices with degree > i,\nhave two edges of the same colour and this number will not be more than K\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nint no_of_colours = 0;\nvector < pair <int, int> > tree[MAX_N];\nvector <int> colour(MAX_N, 0);\n\nvoid dfs(int v, int parent_v, int last_colour)\n{\n    int next_colour = (last_colour + 1)%no_of_colours;\n\n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i].first;\n\n        if(child_v == parent_v)\n        {\n            continue;\n        }\n\n        colour[tree[v][i].second] = next_colour;\n\n        dfs(child_v, v, next_colour);\n\n        next_colour = (next_colour + 1)%no_of_colours;\n    }\n}\n\nint main()\n{\n    int no_of_vertices, k;\n    cin >> no_of_vertices >> k;\n\n    vector <int> degree(no_of_vertices + 1, 0);\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n\n        tree[u].push_back(make_pair(v, i));\n        tree[v].push_back(make_pair(u, i));\n\n        degree[u]++; degree[v]++;\n    }\n\n    vector <int> frequency(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        frequency[degree[i]]++;\n    }\n\n    vector <int> suffix_sum(no_of_vertices + 5, 0);\n    for(int i = no_of_vertices; i >= 1; i--)\n    {\n        suffix_sum[i] = suffix_sum[i + 1] + frequency[i];\n    }\n\n    for(int i = no_of_vertices; i >= 1; i--)\n    {\n        if(suffix_sum[i] > k)\n        {\n            no_of_colours = i;\n            break;\n        }\n    }\n\n    dfs(1, 0, -1);\n\n    cout << no_of_colours << \"\\n\";\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        cout << colour[i] + 1 << \" \";\n    }\n\n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Same Sum Blocks Explanation.txt",
    "content": "Let us do this problem by brute force.\n\nWe will solve the problem independently for every sum possible.\nThere are O(n^2) possible sums.\nFor each sum, we will keep track of all the segments [L, R] such that Sum[L, R] = x\n\nThen, for each sum x, we will find the maximum number of segments we can choose.\nWe can do this greedily by choosing the first available segment at each point.\n\nNote that the segments are already sorted by right so we don't need to sort them again .\n\n-----\n\nstruct segment\n{\n    int left, right;\n\n    segment(){}\n\n    segment(int L, int R)\n    {\n        left = L; right = R;\n    }\n};\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <int> prefix_sum(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = A[i] + prefix_sum[i - 1];\n    }\n\n    map <int, vector <segment> > sum_blocks;\n    for(int r = 1; r <= no_of_elements; r++)\n    {\n        for(int l = 1; l <= r; l++)\n        {\n            int sum = prefix_sum[r] - prefix_sum[l - 1];\n\n            sum_blocks[sum].push_back(segment(l, r));\n        }\n    }\n\n    vector <segment> answer;\n    for(auto it = sum_blocks.begin(); it != sum_blocks.end(); it++)\n    {\n        int sum = it->first;\n\n        vector <segment> answer_here;\n\n        int last_right = -1;                                ;\n\n        for(int i = 0; i < sum_blocks[sum].size(); i++)\n        {\n            if(sum_blocks[sum][i].left > last_right)\n            {\n                answer_here.push_back(sum_blocks[sum][i]);\n\n                last_right = sum_blocks[sum][i].right;\n            }\n        }\n\n        if(answer_here.size() > answer.size())\n        {\n            answer = answer_here;\n        }\n    }\n\n    cout << answer.size() << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i].left << \" \" << answer[i].right << \"\\n\";\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Explanations/Superhero Battle Explanation.txt",
    "content": "First, let us check if it is possible in less than 1 round.\n\nThen, we will check that the sum of the entire array is not non negative.\nIf it is, then we will never find an answer.\n\nSuppose it isn't, we will always find an answer.\nThe answer will consist of some number of full cycles followed by a partial cycle.\n\nNow, it might be an error if we try to write H as\n\nH = q.P[n] + r\n\n1000 6\n-100 -200 -300 125 77 -4\n\nIs the test case for this. If we calculate the number of total cycles as 1000/Sum, it gives us 2 cycles and then 2 more elements leading to 14 steps.\n\nBut, there is actually an answer in 9 steps.\n\nTo capture such answers, we have to do something slightly different.\n\nWe will iterate over each i from 1 to N, and calculate the number of cycles required for the game to end at this i,\n\nFind the x, so that H + x.P[n] + P[i] ≤ 0\n\nFor finding x, we have to divide (H + P[i])/x and take the ceil of it\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nint main()\n{\n    long long H, no_of_elements;\n    cin >> H >> no_of_elements;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n\n    vector <long long> prefix_sum(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = A[i] + prefix_sum[i - 1];\n    }\n\n    long long answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(H + prefix_sum[i] <= 0)\n        {\n            answer = i;\n            break;\n        }\n    }\n\n    long long sum = abs(prefix_sum[no_of_elements]);\n\n    if(answer != 0)\n    {\n        cout << answer << \"\\n\";\n\n        return 0;\n    }\n    else if(prefix_sum[no_of_elements] >= 0)\n    {\n        cout << \"-1\\n\";\n\n        return 0;\n    }\n\n    answer = 2e18;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        //H + x.P[n]  + P[i] = 0\n        long long rounds_required = ceil(H + prefix_sum[i], sum);\n\n        answer = min(answer, rounds_required*no_of_elements + i);\n    }\n\n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Colored Boots.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_SIZE = 200;\r\nvector <int> A_indices[MAX_SIZE], B_indices[MAX_SIZE];\r\nvector <pair <int, int> > answer;\r\n\r\nvoid match(char a, char b)\r\n{\r\n    int common_elements = min(A_indices[a].size(), B_indices[b].size());\r\n\r\n    while(common_elements > 0)\r\n    {\r\n        pair <int, int> current_pair = make_pair(A_indices[a].back(), B_indices[b].back());\r\n        answer.push_back(current_pair);\r\n\r\n        A_indices[a].pop_back();\r\n        B_indices[b].pop_back();\r\n\r\n        common_elements--;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string A, B;\r\n    cin >> length >> A >> B;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        A_indices[A[i]].push_back(i);\r\n\r\n        B_indices[B[i]].push_back(i);\r\n    }\r\n\r\n    for(char ch = 'a'; ch <= 'z'; ch++)\r\n        match(ch, ch);\r\n\r\n    for(char ch = 'a'; ch <= 'z'; ch++)\r\n        match('?', ch);\r\n\r\n    for(char ch = 'a'; ch <= 'z'; ch++)\r\n        match(ch, '?');\r\n\r\n    match('?', '?');\r\n\r\n    cout << answer.size() << \"\\n\";\r\n    for(int i = 0; i < answer.size(); i++)\r\n    {\r\n        cout << answer[i].first + 1 << \" \" << answer[i].second + 1 << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Game 23.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\ntypedef unsigned long long ULL;\r\n\r\nint exponent(ULL n, ULL divisor)\r\n{\r\n    int exp = 0;\r\n\r\n    while(n%divisor == 0)\r\n    {\r\n        n /= divisor;\r\n\r\n        exp++;\r\n    }\r\n\r\n    return exp;\r\n}\r\n\r\nint main()\r\n{\r\n    ULL target, source;\r\n    cin >> source >> target;\r\n\r\n    int target_power_of_2 = exponent(target, 2);\r\n    int target_power_of_3 = exponent(target, 3);\r\n\r\n    int source_power_of_2 = exponent(source, 2);\r\n    int source_power_of_3 = exponent(source, 3);\r\n\r\n    int no_of_moves = 0;\r\n\r\n    for(int i = source_power_of_2 + 1; i <= target_power_of_2; i++)\r\n    {\r\n        if(source <= target/2)\r\n        {\r\n            source *= 2;\r\n\r\n            no_of_moves++;\r\n        }\r\n    }\r\n\r\n    for(int i = source_power_of_3 + 1; i <= target_power_of_3; i++)\r\n    {\r\n        if(source <= target/3)\r\n        {\r\n            source *= 3;\r\n\r\n            no_of_moves++;\r\n        }\r\n    }\r\n\r\n    const int IMPOSSIBLE = -1;\r\n    cout << (source == target ? no_of_moves : IMPOSSIBLE);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Maximal Continuous Rest.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    vector <int> A(length + 1);\r\n    for(int i = 1; i <= length; i++)\r\n        cin >> A[i];\r\n\r\n    int maximum_1s_till_here = 0, maximum_1s = 0;\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        maximum_1s_till_here = (A[i] == 1 ? maximum_1s_till_here + 1 : 0);\r\n\r\n        maximum_1s = max(maximum_1s, maximum_1s_till_here);\r\n    }\r\n\r\n    int prefix = 0;\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        if(A[i] != 1)\r\n            break;\r\n\r\n        prefix++;\r\n    }\r\n\r\n    int suffix = 0;\r\n    for(int i = length; i >= 1; i--)\r\n    {\r\n        if(A[i] != 1)\r\n            break;\r\n\r\n        suffix++;\r\n    }\r\n\r\n    maximum_1s = max(maximum_1s, prefix + suffix);\r\n    maximum_1s = min(maximum_1s, length);\r\n\r\n    cout << maximum_1s;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Polycarp Restores Permutation.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    cin >> length;\n\n    vector <int> difference(length);\n    for(int i = 1; i <= length - 1; i++)\n        cin >> difference[i];\n\n    vector <int> permutation(length + 1);\n    permutation[1] = 1;\n    int minimum = 1, maximum = 1;\n    for(int i = 2; i <= length; i++)\n    {\n        permutation[i] = permutation[i - 1] + difference[i - 1];\n\n        minimum = min(minimum, permutation[i]);\n        maximum = max(maximum, permutation[i]);\n    }\n\n    if(minimum < 1)\n    {\n        for(int i = 1; i <= length; i++)\n            permutation[i] += abs(minimum) + 1;\n    }\n\n    if(maximum > length)\n    {\n        for(int i = 1; i <= length; i++)\n            permutation[i] -= (maximum - length);\n    }\n\n    int is_permutation = true;\n    vector <int> frequency(length + 1, 0);\n    for(int i = 1; i <= length; i++)\n    {\n        if(permutation[i] < 1 || permutation[i] > length)\n        {\n            is_permutation = false;\n            continue;\n        }\n\n        frequency[permutation[i]]++;\n    }\n\n    for(int i = 1; i <= length; i++)\n    {\n        if(frequency[i] != 1)\n            is_permutation = false;\n    }\n\n    if(!is_permutation)\n    {\n        cout << \"-1\\n\";\n        return 0;\n    }\n\n    for(int i = 1; i <= length; i++)\n        cout << permutation[i] << \" \";\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Privatization of Roads in Berland.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 5;\nint no_of_colours = 0;\nvector < pair <int, int> > tree[MAX_N];\nvector <int> colour(MAX_N, 0);\n\nvoid dfs(int v, int parent_v, int last_colour)\n{\n    int next_colour = (last_colour + 1)%no_of_colours;\n    \n    for(int i = 0; i < tree[v].size(); i++)\n    {\n        int child_v = tree[v][i].first;\n        \n        if(child_v == parent_v)\n        {\n            continue;\n        }\n        \n        colour[tree[v][i].second] = next_colour;\n        \n        dfs(child_v, v, next_colour);\n        \n        next_colour = (next_colour + 1)%no_of_colours;\n    }\n}\n\nint main()\n{\n    int no_of_vertices, k;\n    cin >> no_of_vertices >> k;\n    \n    vector <int> degree(no_of_vertices + 1, 0);\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        cin >> u >> v;\n        \n        tree[u].push_back(make_pair(v, i));\n        tree[v].push_back(make_pair(u, i));\n        \n        degree[u]++; degree[v]++;\n    }\n    \n    vector <int> frequency(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        frequency[degree[i]]++;\n    }\n    \n    vector <int> suffix_sum(no_of_vertices + 5, 0);\n    for(int i = no_of_vertices; i >= 1; i--)\n    {\n        suffix_sum[i] = suffix_sum[i + 1] + frequency[i]; \n    }\n    \n    for(int i = no_of_vertices; i >= 1; i--)\n    {\n        if(suffix_sum[i] > k)\n        {\n            no_of_colours = i;\n            break;\n        }\n    }\n    \n    dfs(1, 0, -1);\n    \n    cout << no_of_colours << \"\\n\";\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        cout << colour[i] + 1 << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Same Sum Blocks.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nstruct segment\n{\n    int left, right;\n    \n    segment(){}\n    \n    segment(int L, int R)\n    {\n        left = L; right = R;\n    }\n};\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n    \n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <int> prefix_sum(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = A[i] + prefix_sum[i - 1];\n    }\n    \n    map <int, vector <segment> > sum_blocks;\n    for(int r = 1; r <= no_of_elements; r++)\n    {\n        for(int l = 1; l <= r; l++)\n        {\n            int sum = prefix_sum[r] - prefix_sum[l - 1];\n            \n            sum_blocks[sum].push_back(segment(l, r));\n        }\n    }\n    \n    vector <segment> answer;\n    for(auto it = sum_blocks.begin(); it != sum_blocks.end(); it++)\n    {\n        int sum = it->first;\n        \n        vector <segment> answer_here;\n        \n        int last_right = -1;                                ;\n        \n        for(int i = 0; i < sum_blocks[sum].size(); i++)\n        {\n            if(sum_blocks[sum][i].left > last_right)\n            {\n                answer_here.push_back(sum_blocks[sum][i]);\n                \n                last_right = sum_blocks[sum][i].right;\n            }\n        }\n        \n        if(answer_here.size() > answer.size())\n        {\n            answer = answer_here;\n        }\n    }\n    \n    cout << answer.size() << \"\\n\";\n    for(int i = 0; i < answer.size(); i++)\n    {\n        cout << answer[i].left << \" \" << answer[i].right << \"\\n\";\n    }\n    \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 547/Programs/Superhero Battle.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nlong long ceil(long long n, long long d)\n{\n    return (n/d) + (n%d != 0);\n}\n\nint main()\n{\n    long long H, no_of_elements;\n    cin >> H >> no_of_elements;\n    \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n    }\n    \n    vector <long long> prefix_sum(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        prefix_sum[i] = A[i] + prefix_sum[i - 1];\n    }\n    \n    long long answer = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(H + prefix_sum[i] <= 0)\n        {\n            answer = i;\n            break;\n        }\n    }\n    \n    long long sum = abs(prefix_sum[no_of_elements]);\n    \n    if(answer != 0)\n    {\n        cout << answer << \"\\n\";\n        \n        return 0;\n    }\n    else if(prefix_sum[no_of_elements] >= 0)\n    {\n        cout << \"-1\\n\";\n        \n        return 0;\n    }\n    \n    answer = 2e18;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        //H + x.P[n]  + P[i] = 0\n        long long rounds_required = ceil(H + prefix_sum[i], sum);\n        \n        answer = min(answer, rounds_required*no_of_elements + i);\n    }\n    \n    cout << answer << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 590/Explanations/Special Permutations Explanation.txt",
    "content": "We can interpret the array X as a set of segments on the permutation. \n\nWe can calculate answer[1] naively. \n\nAfter that we can use answer[1] to build answer[i] for all 2 <= i <= n\n\nLet us see how each of the segments are affected when we are calculating answer[i]\n\n1. If X[j] and X[i=j + 1] contains the point i, then it reduces by 1\n\n2. If X[j] = 1 or X[j + 1] = 1, then the answer reduces by \n    a. -abs(X[j] - X[j + 1]) + abs(1 - X[j + 1]), if X[j + 1] > i\n    2. -abs(X[j] - X[j + 1]) + abs(1 - X[j + 1] - 1), if X[j + 1] < i\n\n------\n\nWe need 2 pieces of information to update answer[i]\n\n1. The number of segments covering i\n2. The pairs adjacent to i\n\n-----\n\nLet us see how we will calculate the number of segments covering i\n\nWe will put a +1 when a segment starts and a -1 when a segment ends. \n\nA segment [L, R] covers all the points [L + 1, R - 1] and we will exclude the borders \n\nThe reason is we are handling the case when i is a border separately\n\n-----\n\n    vector <int> segments_starting_at(n + 1, 0);\n    vector <int> segments_ending_at(n + 1, 0);\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(abs(X[i] - X[i + 1]) >= 2)\n        {\n            segments_starting_at[min(X[i], X[i + 1]) + 1]++;\n            segments_ending_at[max(X[i], X[i + 1]) - 1]++;\n        }\n    }\n    \n    vector <long long> segments_covering(n + 1, 0);\n    for(int i = 1; i <= n; i++)\n    {\n        segments_covering[i] = segments_covering[i - 1] + segments_starting_at[i] - segments_ending_at[i - 1];\n        \n    }\n\n-----\n\nWe will collect all pairs like this - \n\n-----\n\n    vector <vector <int> > pairs(n + 1);\n    \n    for(int i = 1; i < no_of_elements; i++)\n    {    \n        pairs[X[i]].push_back(X[i + 1]);\n        pairs[X[i + 1]].push_back(X[i]);\n    }\n\n-----\n\nAfter that, we will calculate the contribution to each pair like this\n\nEvery element in [1, i - 1] would have shifted 1 position to the right and \nevery element in [i + 1, N] would have shifted 1 position to the left \n\nOf course (i - i) = 0 so we do not need to change it\n\n-----\n\n    for(int i = 2; i <= n; i++)\n    {\n        answer[i] = answer[1] - segments_covering[i];\n        \n        for(int j = 0; j < pairs[i].size(); j++)\n        {\n            int d = pairs[i][j];\n            \n            if(d == i)\n            {\n                continue;\n            }\n            \n            if(d < i)\n            {\n                answer[i] += abs(d + 1 - 1) - abs(d - i);\n            }\n            \n            if(d > i)\n            {\n                answer[i] += abs(d - 1) - abs(d - i);\n            }\n        }\n    }\n"
  },
  {
    "path": "Contests/Div 3 590/Explanations/Yet Another Substring Reverse Explanation.txt",
    "content": "The act of reversing a substring means we can bring any 2 substrings together.\n\nWe will represent every substring of distinct characters by a mask of length 20.\n\nThe i-th bit is set if it contains the i-th alphabet and 0 otherwise.\n\nWe will maintain a bitmask for every substring and\nwill see which 2 bitmasks produce the most 1s when combined.\n\nWe can't do it in O(m^2) time, where m is the maximum mask.\n\nInstead we will maintain f(m) where f(m) is true if it is possible to reach\nat most m.\n\nSo, f(m) = max(f(m')), where m' is a mask obtained by unsetting exactly 1 set bit in m\n\n-----\n\n#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint no_of_bits(long long n)\n{\n    int bits = 0;\n\n    while(n)\n    {\n        bits += n%2;\n\n        n /= 2;\n    }\n\n    return bits;\n}\n\nlong long set_bit(long long n, int bit)\n{\n    n |= (1LL << bit);\n\n    return n;\n}\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL <<bit)) != 0);\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    const int NO_OF_LETTERS = 20;\n    int length = S.size();\n    long long max_mask = (1LL << NO_OF_LETTERS);\n\n    vector <long long> max_distinct(max_mask, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        int current_mask = 0;\n\n        for(int j = i; j < S.size(); j++)\n        {\n            if(is_bit_set(current_mask, S[j] - 'a'))\n            {\n                break;\n            }\n\n            current_mask = set_bit(current_mask, S[j] - 'a');\n\n            max_distinct[current_mask] = j - (i - 1);\n\n            //cout << \"Max Distinct \" << current_mask << \" = \" << max_distinct[current_mask] << \"\\n\";\n        }\n    }\n\n    for(int mask = 0; mask < max_mask; mask++)\n    {\n        for(int bit = 0; bit < NO_OF_LETTERS; bit++)\n        {\n            if(is_bit_set(mask, bit))\n            {\n                max_distinct[mask] = max(max_distinct[mask], max_distinct[mask^(1LL << bit)]);\n            }\n        }\n    }\n\n    long long answer = 0;\n    for(int mask = 0; mask < max_mask; mask++)\n    {\n        if(max_distinct[mask] != no_of_bits(mask))\n        {\n            continue;\n        }\n\n        int complement = (max_mask - 1)^mask;\n\n        answer = max(answer, max_distinct[mask] + max_distinct[complement]);\n    }\n\n    cout << answer;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 590/Programs/Special Permutations.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int n, no_of_elements;\n    cin >> n >> no_of_elements;\n    \n    vector <int> X(no_of_elements + 1);\n    vector <int> position(n + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> X[i];\n        \n        position[X[i]] = X[i];\n    }\n    \n    vector <vector <int> > pairs(n + 1);\n    vector <int> segments_starting_at(n + 1, 0);\n    vector <int> segments_ending_at(n + 1, 0);\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        if(abs(X[i] - X[i + 1]) >= 2)\n        {\n            segments_starting_at[min(X[i], X[i + 1]) + 1]++;\n            segments_ending_at[max(X[i], X[i + 1]) - 1]++;\n        }\n        \n        pairs[X[i]].push_back(X[i + 1]);\n        pairs[X[i + 1]].push_back(X[i]);\n    }\n    \n    vector <long long> segments_covering(n + 1, 0);\n    for(int i = 1; i <= n; i++)\n    {\n        segments_covering[i] = segments_covering[i - 1] + segments_starting_at[i] - segments_ending_at[i - 1];\n    }\n    \n    vector <long long> answer(n + 1, 0);\n    for(int i = 1; i < no_of_elements; i++)\n    {\n        answer[1] += abs(X[i] - X[i + 1]);\n    }\n    \n    for(int i = 2; i <= n; i++)\n    {\n        answer[i] = answer[1] - segments_covering[i];\n        \n        for(int j = 0; j < pairs[i].size(); j++)\n        {\n            int d = pairs[i][j];\n            \n            if(d == i)\n            {\n                continue;\n            }\n            \n            if(d < i)\n            {\n                answer[i] += abs(d + 1 - 1) - abs(d - i);\n            }\n            \n            if(d > i)\n            {\n                answer[i] += abs(d - 1) - abs(d - i);\n            }\n        }\n    }\n    \n    for(int i = 1; i <= n; i++)\n    {\n        cout << answer[i] << \" \";\n    }\n    \n    cout << \"\\n\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 590/Programs/Yet Another Substring Reverse.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint no_of_bits(long long n)\n{\n    int bits = 0;\n\n    while(n)\n    {\n        bits += n%2;\n\n        n /= 2;\n    }\n\n    return bits;\n}\n\nlong long set_bit(long long n, int bit)\n{\n    n |= (1LL << bit);\n\n    return n;\n}\n\nint is_bit_set(long long n, int bit)\n{\n    return ( (n&(1LL <<bit)) != 0);\n}\n\nint main()\n{\n    string S;\n    cin >> S;\n\n    const int NO_OF_LETTERS = 20;\n    int length = S.size();\n    long long max_mask = (1LL << NO_OF_LETTERS);\n\n    vector <long long> max_distinct(max_mask, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        int current_mask = 0;\n\n        for(int j = i; j < S.size(); j++)\n        {\n            if(is_bit_set(current_mask, S[j] - 'a'))\n            {\n                break;\n            }\n\n            current_mask = set_bit(current_mask, S[j] - 'a');\n\n            max_distinct[current_mask] = j - (i - 1);\n\n            //cout << \"Max Distinct \" << current_mask << \" = \" << max_distinct[current_mask] << \"\\n\";\n        }\n    }\n\n    for(int mask = 0; mask < max_mask; mask++)\n    {\n        for(int bit = 0; bit < NO_OF_LETTERS; bit++)\n        {\n            if(is_bit_set(mask, bit))\n            {\n                max_distinct[mask] = max(max_distinct[mask], max_distinct[mask^(1LL << bit)]);\n            }\n        }\n    }\n\n    long long answer = 0;\n    for(int mask = 0; mask < max_mask; mask++)\n    {\n        if(max_distinct[mask] != no_of_bits(mask))\n        {\n            continue;\n        }\n\n        int complement = (max_mask - 1)^mask;\n\n        answer = max(answer, max_distinct[mask] + max_distinct[complement]);\n    }\n\n    cout << answer;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 593/Explanations/Books Exchange Explanation.txt",
    "content": "Let us draw a graph and create an edge between vertice (i, P[i]). For each i, we want to know the length of the cycle it is in. \r\n\r\nWe can do this in a DFS. \r\n\r\nNote - Every vertex is visited only one time. So, the complexity is O(n) even though there are 2 for loops :)\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> P(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i];\r\n    }\r\n\r\n    vector <int> visited(no_of_elements + 1, false);\r\n    vector <int> cycle_length(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(visited[i])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        vector <int> cycle;\r\n        int v = i;\r\n\r\n        while(!visited[v])\r\n        {\r\n            visited[v] = true;\r\n\r\n            cycle.push_back(v);\r\n\r\n            v = P[v];\r\n        }\r\n\r\n        for(int g = 0; g < cycle.size(); g++)\r\n        {\r\n            int v = cycle[g];\r\n\r\n            cycle_length[v] = cycle.size();\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << cycle_length[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Div 3 593/Explanations/By Elevator or Stairs Explanation.txt",
    "content": "Let f(i, STAIRS) be the minimium time required to reach floor i using the stairs in the end. \r\n\r\nLet f(i, ELEVATOR) be the minimum time required to reach floor i using the elevator in the end. \r\n\r\nNow, let us calculate the transitions. \r\n\r\nThe base case is f(1, STARIS) = 0, f(1, ELEVATOR) = overhead\r\n\r\n-----\r\n\r\n\r\nf(i, STAIRS) = stairs[i - 1] + min{f(i - 1, STAIRS), f(i - 1, ELEVATOR)}\r\n\r\nf(i, ELEVATOR) = elevator[i - 1] + min{f(i - 1, ELEVATOR), f(i - 1, STAIRS) + overhead}\r\n\r\n---\r\n\r\nint main()\r\n{\r\n    int no_of_floors, overhead;\r\n    cin >> no_of_floors >> overhead;\r\n\r\n    vector <int> stairs(no_of_floors + 1, 0);\r\n    for(int i = 1; i < no_of_floors; i++)\r\n    {\r\n        cin >> stairs[i];\r\n    }\r\n\r\n    vector <int> elevator(no_of_floors + 1, 0);\r\n    for(int i = 1; i < no_of_floors; i++)\r\n    {\r\n        cin >> elevator[i];\r\n    }\r\n\r\n    const int STAIRS = 0, ELEVATOR = 1;\r\n    vector <vector <int> > minimum_time(no_of_floors + 1, vector <int> (2, 0));\r\n    minimum_time[1][STAIRS] = 0, minimum_time[1][ELEVATOR] = overhead;\r\n\r\n    for(int i = 2; i <= no_of_floors; i++)\r\n    {\r\n        minimum_time[i][STAIRS]   = stairs[i - 1] + min(minimum_time[i - 1][STAIRS], minimum_time[i - 1][ELEVATOR]);\r\n\r\n        minimum_time[i][ELEVATOR] = elevator[i - 1] + min(minimum_time[i - 1][ELEVATOR], minimum_time[i - 1][STAIRS] + overhead);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_floors; i++)\r\n    {\r\n        cout << min(minimum_time[i][STAIRS], minimum_time[i][ELEVATOR]) << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Div 3 593/Explanations/Good Numbers Explanation.txt",
    "content": "Let us write each number in ternary base. \n\nA few facts - \n\n1. 1000 > 0222\n\nThis can be proved by summing the series \n\n2.3^n + 2.3^{n - 1} + ... + 2.3^0\n\n= 2 (3^{n + 1} - 1)/2 \n\n= 3^{n + 1} - 1\n\n----\n\nIf the number in ternary has only 1s and 0s, then it is a good number. \n\nOtherwise there is some 2. \n\nSuppose there is some 2 at position k. We want to make this 0. So, we will have to make (k)th position 0, we will have to make increase some other position to it's left. (To maintain the invairant m >= n).\n\nWe cannot make any 1 a 2. \n\nSo, we will make some 0 a 1. \n\nOnce, we will a 0 to a 1, we will make all bits to it's right 0. \n\nFor example, suppose the integer was 100012121002112, then we will make it\n\n100012121002112\n100100000000000\n\n---\n\nvoid solve()\n{\n    unsigned long long n;\n    cin >> n;\n\n    unsigned long long temp_n = n;\n    vector <int> exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        while(temp_n >= powers[i])\n        {\n            temp_n -= powers[i];\n\n            exponent[i]++;\n        }\n    }\n\n    int left_most_2 = powers.size();\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        if(exponent[i] == 2)\n        {\n            left_most_2 = i;\n\n            break;\n        }\n    }\n\n    if(left_most_2 == powers.size())\n    {\n        cout << n << \"\\n\";\n\n        return;\n    }\n\n    int next_zero = left_most_2;\n    for(int i = left_most_2; i < powers.size(); i++)\n    {\n        if(exponent[i] == 0)\n        {\n            next_zero = i;\n\n            break;\n        }\n    }\n\n    vector <int> answer_exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i > next_zero; i--)\n        answer_exponent[i] = exponent[i];\n\n    answer_exponent[next_zero] = 1;\n    for(int i = next_zero - 1; i >= 0; i--)\n    {\n        answer_exponent[i] = 0;\n    }\n\n    unsigned long long answer = 0;\n    for(int i = 0; i < powers.size(); i++)\n    {\n        answer += answer_exponent[i]*powers[i];\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/Div 3 593/Explanations/Yet Another Dividing Into Teams Explanation.txt",
    "content": "If there are no consecutive integers, then we can have 1 team. \r\n\r\nOtherwise, we can have 1 team for the odd integers and 1 team for the even integers. \r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_people;\r\n    cin >> no_of_people;\r\n\r\n    const int MAX = 105;\r\n    vector <int> present(MAX + 1, false);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int skill;\r\n        cin >> skill;\r\n\r\n        present[skill] = true;\r\n    }\r\n\r\n    int no_of_teams = 1;\r\n    for(int i = 1; i < MAX; i++)\r\n    {\r\n        if(present[i] && present[i + 1])\r\n        {\r\n            no_of_teams = 2;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << no_of_teams << \"\\n\";\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 593/Programs/Books Exchange.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> P(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i];\r\n    }\r\n\r\n    vector <int> visited(no_of_elements + 1, false);\r\n    vector <int> cycle_length(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(visited[i])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        vector <int> cycle;\r\n        int v = i;\r\n\r\n        while(!visited[v])\r\n        {\r\n            visited[v] = true;\r\n\r\n            cycle.push_back(v);\r\n\r\n            v = P[v];\r\n        }\r\n\r\n        for(int g = 0; g < cycle.size(); g++)\r\n        {\r\n            int v = cycle[g];\r\n\r\n            cycle_length[v] = cycle.size();\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << cycle_length[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 593/Programs/Elevator or Stairs.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_floors, overhead;\r\n    cin >> no_of_floors >> overhead;\r\n\r\n    vector <int> stairs(no_of_floors + 1, 0);\r\n    for(int i = 1; i < no_of_floors; i++)\r\n    {\r\n        cin >> stairs[i];\r\n    }\r\n\r\n    vector <int> elevator(no_of_floors + 1, 0);\r\n    for(int i = 1; i < no_of_floors; i++)\r\n    {\r\n        cin >> elevator[i];\r\n    }\r\n\r\n    const int STAIRS = 0, ELEVATOR = 1;\r\n    vector <vector <int> > minimum_time(no_of_floors + 1, vector <int> (2, 0));\r\n    minimum_time[1][STAIRS] = 0, minimum_time[1][ELEVATOR] = overhead;\r\n\r\n    for(int i = 2; i <= no_of_floors; i++)\r\n    {\r\n        minimum_time[i][STAIRS]   = stairs[i - 1] + min(minimum_time[i - 1][STAIRS], minimum_time[i - 1][ELEVATOR]);\r\n\r\n        minimum_time[i][ELEVATOR] = elevator[i - 1] + min(minimum_time[i - 1][ELEVATOR], minimum_time[i - 1][STAIRS] + overhead);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_floors; i++)\r\n    {\r\n        cout << min(minimum_time[i][STAIRS], minimum_time[i][ELEVATOR]) << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 593/Programs/Good Numbers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <climits>\n\nusing namespace std;\n\nconst unsigned long long MAX_P = 55, oo = LLONG_MAX;\nunsigned long long max_good = 0;\nvector <unsigned long long> powers;\n\nvoid precompute()\n{\n    powers.push_back(1);\n\n    unsigned long long n = 1;\n    while(n <= oo/3)\n    {\n        n = n*3ULL;\n\n        powers.push_back(n);\n    }\n}\n\nvoid display(unsigned long long n)\n{\n    long long temp_n = n;\n    vector <int> exponent(powers.size(), 0);\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        while(temp_n >= powers[i])\n        {\n            temp_n -= powers[i];\n\n            exponent[i]++;\n        }\n    }\n\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        cout << exponent[i];\n    }\n\n    cout << \"\\n\";\n}\n\nvoid solve()\n{\n    unsigned long long n;\n    cin >> n;\n\n    unsigned long long temp_n = n;\n    vector <int> exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        while(temp_n >= powers[i])\n        {\n            temp_n -= powers[i];\n\n            exponent[i]++;\n        }\n    }\n\n    int left_most_2 = powers.size();\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        if(exponent[i] == 2)\n        {\n            left_most_2 = i;\n\n            break;\n        }\n    }\n\n    if(left_most_2 == powers.size())\n    {\n        cout << n << \"\\n\";\n\n        return;\n    }\n\n    int next_zero = left_most_2;\n    for(int i = left_most_2; i < powers.size(); i++)\n    {\n        if(exponent[i] == 0)\n        {\n            next_zero = i;\n\n            break;\n        }\n    }\n\n    vector <int> answer_exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i > next_zero; i--)\n        answer_exponent[i] = exponent[i];\n\n    answer_exponent[next_zero] = 1;\n    for(int i = next_zero - 1; i >= 0; i--)\n    {\n        answer_exponent[i] = 0;\n    }\n\n    unsigned long long answer = 0;\n    for(int i = 0; i < powers.size(); i++)\n    {\n        answer += answer_exponent[i]*powers[i];\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    precompute();\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Contests/Div 3 593/Programs/Yet Another Dividing Into Teams.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_people;\r\n    cin >> no_of_people;\r\n\r\n    const int MAX = 105;\r\n    vector <int> present(MAX + 1, false);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int skill;\r\n        cin >> skill;\r\n\r\n        present[skill] = true;\r\n    }\r\n\r\n    int no_of_teams = 1;\r\n    for(int i = 1; i < MAX; i++)\r\n    {\r\n        if(present[i] && present[i + 1])\r\n        {\r\n            no_of_teams = 2;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << no_of_teams << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 595/Explanations/Books Exchange Explanation.txt",
    "content": "Let us draw a graph and create an edge between vertice (i, P[i]). For each i, we want to know the length of the cycle it is in. \r\n\r\nWe can do this in a DFS. \r\n\r\nNote - Every vertex is visited only one time. So, the complexity is O(n) even though there are 2 for loops :)\r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> P(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i];\r\n    }\r\n\r\n    vector <int> visited(no_of_elements + 1, false);\r\n    vector <int> cycle_length(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(visited[i])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        vector <int> cycle;\r\n        int v = i;\r\n\r\n        while(!visited[v])\r\n        {\r\n            visited[v] = true;\r\n\r\n            cycle.push_back(v);\r\n\r\n            v = P[v];\r\n        }\r\n\r\n        for(int g = 0; g < cycle.size(); g++)\r\n        {\r\n            int v = cycle[g];\r\n\r\n            cycle_length[v] = cycle.size();\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << cycle_length[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Div 3 595/Explanations/Good Numbers Explanation.txt",
    "content": "Let us write each number in ternary base. \n\nA few facts - \n\n1. 1000 > 0222\n\nThis can be proved by summing the series \n\n2.3^n + 2.3^{n - 1} + ... + 2.3^0\n\n= 2 (3^{n + 1} - 1)/2 \n\n= 3^{n + 1} - 1\n\n----\n\nIf the number in ternary has only 1s and 0s, then it is a good number. \n\nOtherwise there is some 2. \n\nSuppose there is some 2 at position k. We want to make this 0. So, we will have to make (k)th position 0, we will have to make increase some other position to it's left. (To maintain the invairant m >= n).\n\nIf we have to remove a 2 from position k, we need to add another 3^k to this integer. This makes the next position 3^{k + 1} and increases it from either 0 to 1 or from 1 to 2. We do not want to make any 1 a 2. So we will continue this till we find a 0 and make it a 1. \n\nWe cannot increase any 1 to a 2. \n\nSo, we will increase some 0 a 1. \n\nAmong all 0s, we will choose the first 0 to the left of the 2.\n\nOnce, we will a 0 to a 1, we will make all bits to it's right 0. \n\n----\n\nThe reason is that 10000 > 02222\n\n----\n\nFor example, suppose the integer was 100012121002112, then we will make it\n\n100012121002112\n100100000000000\n\n---\n\nvoid solve()\n{\n    unsigned long long n;\n    cin >> n;\n\n    unsigned long long temp_n = n;\n    vector <int> exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        while(temp_n >= powers[i])\n        {\n            temp_n -= powers[i];\n\n            exponent[i]++;\n        }\n    }\n\n    int left_most_2 = powers.size();\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        if(exponent[i] == 2)\n        {\n            left_most_2 = i;\n\n            break;\n        }\n    }\n\n    if(left_most_2 == powers.size())\n    {\n        cout << n << \"\\n\";\n\n        return;\n    }\n\n    int next_zero = left_most_2;\n    for(int i = left_most_2; i < powers.size(); i++)\n    {\n        if(exponent[i] == 0)\n        {\n            next_zero = i;\n\n            break;\n        }\n    }\n\n    vector <int> answer_exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i > next_zero; i--)\n        answer_exponent[i] = exponent[i];\n\n    answer_exponent[next_zero] = 1;\n    for(int i = next_zero - 1; i >= 0; i--)\n    {\n        answer_exponent[i] = 0;\n    }\n\n    unsigned long long answer = 0;\n    for(int i = 0; i < powers.size(); i++)\n    {\n        answer += answer_exponent[i]*powers[i];\n    }\n\n    cout << answer << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/Div 3 595/Explanations/Yet Another Dividing Into Teams Explanation.txt",
    "content": "If there are no consecutive integers, then we can have 1 team. \r\n\r\nOtherwise, we can have 1 team for the odd integers and 1 team for the even integers. \r\n\r\n------\r\n\r\nvoid solve()\r\n{\r\n    int no_of_people;\r\n    cin >> no_of_people;\r\n\r\n    const int MAX = 105;\r\n    vector <int> present(MAX + 1, false);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int skill;\r\n        cin >> skill;\r\n\r\n        present[skill] = true;\r\n    }\r\n\r\n    int no_of_teams = 1;\r\n    for(int i = 1; i < MAX; i++)\r\n    {\r\n        if(present[i] && present[i + 1])\r\n        {\r\n            no_of_teams = 2;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << no_of_teams << \"\\n\";\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 595/Programs/Books Exchange.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> P(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> P[i];\r\n    }\r\n\r\n    vector <int> visited(no_of_elements + 1, false);\r\n    vector <int> cycle_length(no_of_elements + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(visited[i])\r\n        {\r\n            continue;\r\n        }\r\n\r\n        vector <int> cycle;\r\n        int v = i;\r\n\r\n        while(!visited[v])\r\n        {\r\n            visited[v] = true;\r\n\r\n            cycle.push_back(v);\r\n\r\n            v = P[v];\r\n        }\r\n\r\n        for(int g = 0; g < cycle.size(); g++)\r\n        {\r\n            int v = cycle[g];\r\n\r\n            cycle_length[v] = cycle.size();\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cout << cycle_length[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 595/Programs/Good Numbers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <climits>\n\nusing namespace std;\n\nconst unsigned long long MAX_P = 55, oo = LLONG_MAX;\nunsigned long long max_good = 0;\nvector <unsigned long long> powers;\n\nvoid precompute()\n{\n    powers.push_back(1);\n\n    unsigned long long n = 1;\n    while(n <= oo/3)\n    {\n        n = n*3ULL;\n\n        powers.push_back(n);\n    }\n}\n\nvoid display(unsigned long long n)\n{\n    long long temp_n = n;\n    vector <int> exponent(powers.size(), 0);\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        while(temp_n >= powers[i])\n        {\n            temp_n -= powers[i];\n\n            exponent[i]++;\n        }\n    }\n\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        cout << exponent[i];\n    }\n\n    cout << \"\\n\";\n}\n\nvoid solve()\n{\n    unsigned long long n;\n    cin >> n;\n\n    unsigned long long temp_n = n;\n    vector <int> exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        while(temp_n >= powers[i])\n        {\n            temp_n -= powers[i];\n\n            exponent[i]++;\n        }\n    }\n\n    int left_most_2 = powers.size();\n    for(int i = powers.size() - 1; i >= 0; i--)\n    {\n        if(exponent[i] == 2)\n        {\n            left_most_2 = i;\n\n            break;\n        }\n    }\n\n    if(left_most_2 == powers.size())\n    {\n        cout << n << \"\\n\";\n\n        return;\n    }\n\n    int next_zero = left_most_2;\n    for(int i = left_most_2; i < powers.size(); i++)\n    {\n        if(exponent[i] == 0)\n        {\n            next_zero = i;\n\n            break;\n        }\n    }\n\n    vector <int> answer_exponent(powers.size() + 5, 0);\n    for(int i = powers.size() - 1; i > next_zero; i--)\n        answer_exponent[i] = exponent[i];\n\n    answer_exponent[next_zero] = 1;\n    for(int i = next_zero - 1; i >= 0; i--)\n    {\n        answer_exponent[i] = 0;\n    }\n\n    unsigned long long answer = 0;\n    for(int i = 0; i < powers.size(); i++)\n    {\n        answer += answer_exponent[i]*powers[i];\n    }\n\n    cout << answer << \"\\n\";\n}\n\nint main()\n{\n    precompute();\n\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n\n"
  },
  {
    "path": "Contests/Div 3 595/Programs/Yet Another Dividing Into Teams.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_people;\r\n    cin >> no_of_people;\r\n\r\n    const int MAX = 105;\r\n    vector <int> present(MAX + 1, false);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int skill;\r\n        cin >> skill;\r\n\r\n        present[skill] = true;\r\n    }\r\n\r\n    int no_of_teams = 1;\r\n    for(int i = 1; i < MAX; i++)\r\n    {\r\n        if(present[i] && present[i + 1])\r\n        {\r\n            no_of_teams = 2;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << no_of_teams << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 598/Explanations/Equalizing Two Strings Explanation.txt",
    "content": "https://qr.ae/TW4mma\n\n1. If S and T do not all have the same letters, then we cannot make them equal. \n\n---\n\n2. Let us suppose S and T have the same letters and some letter occurs twice. \n\nS = A ... S .. S ... \n\nT = ......X ... Y ... \n\n(Let us assume that the letter S occurs twice). \n\nWe will flip the segment of length such that [S, S] come together in S and do some arbitrary flip of the same length in T. \n\n\nAfter this, we will swap adjacent elements in T to make it equal to S, and always choose the segment [SS] in S. \n\nThis makes sure that S does not change at any step and is the same as making T = S, given that we can swap adjacent elements in T and T has the same elements as S.\n\n---\n\n3. Now, let us suppose that each letter occurs only one time. \n\nThey are both permutations. \n\nA very important quality of permutations is their parity. Let us observe what happens to permutations' inversions, when we flip their parity. \n\n(Inversions is the number of pairs (i, j) such that A[i] > A[j] and (i < j). In other words, the number of pairs that are 'out of order'.)\n\n---\n\nLet us suppose that S' is a segment of S. \n\nThere are 3 types of inversions in S. \n\ni. Both the characters lie in S\nii. One Character lies in S and the other lies in S'\niii. Both the characters lie in S'\n\nType i and Type ii inversions are not affected by reversing S'\n\nLet us see how the Type iii inversions change. \n\nSuppose there were originally X inversions in the segment S'. \n\nThen, when we flip S', the number of inversions becomes C(|S'|,2) - X. \n\nSuppose C(|S'|, 2) is even, then the parity of the number of inversions remains the same. \nSuppose C(|S'|, 2) is odd, then it flips the parity of the number of inversions. \n\nAmazingly, the parity of the inversions depends only on the length of the segment we reverse and not at all on the permutation itself !\n\n---\n\nAt each flip, either the parity of both S and T are the same or the parity of both S and T get flipped. \n\nThis means that if their parities are initially not equal, they will remain so at each step. \n\nWe can check the parity in O(n^2) time since the length of a distinct string (permutation) can be at most 26.\n\n---\n\nSuppose the parities are equal, is it always possible to make S = T. \n\nWe can keep swapping a pair of adjacent elements an even number of times to make sure 1 string is not changed and keep flipping some adjacent pair of the other string too !\n\n---\n\nint parity(string &P)\n{\n    int inversions = 0;\n    for(int i = 0; i < P.size(); i++)\n    {\n        for(int j = i + 1; j < P.size(); j++)\n        {\n            if(P[i] > P[j])\n            {\n                inversions++;\n            }\n        }\n    }\n\n    return (inversions%2);\n}\n\nvoid solve()\n{\n    int length;\n    string S, T;\n    cin >> length >> S >> T;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <int> frequency_S(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        frequency_S[S[i] - 'a']++;\n    }\n\n    vector <int> frequency_T(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < T.size(); i++)\n    {\n        frequency_T[T[i] - 'a']++;\n    }\n\n    int same_characters = true;\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\n    {\n        if(frequency_S[i] != frequency_T[i])\n        {\n            same_characters = false;\n        }\n    }\n\n    int duplicates_present = false;\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\n    {\n        if(frequency_S[i] > 1)\n        {\n            duplicates_present = true;\n        }\n    }\n\n    if(same_characters)\n    {\n        if(duplicates_present)\n        {\n            cout << \"Yes\\n\";\n        }\n        else\n        {\n            cout << (parity(S) == parity(T) ? \"Yes\\n\" : \"No\\n\");\n        }\n    }\n    else\n    {\n        cout << \"No\\n\";\n    }\n}\n\n"
  },
  {
    "path": "Contests/Div 3 598/Explanations/Minimize the Permutation Explanation.txt",
    "content": "Let A[L, R] be the portion of the array we are allowed to do operaitions on. \r\n\r\n1. Initially, we can do operations on A[1, N]. \r\n \r\nFirst, we will search for 1, we will put it either in the first position or put it as left as we can. \r\n\r\nSuppose 1 was originally at position - P. \r\n\r\n2. Now, we can only do operations in A[P, N].\r\n\r\nWe will look for the minimum element in A[P, N] and put the smallest integer in position P or else use all our operations and push it as much towards the left as we can. \r\n\r\n---\r\n\r\nThis works because at each step, we are taking the minimum element and pushing it as much to the left as possible. \r\n\r\nIn the first step, we will put 1 in the first position. Obviously, this is the best choice for the first position. If we put some element to the left of 1 (say X) at the first position, then we cannot bring 1 over till the first position. We can only put 1 at A[X] in the best case. \r\n\r\nIt is better to have 1 at A[1] then at A[X]. \r\n\r\nClearly, the first step is the best. \r\n\r\nWe maintain the invariant that A[L, R] has not been touched. \r\n\r\nNow, when A[L, R] is the only segment we can touch, it is best to put the minimum element in A[L, R] at A[L]. Any other choice would lead to a larger string. \r\n\r\nHence, this algorithm is correct.\r\n\r\n---\r\n\r\nIn general the algorithm is the following - \r\n\r\n1. L = 1, R = N\r\n\r\n2. Look for the minimum element in A[L, R]\r\n\r\n3. Let it be at position P. \r\n\r\n4. Use the swaps to bring A[P] to A[L]. \r\n\r\n5. Set L = min{L + 1, P} and continue this process till either no operations are left or L = N\r\n\r\n---\r\n\r\nvoid solve()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    vector <int> permutation(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        cin >> permutation[i];\r\n    }\r\n\r\n    int last_operated = 0;\r\n    for(int no_of_operations = 0; no_of_operations <= n - 1 && last_operated < n - 1; )\r\n    {\r\n        int minimum = n + 1;\r\n        int p = last_operated + 1;\r\n        for(int i = last_operated + 1; i <= n; i++)\r\n        {\r\n            if(permutation[i] < minimum)\r\n            {\r\n                minimum = permutation[i];\r\n                p = i;\r\n            }\r\n        }\r\n\r\n        for(int i = p - 1; i > last_operated && no_of_operations <= n - 1; i--)\r\n        {\r\n            swap(permutation[i], permutation[i + 1]);\r\n            no_of_operations++;\r\n        }\r\n\r\n        last_operated = max(last_operated + 1, p - 1);\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        cout << permutation[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Div 3 598/Explanations/Payment Without Change Explanation.txt",
    "content": "My idea was to be greedy. \r\n\r\n1. Use as many N's as you have or get as close as possible to the target T. \r\n\r\nIf we use all our N's, we will have reached (aN)\r\n\r\nThe closest we can get to T, is (T/N). We can reach here only if a >= (T/N).\r\n\r\n----\r\n\r\nSo, we will reach min{aN, (T/N)N}\r\n\r\n----\r\n\r\nThe remaining values will have to be made by 1's. \r\n\r\nSo (T - nearest) >= b, for the construction to be possible. \r\n\r\n----\r\n\r\nvoid solve()\r\n{\r\n    long long no_of_n, no_of_1, n, target;\r\n    cin >> no_of_n >> no_of_1 >> n >> target;\r\n\r\n    //Nx + y = B\r\n\r\n    long long nearest = min((target/n)*n, no_of_n*n);\r\n\r\n    cout << ((target - nearest <= no_of_1) ? \"Yes\\n\" : \"No\\n\");\r\n}\r\n\r\n----\r\n\r\nThe editorial had a cleaner solution. \r\n\r\nFirst of all, we need as many 1's as {T (mod N)}\r\n\r\nThen, we just need to check if (aN + b >= T). \r\n\r\nIf yes, we can always go till the nearest or last multiple of N and then use 1s.\r\n\r\nIf we don't have the required number of 1s {T (mod N)}, then we can never reach T. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    long long no_of_n, no_of_1, n, target;\r\n    cin >> no_of_n >> no_of_1 >> n >> target;\r\n\r\n    //Nx + y = B\r\n\r\n    long long nearest = min((target/n)*n, no_of_n*n);\r\n\r\n    cout << (no_of_1 >= (target%n) && (no_of_n&n + no_of_1 >= target) ? \"Yes\\n\" : \"No\\n\");\r\n}"
  },
  {
    "path": "Contests/Div 3 598/Programs/Binary String Minimizing.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    long long length, moves;\r\n    cin >> length >> moves;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    long long current_distance = 0;\r\n    for(int i = 0; i < length && moves > 0; i++)\r\n    {\r\n        if(S[i] == '1')\r\n        {\r\n            current_distance++;\r\n        }\r\n        else\r\n        {\r\n            int steps_taken = min(current_distance, moves);\r\n\r\n            swap(S[i], S[i - steps_taken]);\r\n\r\n            moves -= steps_taken;\r\n        }\r\n    }\r\n\r\n    cout << S << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Div 3 598/Programs/Equalizing Two Strings.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint parity(string &P)\n{\n    int inversions = 0;\n    for(int i = 0; i < P.size(); i++)\n    {\n        for(int j = i + 1; j < P.size(); j++)\n        {\n            if(P[i] > P[j])\n            {\n                inversions++;\n            }\n        }\n    }\n\n    return (inversions%2);\n}\n\nvoid solve()\n{\n    int length;\n    string S, T;\n    cin >> length >> S >> T;\n\n    const int NO_OF_ALPHABETS = 26;\n    vector <int> frequency_S(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < S.size(); i++)\n    {\n        frequency_S[S[i] - 'a']++;\n    }\n\n    vector <int> frequency_T(NO_OF_ALPHABETS, 0);\n    for(int i = 0; i < T.size(); i++)\n    {\n        frequency_T[T[i] - 'a']++;\n    }\n\n    int same_characters = true;\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\n    {\n        if(frequency_S[i] != frequency_T[i])\n        {\n            same_characters = false;\n        }\n    }\n\n    int duplicates_present = false;\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\n    {\n        if(frequency_S[i] > 1)\n        {\n            duplicates_present = true;\n        }\n    }\n\n    if(same_characters)\n    {\n        if(duplicates_present)\n        {\n            cout << \"Yes\\n\";\n        }\n        else\n        {\n            cout << (parity(S) == parity(T) ? \"Yes\\n\" : \"No\\n\");\n        }\n    }\n    else\n    {\n        cout << \"No\\n\";\n    }\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n    {\n        solve();\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Div 3 598/Programs/Minimize the Permutation.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    vector <int> permutation(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        cin >> permutation[i];\r\n    }\r\n\r\n    int last_operated = 0;\r\n    for(int no_of_operations = 0; no_of_operations <= n - 1 && last_operated < n - 1; )\r\n    {\r\n        int minimum = n + 1;\r\n        int p = last_operated + 1;\r\n        for(int i = last_operated + 1; i <= n; i++)\r\n        {\r\n            if(permutation[i] < minimum)\r\n            {\r\n                minimum = permutation[i];\r\n                p = i;\r\n            }\r\n        }\r\n\r\n        for(int i = p - 1; i > last_operated && no_of_operations <= n - 1; i--)\r\n        {\r\n            swap(permutation[i], permutation[i + 1]);\r\n            no_of_operations++;\r\n        }\r\n\r\n        last_operated = max(last_operated + 1, p - 1);\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        cout << permutation[i] << \" \";\r\n    }\r\n\r\n    cout << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Div 3 598/Programs/Payment Without Change.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    long long no_of_n, no_of_1, n, target;\r\n    cin >> no_of_n >> no_of_1 >> n >> target;\r\n\r\n    //Nx + y = B\r\n\r\n    long long nearest = min((target/n)*n, no_of_n*n);\r\n\r\n    cout << ((target - nearest <= no_of_1) ? \"Yes\\n\" : \"No\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 11/Explanations/Co Prime Array Explanation.txt",
    "content": "You are given an array of n elements, you must make it a co-prime array in as few moves as possible.\r\n\r\nIn each move you can insert any positive integral number you want not greater than 109 in any place in the array.\r\n\r\nAn array is co-prime if any two adjacent numbers of it are co-prime.\r\n\r\nIn the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.\r\n\r\n----------------------------------------------\r\n\r\nThis is similar to the question asking what is the smallest currency that cannot be expressed. If there is no 1, it is 1 and if 1 is there all can be expressed.\r\n\r\nOr is there an element in this array which divides every other element ? If it is yes, then it has to be the smallest element.\r\n\r\nOr what is the length of longest coprime sequence in array ? If any two elements are coprime, entire array is coprime.\r\n\r\nHere, the observation needed is that gcd(1, n) = 1.\r\n\r\nInsert all elements into the new vector, but just check if adjacent elements are coprime. If any two adjacent elements are not coprime. Insert a 1 in between.\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    vector <int> coprime_array;\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number_i;\r\n        scanf(\"%d\", &number_i);\r\n\r\n        if(i == 1 || gcd(coprime_array.back(), number_i) == 1)\r\n        {\r\n            coprime_array.push_back(number_i);\r\n        }\r\n        else\r\n        {\r\n            coprime_array.push_back(1);\r\n            coprime_array.push_back(number_i);\r\n        }\r\n    }\r\n\r\n    int no_of_operations = coprime_array.size() - no_of_numbers;\r\n\r\n    printf(\"%d\\n\", no_of_operations);\r\n    for(unsigned int i = 0; i < coprime_array.size(); i++)\r\n        printf(\"%d \", coprime_array[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 11/Explanations/Hard Process Explanation.txt",
    "content": "\r\nHere's the trick. \r\n\r\nMaintain two pointers, [L, R]. \r\n\r\nWe want the largest segment with at most k 0s. \r\n\r\nnow, to do this fix L and let R go as far as possible till it has at most k 0s. \r\n\r\nOnce there are more than K 0's, then\r\n\r\nIncrement L till there are <= K 0's. \r\n\r\nNow, if R is at position X, when no of 0's = K + 1, \r\n\r\nThere is no need to start checking all segments from [L + 1, L + 2], [L + 1, L + 3], .... [L + 1, X] and so on and so forth. \r\n\r\nWe know that [L, X - 1] was a good segment. And all these segments are smaller than it. \r\n\r\nWe only need to check larger segments. So for every possible left from [L, X- 1], we check only larger intervals, [L + 1, X + 1] and so on. \r\n\r\nIf we know [L, X - 1] is a good segment, there is no need to check intervals smaller than that. \r\n\r\n---------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, max_zeroes;\r\n    scanf(\"%d %d\", &no_of_elements, &max_zeroes);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int no_of_0s = 0;\r\n    int change_left = 0, change_right = 0, left = 1, right = 1, max_window_size = 0;\r\n\r\n    while(right <= no_of_elements)\r\n    {\r\n        if(A[right] == 0)\r\n            no_of_0s++;\r\n\r\n        while(no_of_0s > max_zeroes)\r\n        {\r\n            if(A[left] == 0)\r\n                no_of_0s--;\r\n\r\n            left++;\r\n        }\r\n\r\n        int window_size = right - (left - 1);\r\n        if(window_size > max_window_size)\r\n        {\r\n            max_window_size = window_size, change_left = left, change_right = right;\r\n        }\r\n\r\n        right++;\r\n    }\r\n\r\n    for(int i = change_left; i <= change_right; i++) A[i] = 1;\r\n\r\n    printf(\"%d\\n\", max_window_size);\r\n    for(int i = 1; i <= no_of_elements; i++) printf(\"%d \", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 11/Explanations/Number of Parallelograms Explanation.txt",
    "content": "Now fact - diagonals of a parallelogram intersect each other. \n\nSo iterate over every pair of points and keep track of the frequency of each mid-point.\n\nOne implementation trick I learnt in this problem is that if you're using a map for a structure\nyou need to overload the < operator so that the map knows how to order the elements !\n\nIf it can't distinguish between two points, it thinks it's the same.\n\n-----------------------------------\n\nstruct Point\n{\n    int x, y;\n\n    Point(int X, int Y)\n    {\n        x = X, y = Y;\n    }\n\n    //A binary search tree needs the elements to be ordered.\n    int operator<(const Point &P) const //This needs to be overloaded for the map to work\n    {\n        return (x == P.x ? y < P.y : x < P.x);\n    }\n};\n\nlong long choose_2(long long n)\n{\n    return (n*(n - 1))/2;\n}\n\nint main()\n{\n    int no_of_points;\n    cin >> no_of_points;\n\n    vector <Point> P;\n    for(int i = 1; i <= no_of_points; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n\n        P.push_back(Point(x, y));\n    }\n\n    map <Point, int> frequency;\n    for(int i = 0; i < no_of_points; i++)\n    {\n        for(int j = i + 1; j < no_of_points; j++)\n        {\n            //Avoid floating point errors so store (x1 + x2), (y1 + y2) rather than dividing.\n            Point mid_point = Point( (P[i].x  + P[j].x), (P[i].y + P[j].y) );\n\n            frequency[mid_point]++;\n        }\n    }\n\n    long long answer = 0;\n    for(map <Point, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\n    {\n        answer += choose_2(it->second);\n    }\n\n    cout << answer;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 11/Programs/Co Prime Array.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    vector <int> coprime_array;\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number_i;\r\n        scanf(\"%d\", &number_i);\r\n\r\n        if(i == 1 || gcd(coprime_array.back(), number_i) == 1)\r\n        {\r\n            coprime_array.push_back(number_i);\r\n        }\r\n        else\r\n        {\r\n            coprime_array.push_back(1);\r\n            coprime_array.push_back(number_i);\r\n        }\r\n    }\r\n\r\n    int no_of_operations = coprime_array.size() - no_of_numbers;\r\n\r\n    printf(\"%d\\n\", no_of_operations);\r\n    for(unsigned int i = 0; i < coprime_array.size(); i++)\r\n        printf(\"%d \", coprime_array[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 11/Programs/Hard Process.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, max_zeroes;\r\n    scanf(\"%d %d\", &no_of_elements, &max_zeroes);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int no_of_0s = 0;\r\n    int change_left = 0, change_right = 0, left = 1, right = 1, max_window_size = 0;\r\n\r\n    while(right <= no_of_elements)\r\n    {\r\n        if(A[right] == 0)\r\n            no_of_0s++;\r\n\r\n        while(no_of_0s > max_zeroes)\r\n        {\r\n            if(A[left] == 0)\r\n                no_of_0s--;\r\n\r\n            left++;\r\n        }\r\n\r\n        int window_size = right - (left - 1);\r\n        if(window_size > max_window_size)\r\n        {\r\n            max_window_size = window_size, change_left = left, change_right = right;\r\n        }\r\n\r\n        right++;\r\n    }\r\n\r\n    for(int i = change_left; i <= change_right; i++) A[i] = 1;\r\n\r\n    printf(\"%d\\n\", max_window_size);\r\n    for(int i = 1; i <= no_of_elements; i++) printf(\"%d \", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 11/Programs/Number of Parallelograms.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nstruct Point\n{\n    int x, y;\n\n    Point(int X, int Y)\n    {\n        x = X, y = Y;\n    }\n\n    //A binary search tree needs the elements to be ordered.\n    int operator<(const Point &P) const //This needs to be overloaded for the map to work\n    {\n        return (x == P.x ? y < P.y : x < P.x);\n    }\n};\n\nlong long choose_2(long long n)\n{\n    return (n*(n - 1))/2;\n}\n\nint main()\n{\n    int no_of_points;\n    cin >> no_of_points;\n\n    vector <Point> P;\n    for(int i = 1; i <= no_of_points; i++)\n    {\n        int x, y;\n        cin >> x >> y;\n\n        P.push_back(Point(x, y));\n    }\n\n    map <Point, int> frequency;\n    for(int i = 0; i < no_of_points; i++)\n    {\n        for(int j = i + 1; j < no_of_points; j++)\n        {\n            //Avoid floating point errors so store (x1 + x2), (y1 + y2) rather than dividing.\n            Point mid_point = Point( (P[i].x  + P[j].x), (P[i].y + P[j].y) );\n\n            frequency[mid_point]++;\n        }\n    }\n\n    long long answer = 0;\n    for(map <Point, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\n    {\n        answer += choose_2(it->second);\n    }\n\n    cout << answer;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 32/Explanations/Almost Identity Permutations Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUprHm\n\nThe key to note here is that k is very small. \n\nFirst we must choose k spots out of n. \n\nNow, we can fill these k spots in derangement(k) number of ways. \n\nHow to find a recurrence for d(n) ?\n\nConsider we have n numbers .... \n\nNow, let us place n at position i. (There are (n - 1) choices for this.)\n\nThere are two possibilities for i - Either it is at position n, or it is at some other position.\n\nNow if i is placed at position n, then the remaining (n - 2) numbers must be deranged ... given by d(n - 2).\n\nWhat if i is placed at some position other than n ? \n\nThen notice now that we have a situation where every element has exactly one spot it cannot fill. \n\n(1 cannot be in 1, \n2 cannot be in 2, \n3 cannot be in 3, \n.\n.\ni - 1 cannot be in i - 1\ni cannot be in N\ni + 1 cannot be in i + 1\n. \n.\nN - 1 cannot be in N - 1)\n\nWe have i-1 elements and i - 1 positions to fill them, and each element cannot occupy one spot. \n\nTotal answer = (n - 1)(d(n - 1) + d(n - 2))\n\n(n - 1) choices to place n, and then accordingly d(n - 1) or d(n - 2)\n\nFor convenience, when 0 elements are out of place, I want to add 1 to the answer for this question so define d(0) = 1\n\n------------------------------------------------------------------\n\nlong long choose(int n, int r)\n{\n    if(r == 0 || r == n)\n        return 1;\n    if(r == 1 || r == n - 1)\n        return n;\n\n    return choose(n - 1, r) + choose(n - 1, r - 1);\n}\n\nlong long derangements(int n)\n{\n    if(n == 0)\n        return 1;\n    if(n == 1)\n        return 0;\n    if(n == 2)\n        return 1;\n\n    return (n - 1)*(derangements(n - 1) + derangements(n - 2));\n}\n\nint main()\n{\n    int n, k;\n    scanf(\"%d %d\", &n, &k);\n\n    long long answer = 0;\n    for(int i = 0; i <= k; i++)\n    {\n        answer += choose(n, i)*derangements(i);\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 32/Explanations/Buggy Robot.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_instructions;\r\n    string instructions;\r\n    cin >> no_of_instructions >> instructions;\r\n\r\n    int lefts = 0, rights = 0, ups = 0, downs = 0;\r\n\r\n    for(int i = 0; i < no_of_instructions; i++)\r\n    {\r\n        lefts  += (instructions[i] == 'L');\r\n        rights += (instructions[i] == 'R');\r\n        downs  += (instructions[i] == 'D');\r\n        ups    += (instructions[i] == 'U');\r\n    }\r\n\r\n    int max_correct_instructions = 2*min(lefts, rights) + 2*min(ups, downs);\r\n    cout << max_correct_instructions;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 32/Explanations/K-Dominant Character Explanation.txt",
    "content": "\r\nAt first, I thought that if a string is K-dominant, it is also (K + 1)-dominant. \r\n\r\nIf it is not K-dominant, it is not (K - 1)-dominant either.\r\n\r\nThis suggests binary search, How to check if a string is x dominant ?\r\n\r\nDo 26 O(n) scans. For each alphabet, check if it occurs at least once in every substring of length x. \r\n\r\nNow, if there's at least one alphabet that satisfies this, the string is x-dominant.\r\n\r\n--------------------------------------------------------------\r\n\r\nint is_possible(int k, int length)\r\n{\r\n    for(int alphabet = 0; alphabet < NO_OF_LETTERS; alphabet++)\r\n    {\r\n        int alphabet_occurs_in_every_segment = true;\r\n\r\n        for(int left = 1, right = k; right <= length; left++, right++)\r\n        {\r\n            int alphabet_frequency_here = frequency[alphabet][right] - frequency[alphabet][left - 1];\r\n\r\n            if(alphabet_frequency_here == 0)\r\n                alphabet_occurs_in_every_segment = false;\r\n        }\r\n\r\n        if(alphabet_occurs_in_every_segment)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n---------------------------------------------------------------\r\n\r\nDo binary search for this -\r\n\r\nint answer, start = 1, end = length;\r\n\r\n    while(start <= end)\r\n    {\r\n        int mid = (start + end) >> 1;\r\n\r\n        if(is_possible(mid, length))\r\n        {\r\n            if(!is_possible(mid - 1, length))\r\n            {\r\n                answer = mid;\r\n                break;\r\n            }\r\n            else\r\n            {\r\n                end = mid - 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            start = mid;\r\n        }\r\n    }\r\n\r\n------------------------------------------------------------------------------------\r\n\r\nProblem is this might take about 20 x 26 O(n) scans. \r\n\r\nThis is too much !\r\n\r\nHere's how we reduce it. \r\n\r\nThe idea of solving it seperately for each alphabet is correct, \r\n\r\nFor a given alphabet i, how do we find the minimum length k, such that the string is k-dominant for character i.\r\n\r\nThe minimum length is the maximum distance S, between any two consecutive occurences of i.\r\n\r\nIf k > S, then by definition we will have an i on the segment S. If K < S, then there is at least one segment which does not have i. \r\n\r\nNow, we find the k for all alphabets, and the minimum k is our answer !\r\n\r\n-------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_LETTERS = 26;\r\n    int length = S.size(), answer = S.size();\r\n\r\n    for(int alphabet = 0; alphabet < NO_OF_LETTERS; alphabet++)\r\n    {\r\n        int last_occurence = -1, largest_gap_for_this_alphabet = 0;\r\n\r\n        for(int i = 0; S[i] != '\\0'; i++)\r\n        {\r\n            if(S[i] == 'a' + alphabet)\r\n            {\r\n                largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, i - last_occurence);\r\n                last_occurence = i;\r\n            }\r\n        }\r\n\r\n        largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, length - last_occurence);\r\n\r\n        answer = min(answer, largest_gap_for_this_alphabet);\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 32/Explanations/Local Extrema Explanation.txt",
    "content": "Go from 2 to N - 1 and check in O(n).\r\n\r\nint is_extrema(int mid, int start, int end)\r\n{\r\n    return ((start < mid && end < mid) || (mid < start && mid < end));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    int local_extrema = 0;\r\n    for(int i = 2; i < no_of_elements; i++)\r\n        local_extrema += is_extrema(A[i], A[i - 1], A[i + 1]);\r\n\r\n    printf(\"%d\\n\", local_extrema);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 32/Programs/Almost Identity Permutations.cpp",
    "content": "#include <cstdio>\n\nlong long choose(int n, int r)\n{\n    if(r == 0 || r == n)\n        return 1;\n    if(r == 1 || r == n - 1)\n        return n;\n\n    return choose(n - 1, r) + choose(n - 1, r - 1);\n}\n\nlong long derangements(int n)\n{\n    if(n == 0)\n        return 1;\n    if(n == 1)\n        return 0;\n    if(n == 2)\n        return 1;\n\n    return (n - 1)*(derangements(n - 1) + derangements(n - 2));\n}\n\nint main()\n{\n    int n, k;\n    scanf(\"%d %d\", &n, &k);\n\n    long long answer = 0;\n    for(int i = 0; i <= k; i++)\n    {\n        answer += choose(n, i)*derangements(i);\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 32/Programs/Buggy Robot.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_instructions;\r\n    string instructions;\r\n    cin >> no_of_instructions >> instructions;\r\n\r\n    int lefts = 0, rights = 0, ups = 0, downs = 0;\r\n\r\n    for(int i = 0; i < no_of_instructions; i++)\r\n    {\r\n        lefts  += (instructions[i] == 'L');\r\n        rights += (instructions[i] == 'R');\r\n        downs  += (instructions[i] == 'D');\r\n        ups    += (instructions[i] == 'U');\r\n    }\r\n\r\n    int max_correct_instructions = 2*min(lefts, rights) + 2*min(ups, downs);\r\n    cout << max_correct_instructions;\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 32/Programs/K-Dominant Character.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_LETTERS = 26;\r\n    int length = S.size(), answer = S.size();\r\n\r\n    for(int alphabet = 0; alphabet < NO_OF_LETTERS; alphabet++)\r\n    {\r\n        int last_occurence = -1, largest_gap_for_this_alphabet = 0;\r\n\r\n        for(int i = 0; S[i] != '\\0'; i++)\r\n        {\r\n            if(S[i] == 'a' + alphabet)\r\n            {\r\n                largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, i - last_occurence);\r\n                last_occurence = i;\r\n            }\r\n        }\r\n\r\n        largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, length - last_occurence);\r\n\r\n        answer = min(answer, largest_gap_for_this_alphabet);\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 32/Programs/Local Extrema.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_extrema(int mid, int start, int end)\r\n{\r\n    return ((start < mid && end < mid) || (mid < start && mid < end));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    int local_extrema = 0;\r\n    for(int i = 2; i < no_of_elements; i++)\r\n        local_extrema += is_extrema(A[i], A[i - 1], A[i + 1]);\r\n\r\n    printf(\"%d\\n\", local_extrema);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/Connected Components Explanation.txt.txt",
    "content": "We have to count the number of components in the complement graph. \r\nWe also need a way to query if two vertices are connected. \r\n\r\nInstead of using an adjacency vector, we will use adjacency sets. \r\n\r\nWe will also maintain a set of all unvisited vertices. \r\nPick up the first vertex in the unvisited set. \r\nErase it \r\nKeep traversing the unvisited set till there is a vertex with which there is no edge and then repeat\r\n\r\n-----\r\n\r\nWhy does this work ? \r\n\r\nIt looks like it should time out since we are going through the whole unvisited set for each vertex. \r\n\r\nLet us count the number of times we will pick a vertex from the unvisited set. \r\nWe perform two operations \r\n1. Pick up a vertex \r\n2. Skip it and go to next element in the set\r\n\r\nThere are N vertices in the set and each will be picked one time, after which it will be erased. \r\nHow many times do we pick a vertex and skip it ? \r\nWe will skip a vertex only if it has an edge with the current vertex. \r\nSince there are M edges, we can perform at most M skips.  \r\n\r\nSo the number of 'touches' we do to the unvisited set is O(N + M) \r\nWe do N steps of Type 1 and at most M steps of Type 2\r\n\r\nEach has a O(log N) factor \r\n\r\n-----\r\n\r\nint dfs_component_size(int v)\r\n{\r\n    unvisited.erase(v);\r\n \r\n    int size_here = 1;\r\n \r\n    for(set <int> :: iterator it = unvisited.begin(); it != unvisited.end(); )\r\n    {   //printf(\"here %d\\n\", *it);\r\n        if(complement_graph[v].count(*it) == 0)\r\n        {\r\n            int child = *it;\r\n \r\n            size_here += dfs_component_size(child);\r\n \r\n            it = unvisited.lower_bound(child);\r\n        }\r\n        else\r\n        {\r\n            it++;\r\n        }\r\n    }\r\n \r\n    return size_here;\r\n}\r\n \r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n \r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        unvisited.insert(i);\r\n \r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n \r\n        complement_graph[u].insert(v);\r\n        complement_graph[v].insert(u);\r\n    }\r\n \r\n    int no_of_components = 0;\r\n    vector <int> component_size;\r\n \r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(unvisited.count(i) == 1)\r\n        {\r\n            no_of_components++;\r\n \r\n            component_size.push_back(dfs_component_size(i));\r\n        }\r\n    }\r\n \r\n    sort(all(component_size));\r\n \r\n    printf(\"%d\\n\", no_of_components);\r\n    for(int i = 0; i < no_of_components; i++)\r\n        printf(\"%d \", component_size[i]);\r\n \r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/List of Integer Explanation.txt",
    "content": "\nWe need to change the question and try answering a different question.\n\nFinding the n-th integer coprime to P is quite difficult. \n\nLet's look at it differently. I give you a number L. How many numbers less than P are coprime to it ? \n\nPrinciple of inclusion and exclusion. \n\nNow, we know how to do that. \n\nThe number we are looking for is the smallest integer D such that \n\ncoprime_count(n, till D) == K\n\nand coprime_count(n, till D- 1) < K\n\nCoprime_count(n, Limit) is an increasing function. This allows us to use binary search !\n\nAlso, there's another twist. They don't just want k-th coprime number. They want k-th coprime number greater than x.\n\nSo, to overcome this, We need to find the k' coprime number, where k' = k + coprime_count(n, x)\n\nThe most elegant thing about this problem is that I learnt how to elegantly perform inclusion and exclusion division by modifying a sieve. \n\nIt was very elegant indeed. \n\n---------------------------------------------------------------------------\n\nvector <int> inclusion_exclusion_factors[MAX_N];\n\nvoid sieve()\n{\n    for(int i = 1; i < MAX_N; i++)\n        inclusion_exclusion_factors[i].push_back(1);\n\n    for(int i = 2; i < MAX_N; i++)\n    {\n        if(inclusion_exclusion_factors[i].size() > 1) //Not prime\n            continue;\n\n        for(int multiple = i; multiple < MAX_N; multiple += i)\n        {\n            int original_size = inclusion_exclusion_factors[multiple].size();\n\n            for(int j = 0; j < original_size; j++)\n            {\n                int new_factor = (-1)*inclusion_exclusion_factors[multiple][j]*i;\n\n                inclusion_exclusion_factors[multiple].push_back(new_factor);\n            }\n        }\n    }\n}\n\nint no_of_coprime_integers_till(int n, int limit)\n{\n    int answer = 0;\n\n    for(int i = 0; i < inclusion_exclusion_factors[n].size(); i++)\n    {\n        answer += limit/inclusion_exclusion_factors[n][i];\n    }\n\n    return answer;\n}\n\nvoid solve()\n{\n    int n, x, target;\n    scanf(\"%d %d %d\", &x, &n, &target);\n\n    target += no_of_coprime_integers_till(n, x);\n\n    int left = 1, right = 1e9, answer;\n\n    while(left <= right) //f(n, L) < target and f(n, R) >= target\n    {\n        int mid = (left + right) >> 1;\n\n        if(no_of_coprime_integers_till(n, mid) < target)\n        {\n            if(no_of_coprime_integers_till(n, mid + 1) == target)\n            {\n                answer = mid + 1;\n                break;\n            }\n            else\n            {\n                left = mid + 1;\n            }\n        }\n        else if(no_of_coprime_integers_till(n, mid) >= target)\n        {\n            right = mid;\n        }\n    }\n\n    printf(\"%d\\n\", answer);\n}\n\nint main()\n{\n    sieve();\n\n    int no_of_queries;\n    scanf(\"%d\", &no_of_queries);\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/Sum and Replace Explanation.txt",
    "content": "\r\nNow, it happens that d(n) is a function that converges rapidly. Every number will ultimately be reduced to 2. \r\nIn the given range every number goes to 2 in at most 6 times. After that d(2) = 2 and d(1) = 1\r\n\r\nHow do we use this fact ? We can't use lazy propagation for a function like number of divisors. \r\n\r\nHere's what we do ... Use a segment tree for sum and another one for max. \r\n\r\nWhile performing an update check if the max of any node is <= 2. If it is, then we can ignore it as it won't change with the update.\r\n\r\nWe can afford to go to every leaf node and avoid nodes who's max <= 2. \r\nIn the worst case, we will do 6 O(n) scans ! Which is perfectly fine ! It's very reasonable. \r\n\r\nThis is an important trick to note in functions which converge rapidly. We can afford to change each element one-by-one and ignore nodes which have already hit the converged\r\npoint. \r\nWe won't be doing too many updates ... That's the main thing to learn here.\r\n\r\nAgain the idea of a segment tree is to break the query interval into intervals that either lie completely with an interval or ones that lie completely outside the interval.\r\n\r\n---------------------------------------------------------\r\n\r\nvoid precompute_divisors()\r\n{\r\n    vector <int> largest_prime_factor(MAX_N, 0);\r\n    no_of_divisors[1] = 1;\r\n\r\n    for(int i = 2; i < MAX_N; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple < MAX_N; multiple += i)\r\n            {\r\n                largest_prime_factor[multiple] = i;\r\n            }\r\n        }\r\n\r\n        int exponent = 0, reduced_i = i;\r\n\r\n        while(reduced_i%largest_prime_factor[i] == 0)\r\n        {\r\n            reduced_i /= largest_prime_factor[i];\r\n            exponent++;\r\n        }\r\n\r\n        no_of_divisors[i] = (exponent + 1)*no_of_divisors[reduced_i];\r\n    }\r\n}\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nlong long get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    long long left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    long long right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nvoid update(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left || max_tree[n] <= 2)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        A[left] = no_of_divisors[A[left]];\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    update(LEFT(n), left, mid, query_left, query_right);\r\n    update(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_divisors();\r\n\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        const int SUM = 2, REPLACE = 1;\r\n        int query_type, left, right;\r\n        scanf(\"%d %d %d\", &query_type, &left, &right);\r\n\r\n        if(query_type == SUM)\r\n        {\r\n            long long sum = get_sum(1, 1, no_of_elements, left, right);\r\n            printf(\"%I64d\\n\", sum);\r\n        }\r\n        else if(query_type == REPLACE)\r\n        {\r\n            update(1, 1, no_of_elements, left, right);\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/Swap Adjacent Elements Explanation.txt",
    "content": "\r\nClaim - It is possible to sort the permutation if and only if, for every i such that p(i) =/= i, \r\n\r\nthere exists a series of consecutive 1s in between i and p(i) allowing the element p(i) to be swapped one-by-one and placed at position p(i) from position i.\r\n\r\nProof - We can easily see that if i =/= p(i) and there is no stream of one's in between i and p(i), we can never get an array in order as there will always be some \r\nelement p(i) that can never travel to position p(i).\r\n\r\nFor example, Consider this\r\n\r\n1 2 7 4 5 6 3\r\n\r\n0 0 1 1 0 1 \r\n\r\nSince 7 is not in it's place and there is no continuous stream of 1s from 3 to 7, it is impossible for 7 to travel all the way to 3. \r\n\r\n----------------------------------------------------\r\n\r\nNow, to prove the other way around - i.e. it is always possible to sort an array if there exists a stream of 1s in between every i and p(i) where i =/= p(i)\r\n\r\nI will prove that if the condition of stream of 1s in between every i and p(i) is satisfied, then it is always possible to place the SMALLEST out of order element in it's \r\nright place. \r\n\r\nChoose the smallest element x, such that for all y < x, p(y) = y. In other words, pick the smallest element that is not in it's right position. \r\n\r\n{This means that the array is sorted from A[1, 2, .... x - 1]}\r\n\r\nLet x be located at position i. (P(x) = i). \r\n\r\nNow, we can conclude that x < i. Because all y < x, P(y) = y, so P(x) can't be < x. It has to be > x.\r\n\r\nBased on the condition, it means there is a string of consecutive 1s from x to (i - 1), allowing the travel. \r\n\r\nSince it is already established that there is a stream of 1s in between x and (i - 1). We perform the swaps one by one, \r\ntill x moves all the way from position i to position x\r\n\r\nA[1, 2, ... x] The unsorted array is from A[x + 1, ... n]. \r\n\r\nNow, the smallest element that is out of order either lies in between x and i or it doesn't. \r\n\r\nEither way, the condition of it having a string of 1s in between it's current and true position remains invariant. \r\n\r\nBecause if it lies outside [x, i), then it was never disturbed. \r\n\r\nIf it did, then it still remains somewhere in the stream of 1s in between x and i. If it had a string of 1s in the beginning, it still does now, because it is still connected\r\n\r\nSo, we keep placing the minimum element out-of-order in it's right place till the entire array is sorted.\r\n\r\n---------------------------------------------------------------\r\n\r\nHere's what I did - Maintain a prefix sum of the number of 1s till i. \r\n\r\nFor every i, such that p(i) != i\r\n\r\nRight = Max{p(i), i}\r\nLeft = Min{p(i), i}\r\n\r\nNow, there should be continuous 1s from Left to (Right - 1).\r\n\r\nThe expected number of 1s = (Right - 1) - (Left - 1)\r\n\r\nThe number of 1s present = Prefix(Right - 1) - Prefix(Left - 1)\r\n\r\nIf these two numbers are not equal, then it means there is some element which can't go it's true position. \r\n\r\nIf these two numbers are equal for all i, such that i =/= p(i), then it means that the array can always be sorted by placing the minimum out-of-order element in it's right place.\r\n\r\n------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1, 0);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    vector <int> ones_till(n + 1, 0);\r\n    for(int i = 1; i <= n - 1; i++)\r\n    {\r\n        int digit;\r\n        scanf(\"%1d\", &digit);\r\n\r\n        ones_till[i] = (digit == 1) + ones_till[i - 1];\r\n    }\r\n\r\n    int is_sortable = true;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(permutation[i] != i)\r\n        {\r\n            int right = max(i, permutation[i]);\r\n            int left = min(i, permutation[i]);\r\n\r\n            int distance = (right - 1) - (left - 1);\r\n\r\n            if(ones_till[right - 1] - ones_till[left - 1] != distance)\r\n                is_sortable = false;\r\n        }\r\n    }\r\n\r\n    printf(is_sortable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/Tanks Explanation.txt.txt",
    "content": "If the sum of all the tanks is smaller than V, then it is not possible. \r\nLet us suppose the sum is >= V, is it possible ? \r\n\r\nLet us suppose there is some subset who's sum = v (mod K) \r\n\r\nThen, it is always possible. We can pour all the water of this subset into one tank. \r\nThen, we will keep filling in water from the other tanks in steps of size K till the volume = V \r\n\r\nIf there is no subset who's sum = v (mod k), it means that we can never get the sum of any subset = V (mod K) \r\nso it is impossible. \r\n\r\nTo see this, reduce each tank to it's modulo value with K \r\nAdding or removing K will not change the modulo. \r\nIf we have some subset = V (mod K), put everything in one bottle and then keep adding K \r\n\r\nIf we don't have any subset like that, adding or removing K from any of the bottles will not change that so it's not possible.\r\n\r\n-----\r\n\r\n1. There is a case when the empty set is a good set when v = 0 (mod k)\r\nIn that case, empty any one tank and then pour water into that tank\r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    long long no_of_elements, capacity, total_volume;\r\n    cin >> no_of_elements >> capacity >> total_volume;\r\n \r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n \r\n    int sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum += A[i];\r\n    }\r\n \r\n    vector < vector <int> > reachable(no_of_elements + 1, vector <int> (capacity + 1, false));\r\n    reachable[0][0] = true;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        reachable[i][A[i]%capacity] = true;\r\n \r\n        for(int m = 0; m < capacity; m++)\r\n        {\r\n            int new_m = (m + A[i])%capacity;\r\n \r\n            if(reachable[i - 1][m])\r\n            {\r\n                reachable[i][new_m] = true;\r\n \r\n                reachable[i][m] = true;\r\n            }\r\n        }\r\n    }\r\n \r\n    if(sum < total_volume || !reachable[no_of_elements][total_volume%capacity])\r\n    {\r\n        cout << \"NO\\n\";\r\n \r\n        return 0;\r\n    }\r\n \r\n    cout << \"YES\\n\";\r\n    vector <int> is_good(no_of_elements + 1, false);\r\n    for(int i = no_of_elements, looking_for = total_volume%capacity; i >= 1; i--)\r\n    {\r\n        int remaining = (looking_for - A[i]%capacity + capacity)%capacity;\r\n \r\n        if(reachable[i - 1][remaining])\r\n        {\r\n            is_good[i] = true; //cout << \"Remainder of \" << looking_for << \" is reachable with \" << A[i] << \" so it's good. Remaining = \" << remaining << \"\\n\";\r\n \r\n            looking_for = remaining;\r\n        }\r\n \r\n        if(looking_for == 0)\r\n        {\r\n            break;\r\n        }\r\n    }\r\n \r\n    vector <int> good_set, bad_set;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(is_good[i])\r\n        {\r\n            good_set.push_back(i);\r\n        }\r\n        else\r\n        {\r\n            bad_set.push_back(i);\r\n        }\r\n    }\r\n \r\n    for(int i = 1; i < good_set.size(); i++)\r\n    {\r\n        if(A[good_set[i]] == 0)\r\n        {\r\n            continue;\r\n        }\r\n \r\n        cout << ceil(A[good_set[i]], capacity) << \" \" << good_set[i] << \" \" << good_set[0] << \"\\n\";\r\n        //cout << \"Ceil(\" << good_set[i] << \",\" << capacity << \") is \" << ceil(good_set[i], capacity) << \"\\n\";\r\n \r\n        A[good_set[0]] += A[good_set[i]];\r\n        A[good_set[i]] = 0;\r\n    }\r\n \r\n    if(good_set.size() > 0 && A[good_set[0]] > total_volume)\r\n    {\r\n        int other;\r\n        if(good_set.size() >= 2)\r\n        {\r\n            other = good_set[1];\r\n        }\r\n        else\r\n        {\r\n            other = bad_set[0];\r\n        }\r\n \r\n        cout << (A[good_set[0]] - total_volume)/capacity << \" \" << good_set[0] << \" \" << other << \"\\n\";\r\n \r\n        A[other] += (A[good_set[0]] - total_volume)/capacity;\r\n        A[good_set[0]] = total_volume;\r\n    }\r\n \r\n    for(int i = 1; i < bad_set.size(); i++)\r\n    {\r\n        if(A[bad_set[i]] == 0)\r\n        {\r\n            continue;\r\n        }\r\n \r\n        cout << ceil(A[bad_set[i]], capacity) << \" \" << bad_set[i] << \" \" << bad_set[0] << \"\\n\";\r\n \r\n        A[bad_set[0]] += A[bad_set[i]];\r\n        A[bad_set[i]] = 0;\r\n \r\n        if(total_volume%capacity == 0)\r\n        {\r\n            good_set.push_back(bad_set[i]);\r\n        }\r\n    }\r\n \r\n    if(A[good_set[0]] < total_volume)\r\n    {\r\n        int extra = total_volume - A[good_set[0]];\r\n \r\n        cout << ceil(extra,capacity) << \" \" << bad_set[0] << \" \" << good_set[0] << \"\\n\";\r\n \r\n        A[good_set[0]] += extra;\r\n        A[bad_set[0]] -= extra;\r\n    }\r\n \r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/Tea Queue Explanation.txt",
    "content": "\r\nThis problem is made a lot easier, because the inputs are sorted in terms of their l_i's \r\n\r\nOtherwise, we'd need to use structures and call a custom sort. \r\n\r\nHere's what we do, \r\n\r\nFirst initial time = left[1]\r\n\r\nFor each person that arrives, \r\n\r\n\tset current time to max{current time, left[i]} [If current time < left[i], then the current customer will be served. He'll just have to wait till left[i]. \r\n\t\t\t\t\t\t\tSo, directly set the current time to left[i]. If current time > left[i], let it be.]\r\n\t\r\n\t(check if current time <= right[i])\r\n\r\n\t\tif it is, then service time[i] = current time, current time++\r\n\r\nNote - I made the mistake of increasing service time regardless of whether the person was served. That was a mistake. Incrememnt time only if he has been served.\r\n\r\nFor example,\r\n\r\n1 4\r\n1 1\r\n\r\nThe first person is served at moment 1. Now, the time is 2. The second person is not served. This means that he has left the queue. the time REMAINS 2 for the third customer\r\n\r\nIt does NOT increase to 3 even if he didn't take the tea. Only the serviced customers increment the current time.\r\n\r\n---------------------------------------------------------------------\r\n\r\nvoid solve()\r\n{\r\n    int number_of_students;\r\n    scanf(\"%d\", &number_of_students);\r\n\r\n    vector <int> left(number_of_students + 1);\r\n    vector <int> right(number_of_students + 1);\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        scanf(\"%d %d\", &left[i], &right[i]);\r\n\r\n    vector <int> served_time(number_of_students + 1, 0);\r\n\r\n    for(int current_time = left[1], student = 1; student <= number_of_students; student++)\r\n    {\r\n            current_time = max(current_time, left[student]);\r\n\r\n            if(current_time <= right[student])\r\n            {\r\n                served_time[student] = current_time++;\r\n            }\r\n    }\r\n\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        printf(\"%d \", served_time[i]);\r\n\r\n    printf(\"\\n\");\r\n}"
  },
  {
    "path": "Contests/Educational Round 37/Explanation/Water the Gardens Explanation.txt",
    "content": "\r\nNow, the time taken to water the patch of grass in between 1 and tap[1]\r\n\r\nis tap[1] - 1 = tap[1].\r\n\r\nThe time taken to water the patch of grass from the last tap to the end is = N - (tap.back() - 1);\r\n\r\nThe time taken to water the patch of grass in between tap[i] and tap[i + 1] is ceil[distance/2], where distance = tap[i + 1] - (tap[i] - 1)\r\n\r\nThis is because the number of unwatered patches of grass in between tap[i] and tap[i + 1] reduces by 2 each second. So, the distance shrinks by 2 each second.\r\n\r\nIf this number is odd, add one more second. \r\n\r\nThe time taken = max{First patch, all middle patches, Last patch}\r\n\r\n(It's already sorted)\r\n\r\n---------------------------------------------------------------------\r\n\r\nvoid solve()\r\n{\r\n    int number_of_taps, number_of_beds;\r\n    scanf(\"%d %d\", &number_of_beds, &number_of_taps);\r\n\r\n    vector <int> tap(number_of_taps + 1, 0);\r\n    for(int i = 1; i <= number_of_taps; i++)\r\n        scanf(\"%d\", &tap[i]);\r\n\r\n    int time = tap[1];\r\n\r\n    for(int i = 1; i < number_of_taps; i++)\r\n    {\r\n        int distance = tap[i + 1] - tap[i] + 1;\r\n\r\n        int time_for_this_patch = distance/2 + distance%2 ;\r\n\r\n        time = max(time, time_for_this_patch);\r\n    }\r\n\r\n    time = max(time, number_of_beds - tap.back() + 1);\r\n\r\n    printf(\"%d\\n\", time);\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/Connected Components.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <set>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nconst int MAX_N = 2e5 + 15;\nint visited[MAX_N];\nset <int> complement_graph[MAX_N], unvisited;\n\nint dfs_component_size(int v)\n{\n    unvisited.erase(v);\n\n    int size_here = 1;\n\n    for(set <int> :: iterator it = unvisited.begin(); it != unvisited.end(); )\n    {   \n        if(complement_graph[v].count(*it) == 0)\n        {\n            int child = *it;\n\n            size_here += dfs_component_size(child);\n\n            it = unvisited.lower_bound(child);\n        }\n        else\n        {\n            it++;\n        }\n    }\n\n    return size_here;\n}\n\nint main()\n{\n    int no_of_vertices, no_of_edges;\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\n\n    for(int i = 1; i <= no_of_vertices; i++)\n        unvisited.insert(i);\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        complement_graph[u].insert(v);\n        complement_graph[v].insert(u);\n    }\n\n    int no_of_components = 0;\n    vector <int> component_size;\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(unvisited.count(i) == 1)\n        {\n            no_of_components++;\n\n            component_size.push_back(dfs_component_size(i));\n        }\n    }\n\n    sort(all(component_size));\n\n    printf(\"%d\\n\", no_of_components);\n    for(int i = 0; i < no_of_components; i++)\n        printf(\"%d \", component_size[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/List of Integers.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 1e6 + 15;\n\nvector <int> inclusion_exclusion_factors[MAX_N];\n\nvoid sieve()\n{\n    for(int i = 1; i < MAX_N; i++)\n        inclusion_exclusion_factors[i].push_back(1);\n\n    for(int i = 2; i < MAX_N; i++)\n    {\n        if(inclusion_exclusion_factors[i].size() > 1) //Not prime\n            continue;\n\n        for(int multiple = i; multiple < MAX_N; multiple += i)\n        {\n            int original_size = inclusion_exclusion_factors[multiple].size();\n\n            for(int j = 0; j < original_size; j++)\n            {\n                int new_factor = (-1)*inclusion_exclusion_factors[multiple][j]*i;\n\n                inclusion_exclusion_factors[multiple].push_back(new_factor);\n            }\n        }\n    }\n}\n\nint no_of_coprime_integers_till(int n, int limit)\n{\n    int answer = 0;\n\n    for(int i = 0; i < inclusion_exclusion_factors[n].size(); i++)\n    {\n        answer += limit/inclusion_exclusion_factors[n][i];\n    }\n\n    return answer;\n}\n\nvoid solve()\n{\n    int n, x, target;\n    scanf(\"%d %d %d\", &x, &n, &target);\n\n    target += no_of_coprime_integers_till(n, x);\n\n    int left = 1, right = 1e9, answer;\n\n    while(left <= right) //f(n, L) < target and f(n, R) >= target\n    {\n        int mid = (left + right) >> 1;\n\n        if(no_of_coprime_integers_till(n, mid) < target)\n        {\n            if(no_of_coprime_integers_till(n, mid + 1) == target)\n            {\n                answer = mid + 1;\n                break;\n            }\n            else\n            {\n                left = mid + 1;\n            }\n        }\n        else if(no_of_coprime_integers_till(n, mid) >= target)\n        {\n            right = mid;\n        }\n    }\n\n    printf(\"%d\\n\", answer);\n}\n\nint main()\n{\n    sieve();\n\n    int no_of_queries;\n    scanf(\"%d\", &no_of_queries);\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/Sum and Replace.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\n#define LEFT(n) ( (n << 1) )\r\n#define RIGHT(n) ( (n << 1)|1 )\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 1e6 + 10, MAX_ELEMENTS = 5e5 + 6;\r\nvector <int> no_of_divisors(MAX_N, 0);\r\n\r\nint max_tree[3*MAX_ELEMENTS];\r\nlong long sum_tree[3*MAX_ELEMENTS];\r\nint A[MAX_ELEMENTS];\r\n\r\nvoid precompute_divisors()\r\n{\r\n    vector <int> largest_prime_factor(MAX_N, 0);\r\n    no_of_divisors[1] = 1;\r\n\r\n    for(int i = 2; i < MAX_N; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple < MAX_N; multiple += i)\r\n            {\r\n                largest_prime_factor[multiple] = i;\r\n            }\r\n        }\r\n\r\n        int exponent = 0, reduced_i = i;\r\n\r\n        while(reduced_i%largest_prime_factor[i] == 0)\r\n        {\r\n            reduced_i /= largest_prime_factor[i];\r\n            exponent++;\r\n        }\r\n\r\n        no_of_divisors[i] = (exponent + 1)*no_of_divisors[reduced_i];\r\n    }\r\n}\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nlong long get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    long long left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    long long right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nvoid update(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left || max_tree[n] <= 2)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        A[left] = no_of_divisors[A[left]];\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    update(LEFT(n), left, mid, query_left, query_right);\r\n    update(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_divisors();\r\n\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        const int SUM = 2, REPLACE = 1;\r\n        int query_type, left, right;\r\n        scanf(\"%d %d %d\", &query_type, &left, &right);\r\n\r\n        if(query_type == SUM)\r\n        {\r\n            long long sum = get_sum(1, 1, no_of_elements, left, right);\r\n            printf(\"%I64d\\n\", sum);\r\n        }\r\n        else if(query_type == REPLACE)\r\n        {\r\n            update(1, 1, no_of_elements, left, right);\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/Swap Adjacent Elements.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1, 0);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    vector <int> ones_till(n + 1, 0);\r\n    for(int i = 1; i <= n - 1; i++)\r\n    {\r\n        int digit;\r\n        scanf(\"%1d\", &digit);\r\n\r\n        ones_till[i] = (digit == 1) + ones_till[i - 1];\r\n    }\r\n\r\n    int is_sortable = true;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(permutation[i] != i)\r\n        {\r\n            int right = max(i, permutation[i]);\r\n            int left = min(i, permutation[i]);\r\n\r\n            int distance = (right - 1) - (left - 1);\r\n\r\n            if(ones_till[right - 1] - ones_till[left - 1] != distance)\r\n                is_sortable = false;\r\n        }\r\n    }\r\n\r\n    printf(is_sortable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/Tanks.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nlong long ceil(long long n, long long r)\r\n{\r\n    return (n/r) + (n%r != 0);\r\n}\r\n\r\nint main()\r\n{\r\n    long long no_of_elements, capacity, total_volume;\r\n    cin >> no_of_elements >> capacity >> total_volume;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> A[i];\r\n    }\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum += A[i];\r\n    }\r\n\r\n    vector < vector <int> > reachable(no_of_elements + 1, vector <int> (capacity + 1, false));\r\n    reachable[0][0] = true;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        reachable[i][A[i]%capacity] = true;\r\n\r\n        for(int m = 0; m < capacity; m++)\r\n        {\r\n            int new_m = (m + A[i])%capacity;\r\n\r\n            if(reachable[i - 1][m])\r\n            {\r\n                reachable[i][new_m] = true;\r\n\r\n                reachable[i][m] = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(sum < total_volume || !reachable[no_of_elements][total_volume%capacity])\r\n    {\r\n        cout << \"NO\\n\";\r\n\r\n        return 0;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    vector <int> is_good(no_of_elements + 1, false);\r\n    for(int i = no_of_elements, looking_for = total_volume%capacity; i >= 1; i--)\r\n    {\r\n        int remaining = (looking_for - A[i]%capacity + capacity)%capacity;\r\n\r\n        if(reachable[i - 1][remaining])\r\n        {\r\n            is_good[i] = true;\r\n\r\n            looking_for = remaining;\r\n        }\r\n\r\n        if(looking_for == 0)\r\n        {\r\n            break;\r\n        }\r\n    }\r\n\r\n    vector <int> good_set, bad_set;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(is_good[i])\r\n        {\r\n            good_set.push_back(i);\r\n        }\r\n        else\r\n        {\r\n            bad_set.push_back(i);\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i < good_set.size(); i++)\r\n    {\r\n        if(A[good_set[i]] == 0)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        cout << ceil(A[good_set[i]], capacity) << \" \" << good_set[i] << \" \" << good_set[0] << \"\\n\";\r\n\r\n        A[good_set[0]] += A[good_set[i]];\r\n        A[good_set[i]] = 0;\r\n    }\r\n\r\n    if(good_set.size() > 0 && A[good_set[0]] > total_volume)\r\n    {\r\n        int other;\r\n        if(good_set.size() >= 2)\r\n        {\r\n            other = good_set[1];\r\n        }\r\n        else\r\n        {\r\n            other = bad_set[0];\r\n        }\r\n\r\n        cout << (A[good_set[0]] - total_volume)/capacity << \" \" << good_set[0] << \" \" << other << \"\\n\";\r\n\r\n        A[other] += (A[good_set[0]] - total_volume)/capacity;\r\n        A[good_set[0]] = total_volume;\r\n    }\r\n\r\n    for(int i = 1; i < bad_set.size(); i++)\r\n    {\r\n        if(A[bad_set[i]] == 0)\r\n        {\r\n            continue;\r\n        }\r\n\r\n        cout << ceil(A[bad_set[i]], capacity) << \" \" << bad_set[i] << \" \" << bad_set[0] << \"\\n\";\r\n\r\n        A[bad_set[0]] += A[bad_set[i]];\r\n        A[bad_set[i]] = 0;\r\n\r\n        if(total_volume%capacity == 0)\r\n        {\r\n            good_set.push_back(bad_set[i]);\r\n        }\r\n    }\r\n\r\n    if(A[good_set[0]] < total_volume)\r\n    {\r\n        int extra = total_volume - A[good_set[0]];\r\n\r\n        cout << ceil(extra,capacity) << \" \" << bad_set[0] << \" \" << good_set[0] << \"\\n\";\r\n\r\n        A[good_set[0]] += extra;\r\n        A[bad_set[0]] -= extra;\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/Tea Queue.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int number_of_students;\r\n    scanf(\"%d\", &number_of_students);\r\n\r\n    vector <int> left(number_of_students + 1);\r\n    vector <int> right(number_of_students + 1);\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        scanf(\"%d %d\", &left[i], &right[i]);\r\n\r\n    vector <int> served_time(number_of_students + 1, 0);\r\n\r\n    for(int current_time = left[1], student = 1; student <= number_of_students; student++)\r\n    {\r\n            current_time = max(current_time, left[student]);\r\n\r\n            if(current_time <= right[student])\r\n            {\r\n                served_time[student] = current_time++;\r\n            }\r\n    }\r\n\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        printf(\"%d \", served_time[i]);\r\n\r\n    printf(\"\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 37/Programs/Water the Gardens.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int number_of_taps, number_of_beds;\r\n    scanf(\"%d %d\", &number_of_beds, &number_of_taps);\r\n\r\n    vector <int> tap(number_of_taps + 1, 0);\r\n    for(int i = 1; i <= number_of_taps; i++)\r\n        scanf(\"%d\", &tap[i]);\r\n\r\n    int time = tap[1];\r\n\r\n    for(int i = 1; i < number_of_taps; i++)\r\n    {\r\n        int distance = tap[i + 1] - tap[i] + 1;\r\n\r\n        int time_for_this_patch = distance/2 + distance%2 ;\r\n\r\n        time = max(time, time_for_this_patch);\r\n    }\r\n\r\n    time = max(time, number_of_beds - tap.back() + 1);\r\n\r\n    printf(\"%d\\n\", time);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 44/Explanations/Chess Placing Explanation.txt",
    "content": "There are only two possibilities. At the end, either all the squares are on black squares or they're all on white squares. \n\nCalculate the number of moves if all pieces are on black squares, and if all the pieces are on white squares and the answer is the minimum of these two. \n\nTo calculate the minimum number of moves to put all pieces on squares of the same colour, it is always best to put on square i, the piece closest to it. \n\nSo Ans = |P[i] - 2i|, to put all pieces on even squares. \n\nOf course, the pieces must be sorted before this. \n\nThe proof is that if P[i] is the closest to 2i, if we replace P[i] by any piece > P[i], then we increase the number of moves. \n\n-----------------------------------\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    vector <int> A(n/2 + 1);\n    for(int i = 1; 2*i <= n; i++)\n        cin >> A[i];\n\n    sort(all(A));\n\n    int black_moves = 0;\n    for(int i = 1; 2*i <= n; i++)\n        black_moves += abs(A[i] - (2*i - 1));\n\n    int white_moves = 0;\n    for(int i = 1; 2*i <= n; i++)\n        white_moves += abs(A[i] - 2*i);\n\n    int minimum_moves = min(black_moves, white_moves);\n    cout << minimum_moves;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 44/Explanations/Switches and Lamps Explanation.txt",
    "content": "Count the number of switches that each lamp is connected to. \r\n\r\n(In other words, find the sum of each column.)\r\n\r\nThe go through all switches and check if there is any switch that can be ignored. \r\n\r\nA switch can be ignored, if each of it's connected lamp has another switch connected to it. \r\n\r\ni.e. If Switch[i][j] = 1, and lamp[j] > 1, then the i-th switch can be ignored. \r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_switches, no_of_lamps;\r\n    cin >> no_of_switches >> no_of_lamps;\r\n\r\n    vector <string> switches(no_of_switches);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        cin >> switches[i];\r\n\r\n    vector <int> no_of_switches_for(no_of_lamps, 0);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n            no_of_switches_for[lamp] += (switches[i][lamp] == '1');\r\n\r\n    int one_ignorable = false;\r\n\r\n    for(int i = 0; i < no_of_switches; i++)\r\n    {\r\n        int can_ignore_this_one = true;\r\n\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n        {\r\n            if(switches[i][lamp] == '1' && no_of_switches_for[lamp] == 1)\r\n                can_ignore_this_one = false;\r\n        }\r\n\r\n        if(can_ignore_this_one)\r\n            one_ignorable = true;\r\n    }\r\n\r\n    cout << (one_ignorable ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 44/Programs/Chess Placing.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int n;\n    cin >> n;\n\n    vector <int> A(n/2 + 1);\n    for(int i = 1; 2*i <= n; i++)\n        cin >> A[i];\n\n    sort(all(A));\n\n    int black_moves = 0;\n    for(int i = 1; 2*i <= n; i++)\n        black_moves += abs(A[i] - (2*i - 1));\n\n    int white_moves = 0;\n    for(int i = 1; 2*i <= n; i++)\n        white_moves += abs(A[i] - 2*i);\n\n    int minimum_moves = min(black_moves, white_moves);\n    cout << minimum_moves;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 44/Programs/Switches and Lamps.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <cstdio>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_switches, no_of_lamps;\r\n    cin >> no_of_switches >> no_of_lamps;\r\n\r\n    vector <string> switches(no_of_switches);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        cin >> switches[i];\r\n\r\n    vector <int> no_of_switches_for(no_of_lamps, 0);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n            no_of_switches_for[lamp] += (switches[i][lamp] == '1');\r\n\r\n    int one_ignorable = false;\r\n\r\n    for(int i = 0; i < no_of_switches; i++)\r\n    {\r\n        int can_ignore_this_one = true;\r\n\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n        {\r\n            if(switches[i][lamp] == '1' && no_of_switches_for[lamp] == 1)\r\n                can_ignore_this_one = false;\r\n        }\r\n\r\n        if(can_ignore_this_one)\r\n            one_ignorable = true;\r\n    }\r\n\r\n    cout << (one_ignorable ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 46/Explanations/CodeHorses T Shirts Explanation.txt",
    "content": "If something is common in both lists, then neglect it. \n\nNow all the differences take exactly one change each.\n\n-----------------------------------\n\nint main()\n{\n    int no_of_shirts;\n    cin >> no_of_shirts;\n\n    map <string, int> size_frequency;\n    for(int i = 1; i <= no_of_shirts; i++)\n    {\n        string shirt_size;\n        cin >> shirt_size;\n\n        size_frequency[shirt_size]++;\n    }\n\n    int no_of_changes = 0;\n    for(int i = 1; i <= no_of_shirts; i++)\n    {\n        string shirt_size;\n        cin >> shirt_size;\n\n        if(size_frequency[shirt_size] > 0)\n            size_frequency[shirt_size]--;\n        else\n            no_of_changes++;\n    }\n\n    cout << no_of_changes;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 46/Explanations/Covered Points Count Explanation.txt",
    "content": "Keep track of the begginng and end of each segment and then sort them. \r\n\r\nThen go through them. The number of lines that are presently covered can be found out by going through the lines and changing accordingly whether we are at a beginning or an end. \r\n\r\nThe amount that is covered can be found out by taking the difference of the last two points. \r\n\r\n-------------\r\n\r\nint main()\r\n{\r\n    int no_of_segments;\r\n    scanf(\"%d\", &no_of_segments);\r\n\r\n    vector <info> edge(2*no_of_segments + 1);\r\n    edge[0] = info(0, 0);\r\n    for(int i = 1; i <= no_of_segments; i++)\r\n    {\r\n        LL left, right;\r\n        scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n        edge[2*i - 1] = info(left, 1);\r\n        edge[2*i] = info(right + 1, -1);\r\n    }\r\n\r\n    sort(all(edge));\r\n\r\n    vector <LL> points_covered_by(no_of_segments + 1, 0);\r\n    int no_of_covering_lines = 0;\r\n\r\n    for(int i = 1; i <= 2*no_of_segments; i++)\r\n    {\r\n        points_covered_by[no_of_covering_lines] += edge[i].location - edge[i - 1].location;\r\n\r\n        no_of_covering_lines += edge[i].new_segments;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_segments; i++)\r\n        printf(\"%I64d \", points_covered_by[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 46/Explanations/Yet Another Problem on Subsequence Explanation.txt",
    "content": "Let f(i) denote the number of sequences if A[i] is the first element. \r\n\r\nIf A[i] <= 0, then f(i) = 0\r\n\r\nOtherwise, we have to count the number of ways of choosing A[i] elements from [i + 1, ... , j] x f(j). \r\n\r\nUltimately, we have to sum f(i) for all i.\r\n\r\n-----------------\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <long long> answer_from(no_of_elements + 2, 0);\r\n    answer_from[no_of_elements + 1] = 1;\r\n\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        if(A[i] <= 0)\r\n        {\r\n            answer_from[i] = 0;\r\n            continue;\r\n        }\r\n\r\n        for(int j = i + A[i]; j <= no_of_elements; j++)\r\n        {\r\n            answer_from[i] += (choose[j - i][A[i]]*answer_from[j + 1])%MOD;\r\n        }\r\n\r\n        answer_from[i] %= MOD;\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        answer += answer_from[i];\r\n\r\n    printf(\"%I64d\\n\", answer%MOD);\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 46/Programs/CodeHorses T Shirts.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <map>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_shirts;\n    cin >> no_of_shirts;\n\n    map <string, int> size_frequency;\n    for(int i = 1; i <= no_of_shirts; i++)\n    {\n        string shirt_size;\n        cin >> shirt_size;\n\n        size_frequency[shirt_size]++;\n    }\n\n    int no_of_changes = 0;\n    for(int i = 1; i <= no_of_shirts; i++)\n    {\n        string shirt_size;\n        cin >> shirt_size;\n\n        if(size_frequency[shirt_size] > 0)\n            size_frequency[shirt_size]--;\n        else\n            no_of_changes++;\n    }\n\n    cout << no_of_changes;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 46/Programs/Covered Points Count.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct info\r\n{\r\n    LL location;\r\n    int new_segments;\r\n\r\n    info(LL loc = 0, int new_seg = 0)\r\n    {\r\n        location = loc;\r\n        new_segments = new_seg;\r\n    }\r\n\r\n    const operator <(info &A)\r\n    {\r\n        return (location < A.location);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_segments;\r\n    scanf(\"%d\", &no_of_segments);\r\n\r\n    vector <info> edge(2*no_of_segments + 1);\r\n    edge[0] = info(0, 0);\r\n    for(int i = 1; i <= no_of_segments; i++)\r\n    {\r\n        LL left, right;\r\n        scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n        edge[2*i - 1] = info(left, 1);\r\n        edge[2*i] = info(right + 1, -1);\r\n    }\r\n\r\n    sort(all(edge));\r\n\r\n    vector <LL> points_covered_by(no_of_segments + 1, 0);\r\n    int no_of_covering_lines = 0;\r\n\r\n    for(int i = 1; i <= 2*no_of_segments; i++)\r\n    {\r\n        points_covered_by[no_of_covering_lines] += edge[i].location - edge[i - 1].location;\r\n\r\n        no_of_covering_lines += edge[i].new_segments;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_segments; i++)\r\n        printf(\"%I64d \", points_covered_by[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 46/Programs/Yet Another Problem on Subsequence.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX = 1e3 + 5, MOD = 998244353;\r\nlong long choose[MAX][MAX];\r\n\r\nvoid precompute()\r\n{\r\n    for(int n = 0; n < MAX; n++)\r\n    {\r\n        for(int r = 0; r <= n; r++)\r\n        {\r\n            if(r == 0 || r == n)\r\n                choose[n][r] = 1;\r\n            else\r\n                choose[n][r] = (choose[n - 1][r] + choose[n - 1][r - 1])%MOD;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <long long> answer_from(no_of_elements + 2, 0);\r\n    answer_from[no_of_elements + 1] = 1;\r\n\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        if(A[i] <= 0)\r\n        {\r\n            answer_from[i] = 0;\r\n            continue;\r\n        }\r\n\r\n        for(int j = i + A[i]; j <= no_of_elements; j++)\r\n        {\r\n            answer_from[i] += (choose[j - i][A[i]]*answer_from[j + 1])%MOD;\r\n        }\r\n\r\n        answer_from[i] %= MOD;\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        answer += answer_from[i];\r\n\r\n    printf(\"%I64d\\n\", answer%MOD);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 51/Explanation/Bicolourings Explanation.txt",
    "content": "A common idea to solve questions involving tiling is bitmasks. \n\nLet us represent black with 0 and white with 1. \n\nSuppose our last column is \n\n0 \n1\n\n----------------------------------\n\nHow many NEW components do we get by adding another column ?\n\nLet's go case by case. \n\nCase 1 :\n\n0 0\n1 0\n\nThe number of components remains the same. \n\nCase 2 : \n\n0 0 \n1 1\n\nNumber of components remains the same. \n\nCase 3 : \n\n0 1\n1 0\n\nWe have created two new components.\n\nCase 4 : \n\n0 1\n1 1\n\nThe number of components remains the same. \n\n---------------------------------------------------\n\nLet us analyse all the 16 cases. \n\nint additional_components(int second_last, int last)\n{\n    switch(second_last)\n    {\n        case BB : switch(last)\n                  {\n                      case BB : return 0;\n                      case BW : return 1;\n                      case WB : return 1;\n                      case WW : return 1;\n                  }\n        case BW : switch(last)\n                  {\n                      case BB : return 0;\n                      case BW : return 0;\n                      case WB : return 2;\n                      case WW : return 0;\n                  }\n        case WB : switch(last)\n                  {\n                      case BB : return 0;\n                      case BW : return 2;\n                      case WB : return 0;\n                      case WW : return 0;\n                  }\n        case WW : switch(last)\n                  {\n                      case BB : return 1;\n                      case BW : return 1;\n                      case WB : return 1;\n                      case WW : return 0;\n                  }\n    }\n}\n\n----------------------------------------------------\n\n\nNow, let f(n, k, xx) denote the number of ways of having \n- n columns\n- k components\n- xx last column\n\nSuppose we have inserted a new column xy\nNow, \n\n(xx, xy) will fall in one of the 16 cases mentioned above. \n\nLet the number of components be k' now.\n\nAccordingly, f(n + 1, k', xy) += f(n, k, xx)\n\n----------------------------------------------\n\nSo, this is how we define the recurrence - \n\nFor every possible last column we can have, we iterate over every possible second last column and add it to the answer with the corresponding number of components.\n\nf(n + 1, k', xy) = sum(f(n, k, xx))\n\nfor all (k, xx) such that inserting the column xy after xx results in k' components from k components. \n\nThe code may make it clearer.\n\n--------------------------------------------\n\nfor(int column = 2; column <= no_of_columns; column++)\n    {\n        for(int components = 1; components <= 2*no_of_columns; components++)\n        {\n            for(int last = 0; last < NO_OF_COLUMN_ARRANGEMENTS; last++)\n            {\n                for(int second_last = 0; second_last < NO_OF_COLUMN_ARRANGEMENTS; second_last++)\n                {\n                    int new_components = components + additional_components(second_last, last);\n\n                    no_of_ways[column][new_components][last] += no_of_ways[column - 1][components][second_last];\n\n                    no_of_ways[column][new_components][last] %= MOD;\n                }\n            }\n        }\n    }\n\n------------------------------\n\nWhat is the base case ? \n\nf(1, 1, BB) = f(1, 1, WW) = 1\nf(1, 2, BW) = f(1, 2, WB) = 1\n\n\nAll other f(1, _ , __) = 0\n\n-----------------------------------------------\n\nNow, the answer = \n\nf(n, k, BB) + f(n, k, BW) + f(n, k, WB) + f(n, k, WW)\n\nLL answer = 0;\n    for(int last = 0; last < NO_OF_COLUMN_ARRANGEMENTS; last++)\n    {\n        answer += no_of_ways[no_of_columns][no_of_components][last];\n\n        answer %= MOD;\n    }\n\n"
  },
  {
    "path": "Contests/Educational Round 51/Explanation/Relatively Prime Pairs Explanation.txt",
    "content": "gcd(n, n + 1) = 1\r\n\r\nPrint pairs of consecutive integers. \r\n\r\n------------------------------------\r\n\r\n\r\nint main()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    printf(\"YES\\n\");\r\n    for(long long i = left; i <= right; i += 2)\r\n        printf(\"%I64d %I64d\\n\", i, i + 1);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 51/Explanation/Vasya and Multisets Explanation.txt",
    "content": "Observation - If an element occurs two times, then it does not affect the difference in the number of nice elements in the multisets. \r\n\r\nProof - If we place them in same multiset, then the number of nice elements in both subsets remain the same and does not increase.\r\n\r\nIf we place them in different multisets, then the number of nice elements in both subsets increases by one.\r\n\r\n---------------------------------------------------\r\n\r\nCase 1 - There are an even number of elements which occcur one time. \r\n\r\nThen we place half of them in either multiset. \r\n\r\nAnd place all the remaining elements in A.\r\n\r\n--------------------------------------------\r\n\r\nCase 2 - There are an odd number of elements which occur one time. \r\n\r\nCase 2a - There is at least one element who's frequency is greater than 2. \r\n\r\nIf there are (2n + 1) elements which occur one time, then place n of them in A, (n + 1) of them in B. \r\n\r\nThen place exactly one occurence of the element who's frequency > 2 in A, and place the others in B. \r\n\r\nNow, A and B both have exactly (n + 1) nice elements. \r\n\r\nWe know place the remaining elements in A.\r\n\r\n---------------------------------------------\r\n\r\nCase 2b - There is no element who's frequency > 2\r\n\r\nSince there are an odd number of elements who's frequency is 1, there must be one multiset which has more nice elements than the other. \r\n\r\nAs per our observation, elements who's frequency is 2, will not make the difference of nice elements in A and B 0 from 1. \r\n\r\nSo, it is never possible in this case. \r\n\r\n----------------------------------------------\r\n\r\nHow do we implement this ? \r\n\r\nWe keep track of where we placed the last nice element (A or B). \r\nWhenever we come across any other nice element, place it in the OPPOSITE side. \r\n\r\nIf an element comes who's frequency is greater than 1, then just dump it in A. \r\n\r\nThis suffices for Case 1. \r\n\r\nWhat to do about the Case 2b ? \r\n\r\nIn that case, the first time we encounter an element who's frequency is greater than 2, we mark it as a special character and then place it on either side. Whenever we come across it's next occurences, we will place it on the opposite side than the first side. \r\n\r\nSomething like this - \r\n\r\n        if(frequency[A[i]] > 2 && special == NOT_USED)\r\n        {\r\n            split += opposite(last);\r\n            special_place = opposite(last);\r\n            last = opposite(last);\r\n\r\n            special_char = A[i];\r\n            special = USED;\r\n        }\r\n        else if(A[i] == special_char)\r\n        {\r\n            split += opposite(special_place);\r\n        }\r\n\r\n\r\n-----------------------------------\r\n\r\nThe below code will make it clearer.\r\n\r\nconst int USED = 0, NOT_USED = 1;\r\n    int special = (frequency_1_elements%2 == 0 ? USED : NOT_USED), special_char = -1;\r\n    char last = 'B', special_place;\r\n\r\n    for(int i = 0; i < no_of_numbers; i++)\r\n    {\r\n        if(frequency[A[i]] == 1)\r\n        {\r\n            split += opposite(last);\r\n            last = opposite(last);\r\n        }\r\n        else if(frequency[A[i]] > 2 && special == NOT_USED)\r\n        {\r\n            split += opposite(last);\r\n            special_place = opposite(last);\r\n            last = opposite(last);\r\n\r\n            special_char = A[i];\r\n            special = USED;\r\n        }\r\n        else if(A[i] == special_char)\r\n        {\r\n            split += opposite(special_place);\r\n        }\r\n        else\r\n        {\r\n            split += 'A';\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Educational Round 51/Explanation/Vasya and Password Explanation.txt",
    "content": "First, we'll check if S is valid.\r\n\r\nint is_proper(string S)\r\n{\r\n    int upper_case = 0, lower_case = 0, digits = 0;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if('a' <= S[i] && S[i] <= 'z') lower_case++;\r\n        if('A' <= S[i] && S[i] <= 'Z') upper_case++;\r\n        if('0' <= S[i] && S[i] <= '9') digits++;\r\n    }\r\n\r\n    return (upper_case > 0 && lower_case > 0 && digits > 0);\r\n}\r\n\r\n-------------------------------\r\n\r\nIf S is already valid, don't do anything. \r\n\r\nif(upper_case > 0 && lower_case > 0 && digits > 0)\r\n    {\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n\r\n----------------------------------\r\n\r\nIf S has only digits, but lacks upper case and lower case, then we can change the first two digits. \r\n\r\n    if(upper_case == 0 && lower_case == 0 && digits > 0)\r\n    {\r\n        S[0] = 'A'; S[1] = 'a';\r\n\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n    else if(upper_case == 0 && lower_case > 0 && digits == 0)\r\n    {\r\n        S[0] = 'A'; S[1] = '0';\r\n\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n    else if(upper_case > 0 && lower_case == 0 && digits == 0)\r\n    {\r\n        S[0] = 'a'; S[1] = '0';\r\n\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n\r\n---------------------------------------\r\n\r\nIf S has two properties but lacks the third, then keep changing one of the characters till you get a valid string. There will be atmost 2 checks like this.\r\n\r\nfor(int i = 0; i < S.size(); i++)//Runs at most 2 times.\r\n    {\r\n        char original = S[i];\r\n\r\n        S[i] = '0'; if(is_proper(S)){cout << S << \"\\n\"; return;}\r\n        S[i] = 'a'; if(is_proper(S)){cout << S << \"\\n\"; return;}\r\n        S[i] = 'A'; if(is_proper(S)){cout << S << \"\\n\"; return;}\r\n\r\n        S[i] = original;\r\n    }\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 51/Programs/Bicolourings.cpp",
    "content": "#include <cstdio>\n#include <cstring>\n\nconst int NO_OF_COLUMN_ARRANGEMENTS = 4, MAX_N = 1005;\nconst int MOD = 998244353;\nconst int BB = 0, BW = 1, WB = 2, WW = 3;\n\ntypedef long long LL;\nLL no_of_ways[MAX_N][2*MAX_N][NO_OF_COLUMN_ARRANGEMENTS];\n\nint additional_components(int second_last, int last)\n{\n    switch(second_last)\n    {\n        case BB : switch(last)\n                  {\n                      case BB : return 0;\n                      case BW : return 1;\n                      case WB : return 1;\n                      case WW : return 1;\n                  }\n        case BW : switch(last)\n                  {\n                      case BB : return 0;\n                      case BW : return 0;\n                      case WB : return 2;\n                      case WW : return 0;\n                  }\n        case WB : switch(last)\n                  {\n                      case BB : return 0;\n                      case BW : return 2;\n                      case WB : return 0;\n                      case WW : return 0;\n                  }\n        case WW : switch(last)\n                  {\n                      case BB : return 1;\n                      case BW : return 1;\n                      case WB : return 1;\n                      case WW : return 0;\n                  }\n    }\n}\n\nint main()\n{\n    int no_of_columns, no_of_components;\n    scanf(\"%d %d\", &no_of_columns, &no_of_components);\n\n    memset(no_of_ways, 0, sizeof(no_of_ways));\n    no_of_ways[1][1][BB] = no_of_ways[1][1][WW] = 1;\n    no_of_ways[1][2][BW] = no_of_ways[1][2][WB] = 1;\n\n    for(int column = 2; column <= no_of_columns; column++)\n    {\n        for(int components = 1; components <= 2*no_of_columns; components++)\n        {\n            for(int last = 0; last < NO_OF_COLUMN_ARRANGEMENTS; last++)\n            {\n                for(int second_last = 0; second_last < NO_OF_COLUMN_ARRANGEMENTS; second_last++)\n                {\n                    int new_components = components + additional_components(second_last, last);\n\n                    no_of_ways[column][new_components][last] += no_of_ways[column - 1][components][second_last];\n\n                    no_of_ways[column][new_components][last] %= MOD;\n                }\n            }\n        }\n    }\n\n    LL answer = 0;\n    for(int last = 0; last < NO_OF_COLUMN_ARRANGEMENTS; last++)\n    {\n        answer += no_of_ways[no_of_columns][no_of_components][last];\n\n        answer %= MOD;\n    }\n\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 51/Programs/Relatively Prime Pairs.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    printf(\"YES\\n\");\r\n    for(long long i = left; i <= right; i += 2)\r\n        printf(\"%I64d %I64d\\n\", i, i + 1);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 51/Programs/Vasya and Multisets.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nchar opposite(char ch)\r\n{\r\n    return (ch == 'A' ? 'B' : 'A');\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_numbers;\r\n    cin >> no_of_numbers;\r\n\r\n    vector <int> A(no_of_numbers);\r\n    for(int i = 0; i < no_of_numbers; i++)\r\n        cin >> A[i];\r\n\r\n    const int MAX = 105;\r\n    vector <int> frequency(MAX, 0);\r\n    for(int i = 0; i < no_of_numbers; i++)\r\n        frequency[A[i]]++;\r\n\r\n    int frequency_1_elements = 0, frequency_more_than_2_elements = 0;\r\n    for(int i = 0; i < MAX; i++)\r\n    {\r\n        if(frequency[i] == 1) frequency_1_elements++;\r\n\r\n        if(frequency[i] > 2) frequency_more_than_2_elements++;\r\n    }\r\n\r\n    if(frequency_1_elements%2 == 1 && frequency_more_than_2_elements == 0)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return 0;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n    string split;\r\n\r\n    const int USED = 0, NOT_USED = 1;\r\n    int special = (frequency_1_elements%2 == 0 ? USED : NOT_USED), special_char = -1;\r\n    char last = 'B', special_place;\r\n\r\n    for(int i = 0; i < no_of_numbers; i++)\r\n    {\r\n        if(frequency[A[i]] == 1)\r\n        {\r\n            split += opposite(last);\r\n            last = opposite(last);\r\n        }\r\n        else if(frequency[A[i]] > 2 && special == NOT_USED)\r\n        {\r\n            split += opposite(last);\r\n            special_place = opposite(last);\r\n            last = opposite(last);\r\n\r\n            special_char = A[i];\r\n            special = USED;\r\n        }\r\n        else if(A[i] == special_char)\r\n        {\r\n            split += opposite(special_place);\r\n        }\r\n        else\r\n        {\r\n            split += 'A';\r\n        }\r\n    }\r\n\r\n    cout << split;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 51/Programs/Vasya and Password.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint is_proper(string S)\r\n{\r\n    int upper_case = 0, lower_case = 0, digits = 0;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if('a' <= S[i] && S[i] <= 'z') lower_case++;\r\n        if('A' <= S[i] && S[i] <= 'Z') upper_case++;\r\n        if('0' <= S[i] && S[i] <= '9') digits++;\r\n    }\r\n\r\n    return (upper_case > 0 && lower_case > 0 && digits > 0);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    int upper_case = 0, lower_case = 0, digits = 0;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if('a' <= S[i] && S[i] <= 'z') lower_case++;\r\n        if('A' <= S[i] && S[i] <= 'Z') upper_case++;\r\n        if('0' <= S[i] && S[i] <= '9') digits++;\r\n    }\r\n\r\n    if(upper_case > 0 && lower_case > 0 && digits > 0)\r\n    {\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n    else if(upper_case == 0 && lower_case == 0 && digits > 0)\r\n    {\r\n        S[0] = 'A'; S[1] = 'a';\r\n\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n    else if(upper_case == 0 && lower_case > 0 && digits == 0)\r\n    {\r\n        S[0] = 'A'; S[1] = '0';\r\n\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n    else if(upper_case > 0 && lower_case == 0 && digits == 0)\r\n    {\r\n        S[0] = 'a'; S[1] = '0';\r\n\r\n        cout << S << \"\\n\";\r\n        return;\r\n    }\r\n\r\n    for(int i = 0; i < S.size(); i++)//Runs at most 2 times.\r\n    {\r\n        char original = S[i];\r\n\r\n        S[i] = '0'; if(is_proper(S)){cout << S << \"\\n\"; return;}\r\n        S[i] = 'a'; if(is_proper(S)){cout << S << \"\\n\"; return;}\r\n        S[i] = 'A'; if(is_proper(S)){cout << S << \"\\n\"; return;}\r\n\r\n        S[i] = original;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 52/Explanations/Vasya and Chocolates Explanation.txt",
    "content": "The maximum amount of money that can be spent = Money/c\n\nThese many candies are paid for. \n\nFor every 'a' free candies, 'b' free candies are gotten.\n\n-------------------\n\nvoid solve()\n{\n    long long money, a, b, cost;\n    cin >> money >> a >> b >> cost;\n\n    long long paid_candies = (money/cost);\n    long long free_candies = (paid_candies/a)*b;\n\n    long long total_candies = paid_candies + free_candies;\n    cout << total_candies << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/Educational Round 52/Explanations/Vasya and Isolated Vertices Explanation.txt",
    "content": "Now, let us try to minimise the number of isolated vertices. \r\n\r\nWe will connect 2 new vertices with each edge. \r\n\r\nWe need V/2 number of edges. \r\n\r\nIf we have less ... Then isolated = V - 2E\r\n\r\nWhat if we try to maximise it ?\r\n\r\nLet us have a fully connected component of as small size as possible. \r\n\r\nA fully connected component of size k requires C(k, 2) edges. Use up edges greedily like this and see how many are remaining.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    long long vertices, edges;\r\n    cin >> vertices >> edges;\r\n\r\n    int minimum_isolated_vertices = max(0, vertices - 2*edges);\r\n\r\n    long long i = 0;\r\n    while(edges > 0 && choose_2(i) <= edges)\r\n        i++;\r\n\r\n    int fully_connected_component = (choose_2(i - 1) == edges ? i - 1 : i);\r\n    int maximum_isolated_vertices = vertices - fully_connected_component;\r\n\r\n    cout << minimum_isolated_vertices << \" \" << maximum_isolated_vertices << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 52/Programs/Vasya and Chocolates.cpp",
    "content": "#include <iostream>\n\nusing namespace std;\n\nvoid solve()\n{\n    long long money, a, b, cost;\n    cin >> money >> a >> b >> cost;\n\n    long long paid_candies = (money/cost);\n    long long free_candies = (paid_candies/a)*b;\n\n    long long total_candies = paid_candies + free_candies;\n    cout << total_candies << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 52/Programs/Vasya and Isolated Vertices.cpp",
    "content": "#include <iostream>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n\r\nusing namespace std;\r\n\r\nlong long choose_2(long long n)\r\n{\r\n    return (n*(n - 1))/2;\r\n}\r\n\r\nint main()\r\n{\r\n    long long vertices, edges;\r\n    cin >> vertices >> edges;\r\n\r\n    int minimum_isolated_vertices = max(0, vertices - 2*edges);\r\n\r\n    long long i = 0;\r\n    while(choose_2(i) <= edges)\r\n        i++;\r\n\r\n    int fully_connected_component = (choose_2(i - 1) == edges ? i - 1 : i);\r\n    int maximum_isolated_vertices = vertices - fully_connected_component;\r\n\r\n    cout << minimum_isolated_vertices << \" \" << maximum_isolated_vertices << \"\\n\";\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 54/Explanation/Divisor Subtraction Explanation.txt",
    "content": "Case 1 -  n is even\r\n \r\nThe smallest divisor is 2. We subtract 2 and the smallest divisor is always 2. So the answer is simply n/2. \r\n\r\nCase 2 - n is odd, \r\n\r\nThen we subtract the smallest odd divisor from n. This makes n even and the problem is reduced the Case 1\r\n\r\nAnswer = 1 + (n - p)/2, where p is the smallest prime factor of n\r\n\r\n-----------\r\n\r\nint main()\r\n{\r\n    long long n;\r\n    cin >> n;\r\n\r\n    const long long NOT_FOUND = 0;\r\n    long long smallest_odd_prime_factor = NOT_FOUND;\r\n    if(n%2 == 1)\r\n    {\r\n        for(long long i = 3; i*i <= n; i++)\r\n        {\r\n            if(n%i == 0)\r\n            {\r\n                smallest_odd_prime_factor = i;\r\n                break;\r\n            }\r\n        }\r\n\r\n        if(smallest_odd_prime_factor == NOT_FOUND)\r\n            smallest_odd_prime_factor = n;\r\n    }\r\n\r\n    long long even_operations = (n - smallest_odd_prime_factor)/2;\r\n    long long no_of_operations = (n%2 == 1) + even_operations;\r\n\r\n    cout << no_of_operations;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 54/Explanation/Meme Problem Explanation.txt",
    "content": "Now, we have two equations to solve - \r\n\r\na + b = d\r\nab = d\r\n\r\nNow, we simply reduce it to one variable\r\n\r\nb(d - b) = d\r\n\r\nbd - b^2 = d\r\n\r\nb^2 - bd + d = 0\r\n\r\n---------------\r\n\r\nWe solve this quadratic equation and print 10 decimal places.\r\n\r\nThere is not solution only when d = 1.\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int d;\r\n    scanf(\"%d\", &d);\r\n\r\n    if(d == 0)\r\n    {\r\n        printf(\"Y 0.000000 0.000000\\n\");\r\n    }\r\n    else if(d*d - 4*d < 0)\r\n    {\r\n        printf(\"N\\n\");\r\n    }\r\n    else\r\n    {\r\n        double b = (d + sqrt(d*d - 4*d))/2;\r\n        double a = b/(b - 1);\r\n\r\n        printf(\"Y %.10f %.10f\\n\", a, b);\r\n    }\r\n}"
  },
  {
    "path": "Contests/Educational Round 54/Explanation/Minimizing the String Explanation.txt",
    "content": "Let us have two strings - \n\nA1 A2 A3 ... An\nB1 B2 B3 ... Bn\n\nNow, A < B, if the first unequal character in A is smaller than in B. \n\nLet j be the first position such that A(j) =/= B(j) \n\nThen A < B if A(j) < B(j)\n\n------------------\n\nNow we go through the string given to us and remove the first character i such that S(i) > S(i + 1). \n\nNow, let us prove that such a string S' will be smaller than all other strings obtained by removing one character from S.\n\n\n---\n\nCase 1 - We have removed some character after i\n\nThen both strings have the same first (i - 1) characters. \n\nThen the other strings will have S(i) and S' will have S(i + 1) at the i-th position. So, S' < S\n\n---\n\nCase 2 - We remove some character before i\n\nThen suppose we have removed j-th character. \n\nBoth strings have same first j - 1 characters. \n\nS' has A(j) and the other other string has A(j + 1)\n\nBy definition i is the first position where S(i + 1) < S(i)\n\nThis means A(j + 1) >= A(j)\n\nSo this proves that the other string cannot be smaller than S'.\n\n--------\n\nThis completes our proof that we obtain the minimum such string by removing the first character where S(i + 1) < S(i)\n\n-----\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    vector <int> is_ignored(length, false);\n    for(int i = 0; i < length; i++)\n    {\n        if(i + 1 == length || S[i] > S[i + 1])\n        {\n            is_ignored[i] = true;\n            break;\n        }\n    }\n\n    for(int i = 0; i < length; i++)\n        if(!is_ignored[i])\n            cout << S[i];\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 54/Programs/Divisor Subtraction.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long n;\r\n    cin >> n;\r\n\r\n    const long long NOT_FOUND = 0;\r\n    long long smallest_odd_prime_factor = NOT_FOUND;\r\n    if(n%2 == 1)\r\n    {\r\n        for(long long i = 3; i*i <= n; i++)\r\n        {\r\n            if(n%i == 0)\r\n            {\r\n                smallest_odd_prime_factor = i;\r\n                break;\r\n            }\r\n        }\r\n\r\n        if(smallest_odd_prime_factor == NOT_FOUND)\r\n            smallest_odd_prime_factor = n;\r\n    }\r\n\r\n    long long even_operations = (n - smallest_odd_prime_factor)/2;\r\n    long long no_of_operations = (n%2 == 1) + even_operations;\r\n\r\n    cout << no_of_operations;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 54/Programs/Meme Problem.cpp",
    "content": "#include <cstdio>\r\n#include <cmath>\r\n\r\n/*\r\nb + b/(b - 1) = d\r\n\r\nb^2 - b + b = db - d\r\n\r\nb^2 -db + d = 0\r\n\r\nd + root(d^2 - 4d)/2\r\n*/\r\n\r\nvoid solve()\r\n{\r\n    int d;\r\n    scanf(\"%d\", &d);\r\n\r\n    if(d == 0)\r\n    {\r\n        printf(\"Y 0.000000 0.000000\\n\");\r\n    }\r\n    else if(d*d - 4*d < 0)\r\n    {\r\n        printf(\"N\\n\");\r\n    }\r\n    else\r\n    {\r\n        double b = (d + sqrt(d*d - 4*d))/2;\r\n        double a = b/(b - 1);\r\n\r\n        printf(\"Y %.10f %.10f\\n\", a, b);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 54/Programs/Minimizing the String.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int length;\n    string S;\n    cin >> length >> S;\n\n    vector <int> is_ignored(length, false);\n    for(int i = 0; i < length; i++)\n    {\n        if(i + 1 == length || S[i] > S[i + 1])\n        {\n            is_ignored[i] = true;\n            break;\n        }\n    }\n\n    for(int i = 0; i < length; i++)\n        if(!is_ignored[i])\n            cout << S[i];\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 55/Explanation/Increasing Frequency Explanation.txt",
    "content": "Quora Blog Link - https://qr.ae/TUtpPB\n\n-------------------------\n\nint main()\n{\n    int no_of_elements, target;\n    cin >> no_of_elements >> target;\n\n\n    vector <int> A(no_of_elements + 1);\n    vector <int> sum(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        position[A[i]].push_back(i);\n\n        sum[i] = sum[i - 1] + (A[i] == target);\n    }\n\n    int maximum_changes = 0;\n\n    for(int i = 0; i < MAX_N; i++)\n    {\n        if(i == target) continue;\n\n        int max_ending_here = 0;\n\n        for(int j = 0; j < position[i].size(); j++)\n        {\n            int p = position[i][j], q = (j == 0 ? 0 : position[i][j - 1]);\n\n            int no_of_minus_ones = sum[p] - sum[q];\n\n            max_ending_here = max(max_ending_here - no_of_minus_ones + 1, 1);\n\n            maximum_changes = max(maximum_changes, max_ending_here);\n        }\n    }\n\n    int target_frequency = position[target].size();\n    int maximum_occurences = maximum_changes + target_frequency;\n\n    cout << maximum_occurences;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 55/Programs/Increasing Frequency.cpp",
    "content": "#include <iostream>\n#include <map>\n#include <vector>\n\nusing namespace std;\n\nconst int MAX_N = 5e5 + 5, oo = 1e9;\nvector <int> position[MAX_N];\n\nint main()\n{\n    int no_of_elements, target;\n    cin >> no_of_elements >> target;\n\n\n    vector <int> A(no_of_elements + 1);\n    vector <int> sum(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        cin >> A[i];\n\n        position[A[i]].push_back(i);\n\n        sum[i] = sum[i - 1] + (A[i] == target);\n    }\n\n    int maximum_changes = 0;\n\n    for(int i = 0; i < MAX_N; i++)\n    {\n        if(i == target) continue;\n\n        int max_ending_here = 0;\n\n        for(int j = 0; j < position[i].size(); j++)\n        {\n            int p = position[i][j], q = (j == 0 ? 0 : position[i][j - 1]);\n\n            int no_of_minus_ones = sum[p] - sum[q];\n\n            max_ending_here = max(max_ending_here - no_of_minus_ones + 1, 1);\n\n            maximum_changes = max(maximum_changes, max_ending_here);\n        }\n    }\n\n    int target_frequency = position[target].size();\n    int maximum_occurences = maximum_changes + target_frequency;\n\n    cout << maximum_occurences;\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 56/Explanations/Beautiful Graph Explanation.txt",
    "content": "1. For a moment, let us forget about the numbers 1, 2 and 3 and just focus on parity. For two vertices to have an odd sum, they must be of different parity. \r\n\r\n2. For each vertex, we must connect a vertex of a different parity to it. \r\n\r\n3. There are two ways of choosing the odd parity and one way of choosing an even number. \r\n\r\n4. When we are given a graph, we must check if it is possible to treat this graph as a bipartite graph. In that case, each group will have one parity. \r\n\r\nNote - If a graph is not bipartite, it will have a cycle of odd length. \r\n\r\n5. If the component sizes are C1 and C2, then we can make the C1 component odd in 2^C1 ways and the C2 component odd in 2^C2 ways. Answer = 2^C1 + 2^C2\r\n\r\n----------------\r\n\r\nA few points I missed - \r\n\r\n1. The graph is not necessarily connected. In that case, the above algorithm must be repeated for each connected component. \r\n\r\n2. For each test case, don't clean all MAX_N points ... as that will time out, clean only n.\r\n\r\n3. To check if a graph is bipartite, do BFS. Paint a graph as red, and all of it's unpainted children as blue and all the blue's unpainted children red and so on. If there comes a point when a vertex and it's child have the same colour, the graph is not bipartite. \r\n\r\n-------\r\n\r\nlong long get_component_answer_bfs(int source)\r\n{\r\n    queue <int> Q;\r\n    Q.push(source);\r\n\r\n    colour[source] = 1;\r\n\r\n    vector <long long> component(2, 0);\r\n    component[colour[source]]++;\r\n\r\n    long long this_component_answer = 1;\r\n\r\n    while(!Q.empty())\r\n    {\r\n        int current_v = Q.front();\r\n\r\n        Q.pop();\r\n\r\n        for(int i = 0; i < graph[current_v].size(); i++)\r\n        {\r\n            int child_v = graph[current_v][i];\r\n\r\n            if(colour[child_v] == NOT_KNOWN)\r\n            {\r\n                colour[child_v] = get_complement(colour[current_v]);\r\n\r\n                component[colour[child_v]]++;\r\n\r\n                Q.push(child_v);\r\n            }\r\n            else if(colour[child_v] == colour[current_v]) //It's not bipartite\r\n            {\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    this_component_answer = (power_mod(2, component[0]) + power_mod(2, component[1]))%MOD;\r\n\r\n    return this_component_answer;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    long long answer = 1;\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(colour[i] == NOT_KNOWN)\r\n            answer = (answer*get_component_answer_bfs(i))%MOD;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    clean_for_next_query(no_of_vertices);\r\n}"
  },
  {
    "path": "Contests/Educational Round 56/Explanations/Dice Rolling Explanation.txt",
    "content": "Obviously, there are many answers to this question. The simplest is ceil(n/7).\r\n\r\n---------------\r\n\r\nvoid solve()\r\n{\r\n    int target_score;\r\n    cin >> target_score;\r\n\r\n    int no_of_rolls = ceil(target_score, 7);\r\n    cout << no_of_rolls << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Educational Round 56/Explanations/Letters Rearranging Explanation.txt",
    "content": "Now, the only time when it is impossible to re-arrange a string to get a non-palindrome is when all characters are the same !\n\nIf all characters are the same, then don't do anything. \n\nElse, print any valid non-palindrome. \n\nNow, there are many ways to do this. \n\nBut, here was my elegant solution. \n\n1. Sort the string. \n\n2. If the first and character are the same, it means all the characters are the same. \n\n3. If they aren't then simply print the string in sorted order. \n\n--------\n\nvoid solve()\n{\n    string S;\n    cin >> S;\n\n    sort(all(S));\n\n    cout << (S[0] == S[S.size() - 1] ? \"-1\" : S) << \"\\n\";\n}\n\nint main()\n{\n    int no_of_queries;\n    cin >> no_of_queries;\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 56/Explanations/Mishka and Last Exam Explanation.txt",
    "content": "We will be greedy. For each B[i], \r\n\r\n1. Try to make A[i] as small as possible. The smallest possible value that A[i] can take on is A[i - 1]. \r\n\r\nIf A[i] = A[i - 1], then A[n - i + 1] = B[i] - A[i - 1]\r\n\r\nIt is important to check if (B[i] - A[i - 1]) <= A[n - i + 1 + 1]\r\n\r\nIf it is, then we are done\r\n\r\nA[i] = A[i - 1], \r\nA[n - i + 1] = B[i] - A[i]\r\n\r\n2. If not, then we will make A[n - i + 1] as large as possible and then find A[i]\r\n\r\nA[n - i + 1] = A[n - i + 1 + 1]\r\nA[i] = B[i] - A[n - i + 1]\r\n\r\n3. We need not worry that both these situations won't occur as the question guarantees us this. \r\n\r\n-----------------------------\r\n\r\nWe are given that there is always an answer so we need not worry. This greedy algorithm ensures that A[i - 1] <= A[i] and A[i] <= A[i + 1]. We have maintained this invariant in building it. \r\n\r\nIf the answer weren't possible, then we would be getting negative integers at some point. \r\n\r\n--------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <long long> B(no_of_elements/2 + 1);\r\n    for(int i = 1; i <= no_of_elements/2; i++)\r\n        scanf(\"%I64d\", &B[i]);\r\n\r\n    vector <long long> A(no_of_elements + 2, 0);\r\n    int front = 0, back = no_of_elements + 1;\r\n\r\n    const long long oo = 2e18;\r\n    A[back] = oo;\r\n\r\n    for(int i = 1; i <= no_of_elements/2; i++)\r\n    {\r\n        if(B[i] - A[front] > A[back])\r\n        {\r\n            A[back - 1] = A[back]; back--;\r\n            A[front + 1] = B[i] - A[back]; front++;\r\n        }\r\n        else\r\n        {\r\n            A[front + 1] = A[front]; front++;\r\n            A[back - 1] = B[i] - A[front]; back--;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        printf(\"%I64d \", A[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 56/Programs/Beautiful Graph.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <queue>\n\nusing namespace std;\n\nconst int MAX_N = 3e5 + 5, NOT_KNOWN = -1, MOD = 998244353;\nvector <int> graph[MAX_N];\nvector <int> colour(MAX_N, NOT_KNOWN);\n\nlong long power_mod(long long base, long long power)\n{\n    long long result = 1;\n\n    while(power)\n    {\n        if(power%2 == 1)\n            result = (result*base)%MOD;\n\n        base = (base*base)%MOD;\n        power = power >> 1;\n    }\n\n    return result;\n}\n\nvoid clean_for_next_query(int limit)\n{\n    for(int i = 0; i <= limit; i++)\n    {\n        graph[i].clear();\n\n        colour[i] = NOT_KNOWN;\n    }\n}\n\nint get_complement(int x) //Return 1 if 0 and 0 if 1\n{\n    return (1 - x);\n}\n\nlong long get_component_answer_bfs(int source)\n{\n    queue <int> Q;\n    Q.push(source);\n\n    colour[source] = 1;\n\n    vector <long long> component(2, 0);\n    component[colour[source]]++;\n\n    long long this_component_answer = 1;\n\n    while(!Q.empty())\n    {\n        int current_v = Q.front();\n\n        Q.pop();\n\n        for(int i = 0; i < graph[current_v].size(); i++)\n        {\n            int child_v = graph[current_v][i];\n\n            if(colour[child_v] == NOT_KNOWN)\n            {\n                colour[child_v] = get_complement(colour[current_v]);\n\n                component[colour[child_v]]++;\n\n                Q.push(child_v);\n            }\n            else if(colour[child_v] == colour[current_v]) //It's not bipartite\n            {\n                return 0;\n            }\n        }\n    }\n\n    this_component_answer = (power_mod(2, component[0]) + power_mod(2, component[1]))%MOD;\n\n    return this_component_answer;\n}\n\nvoid solve()\n{\n    int no_of_vertices, no_of_edges;\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\n\n    for(int i = 1; i <= no_of_edges; i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        graph[u].push_back(v);\n        graph[v].push_back(u);\n    }\n\n    long long answer = 1;\n\n    for(int i = 1; i <= no_of_vertices; i++)\n    {\n        if(colour[i] == NOT_KNOWN)\n            answer = (answer*get_component_answer_bfs(i))%MOD;\n    }\n\n    printf(\"%I64d\\n\", answer);\n\n    clean_for_next_query(no_of_vertices);\n}\n\nint main()\n{\n    int no_of_queries;\n    scanf(\"%d\", &no_of_queries);\n\n    while(no_of_queries--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 56/Programs/Dice Rolling.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint ceil(int numerator, int denominator)\r\n{\r\n    int quotient = numerator/denominator;\r\n    int remainder = numerator%denominator;\r\n\r\n    return (quotient + (remainder!= 0));\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int target_score;\r\n    cin >> target_score;\r\n\r\n    int no_of_rolls = ceil(target_score, 7);\r\n    cout << no_of_rolls << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 56/Programs/Letters Rearranging.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    sort(all(S));\r\n\r\n    cout << (S[0] == S[S.size() - 1] ? \"-1\" : S) << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 56/Programs/Mishka and Last Exam.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <long long> B(no_of_elements/2 + 1);\r\n    for(int i = 1; i <= no_of_elements/2; i++)\r\n        scanf(\"%I64d\", &B[i]);\r\n\r\n    vector <long long> A(no_of_elements + 2, 0);\r\n    int front = 0, back = no_of_elements + 1;\r\n\r\n    const long long oo = 2e18;\r\n    A[back] = oo;\r\n\r\n    for(int i = 1; i <= no_of_elements/2; i++)\r\n    {\r\n        if(B[i] - A[front] > A[back])\r\n        {\r\n            A[back - 1] = A[back]; back--;\r\n            A[front + 1] = B[i] - A[back]; front++;\r\n        }\r\n        else\r\n        {\r\n            A[front + 1] = A[front]; front++;\r\n            A[back - 1] = B[i] - A[front]; back--;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        printf(\"%I64d \", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 60/Explanations/Best Subsegment Explanation.txt",
    "content": "Fact - The arithmetic mean of any segment cannot be greater than the maximum integer in the array. \n\nProof - \n\n(a1 + a2 + ... + aN) = M x N, where M is the mean. \n\nIf M > max{a1, ... , aN}, then M x N will be greater than (a1 + a2 + ... + aN), which is not possible. \n\n--------\n\nNow, which segments have the mean = Max ?\n\nThose segments that ONLY have the max element. \n\nNow, the question has reduced to finding the longest segment of the array consisting of the given element x.\n\n------------\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    int maximum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n        maximum = max(maximum, A[i]);\n\n    int max_longest_segment = 0, longest_segment_here = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] != maximum)\n        {\n            longest_segment_here = 0;\n        }\n        else\n        {\n            longest_segment_here++;\n\n            max_longest_segment = max(max_longest_segment, longest_segment_here);\n        }\n    }\n\n    cout << max_longest_segment;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 60/Explanations/Emotes Explanation.txt",
    "content": "We will be greedy ... \r\n\r\n1. We will use the maximum element K times in a row. \r\n2. Then, we will use the second maximum element. \r\n\r\nAnd then, we will repeat. \r\n\r\nThis happens in cycles of (K + 1). \r\n\r\nWe need to find out the number of cycles and the cost for each cycle.\r\n\r\n------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, total_chosen, maximum_consecutive;\r\n    cin >> no_of_elements >> total_chosen >> maximum_consecutive;\r\n\r\n    vector <long long> A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n    reverse(all(A));\r\n\r\n    long long no_of_cycles = total_chosen/(maximum_consecutive + 1);\r\n    long long cycle_total = A[0]*maximum_consecutive + A[1];\r\n\r\n    long long remaining = total_chosen%(maximum_consecutive + 1);\r\n\r\n    long long total = cycle_total*no_of_cycles + A[0]*remaining;\r\n\r\n    cout << total;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 60/Programs/Best Subsegment.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    int maximum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n        maximum = max(maximum, A[i]);\n\n    int max_longest_segment = 0, longest_segment_here = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        if(A[i] != maximum)\n        {\n            longest_segment_here = 0;\n        }\n        else\n        {\n            longest_segment_here++;\n\n            max_longest_segment = max(max_longest_segment, longest_segment_here);\n        }\n    }\n\n    cout << max_longest_segment;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 60/Programs/Emotes.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, total_chosen, maximum_consecutive;\r\n    cin >> no_of_elements >> total_chosen >> maximum_consecutive;\r\n\r\n    vector <long long> A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n    reverse(all(A));\r\n\r\n    long long no_of_cycles = total_chosen/(maximum_consecutive + 1);\r\n    long long cycle_total = A[0]*maximum_consecutive + A[1];\r\n\r\n    long long remaining = total_chosen%(maximum_consecutive + 1);\r\n\r\n    long long total = cycle_total*no_of_cycles + A[0]*remaining;\r\n\r\n    cout << total;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 62/Explanations/Detective Book Explanation.txt",
    "content": "When we are at day i, we will keep on going till A[i] at least. So the target for the day is always maximum of max(target, A[i]). \n\nIf we have reached i, and i is the current target, then we will increment the number of days as we will close for the day.\n\n---\n\nint main()\n{\n    int no_of_pages;\n    cin >> no_of_pages;\n\n    vector <int> page(no_of_pages + 1, 0);\n    for(int i = 1; i <= no_of_pages; i++)\n        cin >> page[i];\n\n    int no_of_days = 0, day_target = 0;\n    for(int i = 1; i <= no_of_pages; i++)\n    {\n        day_target = max(day_target, page[i]);\n\n        if(day_target == i)\n        {\n            day_target = 0;\n\n            no_of_days++;\n        }\n    }\n\n    cout << no_of_days;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 62/Explanations/Good Strings Explanation.txt",
    "content": "We will keep only one character in the string. It will either be the first '>' or the last '<', whichever requires fewer deletions. \r\n\r\n--------\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int answer;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == '>')\r\n        {\r\n            answer = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    for(int i = length - 1; i >= 0; i--)\r\n    {\r\n        if(S[i] == '<')\r\n        {\r\n            answer = min(answer, length - 1 - i);\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Educational Round 62/Explanations/Minimum Triangulation Explanation.txt",
    "content": "We want to divide the N numbers - 1, 2, 3, ... , N into N - 2 triplets (a, b, c) such that the sum of the products of abc is minimum\r\n\r\n1. Each side must occur in at least one triplet. \r\n\r\n---\r\n\r\nIf we want to minimise the sum, we need to ensure that the smallest element - 1, is present in each triplet. \r\n\r\nNow each triplet is really the product of 2 integers. We want to minimise the product. \r\n\r\nSo, we will pair 2 with 3. Pairing 2 with any other number will yield a greater product. \r\n\r\nThen, by the same logic we will pair 3 with 4, \r\n\r\n4 with 5 and so on. \r\n\r\n----\r\n\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    int weight = 0;\r\n    for(int i = 3; i <= n; i++)\r\n        weight += i*(i - 1);\r\n\r\n    cout << weight;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 62/Explanations/Playlist Explanation.txt",
    "content": "Let us sort all the songs by beauty and then start processing the songs backwards from the last song till the first. \r\n\r\nWe will iterate over all N songs and calculate the pleasure of the playlist if song i, is the song with minimum beauty in the playlist. \r\nWe will choose the maximum of these pleasures.\r\n\r\nAt our current moment, we will be pointing to the song who's beauty is the minimum.\r\n\r\nAs for the length ... We will choose the maximum K - 1 lengths  from [i + 1, ... , N]. \r\n\r\nFor doing this, we will need to maintain a priority queue of length K.\r\nAt each step, we will remove the smallest length of the priority queue and insert the current length. \r\n\r\n----\r\n\r\nstruct song\r\n{\r\n    LL length, beauty;\r\n\r\n    song(){}\r\n\r\n    song(LL L, LL B)\r\n    {\r\n        length = L, beauty = B;\r\n    }\r\n\r\n    const int operator <(song &S)\r\n    {\r\n        return (beauty < S.beauty);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_songs, max_songs;\r\n    cin >> no_of_songs >> max_songs;\r\n\r\n    vector <song> songs(no_of_songs);\r\n    for(int i = 0; i < no_of_songs; i++)\r\n        cin >> songs[i].length >> songs[i].beauty;\r\n\r\n    sort(all(songs));\r\n\r\n    LL pleasure = 0;\r\n    LL current_beauty, current_length = 0;\r\n    priority_queue <LL, vector <LL>, greater<LL> > lengths;\r\n    int current_chosen = 0;\r\n\r\n    for(int i = no_of_songs - 1; i >= 0; i--)\r\n    {\r\n        current_beauty = songs[i].beauty;\r\n\r\n        if(current_chosen >= max_songs)\r\n        {\r\n            current_length -= lengths.top();\r\n\r\n            lengths.pop();\r\n        }\r\n\r\n        current_length += songs[i].length;\r\n        lengths.push(songs[i].length);\r\n\r\n        pleasure = max(pleasure, current_beauty*current_length);\r\n\r\n        if(current_chosen < max_songs)\r\n        {\r\n            current_chosen++;\r\n        }\r\n    }\r\n\r\n    cout << pleasure;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 62/Programs/Detective Book.cpp",
    "content": "#include <iostream>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_pages;\n    cin >> no_of_pages;\n\n    vector <int> page(no_of_pages + 1, 0);\n    for(int i = 1; i <= no_of_pages; i++)\n        cin >> page[i];\n\n    int no_of_days = 0, day_target = 0;\n    for(int i = 1; i <= no_of_pages; i++)\n    {\n        day_target = max(day_target, page[i]);\n\n        if(day_target == i)\n        {\n            day_target = 0;\n\n            no_of_days++;\n        }\n    }\n\n    cout << no_of_days;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 62/Programs/Good Strings.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int answer;\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(S[i] == '>')\r\n        {\r\n            answer = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    for(int i = length - 1; i >= 0; i--)\r\n    {\r\n        if(S[i] == '<')\r\n        {\r\n            answer = min(answer, length - 1 - i);\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 62/Programs/Minimum Triangulation.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    int weight = 0;\r\n    for(int i = 3; i <= n; i++)\r\n        weight += i*(i - 1);\r\n\r\n    cout << weight;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 62/Programs/Playlist.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <queue>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nstruct song\r\n{\r\n    LL length, beauty;\r\n\r\n    song(){}\r\n\r\n    song(LL L, LL B)\r\n    {\r\n        length = L, beauty = B;\r\n    }\r\n\r\n    const int operator <(song &S)\r\n    {\r\n        return (beauty < S.beauty);\r\n    }\r\n};\r\n\r\nint main()\r\n{\r\n    int no_of_songs, max_songs;\r\n    cin >> no_of_songs >> max_songs;\r\n\r\n    vector <song> songs(no_of_songs);\r\n    for(int i = 0; i < no_of_songs; i++)\r\n        cin >> songs[i].length >> songs[i].beauty;\r\n\r\n    sort(all(songs));\r\n\r\n    LL pleasure = 0;\r\n    LL current_beauty, current_length = 0;\r\n    priority_queue <LL, vector <LL>, greater<LL> > lengths;\r\n    int current_chosen = 0;\r\n\r\n    for(int i = no_of_songs - 1; i >= 0; i--)\r\n    {\r\n        current_beauty = songs[i].beauty;\r\n\r\n        if(current_chosen >= max_songs)\r\n        {\r\n            current_length -= lengths.top();\r\n\r\n            lengths.pop();\r\n        }\r\n\r\n        current_length += songs[i].length;\r\n        lengths.push(songs[i].length);\r\n\r\n        pleasure = max(pleasure, current_beauty*current_length);\r\n\r\n        if(current_chosen < max_songs)\r\n        {\r\n            current_chosen++;\r\n        }\r\n    }\r\n\r\n    cout << pleasure;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 69/Explanations/Array Splitting Explanation.txt",
    "content": "Let us suppose that we want to break (A[1], ... , A[n]) at point P. \n\nWhat is the cost ? \n\n(A[p] - A[1]) + (A[n] - A[p + 1])\n\nSuppose we want to break it at two points - p1 and p2. What is the cost ? \n\n(A[p1] - A[1]) + (A[p2] - A[p1 + 1]) + (A[n] - A[p2 + 1])\n\n= (A[p1] - A[p1 + 1]) + (A[p2] - A[p2 + 1]) + (A[n] - A[1])\n\nEvery time we break it at point p, we will add A[p + 1] - A[p] to the cost. (A[n] - A[1]) is a fixed cost that will be there\nregardless of how we choose our cuts. \n\nSo, we will create an array of all possible costs of all (N - 1) cuts. The cost is (A[i + 1] - A[i])\n\nAmong these costs, we will take the lowest (K - 1) values. These are the cuts we need to split the array into K subarrays.\n\n-----\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n \n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n \nint main()\n{\n    int no_of_elements, no_of_subarrays;\n    cin >> no_of_elements >> no_of_subarrays;\n \n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n \n    vector <long long> costs;\n    for(int i = 1; i < no_of_elements; i++)\n        costs.push_back(A[i] - A[i + 1]);\n \n    sort(all(costs));\n \n    long long total_cost = A[no_of_elements] - A[1];\n \n    for(int i = 0; i < no_of_subarrays - 1; i++)\n        total_cost += costs[i];\n \n    cout << total_cost;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 69/Explanations/DIY Wooden Ladder Explanation.txt",
    "content": "We want the ladder to be as big as possible. SO we will use the largest pieces of wood available to us to make the ladder's bases. \r\n\r\nThen we will be using A[n] and A[n - 1] to make the base. \r\n\r\nNow, we will try to use as many of the (n - 2) available planks available to us to make the ladder. But we cannot use more than (A[n - 1] - 1) planks. \r\n\r\nThe height of the ladder is min{A[n - 1] - 1, n - 2}\r\n\r\n---\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> length(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> length[i];\r\n\r\n    sort(all(length));\r\n\r\n    int no_of_steps = min(length[no_of_elements - 1] - 1, no_of_elements - 2);\r\n    cout << no_of_steps << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Educational Round 69/Explanations/Pillars Explanation.txt",
    "content": "It is not possible, whenever there exists any element A[i], such that there are values greater than A[i] both to it's left and it's right. \r\n\r\nProof - Let A[i] = x, Let Y > x and Z > x\r\n\r\nLet Y be to the left of x and Z to the right of x. \r\n\r\nWithout loss of generatlity, let Z > Y\r\n\r\nWe need to put Y on top of Z and then X on top of Y. \r\n\r\nBut Y has to cross X to reach Z. This is not possible.\r\n\r\n---\r\n\r\nIf this isn't the case, then every array element has all the elements greater than it on one side. We simply move the coins along that direction.\r\n\r\n---\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    vector <long long> max_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        max_till[i] = max(max_till[i - 1], A[i]);\r\n\r\n    vector <long long> max_from(no_of_elements + 2, 0);\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n        max_from[i] = max(max_from[i + 1], A[i]);\r\n\r\n    int possible = true;\r\n    for(int i = 2; i < no_of_elements; i++)\r\n        if(max_till[i] > A[i] && max_from[i] > A[i])\r\n            possible = false;\r\n\r\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 69/Programs/Array Splitting.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\nusing namespace std;\n\nint main()\n{\n    int no_of_elements, no_of_subarrays;\n    cin >> no_of_elements >> no_of_subarrays;\n\n    vector <long long> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n\n    vector <long long> costs;\n    for(int i = 1; i < no_of_elements; i++)\n        costs.push_back(A[i] - A[i + 1]);\n\n    sort(all(costs));\n\n    long long total_cost = A[no_of_elements] - A[1];\n\n    for(int i = 0; i < no_of_subarrays - 1; i++)\n        total_cost += costs[i];\n\n    cout << total_cost;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 69/Programs/DIY Wooden Ladder.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> length(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> length[i];\r\n\r\n    sort(all(length));\r\n\r\n    int no_of_steps = min(length[no_of_elements - 1] - 1, no_of_elements - 2);\r\n    cout << no_of_steps << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 69/Programs/Pillars.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\n#define all(v) (v).begin(), (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    vector <long long> max_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        max_till[i] = max(max_till[i - 1], A[i]);\r\n\r\n    vector <long long> max_from(no_of_elements + 2, 0);\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n        max_from[i] = max(max_from[i + 1], A[i]);\r\n\r\n    int possible = true;\r\n    for(int i = 2; i < no_of_elements; i++)\r\n        if(max_till[i] > A[i] && max_from[i] > A[i])\r\n            possible = false;\r\n\r\n    cout << (possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 69/Rough Notes Link",
    "content": "https://1drv.ms/b/s!AoiWcyvzkQXViBWmPf3yuemGyCPl?e=EWKY9K\n"
  },
  {
    "path": "Contests/Educational Round 73/Explanations/2048 Game Explanation.txt",
    "content": "Add everything that is smaller than 2048 and see if a sum larger than 2048 is possible. \r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    long long sum = 0;\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        if(element <= 2048)\r\n            sum += element;\r\n    }\r\n\r\n    cout << (sum >= 2048 ? \"YES\\n\" : \"NO\\n\");\r\n}"
  },
  {
    "path": "Contests/Educational Round 73/Explanations/Game With String Explanation.txt",
    "content": "If there is any segment < B, then Alice can never touch it. Bob wins.\n\nIf there is more than 1 segment >= 2B, then Bob can make one move on it and then reduce it to a segment of the previous type.\n\nIf there are no segments >= 2B, we will count the number of segments in [A, 2B]. The parity decides the winner.\n\nThe only trick is in knowing what to do when there is only 1 segment of length >= 2B.\n\nAlice will see if there exists a move she can make on this big segment such that the number of normal segments remaining is even.\nIf there is such a move, she wins.\nOtherwise, Bob wins.\n\n------\n\nvoid solve()\n{\n    int move_1, move_2;\n    string S;\n    cin >> move_1 >> move_2 >> S;\n\n    int length = 0;\n    vector <int> segments;\n    for(int i = 0; i < S.size(); i++)\n    {\n        if(S[i] == '.')\n        {\n            length++;\n        }\n\n        if(S[i] != '.' || i == S.size() - 1)\n        {\n            if(length != 0)\n            {\n                segments.push_back(length);\n            }\n\n            length = 0;\n        }\n    }\n\n    int bob_segments = 0, normal_segments = 0, big_segments = 0;\n    int big_segment_size = 0;\n    for(int i = 0; i < segments.size(); i++)\n    {\n        if(move_2 <= segments[i] && segments[i] < move_1)\n        {\n            bob_segments++;\n        }\n\n        if(2*move_2 <= segments[i])\n        {\n            big_segment_size = segments[i];\n\n            big_segments++;\n        }\n\n        if(move_1 <= segments[i] && segments[i] < 2*move_2)\n        {\n            normal_segments++;\n        }\n    }\n\n    if(bob_segments > 0 || big_segments > 1)\n    {\n        cout << \"NO\\n\";\n\n        return;\n    }\n\n    if(big_segments == 0)\n    {\n        cout << (normal_segments%2 == 1 ? \"YES\\n\" : \"NO\\n\");\n\n        return;\n    }\n\n    int winning = false;\n    for(int part_1 = 0; big_segment_size - move_1 - part_1 >= 0; part_1++)\n    {\n        int part_2 = big_segment_size - move_1 - part_1;\n\n        if(part_1 >= 2*move_2 || (move_2 <= part_1 && part_1 < move_1)) continue;\n        if(part_2 >= 2*move_2 || (move_2 <= part_2 && part_2 < move_1)) continue;\n\n\n        if( (normal_segments + (part_1 >= move_1) + (part_2 >= move_1))%2 == 0)\n        {\n            winning = true;\n\n            break;\n        }\n    }\n\n    cout << (winning ? \"YES\\n\" : \"NO\\n\");\n}\n"
  },
  {
    "path": "Contests/Educational Round 73/Explanations/Knights Explanation.txt",
    "content": "The main invariant is that a knight can only attack squares on the other colour from it. \r\n\r\nThis is why we will paint the board like a chessboard. \r\n\r\n---\r\n\r\n#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        for(int j = 1; j <= n; j++)\r\n        {\r\n            char colour = ( (i+j)%2 == 0 ? 'B' : 'W');\r\n            \r\n            cout << colour;\r\n        }\r\n\r\n        cout << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 73/Explanations/Make The Fence Great Again Explanation.txt",
    "content": "The main observation is that every element will be increased at most twice. The reason is that there are only 2 neighbours. \n\nAmong {i, i + 1, i + 2}, there can only be 2 values (at most) such that the neighbours have an equal value. \n\nThen, let f(i, x) be the cost for the first i elements if x additions are done on the i-th element. \n\nWe can process the transition based on the value of A[i - 1] after y additions. \n\nThe answer is min{f(n, 0), f(n, 1), f(n, 2)}\n\n---\n\nvoid solve()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n \n    vector <long long> A(no_of_elements + 1, 0);\n    vector <long long> cost(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%I64d %I64d\", &A[i], &cost[i]);\n    }\n \n    const long long oo = 1e18;\n    vector <vector <long long> > best(no_of_elements + 1, vector <long long> (3, 0));\n    best[0][0] = 0, best[0][1] = best[0][2] = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int no_of_adds = 0; no_of_adds <= 2; no_of_adds++)\n        {\n            best[i][no_of_adds] = oo;\n \n            for(int no_of_previous_adds = 0; no_of_previous_adds <= 2; no_of_previous_adds++)\n            {\n                if(A[i] + no_of_adds != A[i - 1] + no_of_previous_adds)\n                {\n                    best[i][no_of_adds] = min(best[i][no_of_adds], best[i - 1][no_of_previous_adds] + no_of_adds*cost[i]);\n                }\n            }\n        }\n    }\n \n    long long answer = oo;\n    for(int no_of_adds = 0; no_of_adds <= 2; no_of_adds++)\n    {\n        answer = min(answer, best[no_of_elements][no_of_adds]);\n    }\n \n    printf(\"%I64d\\n\", answer);\n}\n"
  },
  {
    "path": "Contests/Educational Round 73/Explanations/Perfect Team Explanation.txt",
    "content": "If there are more normal people than Mathematicians and Coders, than we can have as many teams as the minimum of (M, C) by putting 1 of each in each team. \r\n\r\nOtherwise, we will make as many teams of (N, M, C) as possible. \r\n\r\nAt the end of this, we will have 0 Normal people. \r\n\r\nNow, if M >= 2C or C >= 2M, then the number of teams we can make is C or M respectively. The reason is that there are 2 of the other kind for every one of one kind.\r\n\r\nOtherwise, the number of teams we can make is floor[(M + C)/3]. If 2*Min{M, C} > Max{M, C}, \r\n\r\nThen at each step we will take 2 of the Maximum and 1 of the Minimum. The number of people reduces by 3 each time and we will be unable to make a choice only when the number of people is less than 3. \r\n\r\nHence, the answer is floor[(M + C)/3]. \r\n\r\n---\r\n\r\nvoid solve()\r\n{\r\n    int mathematicians, coders, normal;\r\n    cin >> mathematicians >> coders >> normal;\r\n\r\n    int teams = 0;\r\n    if(normal >= min(mathematicians, coders))\r\n    {\r\n        teams = min(mathematicians, coders);\r\n    }\r\n    else\r\n    {\r\n        teams = normal;\r\n        mathematicians -= teams;\r\n        coders -= teams;\r\n\r\n        if(2*min(mathematicians, coders) <= max(mathematicians, coders))\r\n        {\r\n            teams += min(mathematicians, coders);\r\n        }\r\n        else\r\n        {\r\n            teams += (mathematicians + coders)/3;\r\n        }\r\n    }\r\n\r\n    cout << teams << \"\\n\";\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 73/Programs/2048 Game.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    long long sum = 0;\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        if(element <= 2048)\r\n            sum += element;\r\n    }\r\n\r\n    cout << (sum >= 2048 ? \"YES\\n\" : \"NO\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_tests;\r\n    cin >> no_of_tests;\r\n\r\n    while(no_of_tests--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 73/Programs/Game With String.cpp",
    "content": "#include <string>\r\n#include <iostream>\r\n#include <algorithm>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int move_1, move_2;\r\n    string S;\r\n    cin >> move_1 >> move_2 >> S;\r\n\r\n    int length = 0;\r\n    vector <int> segments;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(S[i] == '.')\r\n        {\r\n            length++;\r\n        }\r\n\r\n        if(S[i] != '.' || i == S.size() - 1)\r\n        {\r\n            if(length != 0)\r\n            {\r\n                segments.push_back(length);\r\n            }\r\n\r\n            length = 0;\r\n        }\r\n    }\r\n\r\n    int bob_segments = 0, normal_segments = 0, big_segments = 0;\r\n    int big_segment_size = 0;\r\n    for(int i = 0; i < segments.size(); i++)\r\n    {\r\n        if(move_2 <= segments[i] && segments[i] < move_1)\r\n        {\r\n            bob_segments++;\r\n        }\r\n\r\n        if(2*move_2 <= segments[i])\r\n        {\r\n            big_segment_size = segments[i];\r\n\r\n            big_segments++;\r\n        }\r\n\r\n        if(move_1 <= segments[i] && segments[i] < 2*move_2)\r\n        {\r\n            normal_segments++;\r\n        }\r\n    }\r\n\r\n    if(bob_segments > 0 || big_segments > 1)\r\n    {\r\n        cout << \"NO\\n\";\r\n\r\n        return;\r\n    }\r\n\r\n    if(big_segments == 0)\r\n    {\r\n        cout << (normal_segments%2 == 1 ? \"YES\\n\" : \"NO\\n\");\r\n\r\n        return;\r\n    }\r\n\r\n    int winning = false;\r\n    for(int part_1 = 0; big_segment_size - move_1 - part_1 >= 0; part_1++)\r\n    {\r\n        int part_2 = big_segment_size - move_1 - part_1;\r\n\r\n        if(part_1 >= 2*move_2 || (move_2 <= part_1 && part_1 < move_1)) continue;\r\n        if(part_2 >= 2*move_2 || (move_2 <= part_2 && part_2 < move_1)) continue;\r\n\r\n\r\n        if( (normal_segments + (part_1 >= move_1) + (part_2 >= move_1))%2 == 0)\r\n        {\r\n            winning = true;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (winning ? \"YES\\n\" : \"NO\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_tests;\r\n    cin >> no_of_tests;\r\n\r\n    while(no_of_tests--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 73/Programs/Knights.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nconst int MAX_N = 105;\r\nchar board[MAX_N][MAX_N];\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    board[1][1] = 'B'; board[1][2] = 'W';\r\n    board[2][1] = 'W'; board[2][2] = 'B';\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        for(int j = 1; j <= n; j++)\r\n        {\r\n            if(i <= 2 && j <= 2)\r\n            {\r\n                continue;\r\n            }\r\n\r\n            if(j <= 2)\r\n            {\r\n                board[i][j] = (board[i - 2][j - 1] == 'B' ? 'W' : 'B');\r\n\r\n                continue;\r\n            }\r\n\r\n            board[i][j] = (board[i - 1][j - 2] == 'B' ? 'W' : 'B');\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        for(int j = 1; j <= n; j++)\r\n        {\r\n            cout << board[i][j];\r\n        }\r\n\r\n        cout << \"\\n\";\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 73/Programs/Make The Fence Great Again.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nvoid solve()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <long long> A(no_of_elements + 1, 0);\n    vector <long long> cost(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%I64d %I64d\", &A[i], &cost[i]);\n    }\n\n    const long long oo = 1e18;\n    vector <vector <long long> > best(no_of_elements + 1, vector <long long> (3, 0));\n    best[0][0] = 0, best[0][1] = best[0][2] = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        for(int no_of_adds = 0; no_of_adds <= 2; no_of_adds++)\n        {\n            best[i][no_of_adds] = oo;\n\n            for(int no_of_previous_adds = 0; no_of_previous_adds <= 2; no_of_previous_adds++)\n            {\n                if(A[i] + no_of_adds != A[i - 1] + no_of_previous_adds)\n                {\n                    best[i][no_of_adds] = min(best[i][no_of_adds], best[i - 1][no_of_previous_adds] + no_of_adds*cost[i]);\n                }\n            }\n        }\n    }\n\n    long long answer = oo;\n    for(int no_of_adds = 0; no_of_adds <= 2; no_of_adds++)\n    {\n        answer = min(answer, best[no_of_elements][no_of_adds]);\n    }\n\n    printf(\"%I64d\\n\", answer);\n}\n\nint main()\n{\n    int no_of_tests;\n    scanf(\"%d\", &no_of_tests);\n\n    while(no_of_tests--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 73/Programs/Perfect Team.cpp",
    "content": "#include <iostream>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int mathematicians, coders, normal;\r\n    cin >> mathematicians >> coders >> normal;\r\n\r\n    int teams = 0;\r\n    if(normal >= min(mathematicians, coders))\r\n    {\r\n        teams = min(mathematicians, coders);\r\n    }\r\n    else\r\n    {\r\n        teams = normal;\r\n        mathematicians -= teams;\r\n        coders -= teams;\r\n\r\n        if(2*min(mathematicians, coders) <= max(mathematicians, coders))\r\n        {\r\n            teams += min(mathematicians, coders);\r\n        }\r\n        else\r\n        {\r\n            teams += (mathematicians + coders)/3;\r\n        }\r\n    }\r\n\r\n    cout << teams << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_tests;\r\n    cin >> no_of_tests;\r\n\r\n    while(no_of_tests--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 74/Explanations/AB String Explanation.txt",
    "content": "Rather than trying to count the good substrings, let us try to count the number of bad substrings. \r\n\r\nLet us use the following fact - \r\n\r\nA substring is bad if and only if it has only one character of a certain type\r\n\r\nProof - If we have only one A in a string, it will never be good since A will not have any palindrome to match with. \r\n\r\nNow, let us prove that any string which has at least 2 of both A and B is always good. \r\n\r\nLet us look at every pair (AA) and (BB)\r\n\r\nCase 1 - AA or BB is consecutive. We have a palindrome right here\r\n\r\nCase 2 - ABBB..BBBA or BAAA...AAAB\r\n\r\nThe two As or two Bs are the end points of a palindrome\r\n\r\n----\r\n\r\nThis proves that a substring is bad if and only if either A or B occurs exactly 1 time. \r\n\r\n-----\r\n\r\nNow, the question is - Find the number of substrings such that there is only occurence of A or B. \r\n\r\nHere is what we will do. \r\n\r\nLook at the segments of As and Bs. \r\n\r\nSuppose we have x As followed by y Bs\r\n\r\nAAAA... AB... BBB\r\n\r\nEach of the x As creates a bad substring with the first B and each of the y Bs creates a bad substring with the last A.\r\n\r\nWe are counting AB twice\r\n\r\nSo, the number of bad substrings here is (x + y - 1)\r\n\r\n-----\r\n\r\nIf we expand to include even one more A or one more B, we will have a good substring on our hands !\r\n\r\nWe will make an array of lengths of segments. \r\n\r\nThen, we will iterate over them and add (Segment[i] + Segment[i + 1] - 1) to our answer.\r\n\r\n----\r\n\r\nint main()\r\n{\r\n    long long length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    vector <int> segments;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(i == 0 || S[i] != S[i - 1])\r\n        {\r\n            segments.push_back(1);\r\n        }\r\n        else\r\n        {\r\n            segments.back()++;\r\n        }\r\n    }\r\n\r\n    long long bad_strings = 0;\r\n    for(int i = 0; i + 1 < segments.size(); i++)\r\n    {\r\n        bad_strings += segments[i] + segments[i + 1] - 1;\r\n    }\r\n\r\n    long long total_strings = (length*(length - 1))/2;\r\n    long long good_substrings = total_strings - bad_strings;\r\n\r\n    cout << good_substrings;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Educational Round 74/Explanations/Keyboard Purchase Explanation.txt",
    "content": "The brute force approach is to visit all permutations of the array and find the cost for each of them. However, the beautiful thing is that we do not have to do that. Just like the Travelling Salesman problem, we just have to maintain a bitmask that corresponds to which alphabets we have already chosen. \r\n\r\nLet f(m) represent a mask m, where the i-th bit is set if we have used the i-th alphabet. \r\n\r\nf(110001) is the minimum cost where we have a keyboard consisting of the first, second and sixth keys.\r\n\r\n----\r\n\r\nThe question is, how do we transition in between states ? \r\n\r\nWhen we add a new character to the keyboard, how do we update the cost ? \r\n\r\nIn order to do this, it appears that we need to know the relative positions of the remaining keys. \r\n\r\nSuppose we know f(110001) and want to calculate f(110011). We want to add the fourth alphabet too. It appears that we know the exact positions of the first, second and sixth alphabets. \r\n\r\nHowever, we do not !\r\n\r\nWe can use the beautiful idea of calculating a sum by the contribution of each of it's components rather than by evaluating each term. \r\n\r\n---\r\n\r\nSuppose, we already have the 1st, 2nd and 6th letters and want to add the 5th letter.\r\n\r\nThe 5-th letter will be added at the 4th position. \r\n\r\nLet us remove the absolute sign and try to evaluate the contribution of the 5-th letter to this mask. \r\n\r\nWhen we add the 5-th letter at the 4-th position, \r\n\r\nEvery time we move from \r\n\r\n1. 5-1, we will be adding (4 - p(1))\r\n2. 5-2, we will be adding (4 - p(2))\r\n3. 5-6, we will be adding (4 - p(6))\r\n\r\nwhere p(i) is the position of the i-th key.\r\n\r\nThere are 3 keys existing that are already placed in earlier positions. To each of them, we will be adding +4.\r\n\r\n----\r\n\r\nEvery time we move from \r\n\r\n4. 5-4, we will be adding (p(4) - 4)\r\n5. 5-3, we will be adding (p(3) - 4)\r\n\r\nSince {4, 3} will be placed after 5, we will be adding -4 to the sum. \r\n\r\n----\r\n\r\nSo, overall the 5-th letter will be contributing +4 every time it visits a key that is already placed and -4 for every time it visits a key that is not yet placed.\r\n\r\n----\r\n\r\nHere, is how we will transition - \r\n\r\n1. Visit all masks from 000000 to 111111\r\n2. For each mask, iterate over all the set bits and assume that this is the key that is added last. \r\n3. Let m' = m without the i-th bit set\r\n4. Calculate the cost of m' if the i-th bit is added last\r\n5. f(m) = min{f(m), f(m') + cost}\r\n\r\nf(0) = 0 and f(111111) is the answer\r\n\r\n------\r\n\r\nint main()\r\n{\r\n    int length, no_of_letters;\r\n    string password;\r\n    cin >> length >> no_of_letters >> password;\r\n\r\n    memset(neighbours, 0, sizeof(neighbours));\r\n    for(int i = 0; i + 1 < length; i++)\r\n    {\r\n        neighbours[password[i] - 'a'][password[i + 1] - 'a']++;\r\n        neighbours[password[i + 1] - 'a'][password[i] - 'a']++;\r\n    }\r\n\r\n    int full_mask = (1 << no_of_letters) - 1;\r\n    for(int mask = 0; mask <= full_mask; mask++)\r\n    {\r\n        const int oo = 1e9;\r\n        cost[mask] = (mask == 0 ? 0 : oo);\r\n\r\n        for(int latest_letter = 0; latest_letter < no_of_letters; latest_letter++)\r\n        {\r\n            if(!is_bit_set(mask, latest_letter))\r\n            {\r\n                continue;\r\n            }\r\n\r\n            int position = bit_count(mask);\r\n            int cost_to_make_this_last = 0;\r\n\r\n            for(int other_letter = 0; other_letter < no_of_letters; other_letter++)\r\n            {\r\n                if(other_letter == latest_letter)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if(is_bit_set(mask, other_letter))\r\n                {\r\n                    cost_to_make_this_last += position*neighbours[latest_letter][other_letter];\r\n                }\r\n                else\r\n                {\r\n                    cost_to_make_this_last -= position*neighbours[latest_letter][other_letter];\r\n                }\r\n            }\r\n\r\n            int mask_without_last = mask^(1 << latest_letter);\r\n\r\n            cost[mask] = min(cost[mask], cost[mask_without_last] + cost_to_make_this_last);\r\n        }\r\n    }\r\n\r\n    cout << cost[full_mask];\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 74/Explanations/Kill Em All Explanation.txt",
    "content": "The best approach is to start throwing the bombs from the rightmost position. \r\n\r\nThe reason it pushes everyone closer to the origin. \r\n\r\nLet us sort the positions - X1 < X2 < ... < Xn\r\n\r\nNow, we will go through the array from finish till last. \r\n\r\nThe current position of X[i] is (X[i] - E.R), where E is the number of explosions that have happened so far and R is the displacement for each blast.\r\n\r\nIf (X[i] <= 0), then we do not need to throw any more missiles and we are done. \r\n\r\nThe beautiful thing is that we do not need to perform a linear sweep through the entire array and update all the individual positions after each blast. \r\nIf we know x blasts have occured, we can easily calculate the current position of the X[i] in O(1) time through simple subtraction.\r\n\r\n-------\r\n\r\nLet the difference d = x - y\r\n\r\nCase 1 - Difference is 1\r\n\r\nThen it is not possible\r\n\r\nCase 2 - Difference is prime\r\n\r\nThen we just subtract by the entire difference d\r\n\r\nCase 3 - Difference is composite \r\n\r\nd = p1^a1 p2^a2 ... pn^an\r\n\r\nd = p1 q, where q = p1^(a1 - 1) p2^a2 ... pn^an\r\n\r\nWe just subtract p1 from d q times\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, distance;\r\n    cin >> no_of_elements >> distance;\r\n\r\n    vector <int> X(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> X[i];\r\n    }\r\n\r\n    sort(all(X));\r\n\r\n    int explosions = 0;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        while(X[i] == X[i - 1])\r\n        {\r\n            i--;\r\n        }\r\n\r\n        if(X[i] - explosions*distance > 0)\r\n        {\r\n            explosions++;\r\n        }\r\n    }\r\n\r\n    cout << explosions << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Educational Round 74/Explanations/Prime Subtraction Explanation.txt",
    "content": "Let the difference d = x - y\n\nCase 1 - Difference is 1\n\nThen it is not possible\n\nCase 2 - Difference is prime\n\nThen we just subtract by the entire difference d\n\nCase 3 - Difference is composite \n\nd = p1^a1 p2^a2 ... pn^an\n\nd = p1 q, where q = p1^(a1 - 1) p2^a2 ... pn^an\n\nWe just subtract p1 from d q times\n\n-----\n\n#include <iostream>\n \nusing namespace std;\n \nvoid solve()\n{\n    long long x, y;\n    cin >> x >> y;\n \n    long long difference = x - y;\n    cout << (difference == 1 ? \"NO\\n\" : \"YES\\n\");\n}\n \nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n \n    while(no_of_test_cases--)\n        solve();\n \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 74/Programs/AB String.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    long long length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    vector <int> segments;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        if(i == 0 || S[i] != S[i - 1])\r\n        {\r\n            segments.push_back(1);\r\n        }\r\n        else\r\n        {\r\n            segments.back()++;\r\n        }\r\n    }\r\n\r\n    long long bad_strings = 0;\r\n    for(int i = 0; i + 1 < segments.size(); i++)\r\n    {\r\n        bad_strings += segments[i] + segments[i + 1] - 1;\r\n    }\r\n\r\n    long long total_strings = (length*(length - 1))/2;\r\n    long long good_substrings = total_strings - bad_strings;\r\n\r\n    cout << good_substrings;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 74/Programs/Keyboard Purchase.cpp",
    "content": "#include <iostream>\r\n#include <cstring>\r\nusing namespace std;\r\n\r\nconst int MAX_ALPHA = 21;\r\nint neighbours[MAX_ALPHA][MAX_ALPHA], cost[1 << MAX_ALPHA];\r\n\r\nint is_bit_set(int n, int bit)\r\n{\r\n    return ( (n&(1 << bit)) != 0);\r\n}\r\n\r\nint bit_count(int n)\r\n{\r\n    int count = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        count += (n%2);\r\n\r\n        n /= 2;\r\n    }\r\n\r\n    return count;\r\n}\r\n\r\nint main()\r\n{\r\n    int length, no_of_letters;\r\n    string password;\r\n    cin >> length >> no_of_letters >> password;\r\n\r\n    memset(neighbours, 0, sizeof(neighbours));\r\n    for(int i = 0; i + 1 < length; i++)\r\n    {\r\n        neighbours[password[i] - 'a'][password[i + 1] - 'a']++;\r\n        neighbours[password[i + 1] - 'a'][password[i] - 'a']++;\r\n    }\r\n\r\n    int full_mask = (1 << no_of_letters) - 1;\r\n    for(int mask = 0; mask <= full_mask; mask++)\r\n    {\r\n        const int oo = 1e9;\r\n        cost[mask] = (mask == 0 ? 0 : oo);\r\n\r\n        for(int latest_letter = 0; latest_letter < no_of_letters; latest_letter++)\r\n        {\r\n            if(!is_bit_set(mask, latest_letter))\r\n            {\r\n                continue;\r\n            }\r\n\r\n            int position = bit_count(mask);\r\n            int cost_to_make_this_last = 0;\r\n\r\n            for(int other_letter = 0; other_letter < no_of_letters; other_letter++)\r\n            {\r\n                if(other_letter == latest_letter)\r\n                {\r\n                    continue;\r\n                }\r\n\r\n                if(is_bit_set(mask, other_letter))\r\n                {\r\n                    cost_to_make_this_last += position*neighbours[latest_letter][other_letter];\r\n                }\r\n                else\r\n                {\r\n                    cost_to_make_this_last -= position*neighbours[latest_letter][other_letter];\r\n                }\r\n            }\r\n\r\n            int mask_without_last = mask^(1 << latest_letter);\r\n\r\n            cost[mask] = min(cost[mask], cost[mask_without_last] + cost_to_make_this_last);\r\n        }\r\n    }\r\n\r\n    cout << cost[full_mask];\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 74/Programs/Kill Em All Explanation.txt",
    "content": "The best approach is to start throwing the bombs from the rightmost position. \r\n\r\nThe reason it pushes everyone closer to the origin. \r\n\r\nLet us sort the positions - X1 < X2 < ... < Xn\r\n\r\nNow, we will go through the array from finish till last. \r\n\r\nThe current position of X[i] is (X[i] - E.R), where E is the number of explosions that have happened so far and R is the displacement for each blast.\r\n\r\nIf (X[i] <= 0), then we do not need to throw any more missiles and we are done. \r\n\r\nThe beautiful thing is that we do not need to perform a linear sweep through the entire array and update all the individual positions after each blast. \r\nIf we know x blasts have occured, we can easily calculate the current position of the X[i] in O(1) time through simple subtraction.\r\n\r\n-------\r\n\r\nLet the difference d = x - y\r\n\r\nCase 1 - Difference is 1\r\n\r\nThen it is not possible\r\n\r\nCase 2 - Difference is prime\r\n\r\nThen we just subtract by the entire difference d\r\n\r\nCase 3 - Difference is composite \r\n\r\nd = p1^a1 p2^a2 ... pn^an\r\n\r\nd = p1 q, where q = p1^(a1 - 1) p2^a2 ... pn^an\r\n\r\nWe just subtract p1 from d q times\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements, distance;\r\n    cin >> no_of_elements >> distance;\r\n\r\n    vector <int> X(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        cin >> X[i];\r\n    }\r\n\r\n    sort(all(X));\r\n\r\n    int explosions = 0;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        while(X[i] == X[i - 1])\r\n        {\r\n            i--;\r\n        }\r\n\r\n        if(X[i] - explosions*distance > 0)\r\n        {\r\n            explosions++;\r\n        }\r\n    }\r\n\r\n    cout << explosions << \"\\n\";\r\n}"
  },
  {
    "path": "Contests/Educational Round 74/Programs/Prime Subtraction.cpp",
    "content": "#include <iostream>\n \nusing namespace std;\n \nvoid solve()\n{\n    long long x, y;\n    cin >> x >> y;\n \n    long long difference = x - y;\n    cout << (difference == 1 ? \"NO\\n\" : \"YES\\n\");\n}\n \nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n \n    while(no_of_test_cases--)\n        solve();\n \n    return 0;\n}\n"
  },
  {
    "path": "Contests/Educational Round 77/Explanations/Yet Another Monster Killing Problem Explanation.txt",
    "content": "We will sort the heroes by their endurance. \n\nWe want to know for the endurance level E, what is the maximum power we have\nFor this, we need to have a suffix maximum\n\nThen, we will start going through the monster array. \nWe will try to take as large a step as possible. \nWe can use binary search to see if we can take a step of size x. \nIf we take a step of size x, then we have to take the maximum of the monsters [i, i + x]\nWe also have to find out whether the maximum power of any hero with endurance >= x is greater than the power in that range.\n\n-----\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n    \n    build(1, 1, no_of_elements);\n\n    int no_of_heroes;\n    cin >> no_of_heroes;\n\n    vector <hero> heroes(no_of_heroes + 1);\n    for(int i = 1; i <= no_of_heroes; i++)\n    {\n        cin >> heroes[i].power >> heroes[i].endurance;\n    }\n\n    sort(all(heroes), sort_by_endurance);\n    \n    vector <int> max_power_for_endurance(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_heroes; i++)\n    {\n        max_power_for_endurance[heroes[i].endurance] = max(max_power_for_endurance[heroes[i].endurance], heroes[i].power);\n    }\n    \n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        max_power_for_endurance[i] = max(max_power_for_endurance[i + 1], max_power_for_endurance[i]);\n        \n        //cout << \"Max Till \" << i << \" = \" << max_power_for_endurance[i] << \"\\n\";\n    }\n    \n    int days = 0;\n    for(int i = 1; i <= no_of_elements; days++)\n    {\n        if(max_power_for_endurance[no_of_elements - i + 1] >= get_max(1, 1, no_of_elements, i, no_of_elements))\n        {\n            days++;\n            break;\n        }\n        \n        int left = 0, right = no_of_elements - i + 1;\n        \n        while(right - left > 1)\n        {   //cout << \"L = \" << left << \" R = \" << right << \"\\n\";\n            int mid = (left + right)/2;\n            \n            //cout << \"Mid = \" << mid << \" Segment Max = [\" << i <<\n            //\",\" << i + mid - 1 << \"] = \" <<get_max(1, 1, no_of_elements, i, i + mid - 1) << \" Endurance Max = \" << max_power_for_endurance[mid] << \"\\n\";\n            if(max_power_for_endurance[mid] >= get_max(1, 1, no_of_elements, i, i + mid - 1))\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n        \n        if(left == 0)\n        {\n            cout << \"-1\\n\";\n            \n            return;\n        }\n        \n        i = i + left; //cout << \"i = \" << i << \"\\n\";\n    }\n    \n    cout << days << \"\\n\";\n}\n"
  },
  {
    "path": "Contests/Educational Round 77/Programs/Dominated Subarray.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    const int MAX = 2e5 + 5;\r\n    vector <int> frequency(MAX, 0);\r\n\r\n    int is_dominated = false;\r\n    int smallest_array = MAX;\r\n    int left = 1, right = 0;\r\n    while(right + 1 <= no_of_elements)\r\n    {\r\n        while(right + 1 <= no_of_elements)\r\n        {\r\n            right++;\r\n\r\n            frequency[A[right]]++;\r\n\r\n            if(frequency[A[right]] >= 2)\r\n            {\r\n                break;\r\n            }\r\n        }\r\n\r\n        while(left <= right)\r\n        {\r\n            if(left > no_of_elements)\r\n            {\r\n                break;\r\n            }\r\n\r\n            if(A[left] == A[right] && frequency[A[right]] == 2)\r\n            {\r\n                break;\r\n            }\r\n\r\n            frequency[A[left]]--;\r\n\r\n            left++;\r\n        }\r\n\r\n        if(frequency[A[right]] == 2)\r\n        {\r\n            smallest_array = min(smallest_array, right - left + 1);\r\n        }\r\n    }\r\n\r\n    cout << (smallest_array == MAX ? -1 : smallest_array) << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 77/Programs/Magic Stick.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    long long x, y;\r\n    cin >> x >> y;\r\n\r\n    if(x == 1 || x == 3)\r\n    {\r\n        cout << (x >= y ? \"Yes\\n\" : \"No\\n\");\r\n\r\n        return;\r\n    }\r\n    else if(x == 2)\r\n    {\r\n        cout << (y <= 3 ? \"Yes\\n\" : \"No\\n\");\r\n\r\n        return;\r\n    }\r\n\r\n    cout << \"Yes\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Educational Round 77/Programs/Two Rival Students.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nvoid solve()\r\n{\r\n    int n, no_of_swaps, a, b;\r\n    cin >> n >> no_of_swaps >> a >> b;\r\n\r\n    int distance = (max(a, b) - min(a, b));\r\n    cout << min(n - 1, no_of_swaps + distance) << \"\\n\";\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    cin >> no_of_test_cases;\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Educational Round 77/Programs/Yet Another Monster Killing Problem.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\n#define all(v) (v).begin(), (v).end()\n#define LEFT(n) (2*n)\n#define RIGHT(n) (2*n + 1)\nusing namespace std;\n\nstruct hero\n{\n    int power, endurance;\n\n    hero()\n    {\n        power = 0;\n        endurance = 0;\n    }\n\n    hero(int P, int E)\n    {\n        P = power; E = endurance;\n    }\n};\n\nint sort_by_endurance(const hero &A, const hero &B)\n{\n    if(A.endurance == B.endurance)\n    {\n        return (A.power < B.power);\n    }\n    \n    return (A.endurance < B.endurance);\n}\n\nconst int MAX_N = 2e5 + 5;\nint max_tree[4*MAX_N], A[MAX_N];\n\nvoid build(int n, int left, int right)\n{\n    if(left == right)\n    {\n        max_tree[n] = A[right];\n\n        return;\n    }\n\n    int mid = (left + right)/2;\n\n    build(LEFT(n), left, mid);\n    build(RIGHT(n), mid + 1, right);\n\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\n}\n\nint get_max(int n, int left, int right, int query_left, int query_right)\n{\n    if(right < query_left || query_right < left)\n        return 0;\n\n    if(query_left <= left && right <= query_right)\n        return max_tree[n];\n\n    int mid = (left + right)/2;\n    int left_max = get_max(LEFT(n), left, mid, query_left, query_right);\n    int right_max = get_max(RIGHT(n), mid + 1, right, query_left, query_right);\n\n    return max(left_max, right_max);\n}\n\nvoid solve()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    for(int i = 1; i <= no_of_elements; i++)\n        cin >> A[i];\n    \n    build(1, 1, no_of_elements);\n\n    int no_of_heroes;\n    cin >> no_of_heroes;\n\n    vector <hero> heroes(no_of_heroes + 1);\n    for(int i = 1; i <= no_of_heroes; i++)\n    {\n        cin >> heroes[i].power >> heroes[i].endurance;\n    }\n\n    sort(all(heroes), sort_by_endurance);\n    \n    vector <int> max_power_for_endurance(no_of_elements + 5, 0);\n    for(int i = 1; i <= no_of_heroes; i++)\n    {\n        max_power_for_endurance[heroes[i].endurance] = max(max_power_for_endurance[heroes[i].endurance], heroes[i].power);\n    }\n    \n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        max_power_for_endurance[i] = max(max_power_for_endurance[i + 1], max_power_for_endurance[i]);\n        \n        //cout << \"Max Till \" << i << \" = \" << max_power_for_endurance[i] << \"\\n\";\n    }\n    \n    int days = 0;\n    for(int i = 1; i <= no_of_elements; days++)\n    {\n        if(max_power_for_endurance[no_of_elements - i + 1] >= get_max(1, 1, no_of_elements, i, no_of_elements))\n        {\n            days++;\n            break;\n        }\n        \n        int left = 0, right = no_of_elements - i + 1;\n        \n        while(right - left > 1)\n        {   //cout << \"L = \" << left << \" R = \" << right << \"\\n\";\n            int mid = (left + right)/2;\n            \n            //cout << \"Mid = \" << mid << \" Segment Max = [\" << i <<\n            //\",\" << i + mid - 1 << \"] = \" <<get_max(1, 1, no_of_elements, i, i + mid - 1) << \" Endurance Max = \" << max_power_for_endurance[mid] << \"\\n\";\n            if(max_power_for_endurance[mid] >= get_max(1, 1, no_of_elements, i, i + mid - 1))\n            {\n                left = mid;\n            }\n            else\n            {\n                right = mid;\n            }\n        }\n        \n        if(left == 0)\n        {\n            cout << \"-1\\n\";\n            \n            return;\n        }\n        \n        i = i + left; //cout << \"i = \" << i << \"\\n\";\n    }\n    \n    cout << days << \"\\n\";\n}\n\nint main()\n{\n    int no_of_test_cases;\n    cin >> no_of_test_cases;\n\n    while(no_of_test_cases--)\n        solve();\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Explanation/Divisors.txt",
    "content": "Let us keep track of the exponent of every prime we encounter. \r\n\r\nWe know that if N = p^n1 p2^n2 ... \r\n\r\nNo of factors = (n1 + 1)(n2 + 1) ... \r\n\r\nCase 1 - The number has either 3 or 5 factors. \r\n\r\nOnly perfect squares have an odd number of factors. \r\n\r\nSo this means the number is of the form p^2 or p^4\r\n\r\nSo, we will check whether the number is a perfect square. \r\n\r\nIf yes, then check if it is a perfect fourth power. Update the exponent accordingly.\r\n\r\nlong long root = (long long) sqrt(A[i]);\r\n\r\n        if(root*root == A[i]) //Perfect square. Either 3 or 5 factors\r\n        {\r\n            long long fourth_root = (long long) sqrt(root);\r\n\r\n            if(fourth_root*fourth_root == root) //A[i] = p^4\r\n            {\r\n                prime_exponent[fourth_root] += 4;\r\n            }\r\n            else\r\n            {\r\n                prime_exponent[root] += 2; //A[i] = p^2\r\n            }\r\n\r\n            factorised[i] = true;\r\n        }\r\n\r\n-------------------------\r\n\r\nCase 2 - N has 4 factors\r\n\r\nNow, we know that it is not a perfect square. \r\n\r\nIt is either of the form pq or p^3 since 4 = 2x2 = 4x1\r\n\r\nLet us check all prime numbers till 10^6\r\n\r\nCase 2a - N has a factor less than 10^6. \r\n\r\nCheck if N is of the form pq or p^3 and update the exponent accordingly\r\n\r\nCase 2b - N has no factor smaller than 10^6\r\n\r\nN has to be of the form pq, since if it was p^3 with all three factors > 10^6, then N > 10^{18}\r\n\r\nLet us check if N has any common factors with any of the other numbers by finding it's gcd. \r\n\r\nCase 2bi\r\nIf it does, then we can factorise N\r\n\r\n\r\nCase 2bii\r\nElse, if N = pq and N occurs f times. The number of factors increases by (f + 1)(f + 1) ... [Since both p and q occur f times].\r\nNote that in this case, we don't need to explicitly know the values of p and q.\r\n\r\n------------------\r\n\r\nlong long factor_1 = 0, factor_2 = 0;\r\n\r\n            for(int p = 0; p < primes.size(); p++)\r\n            {\r\n                if(A[i]%primes[p] == 0)\r\n                {\r\n                    factor_1 = primes[p];\r\n\r\n                    if(factor_1*factor_1*factor_1 == A[i]) // A[i] = p^3\r\n                    {\r\n                        prime_exponent[factor_1] += 3;\r\n                    }\r\n                    else\r\n                    {\r\n                        prime_exponent[factor_1]++;\r\n                        prime_exponent[A[i]/factor_1]++;\r\n                    }\r\n\r\n                    factorised[i] = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if(!factorised[i])\r\n            {\r\n                for(int j = 1; j <= no_of_numbers; j++)\r\n                {\r\n                    if(gcd(A[j], A[i]) > 1 && gcd(A[i], A[j]) < A[i])\r\n                    {\r\n                        factor_1 = gcd(A[i], A[j]);\r\n                        factor_2 = A[i]/factor_1;\r\n\r\n                        prime_exponent[factor_1]++;\r\n                        prime_exponent[factor_2]++;\r\n\r\n                        factorised[i] = true;\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n\r\n            int frequency = 0;\r\n            if(!factorised[i])\r\n            {\r\n                for(int j = 1; j <= no_of_numbers; j++)\r\n                {\r\n                    if(A[i] == A[j])\r\n                    {\r\n                        frequency++;\r\n\r\n                        factorised[j] = true;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if(factor_1 == 0 && factor_2 == 0) //Two new factors\r\n                no_of_divisors = (no_of_divisors*(frequency + 1)*(frequency + 1))%MOD;\r\n        }\r\n\r\n"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Explanation/King Escape Explanation.txt",
    "content": "If the queen is in between the king and the target, then the king can never reach the target square as an entire row or column is blocked. \r\n\r\nHowever, otherwise the king can always reach his target since an entire row/column can't be blocked. There will always be squares.\r\n\r\n----------------\r\n\r\nint main()\r\n{\r\n    int n, queen_x, queen_y, king_x, king_y, center_x, center_y;\r\n    scanf(\"%d %d %d %d %d %d %d\", &n, &queen_x, &queen_y, &king_x, &king_y, &center_x, &center_y);\r\n\r\n    int queen_middle_x = in_middle(king_x, queen_x, center_x);\r\n    int queen_middle_y = in_middle(king_y, queen_y, center_y);\r\n\r\n    printf(queen_middle_x || queen_middle_y ? \"NO\\n\" : \"YES\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Explanation/Permutation Game Explanation.txt",
    "content": "Now from a given number i, we can only move to squares which have higher number. \n\nThis suggests there is optimal substructure. \n\nWinner[n] = 2, since you can't move. \n\n-------------\n\nInsight - If Player 1, makes a move from i, and places it on token j, then she becomes Player 2 for game i\n\n----------------\n\nFrom a given point, check all legal moves to see if any legal move leads to a position that is winning for player 2. If so, make that move. \n\nElse, second player will win that position.\n\n---------------------------\n\nvector <int> winner(no_of_elements + 1, 2);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        for(int step = i; step <= no_of_elements; step += i)\n        {\n            int backward_square = (position[i] - step);\n            if(backward_square > 0 && A[backward_square] > i && winner[backward_square] == 2)\n            {\n                winner[position[i]] = 1;\n            }\n\n            int forward_square = (position[i] + step);\n            if(forward_square <= no_of_elements && A[forward_square] > i && winner[forward_square] == 2)\n            {\n                winner[position[i]] = 1;\n            }\n        }\n    }\n"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Explanation/Square Difference Explanation.txt",
    "content": "The number N = A^2 - B^2\r\n\r\nN = (A - B)(A + B)\r\n\r\n\r\nThis is always composite unless one of these two terms = 1 and the other is prime. \r\n\r\nNow only A - B can be = 1, because both are positive integers. \r\n\r\nAll we need to check is if A + B = 1\r\n\r\n----------------------------------------\r\n\r\nvoid solve()\r\n{\r\n    long long a, b;\r\n    scanf(\"%I64d %I64d\", &a, &b);\r\n    printf(a - b == 1 && is_prime(a + b) ? \"YES\\n\" : \"NO\\n\");\r\n}"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Programs/Divisors.cpp",
    "content": "#include <cstdio>\r\n#include <cmath>\r\n#include <map>\r\n#include <vector>\r\n#include <bits/stdc++.h>\r\n\r\nusing namespace std;\r\n\r\nlong long gcd(long long a, long long b)\r\n{\r\n    if(min(a, b) == 0)\r\n        return max(a, b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nvoid precompute(vector <int> &primes, int LIMIT)\r\n{\r\n    vector <int> is_prime(LIMIT + 1, true);\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i < LIMIT; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] < LIMIT; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 2e6;\r\n    vector <int> primes;\r\n    precompute(primes, LIMIT);\r\n\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    vector <long long> A(no_of_numbers + 1);\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    vector <int> factorised(no_of_numbers + 1, false);\r\n\r\n    const int MOD = 998244353;\r\n    long long no_of_divisors = 1;\r\n    map <long long, int> prime_exponent;\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        if(factorised[i]) continue;\r\n\r\n        long long root = (long long) sqrt(A[i]);\r\n\r\n        if(root*root == A[i]) //Perfect square. Either 3 or 5 factors\r\n        {\r\n            long long fourth_root = (long long) sqrt(root);\r\n\r\n            if(fourth_root*fourth_root == root) //A[i] = p^4\r\n            {\r\n                prime_exponent[fourth_root] += 4;\r\n            }\r\n            else\r\n            {\r\n                prime_exponent[root] += 2; //A[i] = p^2\r\n            }\r\n\r\n            factorised[i] = true;\r\n        }\r\n        else //A[i] has 4 factors. A[i] = pq or A[i] = p^3\r\n        {\r\n            long long factor_1 = 0, factor_2 = 0;\r\n\r\n            for(int p = 0; p < primes.size(); p++)\r\n            {\r\n                if(A[i]%primes[p] == 0)\r\n                {\r\n                    factor_1 = primes[p];\r\n\r\n                    if(factor_1*factor_1*factor_1 == A[i]) // A[i] = p^3\r\n                    {\r\n                        prime_exponent[factor_1] += 3;\r\n                    }\r\n                    else\r\n                    {\r\n                        prime_exponent[factor_1]++;\r\n                        prime_exponent[A[i]/factor_1]++;\r\n                    }\r\n\r\n                    factorised[i] = true;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            if(!factorised[i])\r\n            {\r\n                for(int j = 1; j <= no_of_numbers; j++)\r\n                {\r\n                    if(gcd(A[j], A[i]) > 1 && gcd(A[i], A[j]) < A[i])\r\n                    {\r\n                        factor_1 = gcd(A[i], A[j]);\r\n                        factor_2 = A[i]/factor_1;\r\n\r\n                        prime_exponent[factor_1]++;\r\n                        prime_exponent[factor_2]++;\r\n\r\n                        factorised[i] = true;\r\n                        break;\r\n                    }\r\n                }\r\n            }\r\n\r\n            int frequency = 0;\r\n            if(!factorised[i])\r\n            {\r\n                for(int j = 1; j <= no_of_numbers; j++)\r\n                {\r\n                    if(A[i] == A[j])\r\n                    {\r\n                        frequency++;\r\n\r\n                        factorised[j] = true;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if(factor_1 == 0 && factor_2 == 0) //Two new factors\r\n                no_of_divisors = (no_of_divisors*(frequency + 1)*(frequency + 1))%MOD;\r\n        }\r\n    }\r\n\r\n\r\n    for(map <long long, int> :: iterator it = prime_exponent.begin(); it != prime_exponent.end(); it++)\r\n    {\r\n        int divisors_here = it->second + 1;\r\n\r\n        no_of_divisors = (no_of_divisors*divisors_here)%MOD;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_divisors);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Programs/King Escape.cpp",
    "content": "#include <cstdio>\r\n\r\nint in_middle(int L, int x, int R)\r\n{\r\n    return ((L <= x && x <= R) || (R <= x && x <= L));\r\n}\r\n\r\nint main()\r\n{\r\n    int n, queen_x, queen_y, king_x, king_y, center_x, center_y;\r\n    scanf(\"%d %d %d %d %d %d %d\", &n, &queen_x, &queen_y, &king_x, &king_y, &center_x, &center_y);\r\n\r\n    int queen_middle_x = in_middle(king_x, queen_x, center_x);\r\n    int queen_middle_y = in_middle(king_y, queen_y, center_y);\r\n\r\n    printf(queen_middle_x || queen_middle_y ? \"NO\\n\" : \"YES\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Programs/Permutation Game.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <int> A(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        scanf(\"%d\", &A[i]);\n\n    vector <int> position(no_of_elements + 1);\n    for(int i = 1; i <= no_of_elements; i++)\n        position[A[i]] = i;\n\n    vector <int> winner(no_of_elements + 1, 2);\n    for(int i = no_of_elements; i >= 1; i--)\n    {\n        for(int step = i; step <= no_of_elements; step += i)\n        {\n            int backward_square = (position[i] - step);\n            if(backward_square > 0 && A[backward_square] > i && winner[backward_square] == 2)\n            {\n                winner[position[i]] = 1;\n            }\n\n            int forward_square = (position[i] + step);\n            if(forward_square <= no_of_elements && A[forward_square] > i && winner[forward_square] == 2)\n            {\n                winner[position[i]] = 1;\n            }\n        }\n    }\n\n    for(int i = 1; i <= no_of_elements; i++)\n        printf(\"%c\", winner[i] == 1 ? 'A' : 'B');\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Lyft Level 5 Challenge 2018 - Elimination Round/Programs/Square Difference.cpp",
    "content": "#include <cstdio>\r\n\r\nint is_prime(long long n)\r\n{\r\n    if(n == 1) return false;\r\n\r\n    for(long long i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    long long a, b;\r\n    scanf(\"%I64d %I64d\", &a, &b);\r\n    printf(a - b == 1 && is_prime(a + b) ? \"YES\\n\" : \"NO\\n\");\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Mail.Ru Cup 2018 Round 1/Explanation/Appending Mex.txt",
    "content": "Initially, the mex = 0\n\nAt each step, \n\nCase 1 - Element > mex\n\nThis is not possible as the element has to be at most the Mex. \n\nIf this happens, it's a mistake. Stop.\n\nCase 2 - Element = mex\n\nThen, mex is not mex + 1\n\nCase 3 - Element < mex\n\nThis is allowed. Just move on to the next step.\n\n----------------------------------------------------\n\nint main()\n{\n    int no_of_elements;\n    cin >> no_of_elements;\n\n    int mex_so_far = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        int element;\n        cin >> element;\n\n        if(element > mex_so_far)\n        {\n            cout << i;\n            return 0;\n        }\n        else if(element == mex_so_far)\n        {\n            mex_so_far++;\n        }\n    }\n\n    cout << \"-1\";\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Mail.Ru Cup 2018 Round 1/Explanation/Candies Distribution.txt",
    "content": "We give each person (A[i] - Left[i] - Right[i]) and then perform an O(n^2) check. \r\n\r\n\r\n------------------\r\n\r\n#include <cstdio>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_people;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    vector <int> left(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &left[i]);\r\n\r\n    vector <int> right(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &right[i]);\r\n\r\n    vector <int> candies(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        candies[i] = no_of_people - left[i] - right[i];\r\n\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int left_greater = 0;\r\n        for(int j = 1; j < i; j++)\r\n            left_greater += (candies[j] > candies[i]);\r\n\r\n        int right_greater = 0;\r\n        for(int j = i + 1; j <= no_of_people; j++)\r\n            right_greater += (candies[j] > candies[i]);\r\n\r\n        if(left_greater != left[i] || right_greater != right[i])\r\n        {\r\n            printf(\"NO\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    printf(\"YES\\n\");\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        printf(\"%d \", candies[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Mail.Ru Cup 2018 Round 1/Explanation/Changing the Array Explanation.txt",
    "content": "Now XOR(A[L, ... , R]) = XOR(XOR(A[1, ... , R]), XOR(A[1, ... , L - 1]))\r\n\r\nWe will try to be greedy and at each point try to maximise the number of different xor prefixes. \r\n\r\n-----\r\n\r\nint main()\r\n{\r\n    int no_of_elements, k;\r\n    cin >> no_of_elements >> k;\r\n\r\n    int prefix_xor = 0;\r\n    map <int, int> prefix_xor_frequency;\r\n    prefix_xor_frequency[0] = 1;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        int option_1 = prefix_xor^element;\r\n        int option_2 = prefix_xor^complement(element, k);\r\n\r\n        if(prefix_xor_frequency[option_1] < prefix_xor_frequency[option_2])\r\n            prefix_xor = option_1;\r\n        else\r\n            prefix_xor = option_2;\r\n\r\n        prefix_xor_frequency[prefix_xor]++;\r\n    }\r\n\r\n    LL bad_segments = 0;\r\n    for(map <int, int> :: iterator it = prefix_xor_frequency.begin(); it != prefix_xor_frequency.end(); it++)\r\n    {\r\n        bad_segments += choose_2(it->second);\r\n    }\r\n\r\n    LL total_segments = choose_2(no_of_elements) + no_of_elements;\r\n    LL good_segments = total_segments - bad_segments;\r\n\r\n    cout << good_segments;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Mail.Ru Cup 2018 Round 1/Programs/Appending Mex.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    int mex_so_far = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        if(element > mex_so_far)\r\n        {\r\n            cout << i;\r\n            return 0;\r\n        }\r\n        else if(element == mex_so_far)\r\n        {\r\n            mex_so_far++;\r\n        }\r\n    }\r\n\r\n    cout << \"-1\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Mail.Ru Cup 2018 Round 1/Programs/Candy Distribution.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n    int no_of_people;\n    scanf(\"%d\", &no_of_people);\n\n    vector <int> left(no_of_people + 1);\n    for(int i = 1; i <= no_of_people; i++)\n        scanf(\"%d\", &left[i]);\n\n    vector <int> right(no_of_people + 1);\n    for(int i = 1; i <= no_of_people; i++)\n        scanf(\"%d\", &right[i]);\n\n    vector <int> candies(no_of_people + 1);\n    for(int i = 1; i <= no_of_people; i++)\n        candies[i] = no_of_people - left[i] - right[i];\n\n    for(int i = 1; i <= no_of_people; i++)\n    {\n        int left_greater = 0;\n        for(int j = 1; j < i; j++)\n            left_greater += (candies[j] > candies[i]);\n\n        int right_greater = 0;\n        for(int j = i + 1; j <= no_of_people; j++)\n            right_greater += (candies[j] > candies[i]);\n\n        if(left_greater != left[i] || right_greater != right[i])\n        {\n            printf(\"NO\\n\");\n            return 0;\n        }\n    }\n\n    printf(\"YES\\n\");\n    for(int i = 1; i <= no_of_people; i++)\n        printf(\"%d \", candies[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Mail.Ru Cup 2018 Round 1/Programs/Changing the Array.cpp",
    "content": "#include <iostream>\r\n#include <map>\r\n\r\nusing namespace std;\r\n\r\ntypedef long long LL;\r\n\r\nLL choose_2(LL n)\r\n{\r\n    return (n*(n - 1))/2;\r\n}\r\n\r\nint all_ones(int n)\r\n{\r\n    return ((1 << n) - 1);\r\n}\r\n\r\nint complement(int n, int k)\r\n{\r\n    return (all_ones(k) - n);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, k;\r\n    cin >> no_of_elements >> k;\r\n\r\n    int prefix_xor = 0;\r\n    map <int, int> prefix_xor_frequency;\r\n    prefix_xor_frequency[0] = 1;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        int option_1 = prefix_xor^element;\r\n        int option_2 = prefix_xor^complement(element, k);\r\n\r\n        if(prefix_xor_frequency[option_1] < prefix_xor_frequency[option_2])\r\n            prefix_xor = option_1;\r\n        else\r\n            prefix_xor = option_2;\r\n\r\n        prefix_xor_frequency[prefix_xor]++;\r\n    }\r\n\r\n    LL bad_segments = 0;\r\n    for(map <int, int> :: iterator it = prefix_xor_frequency.begin(); it != prefix_xor_frequency.end(); it++)\r\n    {\r\n        bad_segments += choose_2(it->second);\r\n    }\r\n\r\n    LL total_segments = choose_2(no_of_elements) + no_of_elements;\r\n    LL good_segments = total_segments - bad_segments;\r\n\r\n    cout << good_segments;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Manthan 2018/Explanation/Equalize Explanation.txt",
    "content": "Be greedy and swap only when necessary and possible.\r\n\r\n-----------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string A, B;\r\n    cin >> length >> A >> B;\r\n\r\n    int no_of_changes = 0;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            if(i + 1 < length && A[i + 1] != B[i + 1] && A[i] != A[i + 1]) //swap\r\n            {\r\n                i++;\r\n            }\r\n            no_of_changes++;\r\n        }\r\n    }\r\n\r\n    cout << no_of_changes;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Manthan 2018/Explanation/Packets Explanation.txt",
    "content": "The answer is the number of bits in n.\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    int no_of_bits = count_bits(n);\r\n\r\n    cout << no_of_bits;\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Manthan 2018/Explanation/Reach Median Explanation.txt",
    "content": "The middle element must be = S\r\n\r\nEvery element before the middle must be <= S\r\n\r\nEvery element after the middle must be >= S\r\n\r\n-------------------------------------------------\r\n\r\n    int middle = no_of_elements/2 + 1;\r\n    long long no_of_operations = 0;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(i < middle)\r\n        {\r\n            if(A[i] > median_target)\r\n            {\r\n                no_of_operations += A[i] - median_target;\r\n            }\r\n        }\r\n        else if(i == middle)\r\n        {\r\n            no_of_operations += abs(A[i] - median_target);\r\n        }\r\n        else if(i > middle)\r\n        {\r\n            if(A[i] < median_target)\r\n            {\r\n                no_of_operations += median_target - A[i];\r\n            }\r\n        }\r\n    }"
  },
  {
    "path": "Contests/Manthan 2018/Explanation/Valid BFS Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUN58X\n\nMaintain an adjacency set and then try to simulate the process.\n\n------------------------------------------------------------------------\n\nset <int> tree[MAX_N];\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges;i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        tree[u].insert(v);\n        tree[v].insert(u);\n    }\n\n    vector <int> visit_order(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n        scanf(\"%d\", &visit_order[i]);\n\n    int last = 1;\n    int valid_visit_order = (visit_order[1] == 1);\n\n    for(int i = 2; i <= no_of_vertices; i++)\n    {\n        while(last < i && tree[visit_order[last]].size() == 0)\n            last++;\n\n        int head = visit_order[last], v = visit_order[i];\n\n        if(tree[head].count(v) == 1)\n        {\n            int parent = head, child = v;\n\n            tree[parent].erase(child);\n            tree[child].erase(parent);\n        }\n        else\n        {\n            valid_visit_order = false;\n            break;\n        }\n    }\n\n    printf(valid_visit_order ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Manthan 2018/Programs/Equalize.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string A, B;\r\n    cin >> length >> A >> B;\r\n\r\n    int no_of_changes = 0;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            if(i + 1 < length && A[i + 1] != B[i + 1]) //swap\r\n            {\r\n                i++;\r\n            }\r\n            no_of_changes++;\r\n        }\r\n    }\r\n\r\n    cout << no_of_changes;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Manthan 2018/Programs/Packets.cpp",
    "content": "#include <iostream>\r\n\r\nusing namespace std;\r\n\r\nint count_bits(int n)\r\n{\r\n    int total = 0;\r\n\r\n    while(n)\r\n    {\r\n        n = n >> 1;\r\n        total++;\r\n    }\r\n\r\n    return total;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    int no_of_bits = count_bits(n);\r\n\r\n    cout << no_of_bits;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Manthan 2018/Programs/Reach Median.cpp",
    "content": "#include <cstdio>\r\n#include <cstdlib>\r\n#include <string>\r\n#include <algorithm>\r\n#include <vector>\r\n#include <iostream>\r\n\r\n#define all(v) (v).begin() + 1, (v).end()\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_elements, median_target;\r\n    cin >> no_of_elements >> median_target;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n\r\n    int middle = no_of_elements/2 + 1;\r\n    long long no_of_operations = 0;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(i < middle)\r\n        {\r\n            no_of_operations += max(0, A[i] - median_target);\r\n        }\r\n        else if(i == middle)\r\n        {\r\n            no_of_operations += abs(A[i] - median_target);\r\n        }\r\n        else if(i > middle)\r\n        {\r\n            no_of_operations += max(0, median_target - A[i]);\r\n        }\r\n    }\r\n\r\n    cout << no_of_operations;\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Contests/Manthan 2018/Programs/Valid BFS.cpp",
    "content": "#include <cstdio>\n#include <vector>\n#include <set>\n\nusing namespace std;\n\nconst int MAX_N = 2e5 + 15;\nset <int> tree[MAX_N];\n\nint main()\n{\n    int no_of_vertices;\n    scanf(\"%d\", &no_of_vertices);\n\n    int no_of_edges = no_of_vertices - 1;\n    for(int i = 1; i <= no_of_edges;i++)\n    {\n        int u, v;\n        scanf(\"%d %d\", &u, &v);\n\n        tree[u].insert(v);\n        tree[v].insert(u);\n    }\n\n    vector <int> visit_order(no_of_vertices + 1, 0);\n    for(int i = 1; i <= no_of_vertices; i++)\n        scanf(\"%d\", &visit_order[i]);\n\n    int last = 1;\n    int valid_visit_order = (visit_order[1] == 1);\n\n    for(int i = 2; i <= no_of_vertices; i++)\n    {\n        while(last < i && tree[visit_order[last]].size() == 0)\n            last++;\n\n        int head = visit_order[last], v = visit_order[i];\n\n        if(tree[head].count(v) == 1)\n        {\n            int parent = head, child = v;\n\n            tree[parent].erase(child);\n            tree[child].erase(parent);\n        }\n        else if(tree[head].count(v) == 0)\n        {\n            valid_visit_order = false;\n            break;\n        }\n    }\n\n    printf(valid_visit_order ? \"Yes\\n\" : \"No\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Moscow Team Olympiad 2018/Explanation/Equations of Mathematical Magic Explanation.txt",
    "content": "We want all x that satisfy the following equation - \r\n\r\na - x = a^x\r\n\r\nLet us look at a from the last bit onwards\r\n\r\nSuppose the last bit of a is 1, then the last bit of x can 1\r\n\r\n1 - 1 = 1^1 = 0\r\n\r\nIt can also be 0 \r\n\r\n1 - 0 = 1^0 = 1\r\n\r\nWhat if the last bit of a is 0 ?\r\n\r\nThen last bit of x can be 0\r\n\r\n0 - 0 = 0^0 = 0\r\n\r\nSuppose the last bit of a is 0 and the last bit of x is 1. What happens ?\r\n\r\nLet us look at the leftmost 1 in a. All the bits till this leftmost 1 are toggled. \r\n\r\nFor example if fifth bit is the leftmost 1 and after that there are 4 0s. \r\n\r\nIf we subtract 1 from the first bit, the the other four bits in A are toggled. \r\n\r\nNow whatever the value of x is for bits 2, 3, 4, 5 ... A - x cannot be equal to A^x because the bits of A are different here now. \r\n\r\n---------------\r\n\r\nHence, there are two possibilites for every 1 and only one possibility for every 0.\r\n\r\n---------------------------------------------\r\n\r\nvoid solve()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    long long no_of_ways = 1;\r\n\r\n    while(n)\r\n    {\r\n        if(n%2 == 1)\r\n            no_of_ways = no_of_ways << 1;\r\n\r\n        n = n >> 1;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_ways);\r\n}"
  },
  {
    "path": "Contests/Moscow Team Olympiad 2018/Explanation/Make a Triangle Explanation.txt",
    "content": "Let the sides be a < b < c\n\nThe triangle is valid if c < a + b\n\nNow, if c < a + b, \n\nThen since a < c and b < c the other two sides satisfy the inequality.\n\n-------------------------------------\n\nWe just change the smallest side, the other two sides will obey the inequality.\n\n-----------------------\n\n#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    vector <int> A(3);\n    cin >> A[0] >> A[1] >> A[2];\n\n    sort(A.begin(), A.end());\n\n    int minutes = 0;\n\n    if(A[0] + A[1] <= A[2])\n    {\n        minutes += (A[2] + 1 - A[1] - A[0]);\n    }\n\n    cout << minutes;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Moscow Team Olympiad 2018/Explanation/Oh Those Palindromes Explanation.txt",
    "content": "It is always optimal to print chunks of each character together. \r\n\r\n(One way of doing this is by simply sorting the string.)\r\n\r\n-----------\r\n\r\nWhy is it optimal ?\r\n\r\nEvery palindrome will have at least two characters.\r\n\r\nSuppose a certain character occurs f times. \r\n\r\nThen it can be involved in at most C(f, 2) + C(f, 1) = f(f + 1)/2  palindromes.\r\n\r\nWe get C(f, 2) whenever this character is the end points of any palindrome\r\nWe get C(f, 1) whenever we have a 1-character palindrome.\r\n\r\n\r\nWhen they are all printed together there will be f(f + 1)/2 palindromes. \r\n\r\nPalindrome of length 1, 2, 3, ... , f\r\n\r\n-----------------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    int length;\r\n    cin >> length >> S;\r\n\r\n    sort(S, S + length);\r\n    printf(\"%s\\n\", S);\r\n    return 0;\r\n} "
  },
  {
    "path": "Contests/Moscow Team Olympiad 2018/Programs/Equations of Mathematical Magic.cpp",
    "content": "#include <cstdio>\r\n\r\nvoid solve()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    long long no_of_ways = 1;\r\n\r\n    while(n)\r\n    {\r\n        if(n%2 == 1)\r\n            no_of_ways = no_of_ways << 1;\r\n\r\n        n = n >> 1;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_ways);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_test_cases;\r\n    scanf(\"%d\", &no_of_test_cases);\r\n\r\n    while(no_of_test_cases--)\r\n        solve();\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Moscow Team Olympiad 2018/Programs/Make a Triangle.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nint main()\n{\n    vector <int> A(3);\n    cin >> A[0] >> A[1] >> A[2];\n\n    sort(A.begin(), A.end());\n\n    int minutes = 0;\n\n    if(A[0] + A[1] <= A[2])\n    {\n        minutes += (A[2] + 1 - A[1] - A[0]);\n    }\n\n    cout << minutes;\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Moscow Team Olympiad 2018/Programs/Oh Those Palindromes.cpp",
    "content": "#include <iostream>\r\n#include <string>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    string S;\r\n    int length;\r\n    cin >> length >> S;\r\n\r\n    sort(S, S + length);\r\n    printf(\"%s\\n\", S);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Explanation/In Search of An Easy Problem Explanation.txt",
    "content": "If any one is hard, then stop.\r\n\r\n----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_opinions;\r\n    scanf(\"%d\", &no_of_opinions);\r\n\r\n    int is_hard = false;\r\n    while(no_of_opinions--)\r\n    {\r\n        const int HARD = 1;\r\n\r\n        int opinion;\r\n        scanf(\"%d\", &opinion);\r\n\r\n        if(opinion == HARD)\r\n            is_hard = true;\r\n    }\r\n\r\n    printf(is_hard ? \"HARD\\n\" : \"EASY\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Explanation/Vasya and Cornfield.txt",
    "content": "To check if a point lies inside a rectangle, we have to ensure the points lie on the right side of each of the four lines. \r\n\r\n-------------------------------\r\n\r\nint main()\r\n{\r\n    int n, d;\r\n    scanf(\"%d %d\", &n, &d);\r\n\r\n    int no_of_grasshoppers;\r\n    scanf(\"%d\", &no_of_grasshoppers);\r\n\r\n    while(no_of_grasshoppers--)\r\n    {\r\n        int x, y;\r\n        scanf(\"%d %d\", &x, &y);\r\n\r\n        printf(-d <= x - y && x - y <= d && d <= x + y && x + y <= 2*n - d ? \"YES\\n\" : \"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Explanation/Vasya and Golden Ticket Explanation.txt",
    "content": "Now if the question was asking if there is some way to break it into 2 segments of equal sums, it would be a pretty easy question ... we'd just need to look for a prefix who's sum = S/2. \n\n-------------------------\n\nLet us break it down into a smaller question ...\n\nGiven K, how do we check if A can be divided into K segments each of who's sums are equal.\n\nIf the sum of the array is S, then the sum of each segment should be S/K. (S should be divisible by K.)\n\n-------------------------------------\n\nThat means we must search for some prefix who's sum = S/k. \n\nThen remove that prefix, and once again look for a prefix who's sum = S/k. \n\nWe keep doing this ... If at any point our sum exceeds S/k, then it means we can't divide the array into segments who's sum is K because the current segment will always have sum > k.\n\n----------------------------------\n\nint possible_to_divide(vector <int> &A, int target_no_of_parts)\n{\n    int sum = 0;\n    for(int i = 1; i < A.size(); i++)\n        sum += A[i];\n\n    int target_part_sum = sum/target_no_of_parts;\n\n    int parts_that_are_made = 0;\n\n    for(int current_part_sum = 0, i = 1; i < A.size(); i++)\n    {\n        current_part_sum += A[i];\n\n        if(current_part_sum == target_part_sum)\n        {\n            parts_that_are_made++;\n\n            current_part_sum = 0;\n        }\n\n        if(current_part_sum > target_part_sum)\n            return false;\n    }\n\n    return (parts_that_are_made == target_no_of_parts);\n}\n\n-----------------------------\n\nSo first find Sum S, and then iterate over all divisors of S.\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Explanation/Vasya and Good Sequences Explanation.txt",
    "content": "Fact - If the number of 1's in the range is odd, or if any number has more than half the number of 1s in the range, it is not possible. \r\n\r\nProof - If there are an odd number of 1s clearly, there will always be at least one 1 left over. \r\n\r\nIf one number has more than half the number of 1s, then there will always be some 1s in it that are left over. \r\n\r\n-----------------------------------------------------\r\n\r\nFact - This condition is necessary, but it is also sufficient. \r\n\r\nProof - Let us place exactly two 1s in each bit position. \r\n\r\nFor example, the first position from the left has exactly 2 ones. \r\nThe second position has exactly 2 ones. \r\nThe third has exactly 2 ones. \r\n\r\nAnd so on.\r\n\r\n-----------------------\r\n\r\nHow do we do this ? \r\n\r\nFirst we count all ranges, where the sum is even. \r\n\r\nlong long good_sequences = 0;\r\n    long long odd_sums = 0;\r\n    long long even_sums = 1;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(sum[i]%2 == 0)\r\n        {\r\n            good_sequences += even_sums;\r\n\r\n            even_sums++;\r\n        }\r\n        else\r\n        {\r\n            good_sequences += odd_sums;\r\n\r\n            odd_sums++;\r\n        }\r\n    }\r\n\r\n---------------------------------\r\n\r\nNow, we have to discount the number of ranges where"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Explanation/Vasya and Triangle Explanation.txt",
    "content": "Area = 1/2 |  1 1  1  |\r\n           | x1 x2 x3 |\r\n           | y1 y2 y3 |\r\n\r\nThe determinant is an integer since all the lattice points are integers. \r\n\r\nSo, we can say that \r\n\r\n2*Area = Integer. \r\n\r\n------------------------------\r\n\r\nNow, 2*Area = 2(mn)/k = (2mn)/k\r\n\r\nThis means that k must divide 2mn. \r\n\r\n\r\n---------------------------------------\r\n\r\nIf k does not divide 2mn, then no triangle is possible. \r\n\r\n---------------------------------\r\n\r\n1. Cancel all common factors of k and m. \r\n2. Cancel all common factors of k and n. \r\n\r\nThis means k should be either = 1 or = 2\r\n\r\nk = 1, if (mn) is a multiple of k\r\nk = 2, if (2mn) is a multiple of k\r\n\r\nIf k is any value greater than 2, then it is not possible to have such a triangle. \r\n\r\n--------------------------------------\r\n\r\nNow, how do we construct this triangle ?\r\n\r\nLet g1 = gcd(k, m) and g2 = gcd(k, n)\r\n\r\nm' = m/g1  ... n' = n/g2\r\n\r\nk' = k/(g1g2)\r\n\r\nIf we have a triangle with vertices\r\n\r\n(0, 0) (m', 0), (0, n')\r\n\r\nArea = (m'n')/(2)\r\n\r\n= (mn)/2(g1g2)\r\n\r\nNow, \r\n\r\n---------------------\r\n\r\nCase 1 - if K = 1 after dividing by g1 g2, then it means K = g1 g2. \r\n\r\nArea = mn/2k ... In this case, we multiply numerator and denominator by 2.\r\n\r\nK was initially at least 2, so if K is 1 now, then it means either the m' or n' has been divided by some number >= 2.\r\n\r\nSo, we pick (0, 0) (2m', 0) (0, n') or (0, 0), (m', 0), (0, 2n') whichever is within the limits.\r\n\r\n---------------------------------\r\n\r\nCase 2 - K = 2 after dividing by g1g2 then it means K = 2g1g2\r\n\r\nThen area = (mn)/k .. .There is nothing further to do.\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Programs/In Search of An Easy Problem.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int no_of_opinions;\r\n    scanf(\"%d\", &no_of_opinions);\r\n\r\n    int is_hard = false;\r\n    while(no_of_opinions--)\r\n    {\r\n        const int HARD = 1;\r\n\r\n        int opinion;\r\n        scanf(\"%d\", &opinion);\r\n\r\n        if(opinion == HARD)\r\n            is_hard = true;\r\n    }\r\n\r\n    printf(is_hard ? \"HARD\\n\" : \"EASY\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Programs/Vasya and Cornfield.cpp",
    "content": "#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, d;\r\n    scanf(\"%d %d\", &n, &d);\r\n\r\n    int no_of_grasshoppers;\r\n    scanf(\"%d\", &no_of_grasshoppers);\r\n\r\n    while(no_of_grasshoppers--)\r\n    {\r\n        int x, y;\r\n        scanf(\"%d %d\", &x, &y);\r\n\r\n        printf(-d <= x - y && x - y <= d && d <= x + y && x + y <= 2*n - d ? \"YES\\n\" : \"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Programs/Vasya and Golden Ticket.cpp",
    "content": "#include <cstdio>\n#include <vector>\n\nusing namespace std;\n\nint possible_to_divide(vector <int> &A, int target_no_of_parts)\n{\n    int sum = 0;\n    for(int i = 1; i < A.size(); i++)\n        sum += A[i];\n\n    int target_part_sum = sum/target_no_of_parts;\n\n    int parts_that_are_made = 0;\n\n    for(int current_part_sum = 0, i = 1; i < A.size(); i++)\n    {\n        current_part_sum += A[i];\n\n        if(current_part_sum == target_part_sum)\n        {\n            parts_that_are_made++;\n\n            current_part_sum = 0;\n        }\n\n        if(current_part_sum > target_part_sum)\n            return false;\n    }\n\n    return (parts_that_are_made == target_no_of_parts);\n}\n\nint main()\n{\n    int no_of_digits;\n    scanf(\"%d\", &no_of_digits);\n\n    vector <int> A(no_of_digits + 1);\n    for(int i = 1; i <= no_of_digits; i++)\n        scanf(\"%1d\", &A[i]);\n\n    int sum = 0;\n    for(int i = 1; i <= no_of_digits; i++)\n        sum += A[i];\n\n    int division_possible = false;\n    for(int i = 2; i <= no_of_digits; i++)\n    {\n        if(sum%i == 0)\n        {\n            if(possible_to_divide(A, i))\n            {\n                division_possible = true;\n                break;\n            }\n        }\n    }\n\n    printf(division_possible ? \"YES\\n\" : \"NO\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Programs/Vasya and Good Sequences.cpp",
    "content": "#include <cstdio>\r\n#include <vector>\r\n#include <algorithm>\r\n\r\nusing namespace std;\r\n\r\nint population_count(long long n)\r\n{\r\n    int no_of_1s = 0;\r\n\r\n    while(n)\r\n    {\r\n        if(n%2 == 1)\r\n            no_of_1s++;\r\n\r\n        n = n >> 1;\r\n    }\r\n\r\n    return no_of_1s;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <long long> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n        A[i] = population_count(A[i]);\r\n    }\r\n\r\n    vector <long long> sum(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum[i] = sum[i - 1] + A[i];\r\n\r\n    long long good_sequences = 0;\r\n    long long odd_sums = 0;\r\n    long long even_sums = 1;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(sum[i]%2 == 0)\r\n        {\r\n            good_sequences += even_sums;\r\n\r\n            even_sums++;\r\n        }\r\n        else\r\n        {\r\n            good_sequences += odd_sums;\r\n\r\n            odd_sums++;\r\n        }\r\n    }\r\n\r\n    long long bad_sequences = 0;\r\n    for(int left = 1; left <= no_of_elements; left++)\r\n    {\r\n        const int MAX_RANGE = 128;\r\n\r\n        long long maximum_element = A[left];\r\n\r\n        for(int right = left; right <= min(no_of_elements, left + MAX_RANGE); right++)\r\n        {\r\n            int sum_here = sum[right] - sum[left - 1];\r\n            maximum_element = max(maximum_element, A[right]);\r\n\r\n            if(sum_here%2 == 0 && 2*maximum_element > sum_here)\r\n            {\r\n                bad_sequences++;\r\n            }\r\n        }\r\n    }\r\n\r\n    good_sequences -= bad_sequences;\r\n\r\n    printf(\"%I64d\\n\", good_sequences);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 1/Programs/Vasya and Triangle.cpp",
    "content": "#include <cstdio>\r\n\r\n#define max(a, b) (a > b ? a : b)\r\n#define min(a, b) (a < b ? a : b)\r\ntypedef long long LL;\r\n\r\nLL gcd(LL a, LL b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nint main()\r\n{\r\n    LL x_limit, y_limit, k;\r\n    scanf(\"%I64d %I64d %I64d\", &x_limit, &y_limit, &k);\r\n\r\n    //2*Area = (2mn)/k ... K should divide 2mn\r\n    LL g = gcd(x_limit, k);\r\n    LL x = x_limit/g;\r\n    k /= g;\r\n\r\n    g = gcd(y_limit, k);\r\n    LL y = y_limit/g;\r\n    k /= g;\r\n\r\n    if(k == 1)\r\n    {\r\n        if(2*x <= x_limit)\r\n            x = 2*x;\r\n        else\r\n            y = 2*y;\r\n    }\r\n\r\n    if(k <= 2)\r\n    {\r\n        printf(\"YES\\n\");\r\n        printf(\"0 0\\n%I64d 0\\n0 %I64d\\n\", x, y);\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 2/Explanation/Curiosity Has No Limits.txt",
    "content": "There are only four values each can take. \r\n\r\nLet us first set T[n] = 0, \r\n\r\nThen check if there's any number existing such that \r\n\r\nx|T[n] = A[n - 1] and x&T[n - 1] = B[n - 1]\r\n\r\nIf there is, check if there's any possibile value for T[n - 2] and so on. \r\n\r\nHere is a recurisve way of doing it - \r\n\r\n-----------------\r\n\r\nint is_possible(vector <int> &T, vector <int> &A, vector <int> &B, int n)\r\n{\r\n    if(n == 0)\r\n        return true;\r\n\r\n    for(int ele = 0; ele <= 3; ele++)\r\n    {\r\n        T[n] = ele;\r\n\r\n        if((T[n]|T[n + 1]) == A[n] && (T[n]&T[n + 1]) == B[n])\r\n        {\r\n            if(is_possible(T, A, B, n - 1))\r\n                return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n------------------------------\r\n\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 2/Explanation/Golden Plate.txt",
    "content": "Let us make few observations.\n\n1. If the golden line has r rows and c columns. The total perimeter = 2(r + c) - 4\n(We subtract 4 because 4 squares are counted twice.)\n\n2. For every ring, Both r and c decrease by 4. (Decrease by 2 on either side.)\n\n---------------------\n\n#include <cstdio>\n\nint main()\n{\n    int rows, columns, k;\n    scanf(\"%d %d %d\", &rows, &columns, &k);\n\n    int total_perimeter = 0;\n    int r = rows, c = columns;\n    for(int i = 1; i <= k; i++)\n    {\n        int perimeter = 2*r + 2*c - 4;\n\n        total_perimeter += perimeter;\n\n        r -= 4;\n        c -= 4;\n    }\n\n    printf(\"%d\\n\", total_perimeter);\n    return 0;\n}\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 2/Programs/Curiosity Has No Limits.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n\r\nusing namespace std;\r\n\r\nint is_possible(vector <int> &T, vector <int> &A, vector <int> &B, int n)\r\n{\r\n    if(n == 0)\r\n        return true;\r\n\r\n    for(int ele = 0; ele <= 3; ele++)\r\n    {\r\n        T[n] = ele;\r\n\r\n        if((T[n]|T[n + 1]) == A[n] && (T[n]&T[n + 1]) == B[n])\r\n        {\r\n            if(is_possible(T, A, B, n - 1))\r\n                return true;\r\n        }\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    vector <int> B(no_of_elements + 1);\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        cin >> B[i];\r\n\r\n    vector <int> T(no_of_elements + 1);\r\n    for(int i = 0; i <= 3; i++)\r\n    {\r\n        T[no_of_elements] = i;\r\n\r\n        if(is_possible(T, A, B, no_of_elements - 1))\r\n        {\r\n            cout << \"YES\\n\";\r\n\r\n            for(int i = 1; i <= no_of_elements; i++)\r\n                cout << T[i] << \" \";\r\n\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    cout << \"NO\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Contests/Technocup 2019 Elimination Round 2/Programs/Golden Plate.cpp",
    "content": "#include <cstdio>\n\nint main()\n{\n    int rows, columns, k;\n    scanf(\"%d %d %d\", &rows, &columns, &k);\n\n    int total_perimeter = 0;\n    int r = rows, c = columns;\n    for(int i = 1; i <= k; i++)\n    {\n        int perimeter = 2*r + 2*c - 4;\n\n        total_perimeter += perimeter;\n\n        r -= 4;\n        c -= 4;\n    }\n\n    printf(\"%d\\n\", total_perimeter);\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations - 1/Boy or Girl - Explanation.txt",
    "content": "Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.\r\n\r\nBut yesterday, he came to see \"her\" in the real world and found out \"she\" is actually a very strong man! Our hero is very sad and he is too tired to love again now. So he came up with a way to recognize users' genders by their user names.\r\n\r\nThis is his method: if the number of distinct characters in one's user name is odd, then he is a male, otherwise she is a female. You are given the string that denotes the user name, please help our hero to determine the gender of this user by his method.\r\n\r\nInput\r\nThe first line contains a non-empty string, that contains only lowercase English letters  the user name. This string contains at most 100 letters.\r\n\r\nOutput\r\nIf it is a female by our hero's method, print \"CHAT WITH HER!\" (without the quotes), otherwise, print \"IGNORE HIM!\" (without the quotes).\r\n\r\n------------------------------------------------------------------------------\r\n\r\nBuild another string called distinct_letters and add every character of username only one time.\r\nCount the number of characters of distinct_letters.\r\nCheck the parity and print correct message."
  },
  {
    "path": "Explanations/Explanations - 1/Translation - Explanation.txt",
    "content": "The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the translation. Vasya translated word s from Berlandish into Birlandish as t. Help him: find out if he translated the word correctly.\r\n\r\nInput\r\nThe first line contains word s, the second line contains word t. The words consist of lowercase Latin letters. The input data do not consist unnecessary spaces. The words are not empty and their lengths do not exceed 100 symbols.\r\n\r\nOutput\r\nIf the word t is a word s, written reversely, print YES, otherwise print NO.\r\n\r\n----------------------------------------------------------------------------\r\n\r\nPretty Straightforward. Just check if a string is the reverse of another."
  },
  {
    "path": "Explanations/Explanations - 10/A and B Compilation Errors Explanation.txt",
    "content": "B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.\r\n\r\nInitially, the compiler displayed n compilation errors, each of them is represented as a positive integer. \r\nAfter some effort, B managed to fix some mistake and then another one mistake.\r\n\r\nHowever, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared  \r\nthe compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, \r\ncompilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.\r\n\r\nCan you help B find out exactly what two errors he corrected?\r\n\r\nInput\r\nThe first line of the input contains integer n (3?=?n?=?105)  the initial number of compilation errors.\r\n\r\nThe second line contains n space-separated integers a1,?a2,?...,?an (1?=?ai?=?109)  the errors the compiler displayed for the first time.\r\n\r\nThe third line contains n?-?1 space-separated integers b1,?b2,?...,?bn?-?1  the errors displayed at the second compilation. \r\nIt is guaranteed that the sequence in the third line contains all numbers of the second string except for exactly one.\r\n\r\nThe fourth line contains n?-?2 space-separated integers ?1,??2,?...,??n?-?2  the errors displayed at the third compilation. \r\nIt is guaranteed that the sequence in the fourth line contains all numbers of the third line except for exactly one.\r\n\r\nOutput\r\nPrint two numbers on a single line: the numbers of the compilation errors that disappeared after B made the first and the second correction, respectively.\r\n\r\n--------------------------------------------------------------\r\n\r\nIt's a classic riddle. Alice tells Bob numbers from 1 to 100 in a random order with one number missing. How does Bob find the missing number ?\r\nHe keeps track of the sum and subtracts whatever Alice tells him. It's that simple.\r\n\r\nBut, seeing the data structure tag on this question, I was trying to solve it with maps. It's doable but code gets unnecissarily complex.\r\n\r\nint sum_1 = 0;\r\n    for(int i = 1; i <= no_of_errors; i++)\r\n    {\r\n        scanf(\"%d\", &error_i);\r\n        sum_1 += error_i;\r\n    }\r\n\r\n    //Second List\r\n    int sum_2 = 0;\r\n    for(int i = 1; i <= no_of_errors - 1; i++)\r\n    {\r\n        scanf(\"%d\", &error_i);\r\n        sum_2 += error_i;\r\n    }\r\n\r\n    int sum_3 = 0;\r\n    for(int i = 1; i <= no_of_errors - 2; i++)\r\n    {\r\n        scanf(\"%d\", &error_i);\r\n        sum_3 += error_i;\r\n    }\r\n\r\n\r\n    printf(\"%d \\n%d\\n\", sum_1-sum_2, sum_2 - sum_3);"
  },
  {
    "path": "Explanations/Explanations - 10/Amr and Music Explanation.txt",
    "content": "\r\nHad to use vector of pairs for this one. Learnt to insert a pair into a vector. Use make pair. Sort by defualt sorts the first by the first parameter.\r\nYou can write a custom sort if you want a different sort.\r\n\r\nbool custom_sort(const data_type &a, const data_type &b) ... And define how you want the sort to work and pass this function name to the STL sort\r\n\r\nfirst and second can be used to access elements of a vector pair just like a map.\r\n\r\n-----------------------------------------------\r\n\r\ntypedef pair <int, int> int_pair;\r\n\r\nint main()\r\n{\r\n    int no_of_instruments, no_of_days, day_i;\r\n    scanf(\"%d %d\", &no_of_instruments, &no_of_days);\r\n\r\n    vector < int_pair > no_of_days_to_learn;\r\n    for(int i = 0; i < no_of_instruments; i++)\r\n    {\r\n        scanf(\"%d\", &day_i);\r\n        no_of_days_to_learn.push_back( make_pair(day_i, i + 1));\r\n    }\r\n\r\n    sort(all(no_of_days_to_learn));\r\n\r\n    vector <int> learnt_instrument;\r\n    for(int i = 0; i < no_of_instruments && no_of_days > 0; i++)\r\n    {\r\n        no_of_days -= no_of_days_to_learn[i].first;\r\n\r\n        if(no_of_days >= 0)\r\n            learnt_instrument.push_back(no_of_days_to_learn[i].second);\r\n    }\r\n\r\n    printf(\"%u\\n\", learnt_instrument.size());\r\n    for(unsigned int i = 0; i < learnt_instrument.size(); i++)\r\n            printf(\"%d \", learnt_instrument[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Arrival of General Explanation.txt",
    "content": "A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. \r\nHaving learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.\r\n\r\nBy the military charter the soldiers should stand in the order of non-increasing of their height. \r\nBut as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers \r\nlined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. \r\nPlease note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. \r\nOnly the heights of the first and the last soldier are important.\r\n\r\nFor example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.\r\n\r\nWithin one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.\r\n\r\n-----------------------------------------------------\r\n\r\nWe need to know the position of the leftmost tallest person and rightmost shortest person (Because there can be multiple maxima and minima).\r\n\r\nNormally, the answer is (leftmost - 1) + (n - rightmost)\r\n\r\nHowever, we need to consider the case where leftmost and rightmost need to go past one another to reach the other end.\r\n\r\nThe case where leftmost > rightmost\r\n\r\nSuppose tallest is a, shortest is b.\r\n\r\ni i i b i a i i\r\n\r\nWhile getting a to the beginning, we need to change b's position\r\n\r\na i i i b i i i\r\n\r\nNow b has to move one place less than he originally had to.\r\n\r\n-----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_soldiers;\r\n    scanf(\"%d\", &no_of_soldiers);\r\n\r\n    const int oo = 100 + 1;\r\n    int tallest_soldier = 0, shortest_soldier = oo;\r\n    int leftmost_tallest = -1, rightmost_shortest = -1;\r\n\r\n    for(int i = 1; i <= no_of_soldiers; i++)\r\n    {\r\n        int height_i;\r\n        scanf(\"%d\", &height_i);\r\n\r\n        if(height_i > tallest_soldier)\r\n        {\r\n            tallest_soldier = height_i;\r\n            leftmost_tallest = i;\r\n        }\r\n\r\n        if(height_i <= shortest_soldier)\r\n        {\r\n            shortest_soldier = height_i;\r\n            rightmost_shortest = i;\r\n        }\r\n    }\r\n\r\n    int no_of_swaps = 0;\r\n\r\n    if(leftmost_tallest < rightmost_shortest)\r\n        no_of_swaps = (leftmost_tallest - 1) + (no_of_soldiers - rightmost_shortest);\r\n    else\r\n        no_of_swaps = (leftmost_tallest - 1) + (no_of_soldiers - rightmost_shortest) - 1;\r\n\r\n    printf(\"%d\\n\", no_of_swaps);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Bear and Game Explanation.txt",
    "content": "Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.\r\n\r\nEach minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.\r\n\r\n---------------------------------------\r\n\r\nMissed a case which was not explained in the question clearly.\r\n\r\nIf he doesn't find any gap of boring minutes greater than 15 minutes, then the bear watches 90 minutes.\r\n\r\nThe number of boring minutes in between two interesting moments x and y are all the moments from x + 1 to y - 1 ... This is given by (y- 1) - x \r\n[Inclusive of y - 1, exclusive of x].\r\n\r\nI put in 2 auxilliary variables .. The 0-th interesting minute is 0  and the last interesting minute is 90. (Even if it is boring).\r\n\r\n---------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_interesting_minutes, interesting_minute_i, tv_on_minutes = 0;\r\n    scanf(\"%d\", &no_of_interesting_minutes);\r\n\r\n    bool tv_on = true;\r\n\r\n    vector <int> interesting_minute;\r\n    interesting_minute.push_back(0);\r\n    for(int i = 1; i <= no_of_interesting_minutes; i++)\r\n    {\r\n        scanf(\"%d\", &interesting_minute_i);\r\n        interesting_minute.push_back(interesting_minute_i);\r\n    }\r\n\r\n    if(interesting_minute.back() != 90)\r\n        interesting_minute.push_back(90);\r\n\r\n    for(unsigned int i = 1; i < interesting_minute.size() ; i++)\r\n    {\r\n        if(tv_on)\r\n        {\r\n            int boring_interval = (interesting_minute[i] - 1) - interesting_minute[i - 1];\r\n\r\n            if(boring_interval >= 15)\r\n            {\r\n                tv_on_minutes += 15;\r\n                tv_on = false;\r\n            }\r\n            else\r\n            {\r\n                tv_on_minutes += boring_interval + 1; //Watch the boring interval + the interesting minute\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", tv_on_minutes);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Beautiful Year Explanation.txt",
    "content": "\r\n-------------------------------\r\n\r\nGiven a year, find the next year that has all it's digits distinct.\r\n\r\nUsed a map first but then realised it's too much since there are only 10 digits. Got a bit hard to read so I re-wrote it with a frequency vector.\r\n\r\n------------------------------------------------------\r\n\r\nint is_beautiful(int year)\r\n{\r\n    vector <int> digit_frequency(10, 0);\r\n    while(year > 0)\r\n    {\r\n        digit_frequency[year%10]++;\r\n\r\n        year = year/10;\r\n    }\r\n\r\n    for(int i = 0; i < 10; i++)\r\n        if(digit_frequency[i] > 1)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int year;\r\n    scanf(\"%d\", &year);\r\n\r\n    int beautiful_year;\r\n    for(beautiful_year = year + 1; ; beautiful_year++)\r\n        if(is_beautiful(beautiful_year))\r\n            break;\r\n\r\n    printf(\"%d\\n\", beautiful_year);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Black Square Explanation.txt",
    "content": "Polycarp has a checkered sheet of paper of size n??m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's \"Black Square\", \r\nPolycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.\r\n\r\nYou are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. \r\nAll the cells that do not belong to the square should be white. The square's side should have positive length.\r\n\r\nInput\r\nThe first line contains two integers n and m (1?=?n,?m?=?100)  the sizes of the sheet.\r\n\r\nThe next n lines contain m letters 'B' or 'W' each  the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, \r\notherwise it is painted white.\r\n\r\nOutput\r\nPrint the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. \r\nAll the cells that do not belong to the square should be white. If it is impossible, print -1.\r\n\r\n----------------------------------------------------------\r\n\r\nKeep track of the rightmost, leftmost, topmost, downmost black square the number of black squares.\r\n\r\nThe square of all black squares must contain these extreme black squares. Also, all other black square must be inside this.\r\n\r\nSubtract the number of blocks in this square with the number of black squares.\r\n\r\nA square is only possible if the side of this side is smaller than the minimum of the rectangle side.int main()\r\n{\r\n    int no_of_rows, no_of_columns;\r\n    scanf(\"%d %d\", &no_of_rows, &no_of_columns);\r\n    char rectangle[MAX_LENGTH][MAX_LENGTH];\r\n\r\n    int no_of_black_squares = 0, left_most = no_of_columns + 1, right_most = -1, highest = -1, lowest = no_of_rows + 1;\r\n\r\n    for(int i = 0; i < no_of_rows; i++)\r\n    {\r\n        scanf(\"%s\", rectangle[i]);\r\n\r\n        for(int j = 0; j < no_of_columns; j++)\r\n        {\r\n            if(rectangle[i][j] == 'B')\r\n            {\r\n                no_of_black_squares ++;\r\n\r\n                left_most = min(left_most, j);\r\n                right_most = max(right_most, j);\r\n\r\n                highest = max(highest, i);\r\n                lowest = min(lowest, i);\r\n            }\r\n        }\r\n    }\r\n\r\n    int square_rows = highest - lowest + 1, square_columns = right_most - left_most + 1;\r\n    int square_side = max(square_columns, square_rows);\r\n    int repainted = -1;\r\n\r\n    if(no_of_black_squares == 0)\r\n    {\r\n        repainted = 1;\r\n    }\r\n    else if(square_side <= min(no_of_rows, no_of_columns))\r\n    {\r\n        repainted = square_side*square_side - no_of_black_squares;\r\n    }\r\n\r\n    printf(\"%d\\n\", repainted);\r\n    return 0;\r\n}\r\n----------------------------------------\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Difference Row.txt",
    "content": "You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between \nall pairs of adjacent integers.\n\nMore formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. \nThe value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn).\n\nFind the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.\n\n-----------------------------------------------\n\nThe first observation is that the value of an arrangement telescopes to x1 - xn. To maximise this, we place the biggest element at x1 and the smallest at xn.\n\nThere are many possible arrangements with these two elements at the ends fixed. But, we have to print the lexicographically smallest. \n\nThat means the smallest remaining element in the second spot, next smallest in third spot, etc.\n\nThe array must be sorted in non-decreasing order from 2 to n-1. \n\nSo, sort the entire array and swap the first and last element.\n\nFor swapping, I was going to use XOR ... a = a^b, b = a^b, a = a^b.  But, STL has an inbuilt function for swapping.\n\n---------------------------------\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    vector <int> sequence(no_of_elements);\n\n    for(int i = 0; i < no_of_elements; i++)\n        scanf(\"%d\", &sequence[i]);\n\n    sort(all(sequence));\n\n    swap(sequence[0], sequence.back());\n\n    for(unsigned int i = 0; i < sequence.size(); i++)\n        printf(\"%d \", sequence[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations - 10/Interesting Drink Explanation.txt",
    "content": "Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink \"Beecola\", \r\nwhich can be bought in n different shops in the city. \r\nIt's known that the price of one bottle in the shop i is equal to xi coins.\r\n\r\nVasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. \r\nNow, for each of the days he want to know in how many different shops he can buy a bottle of \"Beecola\".\r\n\r\n-------------------------------------------------\r\n\r\nSort all the drinks in ascending order of price and then use upper bound.\r\n\r\nupper bound returns the rightmost index that is <= key.  It is already one indexed so no need to decrease by 1.  If all the prices are greater, than it will return 0.\r\nIf all are smaller it will return n.\r\n\r\n------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_shops;\r\n    scanf(\"%d\", &no_of_shops);\r\n\r\n    vector <int> price_in_shop(no_of_shops);\r\n    for(int i = 0; i < no_of_shops; i++)\r\n        scanf(\"%d\", &price_in_shop[i]);\r\n\r\n    sort(all(price_in_shop));\r\n\r\n    int no_of_days, budget_day_i;\r\n    scanf(\"%d\", &no_of_days);\r\n\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        scanf(\"%d\", &budget_day_i);\r\n        int no_of_eligible_shops = upper_bound(all(price_in_shop), budget_day_i) - price_in_shop.begin();\r\n\r\n        printf(\"%d\\n\",no_of_eligible_shops); //0 indexed vector so no need to subtract 1.\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Keyboard Layouts Explanation.txt",
    "content": "There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. \r\nIn Berland they use alphabet with 26 letters which coincides with English alphabet.\r\n\r\nYou are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order.\r\n\r\nYou are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, \r\nbut the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.\r\n\r\nSince all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.\r\n\r\nInput\r\nThe first line contains a string of length 26 consisting of distinct lowercase English letters. This is the first layout.\r\n\r\nThe second line contains a string of length 26 consisting of distinct lowercase English letters. This is the second layout.\r\n\r\nThe third line contains a non-empty string s consisting of lowercase and uppercase English letters and digits. This is the text typed in the first layout. \r\nThe length of s does not exceed 1000.\r\n\r\nOutput\r\nPrint the text if the same keys were pressed in the second layout.\r\n\r\n-----------------------------------------------------------\r\n\r\nI did this by making a <char, int> map ... the first keyboard's characters are mapped to a position number.\r\nThen, when the input is read ... I display second_keyboard[map[i]] ...But, it can be done easier and better with a <char, char> map.\r\n\r\nThat way ... program is easier and cleaner.\r\n\r\nIf the character is not an alphabet, just display it as it is. Otherwise, check if it is capital or not and print the corresponding character after checking case.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    char keyboard_1[NO_OF_ALPHABETS], keyboard_2[NO_OF_ALPHABETS];\r\n    scanf(\"%s %s\", keyboard_1, keyboard_2);\r\n\r\n    map <char, char> corresponding_keyboard_2_char;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        corresponding_keyboard_2_char[ keyboard_1[i] ] = keyboard_2[i];\r\n    }\r\n\r\n    char text[MAX_LENGTH];\r\n    scanf(\"%s\", text);\r\n\r\n    for(int i = 0; text[i] != '\\0'; i++)\r\n    {\r\n        if(isalpha(text[i]))\r\n        {\r\n            char input = tolower(text[i]);\r\n            putchar(is_capital(text[i]) ? tocapital(corresponding_keyboard_2_char[input]) : corresponding_keyboard_2_char[input]);\r\n        }\r\n        else\r\n        {\r\n            putchar(text[i]); //Not there in the keyboards\r\n        }\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Life Without Zeroes Explanation.txt",
    "content": "\r\n\r\nGet the number without zeroes\r\n\r\nlong long zeroless(long long n)\r\n{\r\n    long long zeroless_n = 0;\r\n\r\n    while(n > 0)\r\n    {\r\n        int digit = n%10;\r\n        if(digit != 0)\r\n            zeroless_n = zeroless_n*10 + digit;\r\n\r\n        n = n/10;\r\n    }\r\n    return reverse(zeroless_n);\r\n}\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n\r\n    printf(zeroless(a) + zeroless(b) == zeroless(a + b) ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n} \r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Modified GCD Explanation.txt",
    "content": "Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.\r\n\r\nA common divisor for two positive numbers is a number which both numbers are divisible by.\r\n\r\nBut your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from \r\nlow to high (inclusive), i.e. low?=?d?=?high. It is possible that there is no common divisor in the given range.\r\n\r\nYou will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query.\r\n\r\n----------------------------------------------------------------\r\n\r\nKeep a vector containing all the factors of the gcd ...\r\n\r\nLearnt to use the STL binary search functions on this one ...\r\n\r\nUpper bound returns the rightmost index that is <= n\r\nLower bound returns the leftmost index that is <= n\r\n\r\n-------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n\r\n    int gcd = get_gcd(a, b);\r\n\r\n    vector <int> factors;\r\n    for(int i = 1; i*i <= gcd; i++)\r\n    {\r\n        if(gcd%i == 0)\r\n        {\r\n            if(i*i == gcd)\r\n            {\r\n                factors.push_back(i);\r\n            }\r\n            else\r\n            {\r\n                factors.push_back(i);\r\n                factors.push_back(gcd/i);\r\n            }\r\n        }\r\n    }\r\n\r\n    sort(all(factors));\r\n\r\n    int number_of_queries;\r\n    scanf(\"%d\", &number_of_queries);\r\n\r\n    for(int i = 1; i <= number_of_queries; i++)\r\n    {\r\n        int left, right, answer;\r\n        scanf(\"%d %d\", &left, &right);\r\n\r\n        int index = upper_bound(factors.begin(), factors.end(), right) - factors.begin(); //Returns 1 indexed\r\n        index--;\r\n\r\n        if(factors[index] < left)\r\n            answer = -1;\r\n        else\r\n            answer = factors[index];\r\n\r\n        printf(\"%d\\n\", answer);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Next Test Explanation.txt",
    "content": "\r\nis a system which allows to create programming tasks in a simple and professional way. \r\nWhen you add a test to the problem, the corresponding form asks you for the test index. \r\nAs in most cases it is clear which index the next test will have, the system suggests the default value of the index. \r\nIt is calculated as the smallest positive integer which is not used as an index for some previously added test.\r\n\r\nYou are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.\r\n\r\n--------------------------------------\r\n\r\nUsed a frequency table here since the least number is required.\r\n\r\nGot a mistake because it is possible for the answer to be 3001 ... if all 3000 numbers are used.\r\n\r\nMissed a corner case on this one.\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    vector <int> is_used(3000 + 2, false);\r\n    int no_of_tests, test_i, default_for_next;\r\n    scanf(\"%d\", &no_of_tests);\r\n\r\n    for(int i = 1; i <= no_of_tests; i++)\r\n    {\r\n        scanf(\"%d\", &test_i);\r\n        is_used[test_i] = true;\r\n    }\r\n\r\n    for(int i = 1; i <= 3001; i++)\r\n    {\r\n        if(is_used[i] == false)\r\n        {\r\n            default_for_next = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", default_for_next);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Presents Explanation.txt",
    "content": "Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. \r\nHe immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. \r\nAnd on this occasion he organized a New Year party at his place and invited n his friends there.\r\n\r\nIf there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. \r\nThus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. \r\nHe numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. \r\nHe also remembered that each of his friends received exactly one gift.\r\n\r\nNow Petya wants to know for each friend i the number of a friend who has given him a gift.\r\n\r\n-----------------------------------------------\r\n\r\nVery simple implementation. A permutation is given ... We need to display p[p[i]].\r\n\r\n-------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_people;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    vector <int> present_giver_of(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int gift_receiver;\r\n        scanf(\"%d\", &gift_receiver);\r\n\r\n        present_giver_of[gift_receiver] = i;\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        printf(\"%d \", present_giver_of[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Serega and Coat Rack Explanation.txt",
    "content": "Sereja owns a restaurant for n people. The restaurant hall has a coat rack with n hooks. Each restaurant visitor can use a hook to hang his clothes on it. \r\nUsing the i-th hook costs ai rubles. Only one person can hang clothes on one hook.\r\n\r\nTonight Sereja expects m guests in the restaurant. Naturally, each guest wants to hang his clothes on an available hook with minimum price \r\n(if there are multiple such hooks, he chooses any of them). \r\nHowever if the moment a guest arrives the rack has no available hooks, Sereja must pay a d ruble fine to the guest.\r\n\r\nHelp Sereja find out the profit in rubles (possibly negative) that he will get tonight. You can assume that before the guests arrive, \r\nall hooks on the rack are available, all guests come at different time, nobody besides the m guests is visiting Sereja's restaurant tonight.\r\n\r\n-----------------------------------------\r\n\r\nSort all the hook prices.\r\n\r\nCount the number of unhappy guests = max(guests - hooks, 0)\r\n\r\nIt it guests - hooks, if guests is greater and 0 if hooks is greater.\r\n\r\nAll the unhappy guests collect a fine.\r\n\r\n--------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_hooks, fine, no_of_guests;\r\n    scanf(\"%d %d\", &no_of_hooks, &fine);\r\n\r\n    vector <int> hook_prices(no_of_hooks);\r\n    for(int i = 0; i < no_of_hooks; i++)\r\n        scanf(\"%d\", &hook_prices[i]);\r\n\r\n\r\n    sort(all(hook_prices));\r\n\r\n    scanf(\"%d\", &no_of_guests);\r\n\r\n    int unhappy_guests = max(no_of_guests - no_of_hooks, 0);\r\n    int total_fine = unhappy_guests*fine;\r\n\r\n    int no_of_satisfied_guests = no_of_guests - unhappy_guests;\r\n    int income = 0;\r\n    for(int i = 0; i < no_of_satisfied_guests; i++)\r\n        income += hook_prices[i];\r\n\r\n    printf(\"%d\\n\", income - total_fine);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Swap Sort Explanation.txt",
    "content": "In this problem your goal is to sort an array consisting of n integers in at most n swaps. \r\nFor the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.\r\n\r\nNote that in this problem you do not have to minimize the number of swaps  your task is to find any sequence that is no longer than n.\r\n\r\n--------------------------------\r\n\r\nDidn't expect a O(n^2) solution to pass. Took a long time to write it because I suspected there was a better solution.\r\n\r\nBe greedy and perform selection sort. In each iteration place the i-th smallest element at the i-th endex.\r\n\r\nMaintain a vector of pairs to keep track of the indices of the swaps. Don't swap if the element is already at the right position.\r\n\r\n(Although swapping an element with itself in the same index is allowed in this problem)\r\n\r\nIn other words, perform selection sort.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    typedef pair <int, int> pair_int;\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <pair_int> swaps;\r\n    //Selection Sort\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        int min_i_index = i;\r\n        for(int j = i + 1; j < no_of_elements; j++)\r\n        {\r\n            if(element[j] < element[min_i_index])\r\n                min_i_index = j;\r\n        }\r\n\r\n        if(min_i_index != i)\r\n        {\r\n            swaps.push_back(make_pair(i, min_i_index));\r\n\r\n            swap(element[min_i_index], element[i]);\r\n        }\r\n    }\r\n\r\n    printf(\"%u\\n\", swaps.size());\r\n    for(unsigned int i = 0; i < swaps.size(); i++)\r\n    {\r\n        printf(\"%d %d\\n\", swaps[i].first, swaps[i].second);\r\n    }\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Taxi Explanation.txt",
    "content": "Here's the strategy -\r\n\r\nAll the 4s go alone.\r\nThe 3s and 1s are paired up as far as possible. The remaining 3s go alone. \r\n(Note here that after this pairing either the number of 3s or the number of 1s will be 0.)\r\n\r\nThe 2s are paired up together as well as far as possible. If there is a group of 2 remaining (There can only be 0 or 1 remaining group. If there were more, the match and go\r\ntogether), then they are paired up with 2 1s if there are that many 1s.\r\n\r\nThe remaining 1s go in groups of 4. And all the outstanding 1s take another taxi ride.\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_groups;\r\n    scanf(\"%d\", &no_of_groups);\r\n\r\n    int no_of_1s = 0, no_of_2s = 0, no_of_3s = 0, no_of_4s = 0;\r\n    int group_i;\r\n    for(int i = 1; i <= no_of_groups; i++)\r\n    {\r\n        scanf(\"%d\", &group_i);\r\n\r\n        no_of_1s += (group_i == 1);\r\n        no_of_2s += (group_i == 2);\r\n        no_of_3s += (group_i == 3);\r\n        no_of_4s += (group_i == 4);\r\n    }\r\n\r\n    int no_of_rides_with_3_and_1 = min(no_of_3s, no_of_1s);\r\n\r\n    int no_of_rides = no_of_4s + no_of_rides_with_3_and_1 + no_of_2s/2;\r\n\r\n    no_of_3s -= no_of_rides_with_3_and_1;\r\n    no_of_1s -= no_of_rides_with_3_and_1;\r\n    no_of_2s = no_of_2s%2;\r\n\r\n    no_of_rides += no_of_3s; //Pair up as many 3s with 1s and then the remaining 3s go alone.\r\n\r\n    //Pair of 1s with the remaining 2s\r\n    if(no_of_2s > 0)\r\n    {\r\n        no_of_1s -= 2;\r\n        no_of_rides++;\r\n    }\r\n\r\n    if(no_of_1s > 0)\r\n        no_of_rides += no_of_1s/4 + (no_of_1s%4 != 0);\r\n\r\n    printf(\"%d\\n\", no_of_rides);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Toy Cars Explanation.txt",
    "content": "\r\n-------------------------------------------\r\n\r\nIf the i-th row has any collision = 1 or 3, then it means it turned itself over. Otherwise, it never turned itself over.\r\n\r\nint main()\r\n{\r\n    int no_of_cars;\r\n    scanf(\"%d\", &no_of_cars);\r\n\r\n    vector <int> good_cars;\r\n\r\n    for(int i = 1; i <= no_of_cars; i++)\r\n    {\r\n        bool good_car = true;\r\n        for(int j = 1; j <= no_of_cars; j++)\r\n        {\r\n            int collision;\r\n            scanf(\"%d\", &collision);\r\n\r\n            if(collision == 1 || collision == 3)\r\n                good_car = false;\r\n        }\r\n\r\n        if(good_car)\r\n            good_cars.push_back(i);\r\n    }\r\n\r\n    printf(\"%u\\n\",good_cars.size());\r\n    for(unsigned int i = 0; i < good_cars.size(); i++)\r\n        printf(\"%d\\n\", good_cars[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 10/Valera and Plates Explanation.txt",
    "content": "Valera is a lazy student. He has m clean bowls and k clean plates.\r\n\r\nValera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, \r\nhe needs exactly one clean plate or bowl. \r\nWe know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates.\r\n\r\nWhen Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. \r\nSo sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.\r\n\r\n-------------------------------------------\r\n\r\nClean only if there are no clean containers of that kind.\r\n\r\nIf the dish is of type 1, check no of bowls.\r\nIf dish is of type 2, first check if there are any plates, THEN check if there are any bowls.\r\n\r\n-------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_days, no_of_bowls, no_of_plates;\r\n    scanf(\"%d %d %d\", &no_of_days, &no_of_bowls, &no_of_plates);\r\n\r\n    int no_of_cleanings = 0;\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        int dish_type;\r\n        scanf(\"%d\", &dish_type);\r\n\r\n        if(dish_type == 1)\r\n        {\r\n            if(no_of_bowls == 0)\r\n                no_of_cleanings++;\r\n            else\r\n                no_of_bowls--;\r\n        }\r\n\r\n        if(dish_type == 2)\r\n        {\r\n            if(no_of_plates == 0 && no_of_bowls == 0)\r\n                no_of_cleanings++;\r\n            else if(no_of_plates > 0)\r\n                no_of_plates--;\r\n            else\r\n                no_of_bowls--;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_cleanings);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 10/Vanya and Cubes Explanation.txt",
    "content": "\r\n----------------------------------------\r\n\r\nThe i-th floor of this pyramid from the top has T_i cubes.\r\n\r\nKeep subtracting T_i from cubes till it becomes negative ... The floor that makes the number of cubes negative is one less than the number of floors we can have.\r\n\r\n---------------------------------------\r\n\r\nint main()\r\n{\r\n\tint no_of_cubes, height;\r\n\tscanf(\"%d\", &no_of_cubes);\r\n\r\n\tfor(height = 1; ; height++)\r\n\t{\r\n\t\tno_of_cubes -= (height*(height + 1))/2;\r\n\r\n        \tif(no_of_cubes < 0)\r\n            \t\tbreak;\r\n\t}\r\n\r\n\theight--;\r\n\tprintf(\"%d\\n\", height);\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/BerSU Ball Explanation.txt",
    "content": "The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing \r\nwaltz, minuet, polonaise and quadrille moves.\r\n\r\nWe know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.\r\n\r\nFor each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. \r\nWrite a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.\r\n\r\n------------------------------------------------------------\r\n\r\nSort all boys and girls.\r\n\r\nGo through each of the girls, one by one. Binary search for someone of skill g[i] - 1, and then traverse the list till someone of skill at most g[i] + 1\r\nand match to the first available person.\r\n\r\nlower_bound STL binary search function came in handy here.\r\n\r\n---------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_girls;\r\n    scanf(\"%d\", &no_of_girls);\r\n\r\n    vector <int> girl_skills(no_of_girls);\r\n    for(int i = 0; i < no_of_girls; i++)\r\n        scanf(\"%d\", &girl_skills[i]);\r\n\r\n    int no_of_boys;\r\n    scanf(\"%d\", &no_of_boys);\r\n\r\n    vector <int> boy_skills(no_of_boys);\r\n    for(int i = 0; i < no_of_boys; i++)\r\n        scanf(\"%d\", &boy_skills[i]);\r\n\r\n    sort(all(girl_skills));\r\n    sort(all(boy_skills));\r\n\r\n    vector <int> is_available(no_of_boys, true);\r\n\r\n    int no_of_pairs = 0;\r\n    for(int i = 0; i < no_of_girls; i++)\r\n    {\r\n        int eligible_boy = lower_bound(all(boy_skills), girl_skills[i] - 1) - boy_skills.begin();\r\n\r\n        for( ;abs(boy_skills[eligible_boy] - girl_skills[i]) <= 1 && eligible_boy < no_of_boys; eligible_boy++)\r\n        {\r\n            if(is_available[eligible_boy])\r\n            {\r\n                no_of_pairs++;\r\n                is_available[eligible_boy] = false;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_pairs);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Elections Explanation.txt",
    "content": "The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.\r\n\r\nThe electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: \r\nit is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, \r\nthen the winner is the one with a smaller index.\r\n\r\nAt the second stage of elections the winner is determined by the same principle over the cities: \r\nthe winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with \r\na smaller index.\r\n\r\nDetermine who will win the elections.\r\n\r\n------------------------------------\r\n\r\nI misunderstood this question. It isn't the person with the greatest number of total votes. It's the person who won in the most number of cities.\r\n\r\nA tricky test case was when everybody got 0 votes. The winner has to be candidate 1, then.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_candidates, no_of_cities;\r\n    scanf(\"%d %d\", &no_of_candidates, &no_of_cities);\r\n\r\n    vector <int> no_of_wins_for(no_of_candidates + 1, 0);\r\n    for(int city_i = 1; city_i <= no_of_cities; city_i++)\r\n    {\r\n        int round_winner = 1, winner_votes = 0; //If everyone gets 0 votes, the first candidate must win.\r\n\r\n        for(int candidate_i = 1; candidate_i <= no_of_candidates; candidate_i++)\r\n        {\r\n            int votes;\r\n            scanf(\"%d\", &votes);\r\n\r\n            if(votes > winner_votes)\r\n            {\r\n                round_winner = candidate_i;\r\n                winner_votes = votes;\r\n            }\r\n        }\r\n\r\n        no_of_wins_for[round_winner]++;\r\n    }\r\n\r\n    int winner = 0;\r\n    for(int i = 1; i <= no_of_candidates; i++)\r\n        if(no_of_wins_for[i] > no_of_wins_for[winner])\r\n            winner = i;\r\n\r\n    printf(\"%d\\n\", winner);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Football Explanation.txt",
    "content": "Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. \r\nTo simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. \r\nIf there are at least 7 players of some team standing one after another, then the situation is considered dangerous. \r\nFor example, the situation 00100110111111101 is dangerous and 11110111011101 is not. You are given the current situation. Determine whether it is dangerous or not.\r\n\r\n----------------------------------------------\r\n\r\nKeep track of the longest contiguous sequence of identical characters.\r\n\r\nint main()\r\n{\r\n    char players[MAX_LENGTH];\r\n    scanf(\"%s\", players);\r\n\r\n    int maximum_dangerous_sequence = 1, current_dangerous_sequence = 1;\r\n    for(int i = 1; players[i] != '\\0'; i++)\r\n    {\r\n        current_dangerous_sequence = (players[i] == players[i - 1] ? current_dangerous_sequence + 1 : 1);\r\n        maximum_dangerous_sequence = max(maximum_dangerous_sequence, current_dangerous_sequence);\r\n    }\r\n\r\n    printf(maximum_dangerous_sequence >= 7 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Free Cash Alternate Solution Explanation.txt",
    "content": "Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: \r\nthe i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, \r\nbut if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.\r\n\r\nValera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time \r\nthe number of working cashes is no less than the number of clients in the cafe.\r\n\r\nHelp Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.\r\n\r\n-------------------------------------------------\r\n\r\nThis solution takes advanatage of the fact that the times are given in chronological order. This is O(N).\r\n\r\n-----------------------\r\n\r\nint main()\r\n{\r\n    int no_of_customers;\r\n    scanf(\"%d \", &no_of_customers);\r\n\r\n    int hour_i, minute_i, previous_hour = 0, previous_minute = 0;\r\n    int no_of_customers_at_this_time = 0, max_customers_arriving_together = 0;\r\n\r\n    for(int i = 1; i <= no_of_customers; i++)\r\n    {\r\n        scanf(\"%d %d\", &hour_i, &minute_i);\r\n\r\n        no_of_customers_at_this_time = (hour_i == previous_hour && minute_i == previous_minute ? no_of_customers_at_this_time + 1 : 1);\r\n\r\n        max_customers_arriving_together = max(max_customers_arriving_together, no_of_customers_at_this_time);\r\n\r\n        previous_hour = hour_i;\r\n        previous_minute = minute_i;\r\n    }\r\n\r\n    printf(\"%d\\n\", max_customers_arriving_together);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Free Cash Explanation.txt",
    "content": "Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: \r\nthe i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, \r\nbut if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.\r\n\r\nValera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time \r\nthe number of working cashes is no less than the number of clients in the cafe.\r\n\r\nHelp Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.\r\n\r\n-----------------------------------------------\r\n\r\nThe maximum number of customers arriving simulataneously at the same time is the answer. Keep track of the frequency of each arrival time.\r\n\r\nI did this by calculating time in terms of number of minutes from 12.\r\n\r\nThis solution works even if the entries are not in chronological order.\r\nSince they're in chronological order, another way of solving this is to keep track of the longest consecutive sequence of identical elements.\r\n\r\nThat is an O(N) solution ... This is an O(N log N) solution since it involves insertion into a balanced tree.\r\n\r\n---------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    const int NO_OF_MINUTES_IN_HOUR = 60;\r\n    int no_of_customers, no_of_minutes, no_of_hours;\r\n    scanf(\"%d \", &no_of_customers);\r\n\r\n    map <int, int> no_of_customers_arriving_at;\r\n    for(int i = 1; i <= no_of_customers; i++)\r\n    {\r\n        scanf(\"%d %d\", &no_of_hours, &no_of_minutes);\r\n\r\n        int arrival_time = no_of_hours*NO_OF_MINUTES_IN_HOUR + no_of_minutes;\r\n        no_of_customers_arriving_at[arrival_time]++;\r\n    }\r\n\r\n    int max_customers_arriving_together = 0;\r\n    for(map <int, int> :: iterator it = no_of_customers_arriving_at.begin(); it != no_of_customers_arriving_at.end(); it++)\r\n    {\r\n        max_customers_arriving_together = max(max_customers_arriving_together, it->second);\r\n    }\r\n\r\n    printf(\"%d\\n\", max_customers_arriving_together);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Games.txt",
    "content": "Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. \nFor example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. \nWhen a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: \nwhen the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. \nFor each team the color of the home and guest uniform is different.\n\nThere are n teams taking part in the national championship. The championship consists of n·(n - 1) games: each team invites each other team to its stadium. \nAt this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? \nNote that the order of the games does not affect this number.\n\nYou know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have \nthe same number. Help Manao find the answer to his question.\n\n-------------------------------------\n\nFirst of all, no team has the same guest and home uniform.\n\nKeep track of the frequency of each guest uniform.\n\nFor each home uniform h, no_of_changes increses by frequency_guest_uniform[h].\n\nUsed a map to keep track of frequency.\n\n------------------------------\n\nint main()\n{\n    int no_of_teams;\n    scanf(\"%d\", &no_of_teams);\n\n    vector <int> home_uniform(no_of_teams + 1);\n    map <int, int> no_of_guest_uniforms;\n    for(int i = 1; i <= no_of_teams; i++)\n    {\n        int guest_uniform;\n        scanf(\"%d %d\", &home_uniform[i], &guest_uniform);\n\n        no_of_guest_uniforms[guest_uniform]++;\n    }\n\n    int no_of_changes = 0;\n    for(int i = 1; i <= no_of_teams; i++)\n    {\n        no_of_changes += no_of_guest_uniforms[home_uniform[i]];\n    }\n\n    printf(\"%d\\n\", no_of_changes);\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations - 11/Johnny Likes Numbers Explanation.txt",
    "content": "Given n and k, find the next multiple of k after n.\r\n\r\n--------------------------------------------------\r\n\r\nVery simple.   \r\n\r\nnext multiple = n + (k - n%k)\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    int next_multiple = n + (k - n%k);\r\n    printf(\"%d\\n\", next_multiple);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Magic Spheres Explanation.txt",
    "content": "Carl is a beginner magician. He has a blue, b violet and c orange magic spheres. In one move he can transform two spheres of the same color into one sphere of any other color.\r\n To make a spell that has never been seen before, he needs at least x blue, y violet and z orange spheres. Can he get them (possible, in multiple actions)?\r\n\r\n-----------------------------------------------------\r\n\r\nKeep track of the number of spheres you need - this is merely the difference between the required amount and the existing amount or 0, if we already have the required\r\namount and don't need any spheres\r\n\r\n\r\n\r\nKeep track of the number of new spheres possible - this is the difference between existing amount and the required amount divided by 2 or 0 is no new spheres are possible\r\n\r\nUltimately, the trick is possible if the number of new spheres possible is greater than or equal to the number of new spheres required.\r\n\r\n---------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int blue, violet, orange;\r\n    scanf(\"%d %d %d\", &blue, &violet, &orange);\r\n\r\n    int required_blue, required_violet, required_orange;\r\n    scanf(\"%d %d %d\", &required_blue, &required_violet, &required_orange);\r\n\r\n    int no_of_new_spheres_possible = 0, no_of_new_spheres_needed = 0;\r\n\r\n    no_of_new_spheres_needed = max(required_blue - blue, 0) + max(required_orange - orange, 0) + max(required_violet - violet, 0);\r\n\r\n    no_of_new_spheres_possible = max( (blue - required_blue)/2, 0) + max( (orange - required_orange)/2, 0) + max( (violet - required_violet)/2, 0);\r\n\r\n    printf(no_of_new_spheres_possible >= no_of_new_spheres_needed ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/New Year and Hurry Explanation.txt",
    "content": "Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. \r\nThere will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. \r\nLimak knows it will take him 5i minutes to solve the i-th problem.\r\n\r\nLimak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, \r\nwhere he will participate in the contest first.\r\n\r\nHow many problems can Limak solve if he wants to make it to the party?\r\n\r\n--------------------------------------------\r\n\r\nFirst subtract k from total time (4 hours).\r\n\r\nSolve as many problems as you can (either the time is insufficient for the problem or all the problems have been solved).\r\n\r\nGo through the problems with i = 1 to n, Check if time - 5i >= 0, then it can be solved (Solve the problem and then reduce the time)\r\n\r\nI forgot to reduce the time the first time.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int travel_time, no_of_problems;\r\n    scanf(\"%d %d\", &no_of_problems, &travel_time);\r\n\r\n    const int NO_OF_MINUTES_IN_HOUR = 60;\r\n    int time = 4*NO_OF_MINUTES_IN_HOUR;\r\n\r\n    time = time - travel_time;\r\n\r\n    int solved_problems = 0;\r\n\r\n    for(int problem_i = 1; problem_i <= no_of_problems; problem_i++)\r\n    {\r\n        if(time - 5*problem_i >= 0)\r\n        {\r\n            time = time - 5*problem_i;\r\n            solved_problems++;\r\n        }\r\n        else //Time is insufficient\r\n        {\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", solved_problems);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 11/Nicholas and Permutation Explanation.txt",
    "content": "Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.\r\n\r\nNicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. \r\nHe wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. \r\nThe distance between two elements is considered to be equal to the absolute difference between their positions.\r\n\r\n---------------------------------------------\r\n\r\nWe are interested only in the index of 1 and n.\r\n\r\nThere are two strategies to maximise the distance. Place the leftmost index at the first position and then measure (right - 1)\r\n\r\nPlace the rightmost at n and then measure (n - left).\r\n\r\nWe have to take the element closest to the extremum and swap it with it.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int index_1, index_n;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n\r\n        if(element == 1)\r\n            index_1 = i;\r\n        else if(element == n)\r\n            index_n = i;\r\n    }\r\n\r\n    int distance = max( max(index_1, index_n) - 1, n - min(index_1, index_n) );\r\n\r\n    printf(\"%d\\n\", distance);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 11/Petya and Staircases Explanation.txt",
    "content": "Little boy Petya loves stairs very much. But he is bored from simple going up and down them  he loves jumping over several stairs at a time. \r\nAs he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.\r\n\r\n\r\nNow Petya is on the first stair of the staircase, consisting of n stairs. He also knows the numbers of the dirty stairs of this staircase. \r\nHelp Petya find out if he can jump through the entire staircase and reach the last stair number n without touching a dirty stair once.\r\n\r\nOne has to note that anyway Petya should step on the first and last stairs, so if the first or the last stair is dirty, \r\nthen Petya cannot choose a path with clean steps only.\r\n\r\n-----------------------------------------\r\n\r\nPetya can jump across consecutive stairs, skip one stair or two stairs.\r\n\r\nJumping across 3 conseutive stairs is not allowed. Just check if there are any 3 consecutive dirty stairs.\r\n\r\nI tried it with a boolean vector first but I didn't see that there can be 1e9 steps ... so, just sorted the dirty steps.\r\n\r\nAlso check if the first or last stair is dirty. Got a runtime error if there are 0 dirty stairs. That was a tricky case.\r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_steps, no_of_dirty_steps;\r\n    scanf(\"%d %d\", &no_of_steps, &no_of_dirty_steps);\r\n\r\n    vector <int> dirty_steps(no_of_dirty_steps);\r\n    for(int i = 0; i < no_of_dirty_steps; i++)\r\n        scanf(\"%d\", &dirty_steps[i]);\r\n\r\n    sort(all(dirty_steps));\r\n\r\n    bool is_possible = true;\r\n    if(no_of_dirty_steps > 0)\r\n    {\r\n        if(dirty_steps.front() == 1 || dirty_steps.back() == no_of_steps)\r\n        {\r\n            is_possible = false;\r\n        }\r\n        else\r\n        {\r\n            for(int i = 2; i < no_of_dirty_steps; i++)\r\n            {\r\n                if(dirty_steps[i] == dirty_steps[i - 1] + 1 && dirty_steps[i] == dirty_steps[i - 2] + 2) //Three consecutive dirty steps\r\n                {\r\n                    is_possible = false;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n    printf(is_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Playing with Dice Explanation.txt",
    "content": "Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. \r\nThe player whose written number got closer to the number on the dice wins. \r\nIf both payers have the same difference, it's a draw.\r\n\r\nThe first player wrote number a, the second player wrote number b. How many ways to throw a dice are there, at which the first player wins, or there is a draw, \r\nor the second player wins?\r\n\r\n-------------------------------------------\r\n\r\nJust be careful to use abs.\r\n\r\nint main()\r\n{\r\n    int num_1, num_2;\r\n    scanf(\"%d %d\", &num_1, &num_2);\r\n\r\n    int one_wins = 0, draw = 0, two_wins = 0;\r\n    for(int dice_i = 1; dice_i <= 6; dice_i++)\r\n    {\r\n        one_wins += (abs(num_1 - dice_i) < abs(num_2 - dice_i));\r\n        two_wins += (abs(num_1 - dice_i) > abs(num_2 - dice_i));\r\n        draw     += (abs(num_1 - dice_i) == abs(num_2 - dice_i));\r\n    }\r\n\r\n    printf(\"%d %d %d\", one_wins, draw, two_wins);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 11/Saitama Destroys Hotel Explanation.txt",
    "content": "Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. \r\nThe elevator is special  it starts on the top floor, can only move down, and has infinite capacity. \r\nFloors are numbered from 0 to s and elevator initially starts on floor s at time 0.\r\n\r\nThe elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. \r\nGenos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.\r\n\r\n---------------------------------------------------\r\n\r\nSimple implementation. Keep track of the total time you've taken to travel. If the passenger arrival time at any floor is greater than total time, then wait and \r\nadd wait time to total travel time.\r\n\r\nwait = max(passenger arrival - total time, 0)\r\n\r\nYou don't wait if the passenger is already there.\r\n\r\nThis is tricky.\r\n\r\nI chose to use two different vectors instead of a vector of pairs because I couldn't think of a good name to give to this vector that would explain it's purpose.\r\n\r\nThe only trick of this problem is that you must calculate the time take to reach floor 0 from the last stop ... don't stop processing at the last stop.\r\n\r\nSimilar to that problem where a bear watches a football game only if there aren't 15 boring minutes in a row. There I forgot to check that last interval from 90 till last stop\r\n\r\n\r\n----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int  no_of_stops, top_floor;\r\n    scanf(\"%d %d\", &no_of_stops, &top_floor);\r\n\r\n    vector <int> floor_stop(no_of_stops);\r\n    vector <int> passenger_arrival_time(no_of_stops);\r\n    for(int i = 0; i < no_of_stops; i++)\r\n        scanf(\"%d %d\", &floor_stop[i], &passenger_arrival_time[i]);\r\n\r\n    reverse(all(floor_stop));\r\n    reverse(all(passenger_arrival_time));\r\n\r\n    int total_travel_time = 0, current_floor = top_floor;\r\n    for(int i = 0; i < no_of_stops; i++)\r\n    {\r\n        total_travel_time += (current_floor - floor_stop[i]);\r\n\r\n        int wait_time = max(passenger_arrival_time[i] - total_travel_time, 0);\r\n\r\n        total_travel_time += wait_time;\r\n\r\n        current_floor = floor_stop[i];\r\n    }\r\n    total_travel_time += current_floor; //Go to floor 0 from the last floor stop\r\n\r\n    printf(\"%d\\n\", total_travel_time);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Sasha and Sticks Explanation.txt",
    "content": "It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.\r\n\r\nToday he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws n sticks in a row. \r\nAfter that the players take turns crossing out exactly k sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. \r\nIf there are less than k sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. \r\nSasha wants to know the result of the game before playing, you are to help him.\r\n\r\n--------------------------------------------\r\n\r\nIn each turn k sticks are drawn. A win is possible if the number of turns is odd.\r\n\r\nint main()\r\n{\r\n    long long no_of_sticks, one_turn_draw;\r\n    scanf(\"%I64d %I64d\", &no_of_sticks, &one_turn_draw);\r\n\r\n    long long no_of_turns = no_of_sticks/one_turn_draw;\r\n    printf(no_of_turns%2 == 1 ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/Soft Drinking Explanation.txt",
    "content": "This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called \"Take-It-Light\" to warm up a bit. \r\nEach bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt.\r\n\r\nTo make a toast, each friend needs nl milliliters of the drink, a slice of lime and np grams of salt. \r\nThe friends want to make as many toasts as they can, provided they all drink the same amount. How many toasts can each friend make?\r\n\r\n----------------------------------------\r\n\r\nIt should be a striaghtforward problem but I was wondering why amount of salt for one round is a multiple of total amount of salt available.\r\nI saw the example explanation given and realised, np was just another variable name and didn't mean product of n and p.\r\nCould have been clearer.\r\n\r\nFind the amount of drink required for one round and the number of rounds possible with it alone.\r\nFind the amount of limes and the number of rounds possible with them alone\r\nFind the amount of salt available and the number of rounds possible with them alone.\r\n\r\nAnswer is minimum of these three.\r\n\r\n------------------------------------------\r\n\r\n#define min(a, b) (a < b ? a : b)\r\n#define min_3(a, b, c) min(a, min(b, c))\r\n\r\nint main()\r\n{\r\n    int no_of_friends , no_of_bottles, bottle_volume, no_of_limes, no_of_slices, total_salt, one_round_drink, one_round_salt;\r\n    scanf(\"%d %d %d %d\", &no_of_friends, &no_of_bottles, &bottle_volume, &no_of_limes);\r\n    scanf(\"%d %d %d %d\", &no_of_slices, &total_salt, &one_round_drink, &one_round_salt);\r\n\r\n    int no_of_toasts = min_3( (no_of_bottles*bottle_volume)/one_round_drink, no_of_limes*no_of_slices, total_salt/one_round_salt )/no_of_friends;\r\n    printf(\"%d\\n\", no_of_toasts);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 11/The Child and The Homework Explanation.txt",
    "content": "Once upon a time a child got a test consisting of multiple-choice questions as homework. A multiple-choice question consists of four choices: \r\nA, B, C and D. Each choice has a description, and the child should find out the only one that is correct.\r\n\r\nFortunately the child knows how to solve such complicated test. The child will follow the algorithm:\r\n\r\nIf there is some choice whose description at least twice shorter than all other descriptions, or at least twice longer than all other descriptions, \r\nthen the child thinks the choice is great.\r\nIf there is exactly one great choice then the child chooses it. Otherwise the child chooses C (the child think it is the luckiest choice).\r\nYou are given a multiple-choice questions, can you predict child's choose?\r\n\r\n-----------------------------------------------------------\r\n\r\nTo check if a length is less than twice any other length, it is enough to compare the smallest and second smallest element.\r\nLikewise for the longest length.\r\n\r\nBecause only the shortest length can be smaller than twice all other length, and if it isn't twice as small as second smallest, then it's not true,\r\nAnd if it is smaller than second smallest, it will be at least twice as small as every other element.\r\n\r\nUsed a vector of int-char pairs for this one.\r\n\r\nSort it ...\r\n\r\nThe default answer is C\r\n\r\nCheck if there are two options (Then answer is C).\r\n\r\nIf there's only one option, choose it.\r\n\r\nBe careful about the length of the option ... It's len - 2, Because you shouldn't count the alphabet and the dot.\r\n\r\nAlso didn't make the common bug of allocating memory for a vector of pairs and then pushing back (Will only access 0s with that)....\r\n\r\nAnother bug could be while checking twice as small ... Perform multiplication of smallest element, not division of second smallest element.\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    typedef pair <int, char> int_char;\r\n\r\n    char option[MAX_LENGTH];\r\n    vector <int_char> option_length;\r\n\r\n    for(int i = 0; i < 4; i++)\r\n    {\r\n        scanf(\"%s\", option);\r\n        option_length.push_back(make_pair(strlen(option) - 2, 'A' + i)); //Excluding the alphabet and the .\r\n    }\r\n\r\n    sort(all(option_length));\r\n\r\n    char answer = 'C';\r\n    if(2*option_length[0].first <= option_length[1].first && option_length[3].first >= 2*option_length[2].first)//Two options\r\n    {\r\n        answer = 'C';\r\n    }\r\n    else if(2*option_length[0].first <= option_length[1].first)\r\n    {\r\n        answer = option_length[0].second;\r\n    }\r\n    else if(option_length[3].first >= 2*option_length[2].first)\r\n    {\r\n        answer = option_length[3].second;\r\n    }\r\n\r\n    printf(\"%c\\n\", answer);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 11/The New Year Meeting Friends Alternate Solution.txt",
    "content": "There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, \r\nand the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance \r\nthey have to travel in order to meet at some point and celebrate the New Year?\r\n\r\nIt's guaranteed that the optimal answer is always integer.\r\n\r\n---------------------------------------------------------------------\r\n\r\nThere is an elegant proof similar to proofs of medians of points.\r\n\r\nLet us suppose they meet at a point x in between the left most and right most.\r\n\r\nNow, regardless of the position of x, left most person must travel x units and right most must travel (d - x) units, where d is the distance from rightmost to leftmost\r\n\r\nd = rightmost - leftmost\r\n\r\nWherever x is, the two corner most people must meet. And they will always travel (x + d - x) = d distance.\r\n\r\nThe third friend must also go the meeting point x.\r\n\r\nDistance = d + |x - middle|\r\n\r\nThe travelling of d distance is fixed, however we can minimise the second summand and make it 0.\r\n\r\nThe distance travelled is minimum when the two corner most friends meet at the location of the middle friend.\r\n\r\nAnd the distance travelled is d.\r\n\r\n------------------------------------------------------\r\n\r\n#define min_3(a, b, c) min(a, min(b, c))\r\n#define max_3(a, b, c) max(a, max(b, c))\r\n\r\nint main()\r\n{\r\n    int location_1, location_2, location_3;\r\n    scanf(\"%d %d %d\", &location_1, &location_2, &location_3);\r\n\r\n    int leftmost  = min_3(location_1, location_2, location_3);\r\n    int rightmost = max_3(location_1, location_2, location_3);\r\n\r\n    printf(\"%d\\n\", rightmost - leftmost);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 11/The New Year Meeting Friends Explanation.txt",
    "content": "There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, \r\nand the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance \r\nthey have to travel in order to meet at some point and celebrate the New Year?\r\n\r\nIt's guaranteed that the optimal answer is always integer.\r\n---------------------------------------------------\r\n\r\nThe constraints were pretty small here so I decided to iterate in between every integer from leftmost to rightmost.\r\n\r\nThere's a better solution though ... Answer is always rightmost-leftmost.\r\n\r\nI put the proof in the other solution\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    const int no_of_friends = 3;\r\n    vector <int> location(no_of_friends);\r\n    scanf(\"%d %d %d\", &location[0], &location[1], &location[2]);\r\n\r\n    sort(all(location));\r\n\r\n    int minimum_distance = 300;\r\n    for(int meet_point = location[0]; meet_point <= location[2]; meet_point++)\r\n    {\r\n        int distance = abs(meet_point - location[0]) + abs(meet_point - location[1]) + abs(meet_point - location[2]);\r\n\r\n        minimum_distance = min(minimum_distance, distance);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_distance);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 11/Word Explanation.txt",
    "content": "Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. \r\nThat's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of \r\nlowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. \r\nFor example, the word HoUse must be replaced with house, and the word ViP  with VIP. If a word contains an equal number of uppercase and lowercase letters, \r\nyou should replace all the letters with lowercase ones. \r\nFor example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.\r\n\r\n-------------------------------------\r\n\r\nSimple implementation.\r\n\r\nint main()\r\n{\r\n    char word[MAX_LENGTH];\r\n    scanf(\"%s\", word);\r\n\r\n    int i, no_of_capitals = 0, no_of_lower_case = 0, length;\r\n    for(i = 0; word[i] != '\\0'; i++)\r\n    {\r\n        no_of_capitals += is_capital(word[i]) ;\r\n    }\r\n    length = i;\r\n    no_of_lower_case = (length - no_of_capitals);\r\n\r\n    if(no_of_lower_case >= no_of_capitals)\r\n    {\r\n        for(i = 0; word[i] != '\\0'; i++)\r\n        {\r\n            putchar(lower_case(word[i]));\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for(int i = 0; i < length; i++)\r\n        {\r\n            putchar(capital(word[i]));\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 2/A and B Chess - Explanation.txt",
    "content": "A and B are preparing themselves for programming contests.\r\n\r\nTo train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.\r\n\r\nFor each chess piece we know its weight:\r\n\r\nthe queen's weight is 9,\r\nthe rook's weight is 5,\r\nthe bishop's weight is 3,\r\nthe knight's weight is 3,\r\nthe pawn's weight is 1,\r\nthe king's weight isn't considered in evaluating position.\r\nThe player's weight equals to the sum of weights of all his pieces on the board.\r\n\r\nAs A doesn't like counting, he asked you to help him determine which player has the larger position weight.\r\n\r\nInput\r\nThe input contains eight lines, eight characters each  the board's description.\r\n\r\nThe white pieces on the board are marked with uppercase letters, the black pieces are marked with lowercase letters.\r\n\r\nThe white pieces are denoted as follows: the queen is represented is 'Q', the rook  as 'R', the bishop  as'B', the knight  as 'N', the pawn  as 'P', the king  as 'K'.\r\n\r\nThe black pieces are denoted as 'q', 'r', 'b', 'n', 'p', 'k', respectively.\r\n\r\nAn empty square of the board is marked as '.' (a dot).\r\n\r\nIt is not guaranteed that the given chess position can be achieved in a real game. \r\nSpecifically, there can be an arbitrary (possibly zero) number pieces of each type, the king may be under attack and so on.\r\n\r\nOutput\r\nPrint \"White\" (without quotes) if the weight of the position of the white pieces is more than the weight of the position of the black pieces, \r\nprint \"Black\" if the weight of the black pieces is more than the weight of the white pieces and print \"Draw\" if the weights of the white and black pieces are equal.\r\n\r\n-----------------------------------------------------------------------------------------------------\r\n\r\nStore the board as an array of 8 strings with each row of the board as one string.\r\n \r\nScan through the board. If you get a piece, check the colour of the piece and add the weight of the piece to the strength of the colour.\r\n\r\nCompare the strengths of the two colours at the end and print the appropriate message."
  },
  {
    "path": "Explanations/Explanations - 2/Chat Room - Explanation.txt",
    "content": "Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. \r\nVasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word \"hello\".\r\nFor example, if Vasya types the word \"ahhellllloou\", it will be considered that he said hello, and if he types \"hlelo\", \r\nit will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word s.\r\n\r\nInput\r\nThe first and only line contains the word s, which Vasya typed. This word consisits of small Latin letters, its length is no less that 1 and no more than 100 letters.\r\n\r\nOutput\r\nIf Vasya managed to say hello, print \"YES\", otherwise print \"NO\".\r\n\r\n--------------------------------------------------------------------\r\n\r\nGo through the message and search for hello characters sequentially.\r\n\r\nFind an h first, and then look for an e, and then look for an l and so on. If you find all five, you've found the message.\r\nIf the message is over and all characters have not been found, then display NO."
  },
  {
    "path": "Explanations/Explanations - 2/Word Capitalisation - Explanation.txt",
    "content": "Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.\r\n\r\nNote, that during capitalization all the letters except the first one remains unchanged.\r\n\r\nInput\r\nA single line contains a non-empty word. This word consists of lowercase and uppercase English letters. The length of the word will not exceed 103.\r\n\r\nOutput\r\nOutput the given word after capitalization.\r\n\r\n----------------------------------------------------------------------------------\r\n\r\nCheck if the first alphabet of the given word is a small letter.\r\n\r\nIf it is, subtract the ASCII value of ('a' - 'A'). In ASCII, the value of capitals is less than small letters. So, simply offset the first alphabet by the required value."
  },
  {
    "path": "Explanations/Explanations - 3/Checking the Calendar - Expanation.txt",
    "content": "You are given names of two days of the week.\r\n\r\nPlease, determine whether it is possible that during some non-leap year the first day of some month was equal to the first day of the week you are given, \r\nwhile the first day of the next month was equal to the second day of the week you are given. Both months should belong to one year.\r\n\r\nIn this problem, we consider the Gregorian calendar to be used. The number of months in this calendar is equal to 12. \r\nThe number of days in months during any non-leap year is: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31.\r\n\r\nNames of the days of the week are given with lowercase English letters: \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\".\r\n\r\nInput\r\nThe input consists of two lines, each of them containing the name of exactly one day of the week. \r\nIt's guaranteed that each string in the input is from the set \"monday\", \"tuesday\", \"wednesday\", \"thursday\", \"friday\", \"saturday\", \"sunday\".\r\n\r\nOutput\r\nPrint \"YES\" (without quotes) if such situation is possible during some non-leap year. Otherwise, print \"NO\" (without quotes).\r\n\r\n-------------------------------------------------------------------------------------------\r\n\r\nLet a month begin on day 1 and have x days. x = 7q + r, r is a number less than 7. The day 7q + 1 will have the same day of the week as the first day\r\nThe next month begins at day r + 1. The difference in between 1(mod 7) and the allowable values of (r + 1) give us the answer.\r\n    \r\nAll days of a week get a number assigned to them from 1 - 7 in the order they appear in the week. We only consider the (day2 - day1) mod 7.\r\nHowever, we don't want negative values, so (2-5) mod 7 should be 4 not -3. So, for computer implementation, write (day2 - day1 + 7) mod 7.\r\n\r\n1.If the month has 31 days, then 31 = 4(7) + 3. The first day is on 1(mod 7). The next month's first day is on 4(mod 7). So, difference of 3 is allowed\r\n 2.IF the month has 30 = 4(7) + 2. A difference of 2 is allowed\r\n3. If the month has 28 = 7(4) days. Both the first days are on 1(mod 7) so a difference of 0 is allowed."
  },
  {
    "path": "Explanations/Explanations - 3/Die Roll - Explanation.txt",
    "content": "Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. \r\nYakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. \r\nDot chose Transylvania as the most mysterious and unpredictable place.\r\n\r\nBut to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. \r\nThat's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, \r\nand the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.\r\n\r\nYakko thrown a die and got Y points, Wakko  W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.\r\n\r\nIt is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.\r\n\r\nInput\r\nThe only line of the input file contains two natural numbers Y and W  the results of Yakko's and Wakko's die rolls.\r\n\r\nOutput\r\nOutput the required probability in the form of irreducible fraction in format A/B, where A  the numerator, and B  the denominator. \r\nIf the required probability equals to zero, output 0/1. If the required probability equals to 1, output 1/1.\r\n\r\n--------------------------------------------------------------------------------------------\r\n\r\nDot wins in all cases where she gets a score >= max{Y, W}\r\n\r\nSo, Dot_wins = 6 - max{Y,W} + 1 {+1 because she wins if she equalises. If she hits the maxima, she wins}"
  },
  {
    "path": "Explanations/Explanations - 4/Chewbecca and Number - Explanation.txt",
    "content": "Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. \r\nInverting digit t means replacing it with digit 9?-?t.\r\n\r\nHelp Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. \r\nThe decimal representation of the final number shouldn't start with a zero.\r\n\r\nInput\r\nThe first line contains a single integer x (1?=?x?=?10^{18})  the number that Luke Skywalker gave to Chewbacca.\r\n\r\nOutput\r\nPrint the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.\r\n\r\n-----------------------------------------------------------------\r\n\r\nAll digits from 5-9 have to be inverted. Everything else is untouched.\r\nThe first digit shouldn't be inverted if it's a 9 since leading 0s aren't allowed."
  },
  {
    "path": "Explanations/Explanations - 4/King Moves - Explanation.txt",
    "content": "The only king stands on the standard chess board. You are given his position in format \"cd\", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. \r\nFind the number of moves permitted for the king.\r\n\r\nKing moves from the position e4\r\nInput\r\nThe only line contains the king's position in the format \"cd\", where 'c' is the column from 'a' to 'h' and 'd' is the row from '1' to '8'.\r\n\r\nOutput\r\nPrint the only integer x  the number of moves permitted for the king.\r\n\r\n---------------------------------------------------------------------------------------------\r\n\r\nCase 1 : King is at a corner piece [a/h][1/8] - There are 3 legal moves in these squares.\r\nCase 2 : King is at the last row or column [a/h][2-7] or [b-g][1/8] - There are 5 legal moves in these squares.\r\nCase 3 : King is anywhere else - 8 legal moves in these squares."
  },
  {
    "path": "Explanations/Explanations - 4/Lineland Mail - Explanation.txt",
    "content": "﻿All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. \r\nNo two cities are located at a single point.\r\n\r\nLineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city \r\n(because if they live in the same city, then it is easier to drop in).\r\n\r\nStrange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.\r\n\r\nFor each city calculate two values ​​mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, \r\nand maxi is the the maximum cost of sending a letter from the i-th city to some other city\r\n\r\nInput\r\nThe first line of the input contains integer n (2 ≤ n ≤ 10^5) — the number of cities in Lineland. \r\nThe second line contains the sequence of n distinct integers x1, x2, ..., xn ( - 10^9 ≤ xi ≤ 10^9), where xi is the x-coordinate of the i-th city. \r\nAll the xi's are distinct and follow in ascending order.\r\n\r\nOutput\r\nPrint n lines, the i-th line must contain two integers mini, maxi, separated by a space, where mini is the minimum cost of sending a letter from the i-th city, \r\nand maxi is the maximum cost of sending a letter from the i-th city.\r\n\r\n------------------------------------------------------------------------------------------------------------------\r\n\r\nThe cities are given in ascending order.\r\n\r\nMinimum - \r\n\tThe minimum distance city is one of the adjacent cities. \r\n\tMin[i] = min{C[i] - C[i-1], C[i+1] - C[i]}\r\n\tThe first and last city have only one adjacent city so we need to write Min[1] = C[2]-C[1] and Min[n] = C[n]-C[n-1] and not use the loop condition to avoid di\r\n\tout of bound access\r\n\r\nMaximum - \r\n\tThe maximum distance is either the first city or the last city. \r\n\tMax[i] = max{C[i] - C[0], C[n] - C[i]}\r\n"
  },
  {
    "path": "Explanations/Explanations - 4/Random Teams- Explanation.txt",
    "content": "\r\n---------------------------------------------------------------------------------------------------------------------------------\r\n\r\nConsider a set of teams t_1, t_2, ... , t_m with number of people p_1, p_2, .... , p_m.\r\n\r\nWe describe a procedure for increasing the number of friendships in an arrangement, given an arrangement. \r\n\r\nCase 1 : There is a single team which has more number of people than any other team. \r\n\r\nWithout loss of generality, let the team with maximum number of people be t_1. It has p_1 people.\r\n\r\nChoose any other team, say t_2. \r\n\r\nLet F denote the total number of friendships. Then, F = F - (p_2 - 1) + p_1 = F + (p_1 - p_2 + 1)\r\nSince p_1 is the maximum number of people, p_1 - p_2 > 0. This means that the total number of friendships increases by atleast one by performing this procedure.\r\n\r\nCase 2: There are multiple teams which have the maximum number of people.\r\nWe select any two of them and transfer one person from one team to another. The number of friendships increases by 1.\r\nThe team we have transfered the person to now has more people than any other team. We now have a single maxima and it is reduced to the first case.\r\n\r\n--------------------------------------------------------------------------\r\n\r\nWe can no longer perform this procedure when every team other than t_1 has only 1 person i.e. when all teams from t_2 to t_m have 1 person only \r\nand t_1 has (n - (m - 1) ) people. The number of friendships in any other arrangement can be increased. This cannot. \r\n\r\nTherefore, this is the configuration with the maximum number of friendships.\r\n\r\nMaximum number of friendships = (n - (m-1) ) C (2) = (n-m+1)(n-m)/2\r\n\r\n--------------------------------------------------------------------------------------\r\n\r\nNow, consider a procedure for reducing the number of friendships in an arrangement.\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 4/Tetrahedron - Explanation.txt",
    "content": "﻿You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.\r\n\r\n\r\nAn ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. \r\nAt each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.\r\n\r\nYou do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. \r\nIn other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. \r\nAs the number can be quite large, you should print it modulo 1000000007 (10^9 + 7).\r\n\r\nInput\r\nThe first line contains the only integer n (1 ≤ n ≤ 10^7) — the required length of the cyclic path.\r\n\r\nOutput\r\nPrint the only integer — the required number of ways modulo 1000000007 (10^9 + 7).\r\n\r\n-------------------------------------------------------------------------------------------\r\n\r\nHere, D is the only vertex that is different from the others. A, B and C are indistinguishable in the sense that they all share one edge with the destination and \r\ntwo edges with the non-destinations.\r\n\r\nLet f(n, X) be the number of ways to reach the destination D from vertex 'X' if there are n moves left and the ant is currently on 'X'.\r\n\r\nf(0, D) = 1 {Because we are already at the destination}\r\nf(0, A/B/C) = 0 {Because we aren't at the destination}\r\n\r\nThis is the reason they are two different cases \r\nFrom a given vertex, the ant can make 3 moves. \r\n\r\nCase 1 : If the ant is on vertex D, then he can move to either vertex A, B or C.\r\n\r\nf(n, D) = 3 f(n-1, D)\r\n\r\nCase 2 : If the ant is on A, B or C, then he can move to either the destination or one of it's other two non-destination neighbours.\r\n\r\nf(n, A/B/C) = f(n-1, D) + 2(n-1, A/B/C)\r\n\r\nSince, the pointer notation would make it hard to read and to evaluate f(n, X) we only need f(n - 1, X), we don't need to store the value in a table. \r\nWe can get away with auxiliary variables storing f(n-1, D) and f(n-1, A/B/C). This improves readability and space consumed. \r\n\r\nf(n, D) is the answer since the ant originally starts from D. \r\n"
  },
  {
    "path": "Explanations/Explanations - 5/Star - Explanation.txt",
    "content": "Print the n-th star number.\r\n\r\nIt consists of a central number and 12 copies of the (n-1)th triangular number. S_n = 6n(n-1) + 1"
  },
  {
    "path": "Explanations/Explanations - 6/A Shell Game - Explanation.txt",
    "content": "Today the Z city residents enjoy a shell game competition. The residents are gathered on the main square to watch the breath-taking performance. \r\nThe performer puts 3 non-transparent cups upside down in a row. Then he openly puts a small ball under one of the cups and starts to shuffle the cups around very quickly so \r\nthat on the whole he makes exactly 3 shuffles. After that the spectators have exactly one attempt to guess in which cup they think the ball is and if the answer is correct\r\n they get a prize. Maybe you can try to find the ball too?\r\n\r\nInput\r\nThe first input line contains an integer from 1 to 3  index of the cup which covers the ball before the shuffles. \r\nThe following three lines describe the shuffles. Each description of a shuffle contains two distinct integers from 1 to 3  indexes of the cups which the performer shuffled \r\nthis time. The cups are numbered from left to right and are renumbered after each shuffle from left to right again. \r\nIn other words, the cup on the left always has index 1, the one in the middle  index 2 and the one on the right  index 3.\r\n\r\nOutput\r\nIn the first line output an integer from 1 to 3  index of the cup which will have the ball after all the shuffles.\r\n\r\n-----------------------------------------------------------------------------------------\r\n\r\nThis problem was interesting because of the way input and output had to be given - files. \r\nI had to use a filepointer to open a file in read mode and another in write mode. Read and write into them. And then close the file at the end of the program.\r\nHowever, I didn't do error control (what happens in case the file pointer is NULL).\r\n\r\nSimple simulation suffices.\r\n\r\nfor(i = 1; i <= NO_OF_SHUFFLES; i++)\r\n    {\r\n        fscanf(input,\"%d %d\",&shell_1, &shell_2);\r\n        if(ball_shell == shell_1)\r\n        {\r\n            ball_shell =  shell_2;\r\n        }\r\n        else if(ball_shell == shell_2)\r\n        {\r\n            ball_shell = shell_1;\r\n        }\r\n    }\r\n"
  },
  {
    "path": "Explanations/Explanations - 7/An Abandoned Sentiment From The Past - Explanation.txt",
    "content": "A few years ago, Hitagi encountered a giant crab, who stole the whole of her body weight. \r\nEver since, she tried to avoid contact with others, for fear that this secret might be noticed.\r\n\r\nTo get rid of the oddity and recover her weight, a special integer sequence is needed. Hitagi's sequence has been broken for a long time, \r\nbut now Kaiki provides an opportunity.\r\n\r\nHitagi's sequence a has a length of n. Lost elements in it are denoted by zeros. Kaiki provides another sequence b, whose length k equals the number of lost elements in a \r\n(i.e. the number of zeros). Hitagi is to replace each zero in a with an element from b so that each element in b should be used exactly once. \r\nHitagi knows, however, that, apart from 0, no integer occurs in a and b more than once in total.\r\n\r\nIf the resulting sequence is not an increasing sequence, then it has the power to recover Hitagi from the oddity. \r\nYou are to determine whether this is possible, or Kaiki's sequence is just another fake. \r\nIn other words, you should detect whether it is possible to replace each zero in a with an integer from b so that each integer from b is used exactly once, \r\nand the resulting sequence is not increasing.\r\n\r\n\r\n---------------------------------------------------------------------------------------------\r\n\r\nFirstly, notice that if there was more than one zero, we can always make the sequence non-increasing by plugging in the values of b in any non-increasing order into a.\r\n\r\nThe only case we need to check is when there is one 0. In that case, check if the number from b is non-increasing with respect to it's \r\nexisting neighbours(1 or 2, depending on the position of the 0). \r\n\r\nAlso, check if any non-zero element of a is smaller than or equal to it's predecessor while reading input. \r\nIt is possible for the replaced element to be in order with it's neighbours, but out of order with some other element. \r\n\r\nFor example, let m be place in between u and v. u < m < v.\r\nIf there is some element k to the left of u, out of order with m, such that, k > m, then k > u as well.\r\nIf there is some element k to the right of v out of order with m, such that, k < m, then k < v as well.\r\nThat is why the elements of a need to be checked while reading the input.\r\n\r\n---------------------------------------------\r\n\r\n    for(i = 0; i < entire_length; i++)\r\n    {\r\n        scanf(\"%d\", &a[i]);\r\n\r\n        if(a[i] == 0)\r\n            zero_index = i;\r\n        else if(i > 0 && a[i] <= a[i - 1])\r\n            is_possible = true;\r\n\r\n    }\r\n    for(i = 0; i < no_of_zeroes; i++)     Only the case where no of missing zeroes is 1 is interesting, so we don't use an array.\r\n        scanf(\"%d\",&missing_number);\r\n\r\n---------------------------------\r\n\r\n    if(no_of_zeroes > 1)\r\n    {\r\n        is_possible = true;\r\n    }\r\n    else\r\n    {\r\n        if(zero_index == 0)\r\n        {\r\n            if(missing_number >= a[zero_index + 1])\r\n                is_possible = true;\r\n        }\r\n        else if(zero_index == entire_length - 1)\r\n        {\r\n            if(missing_number <= a[zero_index - 1])\r\n                is_possible = true;\r\n        }\r\n        else if(missing_number >= a[zero_index + 1] || missing_number <= a[zero_index - 1])\r\n        {\r\n            is_possible = true;\r\n        }\r\n    }\r\n-----------"
  },
  {
    "path": "Explanations/Explanations - 7/Combination Lock Explanation.txt",
    "content": "The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. \r\nScrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. \r\nIn one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa.\r\n\r\n-------------------------------------------------------------------------------------\r\n\r\n What minimum number of actions does he need for that?On each turn check if it's optimal to go forwards or backwards ... Going backwards is simple b-a, forwards is (10 + a) - b because we need to cross 'a' locks after '0'\r\n\r\n-------------------------------------------------\r\n\r\n    for(int i = 0; i < number_of_locks; i++)\r\n    {\r\n        int start, ending;\r\n        start = min(current_state[i], final_state[i]) - '0';\r\n        ending = max(current_state[i], final_state[i]) - '0';\r\n\r\n        number_of_moves += min(ending - start,  10 + start - ending); //Optimal to go forwards or backwards\r\n    }"
  },
  {
    "path": "Explanations/Explanations - 7/Find Marble - Explanation.txt",
    "content": "Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right.\r\n Note that the positions are indexed but the glasses are not.\r\n\r\nFirst Petya puts a marble under the glass in position s. Then he performs some (possibly zero) shuffling operations. \r\nOne shuffling operation means moving the glass from the first position to position p1, the glass from the second position to position p2 and so on. \r\nThat is, a glass goes from position i to position pi. \r\nConsider all glasses are moving simultaneously during one shuffling operation. \r\nWhen the glasses are shuffled, the marble doesn't travel from one glass to another: it moves together with the glass it was initially been put in.\r\n\r\nAfter all shuffling operations Petya shows Vasya that the ball has moved to position t. Vasya's task is to say what minimum number of shuffling operations \r\nPetya has performed or determine that Petya has made a mistake and the marble could not have got from position s to position t.\r\n\r\n-------------------------------------------------------------------------------------------------------------------------------------\r\n\r\nWe keep going from i to p[i] till we reach t or detect a cycle before it. \r\n\r\nSince no location is visited by two glasses, we only need to check if we reach s at some point.\r\nSo, s-> u-> v -> t\r\n\r\nSince s visits u, no other glass visits u. Since u visits v, no other glass visits v. So, if there is a cycle if must end only at s.\r\nOtherwise we would need to maintain a boolean vector with each element to keep track of whether or not we have visited it.\r\n \r\n------------------------------\r\n\r\n    for(i = initial_position; ; i = *(shuffled_result + i), minimum_shuffles++)\r\n        if( (i == initial_position && minimum_shuffles!= 0) || (i == final_position) )\r\n            break;\r\n\r\n    printf(\"%d\\n\", (i == final_position ?  minimum_shuffles : -1) );\r\n\r\n-------------------------------------------\r\n\r\nWe need to check that minimum shuffles is not 0 when i = initial position because it is always true in the starting iteration.\r\nAnother way of doing it. \r\n\r\n    do\r\n    {\r\n        if(i == final_position)\r\n            break;\r\n\r\n        i = *(shuffled_result + i);\r\n        minimum_shuffles++;\r\n    }\r\n    while(i != initial_position);"
  },
  {
    "path": "Explanations/Explanations - 7/Free Ice Cream Explanation.txt",
    "content": "After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.\r\n\r\nAt the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. \r\nEach person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda \r\n(carriers that bring ice cream have to stand in the same queue).\r\n\r\nIf a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, \r\nthen Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.\r\n\r\nKay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.\r\n\r\n------------------------------------------------------\r\n\r\nSimple implementation.\r\n\r\nKeep track of the number of packets and how many requests are unsatisfied.\r\nMissed the fact that overflow can occur the first time.\r\n\r\nfor(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        char action;\r\n        int amount;\r\n        scanf(\" %c %d\", &action, &amount);\r\n\r\n        if(action == '+')\r\n            ice_cream += amount;\r\n        else\r\n            if(amount > ice_cream)\r\n                distressed_kids++;\r\n            else\r\n                ice_cream -= amount;\r\n    }\r\n    printf(\"%I64d %d\\n\", ice_cream, distressed_kids);"
  },
  {
    "path": "Explanations/Explanations - 7/Hexadecimal's Theorem Alternate Solution Explanation.txt",
    "content": "Express a Fibonacci number as the sum of three not necissarily distinct Fibonacci numbers ...\r\n\r\n-------------------------------------------------------\r\n\r\nn = 0 + 0 + n, n and 0 are all Fibonacci numbers and we are done !\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    printf(\"0 0 %d\\n\", n);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 7/Hexadecimal's Theorem Explanation.txt",
    "content": "Express a Fibonacci number as the sum of three not necissarily distinct Fibonacci numbers ...\r\n\r\n---------------------------------------------------\r\n\r\nF(n) = F(n - 1) + F(n - 2) = F(n - 1) + F(n - 3) + F(n - 4) \r\n\r\nSo, I precomputed the list of all Fibonacci numbers, handled the case up to n = 3 manually and then used the above recurrence to get the answer.\r\n\r\n-------------------------------------------------------------------\r\n\r\nvoid precompute_fibonacci()\r\n{\r\n    const int MAX = 1e9;\r\n\r\n    fibonacci.push_back(0);\r\n    fibonacci.push_back(1);\r\n\r\n    for(int i = 2; fibonacci[i - 1] + fibonacci[i - 2] <= MAX; i++)\r\n        fibonacci.push_back(fibonacci[i - 1] + fibonacci[i - 2]);\r\n}\r\n\r\n------------------------------\r\n\r\nprecompute_fibonacci();\r\n\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    if(n == 0) //F(0)\r\n        printf(\"0 0 0\\n\");\r\n    else if(n == 1)//F(1) and F(2)\r\n        printf(\"1 0 0\\n\");\r\n    else if(n == 2) //F(3)\r\n        printf(\"1 1 0\\n\");\r\n    else\r\n    {\r\n        int index = 4;\r\n\r\n        while(fibonacci[index] != n)\r\n         index++;\r\n\r\n        printf(\"%d %d %d\\n\",fibonacci[index - 1], fibonacci[index - 3], fibonacci[index - 4]);\r\n    }\r\n\r\n----------------------------------------------------------\r\n\r\nGood use of the recurrence but there is a much simpler solution  ! \r\nn = 0 + 0 + n, n and 0 are all Fibonacci numbers and we are done !"
  },
  {
    "path": "Explanations/Explanations - 7/Mahmod and Longest Uncommon Subsequence - Explanation.txt",
    "content": "While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. \r\nThey solved it, and then Ehab challenged Mahmoud with another problem.\r\n\r\nGiven two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and\r\n not a subsequence of the other.\r\n\r\nA subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, \r\nfor example, strings \"ac\", \"bc\", \"abc\" and \"a\" are subsequences of string \"abc\" while strings \"abbc\" and \"acb\" are not. \r\nThe empty string is a subsequence of any string. Any string is a subsequence of itself.\r\n\r\n-------------------------------------------------------------------------------------------------\r\n\r\nIf the strings are not equal, then the longest uncommon subsequence is the larger string.\r\nIf they are equal, there is no uncommon subsequence.\r\n\r\nprintf(\"%d\\n\", (strcmp(string_1, string_2) != 0 ? max( strlen(string_1),strlen(string_2) ) : -1) );"
  },
  {
    "path": "Explanations/Explanations - 7/Optimal Point on a Line - Explanation.txt",
    "content": "You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.\r\n\r\n-----------------------------------------------------------------------\r\n\r\nThe median minimises the distance. \r\n\r\nIf there is a sorted list of n elements, x1 x2 ... xn, then the element at position n/2 is the median. \r\n\r\nLet us prove that the median has the least distance to all the points. \r\n\r\nCase 1: n is even,\r\n\r\nIf there are two points x1, and x2, the answer is one of these points. \r\n\r\n(|xn - x| + |x1 - x|) + (|x(n-1) - x| + |x2 - x|) + ... + (|x(n/2) - x|  + |x(n/2+1) - x)|)\r\n\r\nThe point that minimises this distance must lie inside each of these intervals. The two medians satisfy this property.\r\n\r\nCase 2: n is odd.\r\n\r\nLet there be 3 elements - x1, x2 and x3. Here, the minimum sum of distances from one point to the other 2 is by x2. \r\n\r\nAs we add pairs of points to this set - one at the extreme right and one at the extreme left. By the same logic, if there are 2n + 1 points, and we split it into \r\nn pairs and xm, where xm is the median, xm is the only point that lies inside every interval. So, it minimises the distance.\r\n\r\n-------------------------------\r\n\r\n    sort(points, points + no_of_points);\r\n    median = points[(no_of_points - 1)/2];\r\n\r\n-----------------------\r\n\r\nArray is indexed from 0. So, we consider (n-1)/2 Instead of n/2 since the last element is (n-1)"
  },
  {
    "path": "Explanations/Explanations - 7/Pashmak and Flowers - Explanation.txt",
    "content": "Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. \r\nParmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. \r\nShe wants to have those pairs of flowers that their beauty difference is maximal possible!\r\n\r\nYour task is to write a program which calculates two things:\r\n\r\nThe maximum beauty difference of flowers that Pashmak can give to Parmida.\r\nThe number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and \r\nnot chosen in the second way.\r\n\r\n---------------------------------------------------------------------------------------------\r\n\r\nWe need to count the number of maxima and the number of minima and multiply them. I had overlooked overflow at first in multiplication and the case where the \r\nmaxima and minima are equal. In that case, the answer is n(n-1)/2, where n is the number of flowers because all flowers are equally beautiful. Multiplying number of minima \r\nand maxima will not be correct in that case since it will be overcounting pairs.\r\n\r\n    for(i = 1; i <= no_of_flowers; i++)\r\n    {\r\n        scanf(\"%d\",&current_beauty);\r\n\r\n        if(current_beauty == most_beautiful)\r\n            no_of_maxima++;\r\n\r\n        if(current_beauty == least_beautiful)\r\n            no_of_minima++;\r\n\r\n        if(current_beauty < least_beautiful)\r\n            least_beautiful = current_beauty, no_of_minima = 1;\r\n\r\n        if(current_beauty > most_beautiful)\r\n            most_beautiful = current_beauty, no_of_maxima = 1;\r\n    }\r\n\r\n    //If all flowers are equally beautiful, then choices = n(n-1)/2\r\n    no_of_choices = ( most_beautiful == least_beautiful ? (no_of_flowers*1LL*(no_of_flowers - 1) )/2 : no_of_minima*1LL*no_of_maxima );\r\n\r\n    printf(\"%d %I64d\\n\",(most_beautiful - least_beautiful), no_of_choices);\r\n\r\n--------------------------------------------------------------------------------------------------\r\n\r\nNote - type casting by multiplying by 1LL is necessary to avoid overflow, otherwise 32 bit multiplication will be performed."
  },
  {
    "path": "Explanations/Explanations - 7/Young Physicist - Explanation.txt",
    "content": "A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. \r\nAnd, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. \r\nNext day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: \r\nYou are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). \r\nVasya had only to answer whether it is in equilibrium. \"Piece of cake\"  thought Vasya, we need only to check if the sum of all vectors is equal to 0. \r\nSo, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. \r\nHelp him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.\r\n\r\n---------------------------------------------------------------------------------\r\n\r\n    for(i = 1; i <= no_of_vectors; i++)\r\n    {\r\n        scanf(\"%d %d %d\",&x, &y, &z);\r\n        total_x += x;\r\n        total_y += y;\r\n        total_z += z;\r\n    }\r\n\r\n    printf(total_x == 0 && total_y == 0 && total_z == 0 ? \"YES\\n\" : \"NO\\n\");"
  },
  {
    "path": "Explanations/Explanations - 8/A and B Team Training Explanation.txt",
    "content": "A and B are preparing themselves for programming contests.\r\n\r\nAn important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. \r\nTherefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.\r\n\r\nA believes that the optimal team of three people should consist of one experienced participant and two newbies. \r\nThus, each experienced participant can share the experience with a large number of people.\r\n\r\nHowever, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.\r\n\r\nAs a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. \r\nFurthermore, they agree that the total number of teams should be as much as possible.\r\n\r\nThere are n experienced members and m newbies on the training session. Can you calculate what maximum number of teams can be formed?\r\n\r\n------------------------------------------------\r\n\r\nEach team must have one experienced and one new person ... So, the number of teams can never exceed min(experienced, new).\r\n\r\nSo, we start from the maximum number of teams greedily and go down to 1 and choose the greatest configuration that is possible.\r\n\r\nTo check if a configuration of i teams is possible ... We make i teams consisting of 1 experienced and 1 new person. Then, we check if we have enough people to fill the \r\nthird spot in all the i teams.\r\n\r\n-----------------------------------------\r\n\r\n    no_of_teams = min(experienced_people_no, newbie_no);\r\n\r\n    while(no_of_teams > 0)\r\n    {\r\n        no_of_available_people = (experienced_people_no + newbie_no) - 2*no_of_teams;\r\n\r\n        if(no_of_available_people >= no_of_teams)\r\n            break;\r\n\r\n        no_of_teams--;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_teams);"
  },
  {
    "path": "Explanations/Explanations - 8/Almost Primes Explanation.txt",
    "content": "A number is said to be almost primes if it has exactly two distinct prime factors.\r\nFor a given n, display the number of almost primes up to n.\r\n\r\n-------------------------------------------------------\r\n\r\nDo a sieve ... Initially all numbers have 0 prime factors ... \r\nPick up the first number that has 0 prime factors, and increase the number of factors of all it's multiples by 1.\r\n\r\nAnd then have a prefix array ... no_of_almost_primes_till[i] = no_of_almost_primes_till[i-1] + (is_almost_prime(i) == true)\r\n\r\nEach query can be answered in O(1) time, but in CodeForces there is only one query per test case.\r\n\r\n------------------------------------------------------------\r\n\r\nvector <int> no_of_almost_primes_till(3000 + 1, 0);\r\n\r\nvoid precompute_primes()\r\n{\r\n    vector <int> no_of_prime_factors(3000 + 1, 0);\r\n\r\n    for(int i = 2; i <= 3000; i++)\r\n    {\r\n        if(no_of_prime_factors[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple <= 3000; multiple += i)\r\n            {\r\n                no_of_prime_factors[multiple]++;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= 3000; i++)\r\n    {\r\n        no_of_almost_primes_till[i] = no_of_almost_primes_till[i - 1] + (no_of_prime_factors[i] == 2);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_primes();\r\n\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(\"%d\\n\", no_of_almost_primes_till[n]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 8/Brian's Photos.txt",
    "content": "Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, \nbut to become a photographer instead.\n\nAs you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).\n\nBrain took a lot of colourful pictures on colored and black-and-white film. Then he developed and translated it into a digital form. But now, color and black-and-white photos are in one folder, \nand to sort them, one needs to spend more than one hour!\n\nAs soon as Brain is a photographer not programmer now, he asks you to help him determine for a single photo whether it is colored or black-and-white.\n\nPhoto can be represented as a matrix sized n × m, and each element of the matrix stores a symbol indicating corresponding pixel color. There are only 6 colors:\n\n'C' (cyan)\n'M' (magenta)\n'Y' (yellow)\n'W' (white)\n'G' (grey)\n'B' (black)\nThe photo is considered black-and-white if it has only white, black and grey pixels in it. If there are any of cyan, magenta or yellow pixels in the photo \nthen it is considered colored.\n\n----------------------------------------------------\n\nSimple implementation ... But I got a wrong answer because I had forgotten to put a space in front of scanf while scanning a character ... It reads the whitespace too\n\n-------------------------------\n\n    for(int row = 1; row <= no_of_rows; row++)\n    {\n        for(int column = 1; column <= no_of_columns; column++)\n        {\n            char colour;\n            scanf(\" %c\", &colour);\n\n            if(colour != 'B' && colour != 'G' && colour != 'W')\n                is_colourful = true;\n        }\n    }\n\n    printf(is_colourful ? \"#Color\\n\" : \"#Black&White\\n\");\n"
  },
  {
    "path": "Explanations/Explanations - 8/Ceil and Flowers Explanation.txt",
    "content": "Fox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:\r\n\r\nTo make a \"red bouquet\", it needs 3 red flowers.\r\nTo make a \"green bouquet\", it needs 3 green flowers.\r\nTo make a \"blue bouquet\", it needs 3 blue flowers.\r\nTo make a \"mixing bouquet\", it needs 1 red, 1 green and 1 blue flower.\r\nHelp Fox Ciel to find the maximal number of bouquets she can make.\r\n---------------------------------------------------\r\n\r\nI tried some strategies that didn't work ... Like, take as many mixed boquets as possible and then take the rest, and then take as many monochromatic boquets as possible\r\nand then take the mixed boquet.\r\n\r\nThe answer requires noticing that the number of mixed boquets never needs to be more than 3. If we have 3 mixed boquets, we can think of them as 3 boquets of each colour.\r\n\r\nSo, just count how many boquets there would be if there was one mixed boquet, two mixed boquets and no mixed boquets.\r\n\r\n--------------------------------------------------------\r\n\r\n#define min_3(a, b, c) min(a, min(b, c) )\r\n#define max_3(a, b, c) max(a, max(b, c) )\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int green, red, blue;\r\n    scanf(\"%d %d %d\",&red, &green, &blue);\r\n\r\n    int one_mixed_boquet = 0, two_mixed_boquet = 0, no_mixed_boquet;\r\n\r\n    no_mixed_boquet = red/3 + green/3 + blue/3;\r\n\r\n    if(min_3(red,green, blue) >= 1)\r\n        one_mixed_boquet = 1 + (red - 1)/3 + (green - 1)/3 + (blue - 1)/3;\r\n    if(min_3(red, green, blue) >= 2)\r\n        two_mixed_boquet = 2 + (red - 2)/3 + (green - 2)/3 + (blue - 2)/3;\r\n\r\n    printf(\"%d\\n\",max_3(no_mixed_boquet, two_mixed_boquet, one_mixed_boquet));\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 8/Choosing Teams Explanation.txt",
    "content": "The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. \r\nFor each student you know the number of times he/she has participated in the ACM ICPC world programming championship. \r\nAccording to the ACM ICPC rules, each person can participate in the world championship at most 5 times.\r\n\r\nThe head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that,\r\n any person cannot be a member of two or more teams. \r\nWhat maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?\r\n\r\n--------------------------------------------\r\n\r\nSort the people by the number of attempts they have ... Look at people in batches of three .. If for a given i, A[i + 2] + k <= 5, then increment number of teams, i = i + 3.\r\n\r\n----------------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_people, number_of_attempts;\r\n    scanf(\"%d %d\", &number_of_people, &number_of_attempts);\r\n\r\n    vector <int> attempts (number_of_people);\r\n    for(int i = 0; i < number_of_people; i++)\r\n        scanf(\"%d\", &attempts[i]);\r\n\r\n    sort(all(attempts));\r\n\r\n    int no_of_teams = 0, i = 0;\r\n    while(i + 2 < number_of_people && (attempts[i +2] + number_of_attempts) <= 5)\r\n    {\r\n        i += 3;\r\n        no_of_teams++;\r\n    }\r\n\r\n    printf(\"%d\\n\",no_of_teams);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 8/HQ9+ Explanation.txt",
    "content": "HQ9+ is a joke programming language which has only four one-character instructions:\r\n\r\n\"H\" prints \"Hello, World!\",\r\n\"Q\" prints the source code of the program itself,\r\n\"9\" prints the lyrics of \"99 Bottles of Beer\" song,\r\n\"+\" increments the value stored in the internal accumulator.\r\nInstructions \"H\" and \"Q\" are case-sensitive and must be uppercase. The characters of the program which are not instructions are ignored.\r\n\r\nYou are given a program written in HQ9+. You have to figure out whether executing this program will produce any output.\r\n\r\nInput\r\nThe input will consist of a single line p which will give a program in HQ9+. String p will contain between 1 and 100 characters, inclusive. \r\nASCII-code of each character of p will be between 33 (exclamation mark) and 126 (tilde), inclusive.\r\n\r\nOutput\r\nOutput \"YES\", if executing the program will produce any output, and \"NO\" otherwise.\r\n\r\n-----------------------------------------------------------\r\nint main()\r\n{\r\n    bool produces_output = false;\r\n    char program[MAX_LENGTH];\r\n    scanf(\"%s\", program);\r\n\r\n    for(int i = 0; program[i] != '\\0'; i++)\r\n    {\r\n        if(program[i] == 'H' || program[i] == 'Q' || program[i] == '9')\r\n        {\r\n            produces_output = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(produces_output ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 8/Hexadecimal's Numbers Explanation.txt",
    "content": "One beautiful July morning a terrible thing happened in Mainframe: a mean virus Megabyte somehow got access to the memory of his not less mean sister Hexadecimal. \r\nHe loaded there a huge amount of n different natural numbers from 1 to n to obtain total control over her energy.\r\n\r\nBut his plan failed. The reason for this was very simple: Hexadecimal didn't perceive any information, apart from numbers written in binary format. \r\nThis means that if a number in a decimal representation contained characters apart from 0 and 1, it was not stored in the memory. \r\nNow Megabyte wants to know, how many numbers were loaded successfully.\r\n\r\n----------------------------------------------\r\n\r\nAll the numbers which survive are the ones containing only 1s and 0s in the DECIMAL representation...\r\n\r\nIt isn't possible to check from 1 to 1e9, which numbers are good ... Instead Notice that all binary strings survive ... There are at most 2^10 - 1 of these numbers.\r\n\r\nWe get this by summing over 2 + 2^2 + 2^3 + ... + 2^9 ... There are 2^n binary strings of length n. \r\n\r\nSo what is done is have a bitmask that goes from 1 to 2^10 - 1, get the decimal value of the bitmask ... and check if it is smaller than n.\r\n\r\n------------------------------------------\r\n\r\nConverting a bitmask to decimal\r\n\r\nint corresponding_decimal(int bitmask)\r\n{\r\n    int decimal = 0;\r\n\r\n    //Get the bitmask in decimal For example, 11 should be eleven .. So, we treat it like a polynomial, multiply decimal by 10 at each step and add\r\n    //it to whatever bit was there ... 11 will be 1*10 + 1.\r\n    for(int i = 31; i >= 0; i--)\r\n    {\r\n        decimal = decimal*10 + ( (bitmask & (1 << i) ) != 0) ;\r\n    }\r\n    return decimal;\r\n}\r\n\r\nTreat it like a polynomial ... Go from the MSB to the LSB MSB is x^31 ... LSB is x^0 ... To evaluate the polynomail use Horner's method.\r\nAt each step, P = x*P + c, where c is the next coefficient. Here, x is 10 and coefficient is at most 1 ... So just check if it isn't zero and add it.\r\n\r\nA common bug is writing (bitmask & (1 << i)) == 1, that is not correct. We must check that it is NOT 0, instead of checking if it is 1.\r\n\r\nBecause, the AND operation leaves a 1 at the i-th position ... This means the string is 100000...0 (i - 1) zeroes ... It is not 1.\r\n\r\nIf the answer is non-zero, it means the i-th bit is set. So 1 is added as that is what the relational operator returns.\r\n\r\n-----------------------------------------------------\r\n\r\n    int max_numbers = (1 << 10) - 1; //At most 2^10 - 1 numbers\r\n    for(int bitmask = 1; bitmask <= max_numbers; bitmask++)\r\n    {\r\n        if(corresponding_decimal(bitmask) > limit)\r\n            break;\r\n\r\n\r\n        no_of_saved_numbers++;\r\n    }"
  },
  {
    "path": "Explanations/Explanations - 8/Jzzhu and Sequences Explanation.txt",
    "content": "F(i) = F(i - 1) + F(i + 1)\r\n\r\n----------------------------------------\r\n\r\nCodeChef had a very similar problem and a DP won't pass the time limit... Notice that the sequence is periodic with period 6. \r\nJust handle the overflow.\r\n\r\n---------------------------------------------\r\n\r\n    X = (X + MOD)%MOD;\r\n    Y = (Y + MOD)%MOD;\r\n\r\n    switch(number_of_terms%6)\r\n    {\r\n        case 1: answer = X; break;\r\n\r\n        case 2: answer = Y; break;\r\n\r\n        case 3: answer = Y + MOD - X; break;\r\n\r\n        case 4: answer = 0 + MOD - X; break;\r\n\r\n        case 5: answer = 0 + MOD - Y; break;\r\n\r\n        case 0: answer = X + MOD - Y; break;\r\n    }\r\n\r\n    answer = (answer + MOD)%MOD;"
  },
  {
    "path": "Explanations/Explanations - 8/K Factorisation Explanation.txt",
    "content": "\r\n--------------------------------------------------\r\n\r\nIf we just run through the factors like i, n/i for i = 1 to root(n), we won't get a list of numbes who's product is n.\r\n\r\nFor that, we need the prime factorisation of n ...\r\n\r\nWrite all of the prime factors (with duplicity) of n down on a vector ... Replace any two numbers by their product and reduce the size of the list till it becomes = k.\r\n\r\nIf the initial size of the list is less than k, then it is not possible.\r\nGiven a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.\r\n\r\n--------------------------------\r\n\r\nTO find the prime factorisation, we start from i = 2 and go up to N. \r\n\r\nWhenever i divides n, continuously divide n/i till it is no longer divisible by i (so that if N is divisible by i, it will not be divisible by any of i's factors when \r\nwe encounter them. ... This is similar to a sieve.) Add i to the list.\r\n\r\n----------------------------------------\r\n\r\nI have multiplied the last two elements of the vector once it crosses k.. Although the final solution didn't use it... I learnt how to pass vectors as parameters by reference\r\n\r\n--------------------------\r\n\r\nint main()\r\n{\r\n    unsigned int n, number_of_factors;\r\n    scanf(\"%d %d\", &n, &number_of_factors);\r\n\r\n    vector <int> factor;\r\n    for(unsigned int i = 2; i <= n ; i++)\r\n    {\r\n        while(n%i == 0)\r\n        {\r\n            if(factor.size() == number_of_factors)\r\n                factor.back() *=i;\r\n            else\r\n                factor.push_back(i);\r\n\r\n            n = n/i;\r\n        }\r\n    }\r\n\r\n    if(factor.size() < number_of_factors)\r\n        printf(\"-1\\n\");\r\n    else\r\n        for(unsigned int i = 0; i < number_of_factors; i++)\r\n            printf(\"%d \",factor[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 8/Noldbach Problem Explanation.txt",
    "content": "Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. \r\nThat got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. \r\nSince Nick is interested only in prime numbers, Noldbach problem states that at least k prime numbers from 2 to n inclusively can be expressed as \r\nthe sum of three integer numbers: two neighboring prime numbers and 1. \r\n\r\nFor example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.\r\n\r\nTwo prime numbers are called neighboring if there are no other prime numbers between them.\r\n\r\nYou are to help Nick, and find out if he is right or wrong.\r\n\r\n------------------------------------------------------\r\n\r\nHere's what I did ... Precomputed a list of all primes till 1000.\r\n\r\nMaintained a boolean vector of length 1000 such that B[i] is true, if it is Noldbach number and false otherwise.\r\n\r\nNow, instead of iterating from i = 1 to N in the given range to check the given conditions ...\r\n\r\nPick up the primes in the precomputed vector and check if they're Noldbach numbers ... This means we have to do log N iterations instead of O(N) for each query ...\r\n\r\nHowever precomputation is O(N log log N + log N).\r\n\r\nThere were some answers that didn't precompute anythhing... Go from i = 1 to N, apply a O(root(n)) test on all numbers ... Push it into a vector\r\nThen for all primes in the given range, check if each prime is the sum of consecutive primes + 1.\r\n\r\nO(log^2 N).\r\n\r\n--------------------------------------\r\n\r\nvector <int> noldbach_number(1000 + 1, false);\r\nvector <int> primes;\r\n\r\nvoid precompute_noldbach()\r\n{\r\n    vector <int> is_prime(1000 + 1, true);\r\n\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= 1000; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            for(int multiple = 2*i; multiple <= 1000; multiple += i)\r\n            {\r\n                is_prime[multiple] = false;\r\n            }\r\n            primes.push_back(i);\r\n        }\r\n    }\r\n\r\n    for(int i = 0; primes[i] + primes[i + 1] <= 1000 ; i++)\r\n    {\r\n        noldbach_number[primes[i] + primes[i + 1] + 1] = true;\r\n    }\r\n\r\n}\r\n\r\n--------------------------------------------------------\r\n\r\nSieve is done first to build a vector of primes ... Then the noldbach numbers are precomputed. \r\n\r\n----------------------------------------------\r\n\r\nint main()\r\n{\r\n    precompute_noldbach();\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    int conjecture_count = 0;\r\n    for(int i = 0; primes[i] <= n; i++)\r\n    {\r\n        if(noldbach_number[primes[i]])\r\n            conjecture_count++;\r\n    }\r\n\r\n    printf(conjecture_count >= k ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 8/Oleysa and Rodion Explanation.txt",
    "content": "Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.\r\n\r\nYour task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print -1\r\n\r\n--------------------------------------------------\r\n\r\nUse the simplest solution that works ...\r\n\r\nI was initially going for searching for the lcm and then pad it with zeroes ... But, there's a better solution !\r\n\r\nPrint K and then fill the remaining N-1 spots with 0s. ... The only time we need to print -1 is when n = 1, k = 10\r\n\r\n----------------------------------------------\r\n\r\n    if(number_of_digits == 1 && multiple == 10)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"%d\", multiple);\r\n\r\n        int no_of_zeroes = (multiple == 10 ? number_of_digits - 2 : number_of_digits - 1);\r\n\r\n        for(int zero_count = 1; zero_count <= no_of_zeroes; zero_count++)\r\n            printf(\"0\");\r\n    }"
  },
  {
    "path": "Explanations/Explanations - 8/Petr and Book Explanation.txt",
    "content": "One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages.\r\n\r\nPetr decided to start reading it starting from the next day, that is, from Monday. \r\nPetr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. \r\nSome days are so busy that Petr will have no time to read whatsoever. However, we know that he will be able to read at least one page a week.\r\n\r\nAssuming that Petr will not skip days and will read as much as he can every day, determine on which day of the week he will read the last page of the book.\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_pages;\r\n    scanf(\"%d\", &no_of_pages);\r\n\r\n    int i;\r\n    vector <int> pages_read_on_day(7);\r\n    for(i = 0; i < 7; i++)\r\n        scanf(\"%d\", &pages_read_on_day[i]);\r\n\r\n\r\n    i = 0;\r\n    while(true)\r\n    {\r\n         no_of_pages -= pages_read_on_day[i];\r\n\r\n        if(no_of_pages <= 0)\r\n            break;\r\n\r\n        i = (i + 1)%7;\r\n    }\r\n\r\n    printf(\"%d\\n\",i + 1);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 8/Petya and Strings Explanation.txt",
    "content": "Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. \r\nNow Petya wants to compare those two strings lexicographically. The letters' case does not matter, \r\nthat is an uppercase letter is considered equivalent to the corresponding lowercase letter. Help Petya perform the comparison.\r\n\r\n-------------------------------------------------------\r\n\r\nMaybe if I had more time, I would make both strings lower character and then use strcmp so that there's no abrupt end ... But I wanted to finish this as soon as possible.\r\n\r\n#define tolower(c) (c < 'a' ? (c + 'a' - 'A') : c)\r\n\r\nint main()\r\n{\r\n    char string_1[MAX_LENGTH], string_2[MAX_LENGTH];\r\n    scanf(\"%s %s\", string_1, string_2);\r\n\r\n    for(int i = 0; string_1[i] != '\\0'; i++)\r\n    {\r\n        if(tolower(string_1[i]) > tolower(string_2[i]) )\r\n        {\r\n            printf(\"1\\n\");\r\n            return 0;\r\n        }\r\n        else if(tolower(string_1[i]) < tolower(string_2[i]) )\r\n        {\r\n            printf(\"-1\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    printf(\"0\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 8/Sum of Digits Explanation.txt",
    "content": "Having watched the last Harry Potter film, little Gerald also decided to practice magic. \r\nHe found in his father's magical book a spell that turns any number in the sum of its digits. \r\nAt the moment Gerald learned that, he came across a number n. How many times can Gerald put a spell on it until the number becomes one-digit?\r\n\r\n----------------------------------------------\r\n\r\nThis is similar to the big GCD problem ... We only need to use big numbers once ...\r\n\r\nIf the initial number is 10^ ... the digit sum can't be greater than 9x10^5, and then can't be bigger than 54 and then one more ... So, since the number of spells can be \r\nat most 4, first find digit sum on the string and then use the normal digit sum function.\r\n\r\nSingle digit numbers require 0 spells.\r\n\r\n------------------------------------------\r\n\r\n   if(number[1] != '\\0')\r\n    {\r\n        for(i = 0; number[i] != '\\0'; i++)\r\n            digit_sum += (number[i] - '0');\r\n\r\n        no_of_spells = 1;\r\n        while(digit_sum >= 10)\r\n        {\r\n            no_of_spells++;\r\n            digit_sum = find_digit_sum(digit_sum);\r\n        }\r\n    }"
  },
  {
    "path": "Explanations/Explanations - 8/T Primes Alternate Solution Explanation.txt",
    "content": "Last time I maintained a set so the complexity was \r\n\r\nO(D log log D + N log S), D = 1e6, N is the number of queries and S is the size of the set.\r\n\r\nNow I just maintained a vector ... Checked if the query is a perfect square and if that square root is prime.\r\n\r\nO(D log log D + T), where T is the complexity of finding square root ... This was much faster ... Probably because it was quicker to find the square root than a tree query.\r\n\r\n---------------------------------------------------------\r\n\r\nvector <int> is_prime(1000000 + 1, true);\r\n\r\nvoid precompute_prime_squares()\r\n{\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    for(int i = 2; i <= 1e6; i++)\r\n        if(is_prime[i])\r\n            for(int multiple = 2*i; multiple <= 1e6; multiple += i)\r\n                is_prime[multiple] = false;\r\n\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    precompute_prime_squares();\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        long long number, root;\r\n        scanf(\"%I64d\", &number);\r\n\r\n        root = (int) sqrt(number);\r\n\r\n        printf(root*root == number && is_prime[root] ? \"YES\\n\" : \"NO\\n\");\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 8/T Primes Explanation.txt",
    "content": "A number is said to be T prime if it has three positive divisors... Given a number upto 10^12, say if it is a T prime...\r\n\r\n-------------------------------------\r\n\r\nThe only numbers which have an odd number of divisors are perfect squares. If it has three divisors, then it means that T primes are squares of prime numbers ...\r\n\r\nHere's what I did ... Did Sieve of Erathosthenes to find all primes up to 1e6 ... Maintained a set of all the square primes ...\r\n\r\nChecking the count of a set is O(log N), where N is the size of a set ...\r\n\r\nI looked at some other approaches ...\r\n\r\nPeople used optimised IO ... putchar and such ... Precomputed primes up to 1e6 ...\r\n\r\nInput N, M = int sqrt(M) ... If M*M = N & is_prime(M) ... YES\r\n\r\nThis seems to have less time complexity because the query is answered in O(1) time once we know the square root as opposed to log(N) time ... \r\n\r\nBut, I didn't use this because I am uncomfortable with the behaviour of any floating point functions .. I don't know what exactly sqrt does ... Rounding off may cause errors.\r\n\r\nAlso, calculating the square of a number is much easier than calculating it's square root ...\r\n\r\nSo, that solution is O(N log log N + T), where T is the time taken to find the square root of a number.\r\nMine is O(N log log N + log N), because of the time taken to query the count of an element in a set ... (balanced tree).\r\n\r\n------------------------------------------------------------\r\n\r\nset <long long> prime_square;\r\n\r\nvoid precompute_prime_squares()\r\n{\r\n    vector <int> is_prime(1000000 + 1, true);\r\n\r\n    for(int i = 2; i <= 1e6; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            prime_square.insert(i*1LL*i);\r\n\r\n            for(int multiple = 2*i; multiple <= 1e6; multiple += i)\r\n                is_prime[multiple] = false;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    precompute_prime_squares();\r\n\r\n    for(int i = 1; i <= no_of_queries; i++)\r\n    {\r\n        long long number;\r\n        scanf(\"%I64d\", &number);\r\n\r\n        printf(prime_square.count(number) == 1 ? \"YES\\n\" : \"NO\\n\");\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 8/Wet Shark and Odd and Even Explanation.txt",
    "content": "Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. \r\nPlease, calculate this value for Wet Shark.\r\n\r\nNote, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.\r\n-------------------------------------------------\r\n\r\n\r\nIf sum is odd, subtract the smallest odd number ... Else, the sum is the answer.\r\n\r\n    min_odd_number = 1e9 + 1;\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &number_i);\r\n        sum += number_i;\r\n\r\n        if(number_i%2 == 1)\r\n            min_odd_number = min(min_odd_number, number_i);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", sum%2 == 0 ? sum : sum - min_odd_number);"
  },
  {
    "path": "Explanations/Explanations - 8/Yarslav and Permutations Explanation.txt",
    "content": "Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. \r\nNow Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.\r\n\r\nHelp Yaroslav.\r\n\r\n----------------------------------------------------\r\n\r\nWe cannot stop two numbers from being placed next to each other if one of them occurs more than ceil(n/2) times.\r\nWe can prove this using the pigonehole principle .... \r\nIf n is even, there are n adjacent pairs ... If one element occurs more than n/2 times, there must be one pair with both it's elements being the same.\r\n\r\nIf n is odd, then there are n adjacent pairs and the last element ... So, if n occurs more than n/2 + 1 times, a same-pair can't be avoided.\r\n\r\nAlso, it is easy to see that if there is an element that occurs more than n/2 times, it must be the most frequent element ...\r\nAnd if the most frequent element doesn't occur n/2 times, none of them do !\r\n\r\nI used a hash-map for this one ...\r\n\r\nWhile inserting an element into the map, first it checks if a node with the key exists ... If it doesn't exist, a node with the key value is created initialised to 0.\r\nThen, we increment it.\r\n\r\nWhile accessing the elements of the map, first create an iterator of map .. iterator goes from .begin() to end() .. These are references.\r\nCompare the frequency to it->second ... Because the second is the value, the first is the key ... In our case, the second is the frequency, the first is the element.\r\n\r\n--------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_elements, element_i;\r\n    scanf(\"%d\", &number_of_elements);\r\n\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        frequency[element_i]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n        max_frequency = max(max_frequency, it->second);\r\n\r\n    int half_size = number_of_elements/2 + number_of_elements%2;\r\n\r\n    printf(max_frequency > half_size ? \"NO\\n\" : \"YES\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Appleman and Toastman Explanation.txt",
    "content": "\r\nAppleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:\r\n\r\nEach time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.\r\nEach time Appleman gets a group consisting of a single number, he throws this group out.\r\nEach time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) \r\nand gives each of them to Toastman.\r\n\r\nAfter guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?\r\n\r\n--------------------------------------------------------\r\n\r\n\r\nHere's the best strategy.\r\n\r\nSort the elements \r\n\r\na1 < a2 < ... < an.\r\n\r\nThe idea is to choose as many large sums as many times as possible.\r\n\r\nan is the largest element ... So, we try to choose it as many times as possible.\r\n\r\n----------------------------------------\r\n\r\na1 + a2 + ... + an. Lose the smallest element\r\n     a2 + ... + an\r\n         a3+..+ an\r\n\r\n\t\tan.\r\n\r\nWe can see that an is a part of n different sums so an gets counted n times to the score.\r\n\r\nConsider another element not an ... Say, ap, p < n\r\n\r\na1 + a2 + ... ap + ... + an\r\n     a2 + ... ap + ... + an\r\n           \r\n              ap + .... + an\r\n\r\nap is a part of p different groups ... It gets counted one more time as a single ton element ... \r\n\r\nSo, it gets counted p + 1 times.\r\n\r\nEvery element is counted i + 1 times, except the last element which is only counted i times. This is because the sum starting at ai, and the singleton ai are the same\r\nsum for an.\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_groups;\r\n    long long answer = 0;\r\n    scanf(\"%d\", &no_of_groups);\r\n\r\n    vector <int> group(no_of_groups + 1, 0);\r\n    for(int i = 1; i <= no_of_groups; i++)\r\n    {\r\n        scanf(\"%d\", &group[i]);\r\n    }\r\n\r\n\r\n    sort(all(group));\r\n    for(unsigned int i = group.size() - 1; i >= 1; i--)\r\n    {\r\n        int no_of_times_i_is_counted = (i == group.size() - 1 ? i : i + 1);\r\n        answer += no_of_times_i_is_counted*1LL*group[i];\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n\r\n-------------------------------\r\n\r\nWasn't as easy as it looks ... Then I realised it's A for div 1, and C for div 2 ! That explains a lot ! \r\nAnyway, good problem ... I enjoy problems which take advantage of double counting .. .It's hard to iterated each sum ... But easy to count number of sums each element is \r\na part of.\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 9/Bear and Five Cards Explanation.txt",
    "content": "A little bear Limak plays a game. He has five cards. There is one number written on each card. Each number is a positive integer.\r\n\r\nLimak can discard (throw out) some cards. His goal is to minimize the sum of numbers written on remaining (not discarded) cards.\r\n\r\nHe is allowed to at most once discard two or three cards with the same number. \r\nOf course, he won't discard cards if it's impossible to choose two or three cards with the same number.\r\n\r\nGiven five numbers written on cards, cay you find the minimum sum of numbers on remaining cards?\r\n\r\n------------------------------------------------\r\n\r\nSince the constraints are quite small, I thought of maintaining a frequency table up to 100 and then going downwards and taking out the first element possible.\r\nThen, I realised there might be a conflict ... For example, we may have a hoice of taking out 2 30s or 3 25s ... Going downwards and taking out the first choice\r\nmight not be optimal. You need to keep track of the maximum sum subtracted.\r\n\r\nI chose to do it with a map. It is maintained as a balanced tree underneath. \r\n\r\nTo find the minimum amount, it will only take five iterations, at most, instead of 100 like the table.\r\n\r\nGo through each entry of the map ... If it's frequency is greater than 1, check the amount that can be subtracted - either 2n or 3n, depending on it's frequency.\r\n\r\nCompare it with the overall maximum amount that can be subtracted.\r\n\r\nAn advantage of map is that it would still work efficieintly if the card number went up to 1e18 ... It will only take O(n) worst case processing, where n is the number of \r\ncards.\r\n\r\nWe already have the array sum because it was calculated along with the input. Subtract the maximum subtractable amount from the sum and display it.\r\nEnsure it is initialised to 0.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    map <int, int> frequency;\r\n    const int no_of_cards = 5;\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= no_of_cards; i++)\r\n    {\r\n        int card_i;\r\n        scanf(\"%d\", &card_i);\r\n\r\n        sum += card_i;\r\n        frequency[card_i]++;\r\n    }\r\n\r\n    int max_subtracted = 0;\r\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        int number_i = it->first;\r\n        int frequency_i = it->second;\r\n        int subtracted_amount = 0;\r\n\r\n        if(frequency_i > 1)\r\n        {\r\n            subtracted_amount = (frequency_i > 2 ? 3*number_i : 2*number_i);\r\n        }\r\n\r\n        max_subtracted = max(max_subtracted, subtracted_amount);\r\n    }\r\n\r\n    printf(\"%d\\n\", sum - max_subtracted);\r\n    return 0;\r\n}\r\n\r\n---------------------------------\r\n\r\nSTL is so powerful. Hash table implemented as balanced trees make everything so easy and efficient."
  },
  {
    "path": "Explanations/Explanations - 9/Bus to Udayland Explanation.txt",
    "content": "ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats.\r\n There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.\r\n\r\nZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. \r\nTwo seats are considered neighbouring if they are in the same row and in the same pair. \r\nGiven the configuration of the bus, can you help ZS and Chris determine where they should sit?\r\n\r\n-------------------------------------------------------------\r\n\r\nSimple implementation error ... I got a run time error because I embarassingly interchanged the rows and columns while declaring the matrix ...\r\nRows come first ! lol.\r\n\r\nint main()\r\n{\r\n    char bus_seating[MAX_ROWS][ROW_LENGTH];\r\n    int no_of_rows;\r\n    scanf(\"%d\", &no_of_rows);\r\n\r\n    bool can_sit_together = false;\r\n\r\n    for(int i = 0; i < no_of_rows; i++)\r\n    {\r\n        scanf(\"%s\", bus_seating[i]);\r\n\r\n        if(bus_seating[i][0] == 'O' && bus_seating[i][1] == 'O' && can_sit_together == false)\r\n        {\r\n            bus_seating[i][0] = bus_seating[i][1] = '+';\r\n            can_sit_together = true;\r\n        }\r\n\r\n        if(bus_seating[i][3] == 'O' && bus_seating[i][4] == 'O' && can_sit_together == false)\r\n        {\r\n            bus_seating[i][3] = bus_seating[i][4] = '+';\r\n            can_sit_together = true;\r\n        }\r\n    }\r\n\r\n    if(can_sit_together)\r\n    {\r\n        printf(\"YES\\n\");\r\n        for(int i = 0; i < no_of_rows; i++)\r\n            printf(\"%s\\n\",bus_seating[i]);\r\n    }\r\n    else\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Circle Line Explanation.txt",
    "content": "\r\n--------------------------------------------------\r\n\r\nBetween any two stations there are two routes ... One forward, and the other roundabout.\r\nFind both value and give the minimum ...\r\n\r\nBe careful about incrementing i to ensure it behaves like a circle. If i has reached n, the next value of i is 1. Otherwise it is i+1. \r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_stations, start, destination;\r\n    scanf(\"%d\", &no_of_stations);\r\n\r\n    vector <int> distance(no_of_stations + 1);\r\n    for(int i = 1; i <= no_of_stations; i++)\r\n        scanf(\"%d\", &distance[i]);\r\n\r\n    scanf(\"%d %d\", &start, &destination);\r\n\r\n    int straight_distance = 0;\r\n    for(int i = start; i != destination; i = (i == no_of_stations ? 1 : i + 1))\r\n        straight_distance += distance[i];\r\n\r\n    int round_distance = 0;\r\n    for(int i = destination; i != start; i = (i == no_of_stations ? 1 : i + 1))\r\n        round_distance += distance[i];\r\n\r\n    printf(\"%d\\n\", min(straight_distance, round_distance));\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Crazy Computer Explanation.txt",
    "content": "Simple implementation ... \r\n\r\nint main()\r\n{\r\n    int no_of_words, minute_i, maximum_break;\r\n    scanf(\"%d %d\", &no_of_words, &maximum_break);\r\n\r\n    int previous_minute = 0, no_of_words_on_screen = 0;\r\n    for(int i = 1; i <= no_of_words; i++)\r\n    {\r\n        scanf(\"%d\", &minute_i);\r\n        no_of_words_on_screen = (minute_i - previous_minute <= maximum_break ? no_of_words_on_screen + 1 : 1);\r\n\r\n        previous_minute = minute_i;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_words_on_screen);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 9/Crossword Solving Explanation.txt",
    "content": "\r\n----------------------------------------------------\r\n\r\nI thought there was a smarter and slicker solution than taking the smaller string, placing it at every allowable index and counting and keeping track of number of changes.\r\nI almost gave up and decided to code the brute force approach because I saw it would pass the time limit.\r\nIn fact, the 'brute force' approach was the answer itself !\r\n\r\nIt would have been simpler and more believeable if I had known that it is possible to copy one vector to another ... I had solved this question using boolean vectors first.\r\nAnd keeping track of changes at every iteration.\r\n\r\nThere's a simpler and cleaner way.\r\nI learnt how to use clear() on a vector.\r\nAlso, v1 = v2, copies v2 into v1, and v1 now has v2's size. \r\n\r\nCompare at every allowable index and push all changes into a vector ... Compare the size of this vector with the minimum change vector, \r\nIf change. size() < minimum change.size(), minimum_change = change ... Simple as that ...No need of re-initialising an entire vector.\r\n\r\n---------------------------------------------------------\r\n\r\nInitially, size of change is m + 1, so anything replaces it.\r\nRemember clearing current change every iteration or it will just grow.\r\n\r\n-----------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int key_length, text_length;\r\n    char key[MAX_LENGTH], text[MAX_LENGTH];\r\n    scanf(\"%d %d %s %s\", &key_length, &text_length, key, text);\r\n\r\n    vector <int> change(key_length + 1);\r\n    vector <int> current_change;\r\n\r\n    for(int i = 0; i + key_length <= text_length ; i++)\r\n    {\r\n        current_change.clear();\r\n\r\n        for(int j = 0; j < key_length; j++)\r\n        {\r\n            if(key[j] != text[i + j])\r\n            {\r\n                current_change.push_back(j);\r\n            }\r\n        }\r\n\r\n        if(current_change.size() < change.size())\r\n        {\r\n            change = current_change;\r\n        }\r\n    }\r\n\r\n    printf(\"%u\\n\", change.size());\r\n\r\n    if(change.size() > 0)\r\n    {\r\n        for(unsigned int i = 0; i < change.size(); i++)\r\n            printf(\"%d \", change[i] + 1);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Divisibility Explanation.txt",
    "content": "Find the number of numbers that are divisible by k in [a, b] ... a and b can be negative and fit into 64 bit data type.\r\n\r\n-----------------------------------------------------------------------\r\n\r\nIf a and b are on different sides of the number line, then the number of factors is = b/k + a/k + 1... Note that we are adding and not (a-1)/k, but a/k.\r\nWe want to add all factors from 0 to b and from 0 to -a ... We add 1 to ensure 0 is also included in the total.\r\n\r\nIf they are on the same side of the number line, assume without loss of generality that they are both positive, no of factors = b/k - (a -1)/k ...\r\n\r\nHowever, this gave me an error ... If k = 1 and a = 0, the the answer is b/1 - (0-1)/1 = b + 1 ... It shouldn't be + 1 .. The idea is that we are \r\ndiscounting all multiples of k before a ... But when it is 1, then -1/1 = -1 ... Any other number gives -1/n = 0 ... This creates an error.\r\n\r\nTo simplify things, if a = 0, answer = b/k + 1 ... all of k's multiples including 0.\r\nOtherwise, answer = b/k - (a-1)/k.\r\n\r\n---------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long k, left, right, no_of_multiples = 0;\r\n    scanf(\"%I64d %I64d %I64d\", &k, &left, &right);\r\n\r\n    if(right > 0 && left < 0)\r\n    {\r\n        left = abs(left);\r\n\r\n        no_of_multiples = (right)/k + (left)/k + 1; //Add 0 as a multiple as well.\r\n    }\r\n    else\r\n    {\r\n        long long greater_limit = max(abs(right), abs(left));\r\n        long long lower_limit = min(abs(right), abs(left));\r\n\r\n        if(lower_limit == 0)\r\n        {\r\n            no_of_multiples = (greater_limit)/k + 1; //Count 0 as well\r\n        }\r\n        else\r\n        {\r\n            no_of_multiples = (greater_limit)/k - (lower_limit - 1)/k;\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_multiples);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 9/Fox and Number Game Explanation.txt",
    "content": "Fox Ciel is playing a game with numbers now.\r\n\r\nCiel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, \r\nand then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible.\r\n\r\nPlease help Ciel to find this minimal sum.\r\n\r\n-----------------------------------------------\r\n\r\ngcd(a, b) = gcd(a, b - a) ...\r\n\r\nUltimately, all numbers are equal to their gcd. The gcd is invariant.\r\n\r\nSum is n*gcd.\r\n\r\n------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, element_i, array_gcd;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        array_gcd = (i == 1 ? element_i : gcd(array_gcd, element_i));\r\n    }\r\n\r\n    printf(\"%d\\n\", array_gcd*no_of_elements);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 9/Haiku Explanation.txt",
    "content": "Haiku is a genre of Japanese traditional poetry.\r\n\r\nA haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly \r\n(the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syllables). \r\nA haiku masterpiece contains a description of a moment in those three phrases. Every word is important in a small poem, which is why haiku are rich with symbols. \r\nEach word has a special meaning, a special role. The main principle of haiku is to say much using a few words.\r\n\r\nTo simplify the matter, in the given problem we will consider that the number of syllable in the phrase is equal to the number of vowel letters there. \r\nOnly the following letters are regarded as vowels\r\n\r\n-----------------------------------\r\n\r\nProblem is pretty simple, by itself but learnt a couple of things in implementation. First of all, couldn't use scanf because I want the spaces too.\r\n\r\nWas going to use gets, then learnt that gets causes buffer overflow and in turn undefined behaviour because it doesn't know how many bytes to read. \r\nIf it has buffer 2048, and input is 4096 there will be an overflow and unexpected behaviour. \r\n\r\nIt is safer to use fgets ... Fgets also keeps track of newline and stores it into the string. Read from standard input.\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    bool is_haiku = true;\r\n    char line[MAX_LENGTH];\r\n    const int no_of_lines = 3;\r\n\r\n    for(int i = 1; i <= no_of_lines; i++)\r\n    {\r\n        int vowel_count = 0;\r\n\r\n        fgets(line, MAX_LENGTH, stdin);\r\n\r\n        for(int letter = 0; line[letter] != '\\n'; letter++)\r\n            vowel_count += is_vowel(line[letter]);\r\n\r\n        if(i == 2)\r\n        {\r\n            if(vowel_count != 7)\r\n                is_haiku = false;\r\n        }\r\n        else\r\n        {\r\n            if(vowel_count != 5)\r\n                is_haiku = false;\r\n        }\r\n    }\r\n\r\n    printf(is_haiku ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n} "
  },
  {
    "path": "Explanations/Explanations - 9/Is your Horseshow on the Other Hoof Explanation.txt",
    "content": "\r\nSimple implementation...\r\n\r\nCount frequency of each hoof. The strategy is to use 1 hoof of a particular colour and throw away the rest.\r\n\r\nint main()\r\n{\r\n    map <int, int> frequency;\r\n    int  hoof_i, no_of_hooves = 4;\r\n\r\n    for(int i = 1; i <= no_of_hooves;i++)\r\n    {\r\n        scanf(\"%d\", &hoof_i);\r\n        frequency[hoof_i]++;\r\n    }\r\n\r\n    int no_of_new_hooves = 0;\r\n    for(map <int, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        int frequency_i = it->second;\r\n\r\n        no_of_new_hooves += frequency_i - 1; //Keep one copy and throw the rest\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_new_hooves);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/K-th Divisor Explanation.txt",
    "content": "Find the k-th factor of N or find that it doesn't exist.\r\n\r\n---------------------------------------------------------------\r\n\r\nThere are two approaches to this.\r\n\r\nGo from i = 1 to root(n) ...\r\n\r\nIf i is a factor, store i and n/i in a vector.\r\nSort the vector in the end.\r\nDisplay v[k - 1] (since vector is 0-indexed).\r\n\r\nI didn't want to do this since it had sorting and it's not entirely necessary.\r\n\r\n1. Go from i = 1 to root(n). Store all the factors till root(n).\r\n2. Let us suppose we have x factors ... If n is  a perfect square, then we have 2x - 1 factors, otherwise, there are 2x factors.\r\n3. If k > no of factors, answer = -1.\r\n\r\n4. Else, if k <= x, answer is V[k - 1], since vector is 0-indexed.\r\n\r\n5. If k > x, then it means answer is N/V[no_of_factors - k]  ... The first factor from the end is linked to the first factor from the start.\r\n\r\n1 ... no_of_factors\r\n2 ... no_of_factors - 1\r\n3 ... no_of_factors - 2\r\n.\r\n. \r\nTheir sum is invariant = no_of_factors + 1,\r\n\r\nSo, if N has f factors in total, and the k-th factor is greater than it's square root, it is N/V[f - k - 1] ... Since, our vector is 0-indexed, we may omit the -1.\r\n(Because k + k' = f - 1, where the k and k' factor multiply to give N)\r\n\r\nThis approach is much superior to the other approach ... (Difference of about 400 ms) This is O(root(N)) ... \r\nThat is O(root(N) + S log S), where S is the number of factors. This is more memory efficient too because the vector can be int and doesn't need to be long.\r\n\r\nI was getting a TLE here ... That wasn't because of the algorithm ... In the loop, I didn't type cast i ... so while i itself will always fit into 32 bit type,\r\ni*i will cause an overflow, and the condition i*i <= n will never be false if the overflow isn't caught.\r\n\r\nIn short, store all the factors of N from 1 till root(n)\r\nGet the number of factors.\r\nIf k > f, answer = -1,\r\nElse if k < root(n), answer = V[k - 1]\r\nElse answer = V[f - k]\r\n\r\n------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long num, answer;\r\n    unsigned int k, max_number_of_divisors;\r\n    scanf(\"%I64d %d\", &num, &k);\r\n\r\n    vector <int> divisors;\r\n    for(int i = 1; i*1LL*i <= num; i++)\r\n        if(num%i == 0)\r\n            divisors.push_back(i);\r\n\r\n    max_number_of_divisors = 2*divisors.size();\r\n\r\n    if(divisors.back()*1LL*divisors.back() == num)\r\n        max_number_of_divisors--; //Square root gets counted twice\r\n\r\n    if(k > max_number_of_divisors)\r\n    {\r\n        answer = -1;\r\n    }\r\n    else\r\n    {\r\n        if(k <= divisors.size())\r\n            answer = divisors[k - 1];\r\n        else\r\n            answer = num/divisors[max_number_of_divisors - k ];\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations - 9/Kitahara Haruki's Gift Explanation.txt",
    "content": "itahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.\r\n\r\nEach apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. \r\nTherefore the total weight of the apples given to Touma Kazusa must be equal to the total weight of the apples given to Ogiso Setsuna.\r\n\r\nBut unfortunately Kitahara Haruki doesn't have a knife right now, so he cannot split any apple into some parts. \r\nPlease, tell him: is it possible to divide all the apples in a fair way between his friends?\r\n\r\n------------------------------------------\r\n\r\nThis problem is really simple, but I still made two mistakes.\r\n\r\nFirst my approach ...\r\n\r\nNotice that the only way to make a matching in between the two families is 1 200 = 2 100.\r\n\r\nSo, we divide 200s into 2 as far as we can. We will be left either with 1 200 or 0 200 ... \r\nIf there is 1, use 2 100s to balance it out and then check if there are an even number of 100s left.\r\nIf there are 0 200s, just check if the number of 100s is even.\r\n\r\nI made a mistake ... I didn't check if the number of 100s is positive .... For example, if there's one 100 and 3 200s .. 1 200 will be left. \r\nIf we use 2 100s to balance it, we will have -1 100, which is not possible.... So, check if we have non negative no of 100s after it's over.\r\n\r\nAlso, by mistake I reduced no of 100s by 2 regardless ... This gives WA for  200 200 ... It is balanced out but if I still subtract 2 100s, \r\nI will have negative 100s.\r\n\r\nSubtract by 2*(no_of_200s)\r\n\r\nThose were the two bugs - check if there are non negative 100s at the end and also subtract 2 only if there is an outstanding 200 weight.\r\n\r\n-----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_apples, weight_i;\r\n    scanf(\"%d\", &no_of_apples);\r\n\r\n    int no_of_100s = 0, no_of_200s = 0;\r\n    for(int i = 1; i <= no_of_apples; i++)\r\n    {\r\n        scanf(\"%d\", &weight_i);\r\n\r\n        no_of_100s += (weight_i == 100);\r\n        no_of_200s += (weight_i == 200);\r\n    }\r\n\r\n    no_of_200s = (no_of_200s%2); //Distribute half of them to either group.\r\n    no_of_100s = no_of_100s - 2*no_of_200s; //Balancing out the 200 - there may be 1 or 0\r\n\r\n    printf(no_of_100s%2 == 0 && no_of_100s >= 0 ? \"YES\\n\" : \"NO\\n\"); //check if remaining 100s can be divided in half.\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations - 9/Little Elephant and Function Explanation.txt",
    "content": "The Little Elephant enjoys recursive functions.\r\n\r\nThis time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. \r\nThe Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:\r\n\r\nIf x?=?1, exit the function.\r\nOtherwise, call f(x?-?1), and then make swap(ax?-?1,?ax) (swap the x-th and (x?-?1)-th elements of a).\r\nThe Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, \r\nthe Little Elephant wants to show the performance of its function. Help him, \r\nfind a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.\r\n\r\n\r\n-------------------------------------------------------\r\n\r\nImportant to have some understanding of recursive stackframes for this one. \r\n\r\nAt first I thought it first swaps, ax and a(x-1) and then calls f(x - 1).\r\n\r\nIn that case the answer is a sorted array, rotated one place to the left. \r\n\r\nLike, 2 3 4 1\r\n\r\nBecause every swap will - 2 3 1 4, 2 1 3 4 and finally 1 2 3 4 ... The order of elements doesn't change ... The smallest element goes to the first position.\r\n\r\nBut, this is wrong.\r\n\r\nWhat happens is that it first calls f(x-1), f(x-2) ... and so on till it reaches f(1) and then starts swapping.\r\n\r\nSo, in other words starting from position 2 till n, ai and a(i - 1) are swapped. \r\n\r\nIn this case, the answer is a sorted array rotated one place to the RIGHT. \r\n\r\nthe order of elements doesn't change this way ... The first element occupies the last position.\r\n\r\n4 1 2 3, 1 4 2 3, 1 2 4 3 and finally 1 2 3 4.\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    printf(\"%d \", no_of_elements);\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        printf(\"%d \", i);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Little Elephant and Problem Explanation.txt",
    "content": "The Little Elephant has got a problem  somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.\r\n\r\nThe Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. \r\nHe thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). \r\nThat is, the Little Elephant could have accidentally swapped some two elements.\r\n\r\nHelp the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.\r\n\r\n-------------------------------------------------------\r\n\r\nSort the array and check how many positions differ with the original array.\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> original_array(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &original_array[i]);\r\n\r\n    vector <int> sorted_array = original_array;\r\n\r\n    sort(all(sorted_array));\r\n\r\n    int differences = 0;\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        differences += (sorted_array[i] != original_array[i]);\r\n\r\n    printf(differences <= 2 ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/New Year and Days Explanation.txt",
    "content": "Today is Wednesday, the third day of the week. What's more interesting is that tomorrow is the last day of the year 2015.\r\n\r\nLimak is a little polar bear. He enjoyed this year a lot. Now, he is so eager to the coming year 2016.\r\n\r\nLimak wants to prove how responsible a bear he is. He is going to regularly save candies for the entire year 2016! He considers various saving plans. \r\nHe can save one candy either on some fixed day of the week or on some fixed day of the month.\r\n\r\nLimak chose one particular plan. He isn't sure how many candies he will save in the 2016 with his plan. Please, calculate it and tell him.\r\n-----------------------------------------------------\r\n\r\nA simple problem, of course ... I found an elegant way of checking conditions.\r\n\r\nDec 30 is Wed ... 31st is Thurs ... 1st is Friday ... Since 2016, is a leap year it will end two days after Jan 1st instead of one.\r\n\r\nSo, it ends on Sat ... There is one extra Fri and Sat.\r\n\r\n\r\nAlso, scanf only reads a string till it encounters a whitespace so I used two of them ... made things easier... No need to use string comparison to identify time period.\r\n\r\n--------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int savings = 0, date;\r\n    char of[2 + 1], time_period[MAX_TIME_LENGTH];\r\n    scanf(\"%d %s %s\", &date ,of, time_period); //Scanf reads a string till it encounters a whitespace ... so I used two strings.\r\n\r\n    if(time_period[0] == 'm') //Month\r\n    {\r\n        savings = 12*(date <= 29) + 11*(date == 30) + 7*(date == 31); //Only one of these can be true.\r\n    }\r\n    else if(time_period[0] == 'w') //Week\r\n    {\r\n        savings = 52 + (date == 5 || date == 6); // Days 6 and 7 occur one more time\r\n    }\r\n\r\n    printf(\"%d\\n\", savings);\r\n    return 0;\r\n}\r\n\r\n------------------------------------------------------------\r\n\r\nThe way savings is written looks like an equation in vector algebra with all the relational expressions resembling dimensions ...\r\nOnly of the dimensions is true at a time for month, and for the day ... only 5 and 6 have an extra day."
  },
  {
    "path": "Explanations/Explanations - 9/One Dimensional Japanese Crossword Explanation.txt",
    "content": "\r\n--------------------------------------\r\n\r\nGo through the string .. Whenever a B is encountered, count the subsegment of Bs.\r\n\r\nint main()\r\n{\r\n    int no_of_blocks, segment_length;\r\n    char crossword[MAX_LENGTH];\r\n\r\n    scanf(\"%d %s\", &no_of_blocks, crossword);\r\n\r\n    vector <int> black_segment_length;\r\n    for(int i = 0; i < no_of_blocks; i += segment_length + 1)\r\n    {\r\n        segment_length = 0;\r\n        while(crossword[i + segment_length] == 'B')\r\n        {\r\n             segment_length++;\r\n        }\r\n\r\n        if(segment_length > 0)\r\n            black_segment_length.push_back(segment_length);\r\n    }\r\n\r\n    printf(\"%u\\n\", black_segment_length.size());\r\n    for(unsigned int i = 0; i < black_segment_length.size(); i++)\r\n        printf(\"%d \",black_segment_length[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Present from Lena Explanation.txt",
    "content": "\r\n--------------------------------------\r\n\r\nThese pattern printing problems are pretty interesting ... The idea is to divide the pattern into many triangles. \r\nAlso, have another loop for printing spaces. \r\n\r\nHere, for some reason, they didn't want a space at the end of a line ... That made the code a bit harder to read but I wasn't getting AC when there was a space.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    for(int row = 0; row <= n; row++)\r\n    {\r\n        for(int space = 0; space < n - row; space++)\r\n            printf(\"  \");\r\n\r\n        for(int number = 0; number <= row; number++)\r\n            if(row == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        for(int number = row - 1; number >= 0; number--)\r\n            if(number == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    for(int row = n - 1; row >= 0; row--)\r\n    {\r\n        for(int space = 0; space < n - row; space++)\r\n            printf(\"  \");\r\n\r\n        for(int number = 0; number <= row; number++)\r\n            if(row == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        for(int number = row - 1; number >= 0; number--)\r\n            if(number == 0)\r\n                printf(\"%d\", number);\r\n            else\r\n                printf(\"%d \", number);\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Prime Matrix.txt",
    "content": "You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: \nchoose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.\n\nYou are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: \nitself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not.\n\nA matrix is prime if at least one of the two following conditions fulfills:\n\nthe matrix has a row with prime numbers only;\nthe matrix has a column with prime numbers only;\nYour task is to count the minimum number of moves needed to get a prime matrix from the one you've got.\n\n----------------------------------------------\n\nLearnt how to implement a matrix as a vector of vectors ... Also, learnt that it's not recommended in real life applications but fine in competitive programming.\n\nvector <vector<int> > matrix(no_of_rows, vector <int> (no_of_columns, 0) )\n\nImportant to put a space in between the > ... vector <int> is the type of the vector and it is allocated, no_of_columns copies of vector <int>s.\n\n--------------------------------------\n\nUsed a sieve ... Got a runtime error because I made a mistake in the inner loop of the sieve ... Used an i.\n\nHere's what I did ... Precomputed all primes till 1e5 + 3. \n\nMade another vector called prime_distance ... where prime_distance[i] contains the minimum number which needs to be added to get to a prime number.\n\nTo get it .. Start at i = 1e5 + 3 and go down to 0 ... Keep track of the latest prime encountered and prime_distance[i] = latest prime - i.\n\n-------------------------\n\nvector <int> prime_distance(1e5 + 4);\n\nvoid precompute_prime_distance()\n{\n    vector <int> is_prime(1e5 + 10, true);\n\n    is_prime[0] = is_prime[1] = false;\n    for(int i = 2; i <= 1e5 + 3; i++)\n    {\n        if(is_prime[i])\n        {\n            for(int multiple = 2*i; multiple <= 1e5 + 3; multiple += i)\n            {\n                is_prime[multiple] = false;\n            }\n        }\n    }\n\n    int last_prime;\n    for(int i = 1e5 + 3; i >= 0; i--)\n\n        if(is_prime[i])\n            last_prime = i;\n\n        prime_distance[i] = last_prime - i;\n    }\n}\n\n------------------------------------------\n\nWhile reading the matrix ... STore prime_distance[i][j] in [i][j].\n\nAfter that find the minimum row and column sum.\n\n-------------------------------------------\n\nint main()\n{\n    const int INFINITY = 1e9 + 1;\n    int no_of_rows, no_of_columns;\n    scanf(\"%d %d\", &no_of_rows, &no_of_columns);\n\n    precompute_prime_distance();\n\n    vector <vector <int> > matrix(no_of_rows, vector<int> (no_of_columns) );\n\n    for(int row = 0; row < no_of_rows; row++)\n    {\n        for(int column = 0; column < no_of_columns; column++)\n        {\n            int element;\n            scanf(\"%d\", &element);\n\n            matrix[row][column] = prime_distance[element];\n        }\n    }\n\n    int min_row_sum = INFINITY;\n    for(int row = 0; row < no_of_rows; row++)\n    {\n        int row_sum = 0;\n        for(int column = 0; column < no_of_columns; column++)\n        {\n            row_sum += matrix[row][column];\n        }\n        min_row_sum = min(min_row_sum, row_sum);\n    }\n\n    int min_column_sum = INFINITY;\n    for(int column = 0; column < no_of_columns; column++)\n    {\n        int column_sum = 0;\n        for(int row = 0; row < no_of_rows; row++)\n        {\n            column_sum += matrix[row][column];\n        }\n        min_column_sum = min(min_column_sum, column_sum);\n    }\n\n    printf(\"%d\\n\",min(min_row_sum, min_column_sum));\n    return 0;\n} \n"
  },
  {
    "path": "Explanations/Explanations - 9/String Task Explanation.txt",
    "content": "\r\n--------------------------------------\r\n\r\nThe only trick of this problem is that y is also considered a vowel. I didn't know how many bytes the STL string allocates so I used both STL string and C string.\r\n\r\n\r\nint main()\r\n{\r\n    char initial_string[MAX_LENGTH];\r\n    string answer;\r\n    scanf(\"%s\", initial_string);\r\n\r\n    for(int i = 0; initial_string[i] != '\\0'; i++)\r\n    {\r\n        if(is_vowel(to_lower(initial_string[i])) == false)\r\n        {\r\n            answer += '.';\r\n            answer += to_lower(initial_string[i]);\r\n        }\r\n    }\r\n\r\n    cout << answer << \"\\n\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations - 9/Subtractions Explanation.txt",
    "content": "\r\n--------------------------------------\r\n\r\nThis is another way of asking the number of steps to find the GCD using the Euclidean algorithm. \r\n\r\nI used static variables here ! Static vriables retain their value through a recursive function call ...\r\n\r\nStatic variables are useful to measure recursion depth and collect meta-data about the recursion. All recursive calls use the same instance of data.\r\n\r\nUsing a static variable would be fine if there was only one query. But, here there are many queries, and the static variable doesn't start at 0 for each query. It \r\nstarts at the value the last query ended. So, better to just write a simply non-tail recursive function.\r\n\r\n-----------------------------------------------\r\n\r\nint no_of_steps_in_finding_gcd(int a, int b)\r\n{\r\n    int m = min(a, b);\r\n    int n = max(a, b);\r\n\r\n    if(m == 0)\r\n        return 0;\r\n    else\r\n        return n/m + no_of_steps_in_finding_gcd(m, n%m);\r\n}\r\n\r\nvoid solve()\r\n{\r\n    int a, b;\r\n    scanf(\"%d %d\", &a, &b);\r\n    printf(\"%d\\n\", no_of_steps_in_finding_gcd(a, b) );\r\n}\r\n\r\n------------------------------"
  },
  {
    "path": "Explanations/Explanations - 9/Toy Army Explanation.txt",
    "content": "The hero of our story, Valera, and his best friend Arcady are still in school, and therefore they spend all the free time playing turn-based strategy \r\n\"GAGA: Go And Go Again\". The gameplay is as follows.\r\n\r\nThere are two armies on the playing field each of which consists of n men (n is always even). \r\nThe current player specifies for each of her soldiers an enemy's soldier he will shoot (a target) and then all the player's soldiers shot simultaneously. \r\nThis is a game world, and so each soldier shoots perfectly, that is he absolutely always hits the specified target. If an enemy soldier is hit, he will surely die.\r\n It may happen that several soldiers had been indicated the same target. Killed soldiers do not participate in the game anymore.\r\n\r\nThe game \"GAGA\" consists of three steps: first Valera makes a move, then Arcady, then Valera again and the game ends.\r\n\r\nYou are asked to calculate the maximum total number of soldiers that may be killed during the game.\r\n\r\n-------------------------------------------------------\r\n\r\nThis is one of those problems that's a lot harder to prove than to code ... \r\n\r\nTo maximise the number of killed soldiers, both sides will have to kill as many soldiers as possible ... \r\n\r\nNotice that if there were only 2 turns, then n soldiers will always be killed no matter what.\r\n\r\nProof - If the first side kills all n soldiers on it's turn, then n soldiers are killed and there are no alive soldiers on the other side for turn 2.\r\n\r\nIf the first side kills k soldiers, .... then the n-k surviving soldiers will all kill 1 soldiers each. They have to do this because they only get 1 turn.\r\n\r\nSo, number of soldiers dead after 2 turns = k + (n - k) = n.\r\n\r\n--------------------------------\r\n\r\nNow, on turn 3 ... the number of soldiers killed has to be maximised ... This is the strategy that needs to be optimised...\r\n\r\nFor this, side 1 has to kill half of side 2's soldiers on it's first turn...\r\n\r\nIF side 1 kills less than half of their soldiers ... Then after all of side 2's soldiers kill a soldier ... side 1 will not have enough soldiers to completely kill side 1.\r\n\r\nIf they killed more than half of their soldiers, then after two turns it would be n + r ... r < n/2 [r is all the people killed on turn 3 - survivors of side 1]\r\n... The way to maximise r is to set r = n/2.  If r is greater, we get a less than optimal result.\r\n\r\n---------------------------------------------\r\n\r\nAns = n + n/2 = 3n/2 ... if n is even ... If n is odd then n/2 is rounded off to the higher side ... \r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_soldiers, killed;\r\n    scanf(\"%d\", &number_of_soldiers);\r\n\r\n    killed = 3*((number_of_soldiers + 1)/2);\r\n    printf(\"%d\\n\", killed);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Anastasia and Pebbles Explanation.txt",
    "content": "Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. \r\nAt first, she decided to collect all the pebbles she could find in the park.\r\n\r\nShe has only two pockets. She can put at most k pebbles in each pocket at the same time. \r\nThere are n different pebble types in the park, and there are wi pebbles of the i-th type. \r\nAnastasia is very responsible, so she never mixes pebbles of different types in same pocket. \r\nHowever, she can put different kinds of pebbles in different pockets at the same time. \r\nUnfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.\r\n\r\nHelp her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, \r\ntaking into consideration that Anastasia can't place pebbles of different types in same pocket.\r\n\r\n----------------------------------------------\r\n\r\nFirst imagine that there's only one pocket ... How long will it take to pick up wi pebbles ? \r\n\r\nceil(wi/k) ...\r\n\r\n\r\nNow we have two pockets ... No of days = ceil(no of pebbles/2)\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_pebble_types, pebble_limit;\r\n    scanf(\"%d %d\", &no_of_pebble_types, &pebble_limit);\r\n\r\n    int days_to_collect_all_pebbles = 0;\r\n    for(int i = 1; i <= no_of_pebble_types; i++)\r\n    {\r\n        int pebble_i;\r\n        scanf(\"%d\", &pebble_i);\r\n\r\n        days_to_collect_all_pebbles += pebble_i/pebble_limit + (pebble_i%pebble_limit != 0); //Ceil\r\n    }\r\n    days_to_collect_all_pebbles = days_to_collect_all_pebbles/2 + days_to_collect_all_pebbles%2;\r\n\r\n    printf(\"%d\\n\", days_to_collect_all_pebbles);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Bear and Three Balls Explanation.txt",
    "content": "Limak is a little polar bear. He has n balls, the i-th ball has size ti.\r\n\r\nLimak wants to give one ball to each of his three friends. Giving gifts isn't easy  there are two rules Limak must obey to make friends happy:\r\n\r\nNo two friends can get balls of the same size.\r\nNo two friends can get balls of sizes that differ by more than 2.\r\nFor example, Limak can choose balls with sizes 4, 5 and 3, or balls with sizes 90, 91 and 92. But he can't choose balls with sizes 5, 5 and 6 \r\n(two friends would get balls of the same size), and he can't choose balls with sizes 30, 31 and 33 (because sizes 30 and 33 differ by more than 2).\r\n\r\nYour task is to check whether Limak can choose three balls that satisfy conditions above.\r\n\r\n----------------------------------------------------\r\n\r\nMaintain a set of all ball numbers ... Pick up every ball and check if ball + 1, ball - 1 are also present in the set.\r\n\r\nEach count operation and insert operation occurs in log N time ... Overall complexity is O(N log N).\r\n\r\nN elements.\r\n\r\n------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_balls;\r\n    scanf(\"%d\", &no_of_balls);\r\n\r\n    set <int> ball;\r\n    for(int i = 1; i <= no_of_balls; i++)\r\n    {\r\n        int ball_i;\r\n        scanf(\"%d\", &ball_i);\r\n        ball.insert(ball_i);\r\n    }\r\n\r\n    bool gift_givable = false;\r\n    for(set <int> :: iterator i = ball.begin(); i != ball.end(); i++)\r\n    {\r\n        int ball_i = *i;\r\n\r\n        if(ball.count(ball_i + 1) == 1 && ball.count(ball_i - 1) == 1)\r\n        {\r\n            gift_givable = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(gift_givable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 12/Co Prime Array Explanation.txt",
    "content": "You are given an array of n elements, you must make it a co-prime array in as few moves as possible.\r\n\r\nIn each move you can insert any positive integral number you want not greater than 109 in any place in the array.\r\n\r\nAn array is co-prime if any two adjacent numbers of it are co-prime.\r\n\r\nIn the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.\r\n\r\n----------------------------------------------\r\n\r\nThis is similar to the question asking what is the smallest currency that cannot be expressed. If there is no 1, it is 1 and if 1 is there all can be expressed.\r\n\r\nOr is there an element in this array which divides every other element ? If it is yes, then it has to be the smallest element.\r\n\r\nOr what is the length of longest coprime sequence in array ? If any two elements are coprime, entire array is coprime.\r\n\r\nHere, the observation needed is that gcd(1, n) = 1.\r\n\r\nInsert all elements into the new vector, but just check if adjacent elements are coprime. If any two adjacent elements are not coprime. Insert a 1 in between.\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    vector <int> coprime_array;\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number_i;\r\n        scanf(\"%d\", &number_i);\r\n\r\n        if(i == 1 || gcd(coprime_array.back(), number_i) == 1)\r\n        {\r\n            coprime_array.push_back(number_i);\r\n        }\r\n        else\r\n        {\r\n            coprime_array.push_back(1);\r\n            coprime_array.push_back(number_i);\r\n        }\r\n    }\r\n\r\n    int no_of_operations = coprime_array.size() - no_of_numbers;\r\n\r\n    printf(\"%d\\n\", no_of_operations);\r\n    for(unsigned int i = 0; i < coprime_array.size(); i++)\r\n        printf(\"%d \", coprime_array[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Dima and Friends Explanation.txt",
    "content": "Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. \r\nIn the morning they decided that they need to clean the place.\r\n\r\nTo decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, \r\nand then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, \r\nrespective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.\r\n\r\nFor example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. \r\nIf there were 2 or say, 8 fingers shown, then his friend would clean the place.\r\n\r\nDima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand \r\n(one to five), so that he did not have to clean the place. Help Dima.\r\n\r\n-----------------------------------------------\r\n\r\nFirstly, no of people = no of friends + 1\r\n\r\nDima will have to clean the apartment if the total number of fingers = 1 mod (no of people)\r\n\r\nGo from i = 1 to 5 and count how many i's when added to other fingers don't make the total 1 mod (no of people).\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_friends;\r\n    scanf(\"%d\", &no_of_friends);\r\n\r\n    int other_fingers = 0;\r\n    for(int i = 1; i <= no_of_friends; i++)\r\n    {\r\n        int finger_i;\r\n        scanf(\"%d\", &finger_i);\r\n\r\n        other_fingers += finger_i;\r\n    }\r\n\r\n    const int NO_OF_FINGERS = 5;\r\n    int no_of_choices = 0, no_of_people = no_of_friends + 1;\r\n\r\n    for(int dima_fingers = 1; dima_fingers <= NO_OF_FINGERS; dima_fingers++)\r\n    {\r\n        int total_fingers = other_fingers + dima_fingers;\r\n        no_of_choices += (total_fingers%no_of_people != 1);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_choices);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Dreamoon and Stairs Alternate Solution Explanation.txt",
    "content": "\r\n-----------------------------------------------------\r\n\r\nOkay, it is established that the lower limit for number of steps = ceil(n/2) ... and upper bound is n.\r\n\r\nLet's say the lower limit, l = q.m + r, by the division algorithm, 0 <= r < m ...\r\n\r\nSo the first mulitple of m greater than l will be \r\n\r\n(q + 1). m \r\n\r\nor q.m if l is a multiple of m.\r\n\r\nMore succintly, it can be written as multiplier = ceil[l/m] = (l/m + (l%m != 0)) , if l is not a multiple of m, then add 1, else it is simply l/m.\r\n\r\nceil(l/m)*m gives the smallest multiple of m greater than l. \r\n\r\nIf l is a multiple of l, it returns l.\r\n\r\nElse it returns another number > l and multiple of m.\r\n\r\nJust check if the smallest multiple of m greater than l is smaller than the no of steps.\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_steps, multiple;\r\n    scanf(\"%d %d\", &no_of_steps, &multiple);\r\n\r\n    int lower_limit = no_of_steps/2 + no_of_steps%2;\r\n\r\n    int smallest_multiplier = lower_limit/multiple + (lower_limit%multiple != 0);\r\n\r\n    int minimum_number_of_steps = smallest_multiplier*multiple;\r\n\r\n    printf(\"%d\\n\", (minimum_number_of_steps <= no_of_steps ? minimum_number_of_steps : - 1));\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Dreamoon and Stairs Explanation.txt",
    "content": "Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m.\r\n\r\nWhat is the minimal number of moves making him climb to the top of the stairs that satisfies his condition?\r\n\r\n---------------------------------------------------------\r\n\r\nEstablish a lower bound for the number of steps you must take - this is ceil(n/2)\r\n\r\nIn this case, we take as many steps of 2 as possible and then take one last step. The number of steps cannot be less than this.\r\n\r\nThe number of steps cannot be greater than the number of steps either. In that case, we take n steps of 1.\r\n\r\nThe lower bound consists of all steps of 2, upper bound consists of all steps of 1.\r\n\r\nI iterated from the lower bound to the upper bound ... and in each step, replace a step of 2 by 2 steps of 1 (Increasing the number of steps by 1).\r\n\r\nChoose the first no of steps that is a multiple of m.\r\n\r\nThis is O(n) ... There is an O(1) solution as well.\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_steps, multiple;\r\n    scanf(\"%d %d\", &no_of_steps, &multiple);\r\n\r\n    int minimum_no_of_steps = no_of_steps/2 + no_of_steps%2;\r\n\r\n    while(minimum_no_of_steps <= no_of_steps)\r\n    {\r\n        if(minimum_no_of_steps%multiple == 0)\r\n        {\r\n            break;\r\n        }\r\n        minimum_no_of_steps++;\r\n    }\r\n\r\n    printf(minimum_no_of_steps > no_of_steps ? \"-1\\n\" : \"%d\\n\", minimum_no_of_steps);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Fashion in Berland Explanation.txt",
    "content": "According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. \r\nAlso if the jacket has only one button, it should be fastened, so the jacket will not swinging open.\r\n\r\nYou are given a jacket with n buttons. Determine if it is fastened in a right way.\r\n--------------------------------------------------------\r\n\r\nThe case where there's one button confused me. I thought one button can't be fashionable no matter what ... But, if there's one button it should be closed.\r\n\r\n---------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_buttons;\r\n    scanf(\"%d\", &no_of_buttons);\r\n\r\n    int no_of_open_buttons = 0;\r\n    for(int i = 1; i <= no_of_buttons; i++)\r\n    {\r\n        int button_i;\r\n        scanf(\"%d\", &button_i);\r\n\r\n        no_of_open_buttons += (button_i == 0);\r\n    }\r\n\r\n    bool fashionable = (no_of_buttons > 1 && no_of_open_buttons == 1) || (no_of_buttons == 1 && no_of_open_buttons == 0);\r\n    printf(fashionable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Inbox (100500) Explanation.txt",
    "content": "Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.\r\n\r\nAlexey's mail program can either show a list of all letters or show the content of a single letter. \r\nAs soon as the program shows the content of an unread letter, it becomes read letter \r\n(if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations:\r\n\r\nMove from the list of letters to the content of any single letter.\r\nReturn to the list of letters from single letter viewing mode.\r\nIn single letter viewing mode, move to the next or to the previous letter in the list. \r\nYou cannot move from the first letter to the previous one or from the last letter to the next one.\r\nThe program cannot delete the letters from the list or rearrange them.\r\n\r\nAlexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. \r\nWhat minimum number of operations does Alexey need to perform to read all unread letters?\r\n\r\n----------------------------------------------\r\n\r\nSo, every unread letter needs to be read ... So the number of operations must be at least as many as the number of unread letters.\r\n\r\nAnother observation is that switching from letter i to i + 1 takes 1 operation ... and switching from i to i + 2 ... needs 2 ... \r\nFirst go to big display mode and then choose 2\r\n\r\nWhenever there are consecutive unread letters, switch in between them and use an extra move to go to big display mode when it isn't like that.\r\n\r\nWe need the following information - no of unread letters and no of unread segments.\r\n\r\nWe need to perform skips = 1 less than the number of unread segments.\r\n\r\nHowever, the special case is when there are 0 unread segments, ... the answer shouldn't be -1 ... Just add max(no of segments - 1, 0) to no of unread letters.\r\n\r\n------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_letters;\r\n    scanf(\"%d\", &no_of_letters);\r\n\r\n    int previous_letter_status = 0, no_of_unread_letters = 0, no_of_unread_segments = 0;\r\n    for(int i = 1; i <= no_of_letters; i++)\r\n    {\r\n        int unread;\r\n        scanf(\"%d\", &unread);\r\n\r\n        no_of_unread_letters += (unread == 1);\r\n\r\n        if(previous_letter_status == 0 && unread == 1)\r\n            no_of_unread_segments++;\r\n\r\n        previous_letter_status = unread;\r\n    }\r\n\r\n    int no_of_operations = no_of_unread_letters + max(no_of_unread_segments - 1, 0); //Incase there are no unread segments, it should be 0\r\n    printf(\"%d\\n\", no_of_operations);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Key Races Explanation.txt",
    "content": "Two boys decided to compete in text typing on the site \"Key races\". During the competition, they have to type a text consisting of s characters. \r\nThe first participant types one character in v1 milliseconds and has ping t1 milliseconds. \r\nThe second participant types one character in v2 milliseconds and has ping t2 milliseconds.\r\n\r\nIf connection ping (delay) is t milliseconds, the competition passes for a participant as follows:\r\n\r\nExactly after t milliseconds after the start of the competition the participant receives the text to be entered.\r\nRight after that he starts to type it.\r\nExactly t milliseconds after he ends typing all the text, the site receives information about it.\r\nThe winner is the participant whose information on the success comes earlier. If the information comes from both participants at the same time, \r\nit is considered that there is a draw.\r\n\r\nGiven the length of the text and the information about participants, determine the result of the game.\r\n\r\n---------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length_text, speed_1, speed_2, ping_1, ping_2;\r\n    scanf(\"%d %d %d %d %d\", &length_text, &speed_1, &speed_2, &ping_1, &ping_2);\r\n\r\n    int total_time_1 = speed_1*length_text + 2*ping_1;\r\n    int total_time_2 = speed_2*length_text + 2*ping_2;\r\n\r\n    if(total_time_1 == total_time_2)\r\n        printf(\"Friendship\\n\");\r\n    else\r\n        printf(total_time_1 < total_time_2 ? \"First\\n\" : \"Second\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 12/Lecture Explanation.txt",
    "content": "You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.\r\n\r\nYou know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, \r\neach language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. \r\nMoreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, \r\nthere exists exactly one word in the other language having has the same meaning.\r\n\r\nYou can write down every word the professor says in either the first language or the second language. Of course, \r\nduring the lecture you write down each word in the language in which the word is shorter. \r\nIn case of equal lengths of the corresponding words you prefer the word of the first language.\r\n\r\nYou are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.\r\n\r\n-------------------------------------------\r\n\r\nI solved the problem more generally - I solved the problem for when the professor talks in mixed languages and output must be the shortest word of each language.\r\n\r\nUse two dictionaries ... One which maps words from first language to second language and other which maps words from second language to first language.\r\n\r\nAnother boolean vector to keep track of which words are in which language.\r\n\r\nFor each word, print the smaller length vector.\r\n\r\nBoth solutions are included ... The one I solved first(the harder problem) and the one in which the lecture is only in the first language.\r\n\r\n--------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length_of_sentence, no_of_words;\r\n    cin >> length_of_sentence >> no_of_words;\r\n\r\n    map <string, string> translated;\r\n\r\n    for(int i = 1; i <= no_of_words; i++)\r\n    {\r\n        string word, translation;\r\n        cin >> word >> translation;\r\n\r\n        translated[word] = translation;\r\n    }\r\n\r\n    for(int i = 1; i <= length_of_sentence; i++)\r\n    {\r\n        string current_word;\r\n        cin >> current_word;\r\n\r\n        cout << (current_word.length() <= translated[current_word].length() ? current_word : translated[current_word]) << \" \";\r\n    }\r\n    return 0;\r\n}\r\n\r\n----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length_of_sentence, no_of_words;\r\n    cin >> length_of_sentence >> no_of_words;\r\n\r\n    map <string, string> dictionary_1_to_2;\r\n    map <string, string> dictionary_2_to_1;\r\n    map <string, int> is_in_language_1;\r\n\r\n    for(int i = 1; i <= no_of_words; i++)\r\n    {\r\n        string word, translation;\r\n        cin >> word >> translation;\r\n\r\n        dictionary_1_to_2[word] = translation;\r\n        dictionary_2_to_1[translation] = word;\r\n\r\n        is_in_language_1[word] = true;\r\n        is_in_language_1[translation] = false;\r\n    }\r\n\r\n    for(int i = 1; i <= length_of_sentence; i++)\r\n    {\r\n        string current_word;\r\n        cin >> current_word;\r\n\r\n        string language_1_word =  is_in_language_1[current_word] ? current_word : dictionary_2_to_1[current_word];\r\n\r\n        string language_2_word = (is_in_language_1[current_word] ? dictionary_1_to_2[current_word] : current_word);\r\n\r\n        cout << (language_1_word.length() <= language_2_word.length() ? language_1_word : language_2_word) << \" \";\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 12/Little Girl and Maximum Sum.txt",
    "content": "The little girl loves the problems on array queries very much.\n\nOne day she came across a rather well-known problem: you've got an array of n elements (the elements of the array are indexed starting from 1); \nalso, there are q queries, each one is defined by a pair of integers li, ri (1 ≤ li ≤ ri ≤ n). \nYou need to find for each query the sum of elements of the array with indexes from li to ri, inclusive.\n\nThe little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes \nthe sum of query replies maximum possible. Your task is to find the value of this maximum sum.\n\n---------------------------------------------------------------\n\nKeep track of the number of times each cell is called upon in a query. Place the largest number in the cell that is queried upon the most.\nPlace the second largest number in the cell that is queried upon the second most ... and so on. \n\nThis part was easy\n\n\nI got a TLE first. The trick was in deciding how to mark the number of times each cell was queried.\n\nfor(int i = 1; i <= no_of_queries; i++)\n    {\n        int left_i, right_i;\n        scanf(\"%d %d\", &left_i, &right_i);\n\n        for(int index = left_i; index <= right_i; index++)\n            no_of_times_index_queried[index]++;\n    }\n\n\nI initially did it by brute force ... Went from li to ri for every query and incremented no of times each cell is called upon ...\n\nThis is O(n^2) and doesn't pass.\n\nA better solution is to mark only li and ri in a seperate vector ... For every index only store the number of queries starting there and ending there.\n\nThen in one pass, find the number of times each cell is queried in the following way -\n\nno_of_times_queried = 0\nfor(i = 0; i <= n; i++)\n\tno_of_times_queried += (no_of_queries_starting[i] - no_of_queries_ending[i])\n\tno_of_times_queried[i] = no_of_times_queried\n\nThis is similar to a problem asking about trains coming and going on platforms ... What is the maximum number of trains that will exist at the same time ?\nThere too .. Keep track of the end points of arrival and leaving only and then no of trains at a given point of time changes by the number of trains that have arrived then\nand decreases by the number of trains that have left then.\n\n-------------------------------------------------------------------------\n\nint main()\n{\n    int no_of_elements, no_of_queries;\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\n\n    vector <int> element(no_of_elements + 1, 0);\n    for(int i = 1; i <= no_of_elements; i++)\n        scanf(\"%d\", &element[i]);\n\n    vector <int> no_of_queries_starting_here(no_of_elements + 1, 0);\n    vector <int> no_of_queries_ending_here(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_queries; i++)\n    {\n        int left_i, right_i;\n        scanf(\"%d %d\", &left_i, &right_i);\n\n        no_of_queries_starting_here[left_i]++;\n\n        if(right_i + 1 <= no_of_elements)\n            no_of_queries_ending_here[right_i + 1]++;\n    }\n\n    int no_of_queries_on_this_index = 0;\n    vector <int> no_of_times_index_queried(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        no_of_queries_on_this_index += (no_of_queries_starting_here[i] - no_of_queries_ending_here[i]);\n\n        no_of_times_index_queried[i] = no_of_queries_on_this_index;\n    }\n\n    sort(all(element));\n    sort(all(no_of_times_index_queried));\n\n    long long maximum_sum = 0;\n    for(int i = 1; i <= no_of_elements; i++)\n        maximum_sum += no_of_times_index_queried[i]*1LL*element[i];\n\n    printf(\"%I64d\\n\", maximum_sum);\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Explanations/Explanations 12/Santa Claus and Candies Explanation.txt",
    "content": "Santa Claus has n candies, he dreams to give them as gifts to children.\r\n\r\nWhat is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. \r\nSanta Class wants to give all n candies he has.\r\n\r\n-----------------------------------------------\r\n\r\nThe number of people who get gifts is equal to the greatest triangular number smaller than n. \r\n\r\nThe strategy I used for distribution was for person i = 1 to p - 1, give p - 1 gifts and give all remaining gifts to the last person.\r\n\r\n--------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_gifts;\r\n    scanf(\"%d\", &no_of_gifts);\r\n\r\n    int no_of_people = 1;\r\n    while(no_of_people*(no_of_people + 1) <= 2*no_of_gifts)\r\n        no_of_people++;\r\n\r\n    no_of_people--;\r\n\r\n    printf(\"%d\\n\", no_of_people);\r\n    for(int i = 1; i < no_of_people; i++)\r\n    {\r\n        printf(\"%d \", i);\r\n        no_of_gifts -= i;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_gifts); //Last person gets all remaining gifts\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Sergey and Dima Explanation.txt",
    "content": "Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. \r\nThe players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. \r\nThe game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.\r\n\r\nSereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.\r\n\r\nInna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.\r\n---------------------------------------\r\n\r\nUse two pointers - one at the front and one at the end ... Add the greater card to whoever's turn it is and advance the pointer used.\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_cards;\r\n    scanf(\"%d\", &no_of_cards);\r\n\r\n    vector <int> card(no_of_cards);\r\n    for(int i = 0; i < no_of_cards; i++)\r\n        scanf(\"%d\", &card[i]);\r\n\r\n    int sergey_sum = 0, dima_sum = 0;\r\n    for(int front_i = 0, back_i = no_of_cards - 1, no_of_turns = 1; no_of_turns <= no_of_cards; no_of_turns++)\r\n    {\r\n        int greater_card = max(card[front_i], card[back_i]);\r\n\r\n        if(card[front_i] >= card[back_i])\r\n            front_i++;\r\n        else\r\n            back_i--;\r\n\r\n        if(no_of_turns%2 == 1)\r\n            sergey_sum += greater_card;\r\n        else\r\n            dima_sum += greater_card;\r\n\r\n    }\r\n\r\n    printf(\"%d %d\\n\", sergey_sum, dima_sum);\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 12/Sleuth Explanation.txt",
    "content": "Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, \r\nhe should investigate a \"crime\" and find out what is happening. He can ask any questions whatsoever that can be answered with \"Yes\" or \"No\". \r\nAll the rest agree beforehand to answer the questions like that: if the questions last letter is a vowel, they answer \"Yes\" and if the last letter is a consonant, \r\nthey answer \"No\". Of course, the sleuth knows nothing about it and his task is to understand that.\r\n\r\nUnfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. Thats why Vasyas friends ask you to \r\nwrite a program that would give answers instead of them.\r\n\r\nThe English alphabet vowels are: A, E, I, O, U, Y\r\n\r\nThe English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z\r\n\r\n----------------------------------------\r\n\r\nThere are spaces so I used fgets ... Y is also a vowel here.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    char question[MAX_LENGTH];\r\n    fgets(question, MAX_LENGTH, stdin);\r\n\r\n    bool last_letter_vowel = false;\r\n    for(int i = strlen(question) - 1; i >= 0; i--)\r\n    {\r\n        if(is_alpha(question[i]) )\r\n        {\r\n            if(is_vowel(question[i]) )\r\n               last_letter_vowel = true;\r\n\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(last_letter_vowel ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 12/The Festive Evening Explanation.txt",
    "content": "It's the end of July  the time when a festive evening is held at Jelly Castle! \r\nGuests from all over the kingdom gather here to discuss new trends in the world of confectionery. \r\nYet some of the things discussed here are not supposed to be disclosed to the general public: \r\nthe information can cause discord in the kingdom of Sweetland in case it turns out to reach the wrong hands. So it's a necessity to not let any uninvited guests in.\r\n\r\nThere are 26 entrances in Jelly Castle, enumerated with uppercase English letters from A to Z. \r\nBecause of security measures, each guest is known to be assigned an entrance he should enter the castle through. \r\nThe door of each entrance is opened right before the first guest's arrival and closed right after the arrival of the last guest \r\nthat should enter the castle through this entrance. No two guests can enter the castle simultaneously.\r\n\r\nFor an entrance to be protected from possible intrusion, a candy guard should be assigned to it. \r\nThere are k such guards in the castle, so if there are more than k opened doors, one of them is going to be left unguarded! \r\nNotice that a guard can't leave his post until the door he is assigned to is closed.\r\n\r\nSlastyona had a suspicion that there could be uninvited guests at the evening. \r\nShe knows the order in which the invited guests entered the castle, and wants you to help her check whether there was a moment when more than k doors were opened.\r\n\r\n-----------------------------------------\r\n\r\nI learnt how to write a clean implementation for this problem. Initially, I used two vectors to keep track of the first and last appearance of each guest.\r\n\r\nAnd the number of doors open increases by 1 if a guest enters at position i and decreases by 1 at position i-1.\r\n\r\n(You must decrease the number of open doors 1 position after the last entry of a guest because the case where there's a single guest of a type -\r\n\r\nABCDEF ... Here, the number of doors open will always be 0. The code was pretty ugly.)\r\n\r\nvector <int> first_appearance(26, -1);\r\n    vector <int> first_entry_at(no_of_guests, false);\r\n    for(int i = 0; guests[i] != '\\0'; i++)\r\n        if(first_appearance[guests[i] - 'A'] == -1)\r\n            first_appearance[guests[i]- 'A'] = i, first_entry_at[i] = true;\r\n\r\n    vector <int> last_appearance(26, -1);\r\n    vector <int> last_entry_at(no_of_guests, false);\r\n    for(int i = no_of_guests - 1; i >= 0; i--)\r\n        if(last_appearance[guests[i] - 'A'] == -1)\r\n            last_appearance[guests[i]- 'A'] = i, last_entry_at[i] = true;\r\n\r\n    int maximum_doors_opened = 1, doors_open = 1;\r\n    for(int i = 1; i < no_of_guests; i++)\r\n    {\r\n        doors_open += first_entry_at[i];\r\n        doors_open -= last_entry_at[i - 1];\r\n\r\n        maximum_doors_opened = max(maximum_doors_opened, doors_open);\r\n    }\r\n\r\n    printf(maximum_doors_opened > no_of_guards ? \"YES\\n\" : \"NO\\n\");\r\n\r\n---------------------------------------------------------------------\r\n\r\nI saw a better way to keep track of the last occurence of each character. Rather than start from the end, and pick up a character only if it is unmapped,\r\nstart from the beginning and always mark each character to it's position. This way you don't have to check if a character is unmarked.\r\nEach character is always set to it's last position.\r\n\r\nand to keep track of number of guests in, use a set. Much cleaner. A set will always ensure distinctness (balanced tree). \r\nIf i is the last position of a character, then delete that element from the set AFTER comparing the size of the set with the required amount.\r\nOtherwise one character guests will throw bugs.\r\n\r\nThis problem was interesting because it's logic was simply but implementation seemed difficult. I learnt a lot. Using a map and a set and the right way to \r\nkeep track of the last occurence of each character. (Go in the opposite direction).\r\n\r\n------------------------------------------------------\r\n\r\nvector <int> first_appearance(26, -1);\r\n    vector <int> first_entry_at(no_of_guests, false);\r\n    for(int i = 0; guests[i] != '\\0'; i++)\r\n        if(first_appearance[guests[i] - 'A'] == -1)\r\n            first_appearance[guests[i]- 'A'] = i, first_entry_at[i] = true;\r\n\r\n    vector <int> last_appearance(26, -1);\r\n    vector <int> last_entry_at(no_of_guests, false);\r\n    for(int i = no_of_guests - 1; i >= 0; i--)\r\n        if(last_appearance[guests[i] - 'A'] == -1)\r\n            last_appearance[guests[i]- 'A'] = i, last_entry_at[i] = true;\r\n\r\n    int maximum_doors_opened = 1, doors_open = 1;\r\n    for(int i = 1; i < no_of_guests; i++)\r\n    {\r\n        doors_open += first_entry_at[i];\r\n        doors_open -= last_entry_at[i - 1];\r\n\r\n        maximum_doors_opened = max(maximum_doors_opened, doors_open);\r\n    }\r\n\r\n    printf(maximum_doors_opened > no_of_guards ? \"YES\\n\" : \"NO\\n\");"
  },
  {
    "path": "Explanations/Explanations 12/The Number on the Board Explanation.txt",
    "content": "Some natural number was written on the board. Its sum of digits was not less than k. \r\nBut you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.\r\n\r\nYou have to find the minimum number of digits in which these two numbers can differ.\r\n\r\n----------------------------------------------------------\r\n\r\nHere's what I first did. Keep track of the sum initially .. Then go through the digits of the number on board and make each digit 9 if it isn't already 9 as long as the \r\nsum is less than k.\r\n\r\nThis was wrong ... Consider the case 11 500.\r\n\r\nAccording to this algorithm, answer will be 2, since 5 becomes 9 and digit sum becomes 9. However, we can make one of the 0s 9 and achieve it in one move.\r\n\r\nSo, then I sorted all the numbers and then made each digit 9, starting from 0.\r\n\r\n-------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int digit_sum;\r\n    char number_on_board[MAX_LENGTH];\r\n    scanf(\"%d %s\", &digit_sum, number_on_board);\r\n\r\n    vector <int> board_number;\r\n    int board_digit_sum = 0;\r\n    for(int i = 0; number_on_board[i] != '\\0'; i++)\r\n    {\r\n        board_digit_sum += number_on_board[i] - '0';\r\n        board_number.push_back(number_on_board[i] - '0');\r\n    }\r\n\r\n    sort(all(board_number));\r\n    int min_no_of_digit_changes = 0;\r\n    for(unsigned int i = 0; i < board_number.size() && board_digit_sum < digit_sum; i++)\r\n    {\r\n        if(board_number[i] != 9)\r\n        {\r\n            board_digit_sum += 9 - board_number[i];\r\n            min_no_of_digit_changes++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", min_no_of_digit_changes);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/A Good Contest Explanation.txt",
    "content": "\r\n----------------------------------------------------\r\n\r\nIf there's any user for whom before >= 2400 and after >= before, then the contest was good.\r\n\r\nint main()\r\n{\r\n    int no_of_users, good_contest = false;\r\n    scanf(\"%d\", &no_of_users);\r\n\r\n    while(no_of_users--)\r\n    {\r\n        char name[MAX_SIZE];\r\n        int before_score, after_score;\r\n        scanf(\"%s %d %d\", name, &before_score, &after_score);\r\n\r\n        if(before_score >= 2400 && after_score > before_score)\r\n            good_contest = true;\r\n    }\r\n\r\n    printf(good_contest ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Arpa's Obvious Problem and Mehrad's Terrible Solution Explanation.txt",
    "content": "\r\nThere is an array ... Count the number of pairs for which A[i]XOR A[j] = x.\r\n\r\nThere are upto 10^5 elements in the array.\r\n\r\n---------------------------------------------------------------------\r\n\r\nSo iterating through every pair in the array takes O(n^2) time and it won't pass the time limit.\r\n\r\nI was thinking of how to do it and then it suddenly hit me !\r\n\r\nXOR(A[i], A[j]) = X\r\nXOR(A[i], A[i], A[j]) = XOR(A[i], X)\r\nXOR(0, A[j]) = XOR(A[i], X)\r\nA[j] = XOR(A[i], X)\r\n\r\nSo, this is an easier operation. \r\n\r\nInstead of iterating through every pair of the array and then checking if it gives X on XOR.\r\n\r\nBuild a frequency table of all elements. This takes O(n log n) time.\r\n\r\nThen go through each frequency bucket. Check what the frequency of XOR(A[i], X) is.\r\nEvery element of A[i] will match with every element of A[j]. Multiply them to get the pairs.\r\n\r\nThere are n elements and each such operation will take O(log n) time. \r\n\r\nOne tricky thing to watch out for is when A[i]'s complement is itself ... in that case, each A[i] will be paired off with every other element in it's frequency bucket.\r\nPair frequency in this case, will be frequency[A[i]^X] - 1. (It doesn't get paired with itself).\r\n\r\nDivide the number of pairs by 2 at the end since we have counted each pair twice. \r\n\r\nO(n log n).\r\n\r\n--------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, target;\r\n    scanf(\"%d %d\", &no_of_elements, &target);\r\n\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        frequency[element_i]++;\r\n    }\r\n\r\n    long long no_of_good_pairs = 0;\r\n    for(map <int, int>:: iterator i = frequency.begin(); i != frequency.end(); i++)\r\n    {\r\n        int element_i = i->first;\r\n        int frequency_i = i->second;\r\n\r\n        int pair_element = target^element_i;\r\n        int pair_frequency = (element_i == pair_element ? frequency_i - 1 : frequency[pair_element]);\r\n\r\n        no_of_good_pairs += pair_frequency*1LL*frequency_i;\r\n    }\r\n\r\n    no_of_good_pairs = no_of_good_pairs/2;\r\n\r\n    printf(\"%I64d\\n\", no_of_good_pairs);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Arrays Explanation.txt",
    "content": "You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers \r\nin array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.\r\n\r\n--------------------------------------------\r\n\r\nCompare the k-th element from the front in A to the m-th element from the back in B.\r\n\r\nint main()\r\n{\r\n    int size_a, size_b;\r\n    scanf(\"%d %d\", &size_a, &size_b);\r\n\r\n    int last_a, first_b, last_a_position, first_b_position;\r\n    scanf(\"%d %d\", &last_a_position, &first_b_position);\r\n\r\n    int element_i;\r\n    for(int i = 1; i <= size_a; i++)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        if(i == last_a_position)\r\n            last_a = element_i;\r\n    }\r\n\r\n    for(int i = size_b; i >= 1; i--)\r\n    {\r\n        scanf(\"%d\", &element_i);\r\n        if(i == first_b_position)\r\n            first_b = element_i;\r\n    }\r\n\r\n    printf(last_a < first_b ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Arya and Bran Explanation.txt",
    "content": "Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.\r\n\r\nAt first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. \r\nEvery day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.\r\n\r\nYour task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. \r\nFormally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).\r\n\r\nPrint -1 if she can't give him k candies during n given days.\r\n--------------------------------------------\r\n\r\nKeep track of the total candies Arya has. \r\nEvery day give the min(8, total). \r\n\r\nCheck if greater than k candies have been given any day.\r\n\r\n-------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_days, target_candies;\r\n    scanf(\"%d %d\", &no_of_days, &target_candies);\r\n\r\n    const int one_day_limit = 8;\r\n    int total_candies = 0, given_candies = 0, required_days = -1;\r\n    for(int day_i = 1; day_i <= no_of_days; day_i++)\r\n    {\r\n        int box_i, given_on_day_i;\r\n        scanf(\"%d\", &box_i);\r\n\r\n        total_candies += box_i;\r\n        given_on_day_i = min(one_day_limit, total_candies);\r\n\r\n        total_candies -= given_on_day_i;\r\n        given_candies += given_on_day_i;\r\n\r\n        if(given_candies >= target_candies)\r\n        {\r\n            required_days = day_i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", required_days);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Bear and Elections Explanation.txt",
    "content": "\r\n-------------------------------------\r\n\r\nThis was very interesting. First time I got to use the data structure priority queues practically ! I've learnt something new today. \r\n\r\nI tried coming up with an O(1) formula, but that doesn't work when there are multiple maxima. Rather than maintain a sorted array ... It's a lot more convenient \r\nto have a priority queue. We can get the largest element in O(1) time. \r\n\r\nKeep comparing limak with the maximum. If he isn't already the maximum, then increase his votes by 1, decrease maxima and put the maxima back in the priority queueu.\r\n\r\n---------------------------------\r\n\r\n#include <cstdio>\r\n#include <queue>\r\n\r\nusing namespace std;\r\n\r\nint main()\r\n{\r\n    int no_of_candidates;\r\n    scanf(\"%d\", &no_of_candidates);\r\n\r\n    int limak_votes;\r\n    priority_queue <int> votes;\r\n\r\n    scanf(\"%d\", &limak_votes);\r\n    for(int i = 2; i <= no_of_candidates; i++)\r\n    {\r\n        int vote_i;\r\n        scanf(\"%d\", &vote_i);\r\n\r\n        votes.push(vote_i);\r\n    }\r\n\r\n    int limak_bribes = 0;\r\n    while(limak_votes + limak_bribes <= votes.top())\r\n    {\r\n        int current_max = votes.top();\r\n        votes.pop();\r\n\r\n        current_max--;\r\n        limak_bribes++;\r\n        votes.push(current_max);\r\n    }\r\n\r\n\r\n    printf(\"%d\\n\", limak_bribes);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Business Trip.txt",
    "content": "What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. \nHe jumped on the bed and threw pillows all day long, until...\n\nToday Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, \nin the morning, in the afternoon and in the evening. \"Wait a second!\" — thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1 ≤ i ≤ 12) \nmonth of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. \nPetya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters.\n\nHelp Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.\n\n----------------------------------------------\n\nBe greedy. Plant the months with the greatest amount of growth first. Sort the array in descending order.\n\nI got a beginner bug because I didn't do bound checking for the array ... I didn't check if the number of months was greater than the number of months at first.\n\n------------------------------\n\nint main()\n{\n    int minimum_growth;\n    scanf(\"%d\", &minimum_growth);\n\n    const int no_of_months = 12;\n    vector <int> growth(no_of_months);\n    for(int i = 0; i < no_of_months; i++)\n        scanf(\"%d\", &growth[i]);\n\n    sort(all(growth));\n    reverse(all(growth));\n\n    int month_i = 0, plant_growth = 0;\n    while(plant_growth < minimum_growth && month_i < no_of_months)\n    {\n        plant_growth += growth[month_i++];\n    }\n\n    printf(\"%d\\n\", plant_growth < minimum_growth ? -1 : month_i);\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 13/Code Obfuscation Explanation.txt",
    "content": "Kostya likes Codeforces contests very much. However, he is very disappointed that his solutions are frequently hacked. That's why he decided to obfuscate \r\n(intentionally make less readable) his code before upcoming contest.\r\n\r\nTo obfuscate the code, Kostya first looks at the first variable name used in his program and replaces all its occurrences with a single symbol a, \r\nthen he looks at the second variable name that has not been replaced yet, and replaces all its occurrences with b, and so on. Kostya is well-mannered, \r\nso he doesn't use any one-letter names before obfuscation. Moreover, there are at most 26 unique identifiers in his programs.\r\n\r\nYou are given a list of identifiers of some program with removed spaces and line breaks. Check if this program can be a result of Kostya's obfuscation.\r\n\r\n------------------------------------------\r\n\r\nMy logic was simple. keep track of all alphabets used ... If a new alphabet is encountered at any point in the string, \r\nall alphabets smaller than it must already have been used.\r\n\r\nTo keep track of all distinct alphabets, use a set data structure. \r\n\r\nFirst, check if the element is already inserted in the set (log n). If it is not, then check if the size of the set < ch - 'a' ... This means that all alphabets smaller\r\nthan ch are not used which makes it an invalid string. If it is valid, insert the character into the string.\r\n\r\n-------------------------------\r\n\r\nint main()\r\n{\r\n    char code[MAX_LENGTH];\r\n    scanf(\"%s\", code);\r\n\r\n    set <char> alphabets_used;\r\n    int code_obfuscation = true;\r\n\r\n    for(int i = 0; code[i] != '\\0'; i++)\r\n    {\r\n        //Before inserting an alphabet, all alphabets smaller than it must already have been used\r\n        if(alphabets_used.count(code[i]) == 0)\r\n        {\r\n            if(alphabets_used.size() < code[i] - 'a')\r\n            {\r\n                code_obfuscation = false;\r\n                break;\r\n            }\r\n        }\r\n        alphabets_used.insert(code[i]);\r\n    }\r\n\r\n\r\n    printf(code_obfuscation ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Drinks Explanation.txt",
    "content": "Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. \r\nThere are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.\r\n\r\nOne day Vasya decided to make himself an orange cocktail. He took equal proportions of each of the n drinks and mixed them. \r\nThen he wondered, how much orange juice the cocktail has.\r\n\r\nFind the volume fraction of orange juice in the final drink.\r\n----------------------------------------------\r\n\r\nThe numerator is the sum of all percentages. The denominator is n.\r\n\r\nBe careful about floating point precision errors. I typecasted everything to double before dividing.\r\n\r\nint main()\r\n{\r\n    int no_of_drinks;\r\n    scanf(\"%d\", &no_of_drinks);\r\n\r\n    double numerator = 0.0;\r\n    for(int i = 1; i <= no_of_drinks; i++)\r\n    {\r\n        int percent_i;\r\n        scanf(\"%d\", &percent_i);\r\n\r\n        numerator += percent_i;\r\n    }\r\n\r\n    double denominator = no_of_drinks*1.0;\r\n    double fraction = numerator/denominator;\r\n\r\n    printf(\"%lf\\n\", fraction);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Epic Game Explanation.txt",
    "content": "gcd(a, b) <= min(a, b) ... \r\n\r\nThis is when both a and b are positive integers. It only changes when one of them is 0. \r\n\r\nKeep decreasing n by the required amount until it reaches 0. Constraints are small. It will pass.\r\n\r\n----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a, b, n;\r\n    scanf(\"%d %d %d\", &a, &b, &n);\r\n\r\n    int winner;\r\n    for(int turn_i = 0; n > 0; turn_i++)\r\n    {\r\n        int current_player = (turn_i%2 == 0 ? a : b) ;\r\n        n -= gcd(current_player, n);\r\n\r\n        if(n == 0)\r\n            winner = turn_i%2;\r\n    }\r\n\r\n    printf(\"%d\\n\", winner);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Functions Again Explanation.txt",
    "content": "\r\nThere is a list of n integers, \r\n\r\nA function f(left, right) = sum(i = left to right - 1) |A[i] - A[i + 1]|. (-1)^{i + 1}\r\n\r\nFind the maximum value of this function.\r\n\r\n----------------------------------------------------------------\r\n\r\nLet's make some observations - \r\n\r\nFirstly, notice that f(i, r) = f(i, i + 1) - f(i + 1, r).\r\n\r\nThis itself is enough to suggest optimal substructure.\r\n\r\nNow, every function must END at a certain index in the array.\r\n\r\nLet Answer(i, j) represent the maximum value of f ending at i, j has two states \r\nRepresenting whether the last difference i.e. - |A[i - 1] - A[i]| should be subtracted or added to f(i - 1, j).\r\n\r\nNotice that EVERY function ending at i must neccessarily include |A[i] - A[i - 1]|.\r\n\r\nThere are two possibilities, either it is added or it is subtracted.\r\n\r\n1. The difference is added, then Answer(i, LAST_DIFFERENCE_ADDED) = max{0, Answer(i - 1, LAST_DIFFERENCE_REMOVED)} +  |A[i - 1] - A[i]|\r\n\r\n\tIf the current difference ending at i is added, then the previous difference ending at i - 1 must be subtracted. \r\n\tOf course, subtracting the previous difference may have made the value of the function negative. \r\n\tIN that case, we don't build upon Answer(i - 1, LAST_DIFFERENCE_REMOVED), but start a new function from i-1 = |A[i - 1] - A[i]|\r\n\r\n2. The difference is subtracted, then Answer(i, LAST_DIFFERENCE_REMOVED) = Answer(i - 1, LAST_DIFFERENCE_ADDED) - |A[i - 1] - A[i]|\r\n\r\n\tIf the current difference ending at i is subtracted, the the previous difference ending at i - 1 must have been added.\r\n\tSo, we just subtract it from Answer(i - 1, LAST_DIFFFERENCE_ADDED).\r\n\r\n\tNote - Here we do not check if the value of Answer at position i-1 is positive because it is not possible to start the function from i-1 and\r\n\tsubtract the first term. By the definition of the function f, the first term MUST be added. So, here, we must build on what was done previously. \r\n\r\nBase case - Answer(2, LAST_DIFFERENCE_ADDED) = |A[2] - A[1]|\r\n            Answer(2, LAST_DIFFERENCE_REMOVED) = 0 .... [We can't start a function from 1 and subtract the first term]\r\n\r\nSO, Answer(3, LAST_DIFFERENCE_REMOVED) = Answer(2, LAST_DIFFERENCE_ADDED) - |A[3] - A[2]| - \r\n    Answer(3, LAST_DIFFERENCE_ADDED) = max{Answer(2, LAST_DIFFERENCE_REMOVED), 0} + |A[3] - A[2]|\r\n\r\n\r\nThis is a 2-dimensional function, but notice for each state, we only need the previous state. So, it can be done in O(1) memory and O(n) time.\r\n\r\nAnswer = max{Answer(i, j)}\r\n\r\n---------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    long long maximum_value, maximum_with_last_difference_added, maximum_with_last_difference_removed;\r\n\r\n    maximum_with_last_difference_added = abs(element[2] - element[1]);\r\n    maximum_with_last_difference_removed = 0;\r\n    maximum_value = maximum_with_last_difference_added;\r\n\r\n    for(int i = 3; i <= no_of_elements; i++)\r\n    {\r\n        long long maximum_with_this_difference_added, maximum_with_this_difference_removed, maximum_value_ending_here;\r\n\r\n        maximum_with_this_difference_added = max(0LL, maximum_with_last_difference_removed) + abs(element[i] - element[i - 1]);\r\n        maximum_with_this_difference_removed = maximum_with_last_difference_added - abs(element[i] - element[i - 1]);\r\n\r\n        maximum_value_ending_here = max(maximum_with_this_difference_added, maximum_with_this_difference_removed);\r\n        maximum_value = max(maximum_value, maximum_value_ending_here);\r\n\r\n        maximum_with_last_difference_added = maximum_with_this_difference_added;\r\n        maximum_with_last_difference_removed = maximum_with_this_difference_removed;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", maximum_value);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Generous Kefa Explanation.txt",
    "content": "One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si  lowercase letter of the Latin alphabet. \r\nAlso Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. \r\nHelp Kefa to find out, can he give out all his baloons, \r\nsuch that no one of his friens will be upset  print YES, if he can, and NO, otherwise. Note, that Kefa's friend will not upset, if he doesn't get baloons at all.\r\n---------------------------------------------------------\r\n\r\nThe number of balloons of any colour should not exceed the number of people. That forces one person to get balloons of the same colour by \r\nthe pigeonhole principle.\r\n\r\n----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_balloons, no_of_people;\r\n    char balloon_colours[MAX_LENGTH];\r\n    scanf(\"%d %d %s\",&no_of_balloons, &no_of_people, balloon_colours);\r\n\r\n    int no_of_balloons_of_colour[NO_OF_ALPHABETS] = {0};\r\n    for(int i = 0; i < no_of_balloons; i++)\r\n    {\r\n        no_of_balloons_of_colour[balloon_colours[i] - 'a']++;\r\n    }\r\n\r\n    int everyone_happy = true;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(no_of_balloons_of_colour[i] > no_of_people)\r\n        {\r\n            everyone_happy = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(everyone_happy ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 13/George and Job Explanation.txt",
    "content": "\r\nThere is an array of n numbers. Choose k intervals of size m each, to maximise the sum of all the elements in these k intervals.\r\n\r\n------------------------------------------\r\n\r\nLet f(i, t) be the maximum sum with the first i number, with t intervals used.\r\n\r\nWe have two options - Either we include the interval ending at i or we do not.\r\n\r\nIf an interval ends at i, then, f(i, t) = f(i - m, t - 1) + sum(i - m + 1 to i)\r\n\r\nIf an interval does not end at i, then f(i, t) = f(i - 1, t).\r\n\r\nf(i, t) = max{f(i - m, t - 1) + sum[i] - sum[i - m], f(i - 1, t)}\r\n\r\nO(NK)\r\n--------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, no_of_intervals, max_interval_size;\r\n    scanf(\"%d %d %d\", &no_of_numbers, &max_interval_size, &no_of_intervals);\r\n\r\n    vector <long long> sum_till(no_of_numbers + 1, 0);\r\n    for(int i = 1; i <= no_of_numbers; i++)\r\n    {\r\n        int number_i;\r\n        scanf(\"%d\", &number_i);\r\n        sum_till[i] = number_i + sum_till[i - 1];\r\n    }\r\n\r\n    typedef vector <long long> v_long;\r\n    vector <v_long> maximum_sum_till(no_of_numbers + 1, v_long(no_of_intervals + 1, 0));\r\n\r\n    for(int interval_i = 1; interval_i <= no_of_intervals; interval_i++)\r\n    {\r\n        for(int number_i = max_interval_size; number_i <= no_of_numbers; number_i++)\r\n        {\r\n            int right = number_i, left = (number_i - max_interval_size) + 1;\r\n            long long interval_ending_here_sum = sum_till[right] - sum_till[left - 1];\r\n\r\n            long long maximum_sum_with_interval_ending_here = maximum_sum_till[left - 1][interval_i - 1] + interval_ending_here_sum ;\r\n\r\n            long long maximum_sum_with_interval_ending_before_here = maximum_sum_till[number_i - 1][interval_i];\r\n\r\n            maximum_sum_till[number_i][interval_i] = max(maximum_sum_with_interval_ending_here, maximum_sum_with_interval_ending_before_here);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", maximum_sum_till[no_of_numbers][no_of_intervals]);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Godsend Explanation.txt",
    "content": "Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. \r\nThe first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, \r\nafter that the remaining parts are glued together into one array and the game continues. \r\nThe second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?\r\n\r\n------------------------------------------------------------\r\n\r\nCase 1 - The array has only even numbers. The first player does not have a move since there is no subarray consisting of an odd sum.\r\n\r\nCase 2 - The array has at least one odd number.\r\n\r\n\tCase 2a - The array has an odd number of odd numbers. This forces the sum of the array to be odd. The first player takes all the array elements and wins.\r\n\t\r\n\tCase 2b - The array has an even number of odd numbers. Let the array have 2p  odd numbers. The first player chooses a segment which has all numbers\r\n\t\t\tbut one of these odd numbers. So, the first player chooses a segment that contains 2p - 1 odd numbers.\r\n\r\n\t\t\tNow, the second player cannot take this element, because any segment containing the left out odd number will have an odd sum,\r\n\t\t\tforcing the sum to be odd. \r\n\r\n\t\t\tEither the second player has no moves or he makes a move which gives the first player an array consisting of only one odd number, \r\n\t\t\tand this reduces to Case 2a. The first player wins by taking the entire array.\r\n\r\nThe second player only wins if there are 0 odd numbers.\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    int only_even_numbers = true;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        if(element_i%2 == 1)\r\n            only_even_numbers = false;\r\n    }\r\n\r\n    printf(only_even_numbers ? \"Second\\n\" : \"First\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Kuriyama Mirai's Stones Explanation.txt",
    "content": "\r\nJust an implementation problem.\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 1, 0);\r\n    vector <long long> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &element[i]);\r\n        sum_till[i] = element[i] + sum_till[i - 1];\r\n    }\r\n\r\n    sort(all(element));\r\n    vector <long long> sorted_sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sorted_sum_till[i] = element[i] + sorted_sum_till[i - 1];\r\n    }\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int query_type, left, right;\r\n        scanf(\"%d %d %d\", &query_type, &left, &right);\r\n\r\n        long long answer = (query_type == 1 ? sum_till[right] - sum_till[left - 1] : sorted_sum_till[right] - sorted_sum_till[left - 1]);\r\n        printf(\"%I64d\\n\", answer);\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Little Dima and Equation Explanation.txt",
    "content": "\r\n-------------------------------------------------\r\n\r\nThe trick for solving these kinds of questions is to brute force over the sum of digits rather than x.\r\nThe sum of digits can go up to 81 in 1e9 -1.\r\n\r\nI got this far. But, I still didn't know how to do the last step.\r\n\r\nThe idea is to simply keep evaluating the LHS and then checking if it is within the constraint. \r\nI used my own power function because I know pow returns double.\r\n\r\n---------------------\r\n\r\nint main()\r\n{\r\n    int a, b, c;\r\n    scanf(\"%d %d %d\", &a, &b, &c);\r\n\r\n    vector <int> solutions;\r\n\r\n    for(int digit_sum = 1; digit_sum <= 81; digit_sum++)\r\n    {\r\n        long long x = b*int_power(digit_sum, a) + c;\r\n        if(sum_of_digits(x) == digit_sum && x > 0 && x < 1e9)\r\n            solutions.push_back(x);\r\n    }\r\n\r\n    printf(\"%d\\n\", solutions.size());\r\n    for(unsigned int i = 0; i < solutions.size(); i++)\r\n        printf(\"%d \", solutions[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Little Elephant and Bits Explanation.txt",
    "content": "\r\nThe Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.\r\n\r\nTo make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. \r\nAt that a new number appears. \r\nIt consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).\r\n\r\nThe Little Elephant wants the number he is going to write on the paper to be as large as possible. \r\nHelp him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.\r\n\r\n--------------------------------------------------\r\n\r\nTo keep the number as large as possible, we need to disturb as less of the set bits as possible. \r\nNotice that any deletion always shifts the position of the bits.\r\n\r\nTo do this we delete the most significant bit that is set to 0. This doesn't affect any of the bits to right of this 0 and keeps the most number of bits intact.\r\nIf there is no 0, then delete any of the digits. (The answer will be the same.)\r\n\r\n-----------------------------------\r\n\r\n\r\nint main()\r\n{\r\n    char number[MAX_SIZE];\r\n    scanf(\"%s\", number);\r\n\r\n    char new_number[MAX_SIZE];\r\n    int first_zero = -1, new_number_i = 0;\r\n\r\n    for(int i = 0; number[i] != '\\0'; i++)\r\n    {\r\n        if(number[i] == '0' && first_zero == -1) \r\n        {\r\n            first_zero = i;\r\n        }\r\n        else\r\n        {\r\n            new_number[new_number_i++] = number[i];\r\n        }\r\n    }\r\n\r\n    int last_digit_position = new_number_i;\r\n    if(first_zero == -1)\r\n        last_digit_position--;\r\n\r\n    new_number[last_digit_position] = '\\0';\r\n\r\n    printf(\"%s\\n\", new_number);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/New Skateboard Explanation.txt",
    "content": "\r\n---------------------------------------------------\r\n\r\nA number is a multiple of 4 if it's last 2 digits are a multiple of 4. \r\n\r\nSo go through every (s[i], s[i + 1]) ... IF they form a number divisible by 4, then every string ending there will be a multiple of 4.\r\n\r\n(All strings from 0 to i = i + 1 multiples of 4).\r\n\r\nAdditionally a new string will be formed if s[i + 1] is also a multiple of 4, (on it's own).\r\n\r\nBe sure to check if the first character is a multiple of 4 before you begin.\r\n\r\n------------------------------------\r\n\r\nint main()\r\n{\r\n    char calculator[MAX_LENGTH];\r\n    scanf(\"%s\", calculator);\r\n\r\n    long long no_of_multiples_of_4 = ( (calculator[0] - '0')%4 == 0);\r\n\r\n    for(int i = 0; calculator[i + 1] != '\\0'; i++)\r\n    {\r\n        int current_suffix = (calculator[i] - '0')*10 + (calculator[i + 1] - '0');\r\n        int no_of_strings_ending_with_this_suffix = i + 1;\r\n\r\n        if(current_suffix%4 == 0)\r\n            no_of_multiples_of_4 += no_of_strings_ending_with_this_suffix;\r\n\r\n        no_of_multiples_of_4 += ( (calculator[i + 1] - '0')%4 == 0);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_multiples_of_4);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Oath of the Night's Watch Explanation.txt",
    "content": "With that begins the watch of Jon Snow. He is assigned the task to support the stewards.\r\n\r\nThis time he has n stewards with him whom he has to provide support. Each steward has his own strength. \r\nJon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has \r\nstrength strictly greater than him.\r\n\r\nCan you find how many stewards will Jon support?\r\n\r\n--------------------------------------------\r\n\r\nThe minimum strength and the maximum cannot be supported. Keep track of their frequency.\r\n\r\nint main()\r\n{\r\n    const int oo = 1e9 + 1;\r\n    int no_of_people, min_strength = oo, max_strength = 0;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    map <int, int> strength_frequency;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        int strength_i;\r\n        scanf(\"%d\", &strength_i);\r\n\r\n        strength_frequency[strength_i]++;\r\n        min_strength = min(strength_i, min_strength);\r\n        max_strength = max(strength_i, max_strength);\r\n    }\r\n\r\n    int number_of_people_supported = max(0, no_of_people - strength_frequency[max_strength] - strength_frequency[min_strength]);\r\n    printf(\"%d\\n\", number_of_people_supported);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Sort the Array Explanation.txt",
    "content": "Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.\r\n\r\nUnfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, \r\nbut only if you are able to answer the following question correctly: \r\nis it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.\r\n\r\n----------------------------------------------------\r\n\r\nCount the number of descending segments. It should be at most 1.\r\n\r\nhowever, that isn't enough. \r\n\r\nConsider - 100 99 1 2 3 ... This has one descending segment, but it doesn't fit.\r\n\r\nChech if A[start] < A[end + 1] ... I did this ... I forgot the case\r\n\r\n1 2 100 99 3 4 5 \r\n\r\nYou also need to check A[end] >= A[start - 1],\r\n\r\nIf there is no descending segment, reverse any 1-element segment of the array.\r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_elements;\r\n    scanf(\"%d\", &number_of_elements);\r\n\r\n    vector <int> element(number_of_elements + 1);\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    int descending_segments = 0, in_descending_segment = false, reversed_segment_fits = false;\r\n    int segment_start = 1, segment_end = number_of_elements;\r\n\r\n    for(int i = 2; i <= number_of_elements && descending_segments <= 1; i++)\r\n    {\r\n        if(in_descending_segment)\r\n        {\r\n            if(element[i] > element[i - 1])\r\n            {\r\n                segment_end = i - 1;\r\n                in_descending_segment = false;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            if(element[i] < element[i - 1])\r\n            {\r\n                in_descending_segment = true;\r\n                segment_start = i - 1;\r\n\r\n                descending_segments++;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(descending_segments == 0)\r\n        segment_end = segment_start;\r\n\r\n    if( (segment_end == number_of_elements || element[segment_start] <= element[segment_end + 1] ) &&\r\n        (segment_start == 1 || element[segment_end] >= element[segment_start - 1]) )\r\n    {\r\n        reversed_segment_fits = true;\r\n    }\r\n\r\n    if(descending_segments <= 1 && reversed_segment_fits)\r\n        printf(\"yes\\n%d %d\\n\", segment_start, segment_end);\r\n    else\r\n        printf(\"no\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Star Sky Explanation.txt",
    "content": "\r\nPrecompputation must be used to speeden this.\r\n\r\nLet f(b, x, y) hold the number of stars of brightness b (initially) in the rectangle from (1, 1) ending at (x, y).\r\n\r\nClearly, f(b, x, y) = f(b, x - 1, y) + f(b, x, y - 1) - f(b, x - 1, y - 1) + (no of stars of brightness b at (x, y))\r\n\r\nAnswer to each query is (b + t)%(MAximum brightness + 1) * no of stars of brightness b.\r\n\r\nThe number of stars of brightness b inside the query rectangle is f(b, x2, y2) - f(b, x2, y1 - 1) - f(b, x1 - 1, y2) + f(b, x1 - 1, y1 - 1)\r\n\r\nBy the principle of exclusion and inclusion.\r\n\r\n------------------------------------------------\r\n\r\nComplexity of this approach for queries is O(qc) + O(cX^2) for precomputation. O(n) for reading input.\r\n\r\nNow, for every query, we only need to go over every brightness, which is small. \r\n\r\nHowever, if for every query, we go over the entire rectangle, then it is O(qX^2) ... Since q can be 10^5 and X can be 100 ... This may take roughly 10^9 iterations.\r\n\r\nWhereas, O(qc) is 10^5 . 10 = 10^6 operations. Precomputation takes (10. 10^4 = 10^5 operations roughly, as does input ... Overall precomputation and input will take\r\n\r\n2. 10^5 operations ... This is done in one second and all queries are answered in one second).\r\n\r\nIf the queries were answered individually by going over the entire rectangle, it would take 10^9 operations which is 1000 seconds.\r\n\r\n------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_stars, no_of_views, maximum_brightness;\r\n    scanf(\"%d %d %d\", &no_of_stars, &no_of_views, &maximum_brightness);\r\n\r\n    int no_of_stars_of_initial_brightness_in[MAX_BRIGHTNESS + 1][MAX_LENGTH + 1][MAX_LENGTH + 1] = {{{0}}};\r\n\r\n    for(int star_i = 1; star_i <= no_of_stars; star_i++)\r\n    {\r\n        int brightness_i, x_i, y_i;\r\n        scanf(\"%d %d %d\", &x_i, &y_i, &brightness_i);\r\n\r\n        no_of_stars_of_initial_brightness_in[brightness_i][x_i][y_i]++;\r\n    }\r\n\r\n    for(int brightness_i = 0; brightness_i <= maximum_brightness; brightness_i++)\r\n    {\r\n        for(int x_i = 1; x_i <= MAX_LENGTH; x_i++)\r\n        {\r\n            for(int y_i = 1; y_i <= MAX_LENGTH; y_i++)\r\n            {\r\n                no_of_stars_of_initial_brightness_in[brightness_i][x_i][y_i] += no_of_stars_of_initial_brightness_in[brightness_i][x_i][y_i - 1]\r\n                                                                              + no_of_stars_of_initial_brightness_in[brightness_i][x_i - 1][y_i]\r\n                                                                              - no_of_stars_of_initial_brightness_in[brightness_i][x_i - 1][y_i - 1];\r\n            }\r\n        }\r\n    }\r\n\r\n    while(no_of_views--)\r\n    {\r\n        int time, x_1,y_1, x_2, y_2;\r\n        scanf(\"%d %d %d %d %d\", &time, &x_1, &y_1, &x_2, &y_2);\r\n\r\n        int sum_of_brightness = 0;\r\n\r\n        for(int brightness_i = 0; brightness_i <= maximum_brightness; brightness_i++)\r\n        {\r\n            int no_of_stars_of_this_brightness = no_of_stars_of_initial_brightness_in[brightness_i][x_2][y_2]\r\n                                               - no_of_stars_of_initial_brightness_in[brightness_i][x_2][y_1 - 1]\r\n                                               - no_of_stars_of_initial_brightness_in[brightness_i][x_1 - 1][y_2]\r\n                                               + no_of_stars_of_initial_brightness_in[brightness_i][x_1 - 1][y_1 - 1];\r\n\r\n            int final_brightness = (brightness_i + time)%(maximum_brightness + 1);\r\n\r\n\r\n            sum_of_brightness += no_of_stars_of_this_brightness*final_brightness;\r\n        }\r\n\r\n        printf(\"%d\\n\", sum_of_brightness);\r\n    }\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 13/Vanya and Books Explanation.txt",
    "content": "\r\n--------------------------------------\r\n\r\nEvery page contributes 1 digit to the total.\r\nEvery page greater than 10 contributes 2 to the total\r\nEvery page greater than 10^2 contributes 3 to the total.\r\n\r\nEvery page greater than 10^r contributes r+1 to the total\r\n\r\nSo, for every power of 10 smaller then n, add n - (10^i - 1) to the total. (Because 10^i is the point from which an additional digit is contributed).\r\n\r\nThis is O(log n) complexity\r\n------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_pages;\r\n    scanf(\"%d\", &no_of_pages);\r\n\r\n    long long no_of_digits_used = 0;\r\n    long long power_of_10 = 1;\r\n\r\n    while(power_of_10 <= no_of_pages)\r\n    {\r\n        no_of_digits_used += no_of_pages - (power_of_10 - 1);\r\n        power_of_10 *= 10;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_digits_used);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 13/Vasya and Digital Root Explanation.txt",
    "content": "Now Vasya wants to quickly find numbers with the given digital root. The problem is, he hasn't learned how to do that and he asked you to help him. \r\nYou task is, given numbers k and d, \r\nfind the number consisting of exactly k digits (the leading zeroes are not allowed), with digital root equal to d, or else state that such number does not exist.\r\n\r\n---------------------------------------------------\r\n\r\nPad the number with k-1 9s and then put a d ... S(n) = S(n + 9).\r\n\r\nI missed the case where d = 0 and k > 1 no solution\r\n\r\n-------------------------\r\n\r\nint main()\r\n{\r\n    int digital_root, no_of_digits;\r\n    scanf(\"%d %d\", &no_of_digits, &digital_root);\r\n\r\n    if(digital_root == 0 && no_of_digits > 1)\r\n        printf(\"No solution\\n\");\r\n    else\r\n    {\r\n        for(int i =no_of_digits; i >= 2; i--)\r\n            printf(\"9\");\r\n        printf(\"%d\\n\", digital_root);\r\n    }\r\n\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 14/Borze Explanation.txt",
    "content": "Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as ., 1 as -. and 2 as --. \r\nYou are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.\r\n\r\n-------------------------------\r\n\r\nThe coding is like Huffman coding. No code is the prefix of another code.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    string borze_code, translation;\r\n    cin >> borze_code;\r\n\r\n    for(unsigned int i = 0; i < borze_code.size(); i++)\r\n    {\r\n        if(borze_code[i] == '.')\r\n            translation += '0';\r\n        else if(borze_code[i] == '-')\r\n        {\r\n            if(borze_code[i + 1] == '.')\r\n                translation += '1';\r\n            else if(borze_code[i + 1] == '-')\r\n                translation += '2';\r\n\r\n            i++;\r\n        }\r\n    }\r\n\r\n    cout << translation;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Chess Tourney Explanation.txt",
    "content": "Berland annual chess tournament is coming!\r\n\r\nOrganizers have gathered 2n chess players who should be divided into two teams with n people each. \r\nThe first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.\r\n\r\nThus, organizers should divide all 2n players into two teams with n people each in such a way that the first team always wins.\r\n\r\nEvery chess player has its rating ri. It is known that chess player with the greater rating always wins the player with the lower rating. \r\nIf their ratings are equal then any of the players can win.\r\n\r\nAfter teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. \r\nEvery chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.\r\n\r\nIs it possible to divide all 2n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?\r\n\r\n--------------------------------------------------------\r\n\r\nHave two divisions - consisting of the first and second half of players according to ratings.\r\n\r\nIf the greatest rated player of second division is weaker than the weakest player of first division, then answer is yes.\r\n\r\nElse it is no.\r\n\r\n-------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_pairs;\r\n    scanf(\"%d\", &no_of_pairs);\r\n\r\n    vector <int> player_rating(2*no_of_pairs + 1, 0);\r\n    for(int i = 1; i <= 2*no_of_pairs; i++)\r\n        scanf(\"%d\", &player_rating[i]);\r\n\r\n    sort(all(player_rating));\r\n\r\n    printf(player_rating[no_of_pairs] < player_rating[no_of_pairs + 1] ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Dragons Explanation.txt",
    "content": "Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. \r\nKirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength.\r\n Initially, Kirito's strength equals s.\r\n\r\nIf Kirito starts duelling with the i-th  dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. \r\nBut if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.\r\n\r\nKirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.\r\n\r\n-------------------------------------------------\r\n\r\nFight the weakest dragon available. If you can't beat him, you can't beat anyone else either.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int strength, no_of_dragons;\r\n    scanf(\"%d %d\", &strength, &no_of_dragons);\r\n\r\n    vector < pair <int, int> > dragon(no_of_dragons);\r\n    for(int i = 0; i < no_of_dragons; i++)\r\n        scanf(\"%d %d\", &dragon[i].first, &dragon[i].second);\r\n\r\n    sort(all(dragon));\r\n\r\n    int can_defeat_all_dragons = true;\r\n    for(int i = 0; i < no_of_dragons; i++)\r\n    {\r\n        int strength_of_dragon = dragon[i].first;\r\n        int bonus = dragon[i].second;\r\n\r\n        if(strength <= strength_of_dragon)\r\n        {\r\n            can_defeat_all_dragons = false;\r\n            break;\r\n        }\r\n        else\r\n        {\r\n            strength += bonus;\r\n        }\r\n    }\r\n\r\n    printf(can_defeat_all_dragons ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Drazil and Factorial Explanation.txt",
    "content": "\r\nF(x) = product of factorials of all digits in decimal representation of x.\r\n\r\nF(135) = 1!.3!.5!\r\n\r\nFor a given a, print the maximum x such that - \r\n\r\n1. x has no 0s and 1s\r\n2. F(x) = F(a)\r\n\r\nIt is guaranteed that a has at least one digit that is not 0 or 1.\r\n\r\n----------------------------------------------------\r\n\r\nTo get the maximum possible x, we generate the x with the most number of digits and then print the digits in descending order.\r\n\r\n2, 3, 5, 7 are prime numbers ... they need to be present for their factorials.\r\n\r\n4! = 2!.2!.3!\r\n6! = 3!.5!\r\n8! = 2!.2!.2!.7!\r\n9! = 2!.3!.3!.7!\r\n\r\nReplace each digit accordingly, sort and then print the answer.\r\n\r\n-------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_digits;\r\n    scanf(\"%d\", &no_of_digits);\r\n\r\n    vector <int> number;\r\n    for(int i = 1; i <= no_of_digits; i++)\r\n    {\r\n        int digit_i;\r\n        scanf(\"%1d\", &digit_i);\r\n\r\n        switch(digit_i)\r\n        {\r\n            case 2:\r\n            case 3:\r\n            case 5:\r\n            case 7: number.push_back(digit_i);\r\n                    break;\r\n\r\n            case 4: number.push_back(2); number.push_back(2); number.push_back(3);\r\n                    break;\r\n\r\n            case 6: number.push_back(3); number.push_back(5);\r\n                    break;\r\n\r\n            case 8: number.push_back(2); number.push_back(2); number.push_back(2); number.push_back(7);\r\n                    break;\r\n\r\n            case 9: number.push_back(2); number.push_back(3); number.push_back(3); number.push_back(7);\r\n                    break;\r\n        }\r\n    }\r\n\r\n    sort(all(number));\r\n\r\n    for(int i = number.size() - 1; i >= 0; i--)\r\n        printf(\"%d\", number[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Football Explanation.txt",
    "content": "One day Vasya decided to have a look at the results of Berland 1910 Football Championships finals. Unfortunately he didn't find the overall score of the match; \r\nhowever, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. \r\nEvery goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. \r\nIt is guaranteed that the match did not end in a tie.\r\n\r\n---------------------------------------\r\n\r\nMaintain a map of the no of goals scored by each team.\r\n\r\nint main()\r\n{\r\n    int no_of_lines;\r\n    cin >> no_of_lines;\r\n\r\n    map <string, int> no_of_goals;\r\n\r\n    while(no_of_lines--)\r\n    {\r\n        string team;\r\n        cin >> team;\r\n\r\n        no_of_goals[team]++;\r\n    }\r\n\r\n    string winner;\r\n    int max_goals = 0;\r\n    for(map <string, int> :: iterator i = no_of_goals.begin(); i != no_of_goals.end(); i++)\r\n    {\r\n        int no_of_goals = i->second;\r\n        if(no_of_goals > max_goals)\r\n        {\r\n            max_goals = no_of_goals;\r\n            winner = i->first;\r\n        }\r\n    }\r\n\r\n    cout << winner;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Helpful Maths Explanation.txt",
    "content": "Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.\r\n\r\nThe teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. \r\nStill, that isn't enough for Xenia. She is only beginning to count, so she can calculate a sum only if the summands follow in non-decreasing order. \r\nFor example, she can't calculate sum 1+3+2+1 but she can calculate sums 1+1+2 and 3+3.\r\n\r\nYou've got the sum that was written on the board. Rearrange the summans and print the sum in such a way that Xenia can calculate the sum.\r\n\r\n-----------------------------------------------\r\n\r\nSort the digits and print them one by one seperated by '+' signs.\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    string expression;\r\n    cin >> expression;\r\n\r\n    typedef unsigned int u_int;\r\n    vector <char> number;\r\n    for(u_int i = 0; i < expression.size(); i++)\r\n    {\r\n        if(expression[i] != '+')\r\n            number.push_back(expression[i]);\r\n    }\r\n\r\n    sort(all(number));\r\n\r\n    for(u_int i = 0; i < number.size() - 1; i++)\r\n    {\r\n        printf(\"%c+\", number[i]);\r\n    }\r\n    printf(\"%c\\n\", number.back());\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Jeff and Digits Explanation.txt",
    "content": "Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. \r\nWhat is the largest possible number divisible by 90 Jeff can make from the cards he's got?\r\n\r\nJeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.\r\n\r\n-------------------------------------------------\r\n\r\nIf there are no 0s, you can never construct a multiple of 90.\r\n\r\nIf there is atleast one 0, then check if there are less than 9 5s. In that case the answer is 0.\r\n\r\nElse the answer is 5 (printed to the greatest possible multiple of 9 possible) followed by all the zeroes.\r\n\r\n--------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_digits;\r\n    scanf(\"%d\", &no_of_digits);\r\n\r\n    int no_of_5s = 0, no_of_0s = 0;\r\n    for(int i = 1; i <= no_of_digits; i++)\r\n    {\r\n        int digit;\r\n        scanf(\"%d\", &digit);\r\n\r\n        no_of_5s += (digit == 5);\r\n        no_of_0s += (digit == 0);\r\n    }\r\n\r\n    if(no_of_0s == 0)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else if(no_of_5s < 9)\r\n    {\r\n        printf(\"0\\n\");\r\n    }\r\n    else\r\n    {\r\n        int no_of_5s_in_number = (no_of_5s/9)*9;\r\n        for(int i = 1; i <= no_of_5s_in_number; i++)\r\n            printf(\"5\");\r\n\r\n        for(int i = 1; i <= no_of_0s; i++)\r\n            printf(\"0\");\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Jzzhu and Children Explanation.txt",
    "content": "There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. \r\nThe i-th child wants to get at least ai candies.\r\n\r\nJzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. He follows the algorithm:\r\n\r\nGive m candies to the first child of the line.\r\nIf this child still haven't got enough candies, then the child goes to the end of the line, else the child go home.\r\nRepeat the first two steps while the line is not empty.\r\nConsider all the children in the order they go home. Jzzhu wants to know, which child will be the last in this order?\r\n\r\n---------------------------------------------\r\n\r\nThe number of times a child stands in line = ceil(a_i/m)\r\n\r\nKeep track of which i has the maximum number of i, if there is a tie, award it to the greater i.\r\n\r\n-------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_children, no_of_candies_given;\r\n    scanf(\"%d %d\", &no_of_children, &no_of_candies_given);\r\n\r\n    int maximum_turns = 0, last_child = 0;\r\n    for(int i = 1; i <= no_of_children; i++)\r\n    {\r\n        int candy_i;\r\n        scanf(\"%d\", &candy_i);\r\n\r\n        int no_of_turns = candy_i/no_of_candies_given + (candy_i%no_of_candies_given != 0);\r\n\r\n        if(no_of_turns >=  maximum_turns)\r\n        {\r\n            maximum_turns = no_of_turns;\r\n            last_child = i;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", last_child);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Panoramix's Prediction Explanation.txt",
    "content": "One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.\r\n\r\nPanoramix's prophecy tells that if some day Asterix and Obelix beat exactly x Roman soldiers, where x is a prime number, and next day they beat exactly y Roman soldiers,\r\n where y is the next prime number after x, \r\nthen it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.\r\n\r\n-----------------------------------------------------------------\r\n\r\nJust check if there's no primes in between and y is also a prime.\r\n\r\nint main()\r\n{\r\n    int x, y;\r\n    scanf(\"%d %d\", &x, &y);\r\n\r\n    int prime_in_middle = false;\r\n    for(int i = x + 1; i < y; i++)\r\n    {\r\n        if(is_prime(i))\r\n        {\r\n            prime_in_middle = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(!prime_in_middle && is_prime(y) ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 14/Powers of Two.txt",
    "content": "Find all pairs of elemnets (A[i], A[j]) that sum up to x in a given array.\n\n----------------------------------\n\nThe naive solution is to iterate through every pair of elements in the array. This is O(n^2).\n\nThere's a better solution. \n\nKeep track of the frequency of each element. \n\nThen pick up every frequency bucket and then see if (2^x - A[i]) exists and what it's frequency is.\n\nNote - FOr practical reasons, checking map[2^x - A[i]] == 0, inserts another node into the frequency table.\n\nSo, before inserting check if 2^x - A[i] is positive, and then if it is present in the original array.\n\nIf it is present in the original array, then multiply the frequency of the element with the frequency of the pair element.\n\n(If an element is it's own pair, then pair frequency = frequency_i - 1)\n\nO(n log n) to take the input, and O(n log n) to find the answer.\n\n-----------------------------------------------\n\nint main()\n{\n    int no_of_elements;\n    scanf(\"%d\", &no_of_elements);\n\n    set <int> original_array;\n    map <int, int> frequency;\n    for(int i = 0; i < no_of_elements; i++)\n    {\n        int element_i;\n        scanf(\"%d\", &element_i);\n\n        frequency[element_i]++;\n        original_array.insert(element_i);\n    }\n\n    long long no_of_pairs = 0;\n    for(map <int, int> :: iterator i = frequency.begin(); i != frequency.end(); i++)\n    {\n        int element_i = i->first;\n        int frequency_i = i->second;\n\n        for(int power = 0; power <= 31; power++)\n        {\n            int power_of_2 = (1 << power);\n\n            int pair_element = power_of_2 - element_i;\n            int pair_frequency = 0;\n\n            if(pair_element > 0 && original_array.count(pair_element) == 1)\n                pair_frequency = (element_i == pair_element ? frequency_i - 1 : frequency[pair_element]);\n\n            no_of_pairs += frequency_i*1LL*pair_frequency;\n\n        }\n    }\n\n    no_of_pairs = no_of_pairs/2;\n\n    printf(\"%I64d\\n\", no_of_pairs);\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 14/Tram Explanation.txt",
    "content": "Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. \r\nAt the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. \r\nAlso, when the tram arrives at the last stop, all passengers exit so that it becomes empty.\r\n\r\nYour task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. \r\nNote that at each stop all exiting passengers exit before any entering passenger enters the tram.\r\n\r\n----------------------------------------\r\n\r\nThe minimum capacity is the maximum number of people on the train at any given point of time.\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_stops;\r\n    scanf(\"%d\", &no_of_stops);\r\n\r\n    int minimum_capacity = 0, no_of_people_on_train = 0;\r\n    for(int i = 1; i <= no_of_stops; i++)\r\n    {\r\n        int no_of_entries, no_of_exits;\r\n        scanf(\"%d %d\",&no_of_exits, &no_of_entries);\r\n\r\n        no_of_people_on_train += (no_of_entries - no_of_exits);\r\n        minimum_capacity = max(minimum_capacity, no_of_people_on_train);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_capacity);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 14/Vasya and String Explanation.txt",
    "content": "High school student Vasya got a string of length n as a birthday present. \r\nThis string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) \r\nconsisting of equal letters.\r\n\r\nVasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?\r\n\r\n------------------------------------------\r\n\r\nWe need to find the maximum length substring that has k characters of one kind and any number of characters of the other kind.\r\n \r\nI learnt some cool tricks from a red person's code. \r\nOne way to 'flip' the string is to write, a[i] = a^b^a[i]. This flips every position of the string.\r\n\r\nI maintained a window with two pointers and kept track of the number of changes. \r\nThe number of changes increases whenever we encounter the type of character we want to change.\r\nAs soon as the number of changes is greater than the maximum number of changes, change the position of window start.\r\n\r\nFor example, |bbabbbabbaba|... and k = 3, we now have 3 a's inside the window\r\n\r\nbba|bbbabbaba|. Put the start one position ahead of the first 'a' you find.\r\n\r\nFind the maximum window length with k a's and any number of b's, and then do the same thing for k b's and any number of a's.\r\n\r\n-------------------------------------------------------\r\n\r\nint get_max_window_length(char string[], char changed_char, int max_changes)\r\n{\r\n    int max_window_length = 0, window_length = 0, no_of_changes = 0;\r\n\r\n    for(int window_end = 0, window_start = 0; string[window_end] != '\\0'; window_end++)\r\n    {\r\n        no_of_changes += (string[window_end] == changed_char);\r\n\r\n        while(no_of_changes > max_changes)\r\n        {\r\n            no_of_changes -= (string[window_start++] == changed_char);\r\n        }\r\n\r\n        window_length = window_end - (window_start - 1);\r\n        max_window_length = max(max_window_length, window_length);\r\n    }\r\n\r\n    return max_window_length;\r\n}\r\n\r\nint main()\r\n{\r\n    int length, max_changes;\r\n    char string[MAX_LENGTH];\r\n    scanf(\"%d %d %s\", &length, &max_changes, string);\r\n\r\n    int beauty = max(get_max_window_length(string, 'a', max_changes), get_max_window_length(string, 'b', max_changes));\r\n\r\n    printf(\"%d\\n\", beauty);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Between the Offices Explanation.txt",
    "content": "As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.\r\n\r\nYou prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. \r\nYou are so busy that you don't remember the number of flights you have made in either direction. \r\nHowever, for each of the last n days you know whether you were in San Francisco office or in Seattle office. \r\nYou always fly at nights, so you never were at both offices on the same day. Given this information, \r\ndetermine if you flew more times from Seattle to San Francisco during the last n days, or not.\r\n\r\n--------------------------------------------------\r\n\r\nCount the number of flights to both cities and compare which one is greater.\r\n\r\n--------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_days;\r\n    const int MAX_DAYS = 102;\r\n    char flights[MAX_DAYS];\r\n    scanf(\"%d %s\", &no_of_days, flights);\r\n\r\n    int flights_from_seattle = 0, flights_to_seattle = 0;\r\n    for(int i = 1; i < no_of_days; i++)\r\n    {\r\n        flights_to_seattle += (flights[i - 1] == 'F' && flights[i] == 'S');\r\n        flights_from_seattle += (flights[i - 1] == 'S' && flights[i] == 'F');\r\n    }\r\n\r\n    printf(\"%s\\n\", flights_from_seattle > flights_to_seattle ? \"YES\" : \"NO\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 15/Cableway Explanation.txt",
    "content": "A group of university students wants to get to the top of a mountain to have a picnic there. For that they decided to use a cableway.\r\n\r\nA cableway is represented by some cablecars, hanged onto some cable stations by a cable. A cable is scrolled cyclically between the first and the last cable stations \r\n(the first of them is located at the bottom of the mountain and the last one is located at the top). As the cable moves, the cablecar attached to it move as well.\r\n\r\nThe number of cablecars is divisible by three and they are painted three colors: red, green and blue, in such manner that after each red cablecar goes a green one, \r\nafter each green cablecar goes a blue one and after each blue cablecar goes a red one. Each cablecar can transport no more than two people, \r\nthe cablecars arrive with the periodicity of one minute (i. e. every minute) and it takes exactly 30 minutes for a cablecar to get to the top.\r\n\r\nAll students are divided into three groups: r of them like to ascend only in the red cablecars, g of them prefer only the green ones and b of them prefer only the blue ones.\r\n A student never gets on a cablecar painted a color that he doesn't like,\r\n\r\nThe first cablecar to arrive (at the moment of time 0) is painted red. Determine the least time it will take all students to ascend to the mountain top.\r\n\r\n------------------------------------------------------------\r\n\r\nFirst of all find the last ride. If the last ride happens at time t, then the answer is t + 30.\r\n\r\nCalculate the number of rides of each colour. \r\n\r\nThe last ride is red if, - it is greater than the number of blue and green rides.\r\nThe last ride is green if - it is >= red and > blue\r\nThe last ride is blue if >= red and >= blue\r\n\r\nThis is because if there's a tie, the rightmost element wins.\r\n\r\nThe arrival time is calculated by 3*(no_of_rides of that colour - 1) + offset.\r\n\r\nThe offset = 0 for red, 1 for green and 2 for blue.\r\n\r\n--------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int red, blue, green;\r\n    scanf(\"%d %d %d\", &red, &green, &blue);\r\n\r\n    int red_rides = red/2 + red%2;\r\n    int blue_rides = blue/2 + blue%2;\r\n    int green_rides = green/2 + green%2;\r\n\r\n    const int ONE_RIDE_DURATION = 30;\r\n    int no_of_minutes, last_ride_arrival;\r\n\r\n    if(red_rides > blue_rides && red_rides > green_rides)\r\n    {\r\n        last_ride_arrival = 3*(red_rides - 1);\r\n        no_of_minutes = last_ride_arrival + ONE_RIDE_DURATION;\r\n    }\r\n    else if(green_rides >= red_rides && green_rides > blue_rides)\r\n    {\r\n        last_ride_arrival = 3*(green_rides - 1) + 1;\r\n        no_of_minutes = last_ride_arrival + ONE_RIDE_DURATION;\r\n    }\r\n    else if(blue_rides >= red_rides && blue_rides >= green_rides)\r\n    {\r\n        last_ride_arrival = 3*(blue_rides - 1) + 2;\r\n        no_of_minutes = last_ride_arrival + ONE_RIDE_DURATION;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 15/Ciferia Explanation.txt",
    "content": "\r\n\r\n---------------------------------------------\r\n\r\nCheck if n is a power of k. \r\n\r\nIf n = k^p, print p-1\r\n\r\n------------------------------------\r\n\r\nint main()\r\n{\r\n    int k, n;\r\n    scanf(\"%d %d\", &k, &n);\r\n\r\n    int power = 0;\r\n    while(n%k == 0)\r\n    {\r\n        n = n/k;\r\n        power++;\r\n    }\r\n\r\n    printf(n > 1 ? \"NO\\n\" : \"YES\\n%d\\n\", power - 1);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Coins Explanation.txt",
    "content": "In Berland a money reform is being prepared. New coins are being introduced. \r\nAfter long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. \r\nAlso the following restriction has been introduced for comfort: the denomination of each coin should be divisible by the denomination of any cheaper coin. \r\nIt is known that among all the possible variants the variant with the largest number of new coins will be chosen. \r\nFind this variant. Print in the order of decreasing of the coins' denominations.\r\n\r\n-----------------------------------\r\n\r\nHave a look at the prime factorisation of n\r\n\r\nn = (p.p.p.p ... p). (q.q. .. q). (r.r. ... r)\r\n\r\nThe number of numbers in the sequence can't be more than the number of prime numbers in n's prime factorisation.\r\nBecause each term must have at least one term less than it's predecessor.\r\n\r\nWe construct a sequence in which each term will have exactly one less prime number in it's prime factorisation.\r\nDivide n by each prime and insert the new n into the sequence till n becomes 1.\r\n\r\n--------------------------------------------\r\n\r\nint main()\r\n{\r\n\tint n;\r\n\tscanf(\"%d\", &n);\r\n\r\n\tvector <int> denominations;\r\n\tdenominations.push_back(n);\r\n\r\n\tfor(int i = 2; n > 1; i++)\r\n\t{\r\n\t\twhile(n%i == 0)\r\n\t\t{\r\n\t\t\tn = n/i;\r\n\t\t\tdenominations.push_back(n);\r\n\t\t}\r\n\t}\r\n\r\n\tfor(int i = 0; i < denominations.size(); i++)\r\n\t\tprintf(\"%d \", denominations[i]);\r\n\r\n\treturn 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 15/Divisibility by Eight Explanation.txt",
    "content": "You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes.\r\n\r\nYour task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) \r\nso that the result contains at least one digit, forms a non-negative integer, doesn't have leading zeroes and is divisible by 8. \r\nAfter the removing, it is forbidden to rearrange the digits.\r\n\r\nIf a solution exists, you should print it.\r\n\r\n----------------------------------------------\r\n\r\nThe number of digits is only 100. So, I used a very simple algorithm.\r\n\r\nIterate over all 1-digit, 2-digit and 3-digit numbers possible in the array.\r\n\r\nAnd check if any of them are multiples of 8.\r\n\r\nNo need to check for 4 digits. Because if a number is 4 digit multiple, it will have a 3-digit suffix which will also be a multiple of 8.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string number;\r\n    cin >> number;\r\n\r\n    int found = false;\r\n    int answer;\r\n\r\n    typedef unsigned int u_int;\r\n\r\n    for(u_int i = 0; i < number.size() && !found; i++)\r\n    {\r\n        if(number[i] == '8' || number[i] == '0')\r\n            found = true, answer = number[i] - '0';\r\n    }\r\n\r\n    for(u_int i = 0; i < number.size() && !found; i++)\r\n    {\r\n        for(u_int j = i + 1; j < number.size() && !found; j++)\r\n        {\r\n            int first_digit = number[i] - '0', second_digit = number[j] - '0';\r\n            int number_formed = 10*first_digit + second_digit;\r\n\r\n            if(number_formed%8 == 0)\r\n                found = true, answer = number_formed;\r\n        }\r\n    }\r\n\r\n    for(u_int i = 0; i < number.size() && !found; i++)\r\n    {\r\n        for(u_int j = i + 1; j < number.size() && !found; j++)\r\n        {\r\n            for(u_int k = j + 1; k < number.size() && !found; k++)\r\n            {\r\n                int first_digit = number[i] - '0', second_digit = number[j]- '0', third_digit = number[k] - '0';\r\n                int number_formed = 100*first_digit + 10*second_digit + third_digit;\r\n\r\n                if(number_formed%8 == 0)\r\n                {\r\n                    answer = number_formed;\r\n                    found = true;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    if(found)\r\n        printf(\"YES\\n%d\\n\", answer);\r\n    else\r\n        printf(\"NO\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Given Length and Sum of Digits.txt",
    "content": "You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. \nThe required numbers should be non-negative integers written in the decimal base without leading zeroes.\n\n-------------------------------------------\n\nHow do we get the maximum number ?\n\nUse as many 9s as possible in the most significant digits and once we have no longer 9s left, we write whichever number we need to make up the sum and pad it with 0s.\n\nHow do we get the minimum number ?\n\nPut a 1 in the first digit and put as many 0s after the 1 as possible. In other words, put as many 9s as possible from the back. And then put a 1 in the first digit.\n\nNumber not posssible if sum = 0, and digits > 0.\n\nNumber possible if sum = 0, d = 1, Answer = 0\n\n--------------------------------------------------\n\nint main()\n{\n    int sum, no_of_digits;\n    scanf(\"%d %d\", &no_of_digits, &sum);\n\n    if(sum == 0 && no_of_digits == 1)\n    {\n        printf(\"0 0\\n\"); return 0;\n    }\n    else if(sum == 0 || sum > 9*no_of_digits)\n    {\n        printf(\"-1 -1\\n\"); return 0;\n    }\n\n    vector <int> minimum_number(no_of_digits + 1, 0);\n\n    int remaining_sum = sum - 1, i;\n    for(i = no_of_digits; i > 0 && remaining_sum > 0; i--)\n    {\n        if(remaining_sum >= 9)\n        {\n            minimum_number[i] = 9;\n            remaining_sum -= 9;\n        }\n        else\n        {\n            minimum_number[i] = remaining_sum;\n            remaining_sum = 0;\n        }\n    }\n\n    minimum_number[1] = (minimum_number[1] == 0 ? 1 : minimum_number[1] + 1);\n\n    vector <int> maximum_number(no_of_digits + 1, 0);\n    remaining_sum = sum;\n    for(i = 1; i <= no_of_digits && remaining_sum > 0; i++)\n    {\n        if(remaining_sum >= 9)\n        {\n            maximum_number[i] = 9;\n            remaining_sum -= 9;\n        }\n        else\n        {\n            maximum_number[i] = remaining_sum;\n            remaining_sum = 0;\n        }\n    }\n    for(int i = 1; i <= no_of_digits; i++) printf(\"%d\", minimum_number[i]);\n\n    printf(\" \");\n\n    for(int i = 1; i <= no_of_digits; i++) printf(\"%d\", maximum_number[i]);\n\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 15/Kefa and Park Explanation.txt",
    "content": "Kefa decided to celebrate his first big salary by going to the restaurant.\r\n\r\nHe lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. \r\nUnfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.\r\n\r\nThe leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, \r\nso there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.\r\n\r\nYour task is to help Kefa count the number of restaurants where he can go.\r\n\r\n-------------------------------------------\r\n\r\nThis was my first ever DFS problem.\r\n\r\nIn addition to the visited vector, keep a vector that keeps track of the number of consecutive cats ending at the current park.\r\n\r\nGo to the next park only if the number of consecutive cats <= m.\r\n\r\nIt is a tree. So a leaf node will have only one edge (and we would have already visited that edge).\r\n\r\nSo, the criteria for checking a leaf is (length == 1 && visited[tree[v][0]])\r\nIncrement the number of paths by 1 every time a leaf is encountered. (We are sure that if we have reached a leaf, no of consecutive cats never crossed m)\r\n\r\nDon't forget to initalise the number of cats at the root, and mark the root as visited before embarking on Depth First Search.\r\n\r\nFor every park that is visited, go to all unvisited parks from there.\r\n\r\n-----------------------------------------------------------------------------\r\n\r\nvoid dfs(int current_park, int &no_of_paths)\r\n{\r\n    if(tree[current_park].size() == 1 && visited[tree[current_park][0]])\r\n        no_of_paths++;\r\n\r\n    for(int i = 0; i < tree[current_park].size(); i++)\r\n    {\r\n        int next_park = tree[current_park][i];\r\n\r\n        if(!visited[next_park])\r\n        {\r\n            visited[next_park] = true;\r\n\r\n            no_of_consecutive_cats_till[next_park] = (has_cat[next_park] ? no_of_consecutive_cats_till[current_park] + 1 : 0);\r\n\r\n            if(no_of_consecutive_cats_till[next_park] <= max_cats)\r\n                dfs(next_park, no_of_paths);\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d %d\", &no_of_vertices, &max_cats);\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        scanf(\"%d\", &has_cat[i]);\r\n\r\n    for(int i = 1; i <= no_of_vertices - 1; i++)\r\n    {\r\n        int x, y;\r\n        scanf(\"%d %d\", &x, &y);\r\n\r\n        tree[x].push_back(y);\r\n        tree[y].push_back(x);\r\n    }\r\n\r\n    no_of_consecutive_cats_till[1] = has_cat[1];\r\n    visited[1] = true;\r\n    int no_of_paths = 0;\r\n\r\n    dfs(1, no_of_paths);\r\n\r\n    printf(\"%d\\n\", no_of_paths);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Mahmoud and Ehab and the xor Explanation.txt",
    "content": "Mahmoud and Ehab are on the third stage of their adventures now. As you know, Dr. Evil likes sets. This time he won't show them any set from his large collection, \r\nbut will ask them to create a new set to replenish his beautiful collection of sets.\r\n\r\nDr. Evil has his favorite evil integer x. He asks Mahmoud and Ehab to find a set of n distinct non-negative integers such the bitwise-xor sum of the integers \r\nin it is exactly x. \r\nDr. Evil doesn't like big numbers, so any number in the set shouldn't be greater than 106.\r\n\r\n-----------------------------------------------------\r\n\r\nIt was an interesting problem. If there wasn't a constraint of distinct numbers, then the answer could be x followed by n-1 0s.\r\n\r\nThere was some connection to the fact that the nim-sum of three numbers can be 0.\r\n\r\nHere are the cases.\r\n\r\nCase 1 - n = 1\r\n\r\n\tAns = x\r\n\r\nCase 2 - n = 2\r\n\r\n\tAns = {0, x}, \r\n\r\nIf x is 0, then there is no possible answer. \r\n\r\nIt turns out, this the only time when there is no answer.\r\n\r\nCase 3 - n >= 3\r\n\r\n\tFirst print all the numbers up to n - 3.\r\n\r\n\tCase 3a. XOR(1, 2, ..., n-3) = x\r\n\t\r\n\t\tIn that case, we have to print 3 more numbers which are distinct and who's xor sum is 0. \r\n\t\tthis can be done quite easily. One possible way is (2^n, 2^{n - 1}, 2^n|2^{n - 1})\r\n\r\n\t\tEnsure 2^n is really large and not <= n - 2\r\n\r\n\tCase 3b. b = XOR(1, 2, ... , n - 3) =/= x\r\n \r\n\t\tNow, we need three numbers, such that it neutralises b, and gives x and is not in that list.\r\n\r\n\t\t(XOR(2^n, b, x), 2^{n - 1}, 2^n|2^{n - 1}) is one such triplet. This leaves the answer = x\r\n\r\n---------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_numbers, x;\r\n    scanf(\"%d %d\", &no_of_numbers, &x);\r\n\r\n    if(no_of_numbers == 1)\r\n    {\r\n        printf(\"YES\\n%d\\n\", x);\r\n    }\r\n    else if(no_of_numbers == 2)\r\n    {\r\n        if(x == 0)\r\n            printf(\"NO\\n\");\r\n        else\r\n            printf(\"YES\\n0 %d\\n\", x);\r\n    }\r\n    else\r\n    {\r\n        const int POWER_2 = 1 << 19, PREVIOUS_POWER_2 = 1 << 18;\r\n        int bitwise_xor = 0;\r\n\r\n        printf(\"YES\\n\");\r\n        for(int i = 1; i <= no_of_numbers - 3; i++)\r\n        {\r\n            bitwise_xor ^= i;\r\n            printf(\"%d \", i);\r\n        }\r\n\r\n        if(bitwise_xor == x)\r\n            printf(\"%d %d %d\\n\", POWER_2, PREVIOUS_POWER_2, (POWER_2|PREVIOUS_POWER_2));\r\n        else\r\n            printf(\"%d %d %d\\n\", PREVIOUS_POWER_2, (POWER_2^bitwise_xor^x), (POWER_2|PREVIOUS_POWER_2));\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\t"
  },
  {
    "path": "Explanations/Explanations 15/Number of Ways Explanation.txt",
    "content": "\r\n\r\n-----------------------------------------------------\r\n\r\nEach part of the array must have sum = S/3.\r\n\r\nOne naive way to implement this is for each i, such that S[i] = S/3, \r\n\r\nCount the number of j, such that S[j] - S[i] = S/3 and j < n.\r\n\r\nThis works in O(n^2) time. There is a faster way to do this.\r\n\r\nPrecompute suffix sums.\r\n\r\nMaintain a new function, where f(i) = the number of j's such that i <=j <= n, S[n] - S[j - 1] = S/3\r\n\r\nThen, for each i such that S[i] = S/3, ans += f(i + 2) [Because the parts must be seperated]\r\n\r\nThis works in O(n) time.\r\n\r\nf(n + 1) = 0\r\nf(i) = f(i + 1) + (S[n] - S[i - 1] == S/3)\r\n--------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <long long> sum_till(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element_i;\r\n        scanf(\"%d\", &element_i);\r\n\r\n        sum_till[i] = sum_till[i - 1] + element_i;\r\n    }\r\n\r\n    vector <long long> sum_from(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_from[i] = sum_till[no_of_elements] - sum_till[i - 1];\r\n    }\r\n\r\n    long long no_of_ways = 0, total_sum = sum_till[no_of_elements];\r\n\r\n    if(total_sum%3 != 0)\r\n    {\r\n        printf(\"%I64d\\n\", no_of_ways);\r\n        return 0;\r\n    }\r\n\r\n    vector <int> no_of_places_that_sum_to_a_third_from(no_of_elements + 2, 0);\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        no_of_places_that_sum_to_a_third_from[i] = no_of_places_that_sum_to_a_third_from[i + 1] +\r\n                                                   (3*sum_from[i] == total_sum);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_elements - 2; i++)\r\n    {\r\n        if(3*sum_till[i] == total_sum)\r\n        {\r\n            no_of_ways += no_of_places_that_sum_to_a_third_from[i + 2];\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_ways);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Pearls in a Row Explanation.txt",
    "content": "There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.\r\n\r\nLet's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.\r\n\r\nSplit the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.\r\n\r\n-----------------------------------------------------------------\r\n\r\nBe greedy about the arrangement. Set the first boundary as soon as you find an element occuring twice.\r\n\r\nIf at the end, we have k segments and there are some elements at the end that don't belong to any segment, add them to the k-th segment.\r\n\r\nThe k-th segment anyway has an element that occurs at least twice. Adding more elements to this segment doesn't change this property. Hence, the segment remains good.\r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_pearls;\r\n    scanf(\"%d\", &no_of_pearls);\r\n\r\n    set <int> current_segment_pearls;\r\n    vector <pair <int, int> > segment;\r\n    int left = 1;\r\n\r\n    for(int right = 1; right <= no_of_pearls; right++)\r\n    {\r\n        int pearl_type;\r\n        scanf(\"%d\", &pearl_type);\r\n\r\n        if(current_segment_pearls.count(pearl_type) == 1)\r\n        {\r\n            segment.push_back(make_pair(left, right));\r\n            current_segment_pearls.clear();\r\n\r\n            left = right + 1;\r\n        }\r\n        else\r\n        {\r\n            current_segment_pearls.insert(pearl_type);\r\n        }\r\n    }\r\n\r\n    if(segment.size() == 0)\r\n        printf(\"-1\\n\");\r\n    else\r\n    {\r\n        segment.back().second = max(segment.back().second, no_of_pearls);\r\n\r\n        printf(\"%u\\n\", segment.size());\r\n        for(int i = 0; i < segment.size(); i++)\r\n            printf(\"%d %d\\n\", segment[i].first, segment[i].second);\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 15/Pie Rules Explanation.txt",
    "content": "You may have heard of the pie rule before. It states that if two people wish to fairly share a slice of pie, one person should cut the slice in half, \r\nand the other person should choose who gets which slice. \r\nAlice and Bob have many slices of pie, and rather than cutting the slices in half, each individual slice will be eaten by just one person.\r\n\r\nThe way Alice and Bob decide who eats each slice is as follows. First, the order in which the pies are to be handed out is decided. There is a special token called the \r\n\"decider\" token, initially held by Bob. Until all the pie is handed out, whoever has the decider token will give the next slice of pie to one of the participants, \r\nand the decider token to the other participant. They continue until no slices of pie are left.\r\n\r\nAll of the slices are of excellent quality, so each participant obviously wants to maximize the total amount of pie they get to eat. \r\nAssuming both players make their decisions optimally, how much pie will each participant receive?\r\n\r\n---------------------------------------------\r\n\r\nLet A(i) denote the maximum amount of pie Alice can get starting from the i-th piece if she has the decided token at piece i.\r\nLet B(i) denote the same thing for Bob.\r\n\r\nSo, at each piece there are two choices - either you take the piece and give the other person the decider token - this is = pie[i] + total_sum_from[i + 1] - B(i + 1)\r\n    or you keep the decider token and keep the piece = A(i + 1).\r\n\r\nSo, \r\n\r\nA(i) = max{A(i + 1), pie[i] + (sum_from[i + 1] - B(i + 1) )} [Alice gets the remainder of whatever Bob takes when Bob starts with decider token from (i + 1).\r\n\r\nB(i) = max{B(i + 1), pie[i] + (sum_from[i + 1] - A(i + 1) )}\r\n\r\nAnswer = B(1), and Sum From[1] - Bob(1)\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_pieces;\r\n    scanf(\"%d\", &no_of_pieces);\r\n\r\n    vector <int> pie(no_of_pieces + 1);\r\n    for(int i = 1; i <= no_of_pieces; i++)\r\n        scanf(\"%d\", &pie[i]);\r\n\r\n    vector <int> sum_from(no_of_pieces + 3, 0);\r\n    const int NO_OF_PLAYERS = 2, ALICE = 0, BOB = 1;\r\n    int maximum_from[no_of_pieces + 1][NO_OF_PLAYERS];\r\n\r\n    for(int i = no_of_pieces; i >= 1; i--)\r\n    {\r\n        sum_from[i] = pie[i] + sum_from[i + 1];\r\n\r\n        if(i == no_of_pieces)\r\n        {\r\n            maximum_from[i][ALICE] = maximum_from[i][BOB] = pie[i];\r\n        }\r\n        else\r\n        {\r\n            maximum_from[i][ALICE] = max(maximum_from[i + 1][ALICE], pie[i] + sum_from[i + 1] - maximum_from[i + 1][BOB]);\r\n            maximum_from[i][BOB] = max(maximum_from[i + 1][BOB], pie[i] + sum_from[i + 1] - maximum_from[i + 1][BOB]);\r\n        }\r\n    }\r\n\r\n    int maximum_for_alice = sum_from[1] - maximum_from[1][BOB];\r\n\r\n    printf(\"%d %d\\n\", maximum_for_alice, maximum_from[1][BOB]);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Quasi-palindrome Explanation.txt",
    "content": "\r\n\r\n---------------------------------------------\r\n\r\nCheck if n is a palindrome without trailing 0s.\r\n\r\n------------------------------------\r\n\r\nint is_palindrome(int n)\r\n{\r\n    int reverse_n = 0, original_n = n;\r\n\r\n    while(n > 0)\r\n    {\r\n        reverse_n = reverse_n*10 + n%10;\r\n        n = n/10;\r\n    }\r\n\r\n    return (reverse_n == original_n);\r\n}\r\n\r\nint palindrome_without_trailing_zeroes(int n)\r\n{\r\n    while(n%10 == 0)\r\n        n = n/10;\r\n\r\n    return is_palindrome(n);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(\"%s\\n\", palindrome_without_trailing_zeroes(n) ? \"YES\" : \"NO\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Team Explanation.txt",
    "content": "Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. \r\nThey've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.\r\n\r\nFor each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. \r\nThey think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:\r\n\r\nthere wouldn't be a pair of any side-adjacent cards with zeroes in a row;\r\nthere wouldn't be a group of three consecutive cards containing numbers one.\r\nToday Vanya brought n cards with zeroes and m cards with numbers one. \r\nThe number of cards was so much that the friends do not know how to put all those cards in the described way. \r\nHelp them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.\r\n\r\n--------------------------------------------------------\r\n\r\nIf the number of 1s are far more than the number of 0s, we can arrange them like this.\r\n\r\n11 0 11 0 11 0 .. .0  .. 0 \r\n\r\nBasically the 0s act like dividers. If there are z zeroes, then there are z+1 boxes for the 1s. \r\nIf the number of 1s, o > 2*(z + 1), \r\n\r\nOne of the boxes will have more than 2 1s by the Pigeonhole Principle. \r\n\r\nWhat about the bound on the number of 0s ?\r\n\r\nIf we look at the string and think of the 1s as seperators, then there can be at most o + 1 boxes. \r\n\r\nz > o + 1, cannot satisfy the equation.\r\n\r\nNow, how do we print such a string ? Trick is to be greedy. \r\n\r\nIf the number of 1s is greater than the number of 0s, print 110, \r\n\r\nIf the number of 1s are equal to the number of 0s, print 10.\r\n\r\nIf the number of 1s is less than the number of 0s, print \r\n\r\nDo this as long as both o AND z are > 0. Once one of them becomes 0, print the other character to the required frequency.\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_1s, no_of_0s;\r\n    scanf(\"%d %d\", &no_of_0s, &no_of_1s);\r\n\r\n    if(no_of_1s > 2*(no_of_0s + 1) || no_of_0s > no_of_1s + 1)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    while(no_of_0s > 0 && no_of_1s > 0)\r\n    {\r\n        if(no_of_1s > no_of_0s)\r\n        {\r\n            printf(\"110\");\r\n            no_of_1s -= 2, no_of_0s--;\r\n        }\r\n        else if(no_of_1s == no_of_0s)\r\n        {\r\n            printf(\"10\");\r\n            no_of_0s--, no_of_1s--;\r\n        }\r\n        else if(no_of_1s < no_of_0s)\r\n        {\r\n            printf(\"01\");\r\n            no_of_0s--, no_of_1s--;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_0s; i++) printf(\"0\");\r\n    for(int i = 1; i <= no_of_1s; i++) printf(\"1\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 15/Triangle Explanation.txt",
    "content": "Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, \r\nshe told his brother about the task that her kindergartener asked her to solve. \r\nThe task was just to construct a triangle out of four sticks of different colours. \r\nNaturally, one of the sticks is extra. It is not allowed to break the sticks or use their partial length. \r\nAnne has perfectly solved this task, now she is asking Johnny to do the same.\r\n\r\nThe boy answered that he would cope with it without any difficulty. However, after a while he found out that different tricky things can occur. \r\nIt can happen that it is impossible to construct a triangle of a positive area, but it is possible to construct a degenerate triangle. \r\nIt can be so, that it is impossible to construct a degenerate triangle even. As Johnny is very lazy, he does not want to consider such a big amount of cases, \r\nhe asks you to help him.\r\n\r\n--------------------------------------\r\n\r\nCheck if it's possible to form a triangle, then check if it's possible to form a segment.\r\n\r\n--------------------------------------------\r\n\r\nint triangle(int side_a, int side_b, int side_c)\r\n{\r\n    return ( (side_a + side_b > side_c) && (side_b + side_c > side_a) && (side_c + side_a > side_b) );\r\n}\r\n\r\nint segment(int side_a, int side_b, int side_c)\r\n{\r\n    return ( (side_a + side_b == side_c) || (side_b + side_c == side_a) || (side_c + side_a == side_b) );\r\n}\r\n\r\nint main()\r\n{\r\n    int side_a, side_b, side_c, side_d;\r\n    scanf(\"%d %d %d %d\", &side_a, &side_b, &side_c, &side_d);\r\n\r\n    if(triangle(side_a, side_b, side_c) || triangle(side_b, side_c, side_d) || triangle(side_c, side_d, side_a) || triangle(side_b, side_a, side_d) )\r\n        printf(\"TRIANGLE\\n\");\r\n    else if(segment(side_a, side_b, side_c) || segment(side_b, side_c, side_d) || segment(side_c, side_d, side_a) || segment(side_b, side_a, side_d) )\r\n        printf(\"SEGMENT\\n\");\r\n    else\r\n        printf(\"IMPOSSIBLE\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 15/USB Flash Drives Explanation.txt",
    "content": "\r\n\r\n----------------------------------------------\r\n\r\nUse the largest files first.\r\n\r\n----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_drives, file_size;\r\n    scanf(\"%d %d\", &no_of_drives, &file_size);\r\n\r\n    vector <int> capacity(no_of_drives);\r\n    for(int i = 0; i < no_of_drives; i++)\r\n        scanf(\"%d\", &capacity[i]);\r\n\r\n    sort(all(capacity));\r\n\r\n    int no_of_drives_used = 0;\r\n    for(int drive_i = no_of_drives - 1; file_size > 0 && drive_i >= 0; drive_i--, no_of_drives_used++)\r\n        file_size -= capacity[drive_i];\r\n\r\n    printf(\"%d\\n\", no_of_drives_used);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Amusing Joke Explanation.txt",
    "content": "\r\nThe sum of frequencies of each letter in the first two names = frequency in third name.\r\n\r\nSo, I incremented frequency in first two strings and decremented in third string and checked if it is 0 at the end.\r\n\r\n------------------------------------------------\r\n\r\nint main()\r\n{\r\n    const int NO_OF_ALPHABETS = 26;\r\n    int frequency[NO_OF_ALPHABETS] = {0};\r\n\r\n    for(int i = 1; i <= 3; i++)\r\n    {\r\n        const int MAX_LENGTH = 103;\r\n        char name[MAX_LENGTH];\r\n        scanf(\"%s\", name);\r\n\r\n        for(int j = 0; name[j] != '\\0'; j++)\r\n            frequency[name[j] - 'A'] += (i == 3 ? -1 : 1);\r\n    }\r\n\r\n    int is_possible = true;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n        if(frequency[i] != 0)\r\n            is_possible = false;\r\n\r\n    printf(is_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Anton and Letters Explanation.txt",
    "content": "Read a line with white spaces.\r\n\r\nint main()\r\n{\r\n    string line;\r\n    getline(cin, line);\r\n\r\n    set <char> letters;\r\n    for(int i = 0; i < line.size(); i++)\r\n    {\r\n        if(is_alpha(line[i]))\r\n            letters.insert(line[i]);\r\n    }\r\n\r\n    cout << letters.size();\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Cards with Numbers Explanation.txt",
    "content": "Easy question. The tricky part is the files.\r\n\r\n--------------------------------\r\n\r\nstruct card\r\n{\r\n    int index, value;\r\n};\r\n\r\nbool sort_by_value(const card &A, const card &B)\r\n{\r\n    return (A.value < B.value);\r\n}\r\n\r\nint main()\r\n{\r\n    FILE *input = fopen(\"input.txt\", \"r\");\r\n    int no_of_cards;\r\n    fscanf(input, \"%d\", &no_of_cards);\r\n\r\n    vector <card> cards(2*no_of_cards);\r\n    for(int i = 0; i < 2*no_of_cards; i++)\r\n    {\r\n        fscanf(input, \"%d\", &cards[i].value);\r\n        cards[i].index = i + 1;\r\n    }\r\n\r\n    sort(all(cards), sort_by_value);\r\n\r\n    FILE *output = fopen(\"output.txt\", \"w\");\r\n\r\n    vector <pair <int, int> > solution;\r\n    for(int i = 0; i < 2*no_of_cards; i += 2)\r\n    {\r\n        if(cards[i].value == cards[i + 1].value)\r\n            solution.push_back(make_pair(cards[i].index, cards[i + 1].index));\r\n        else\r\n        {\r\n            fprintf(output, \"-1\\n\");\r\n            return 0;\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < no_of_cards; i++)\r\n        fprintf(output, \"%d %d\\n\", solution[i].first, solution[i].second);\r\n\r\n    fclose(input);\r\n    fclose(output);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Classroom Watch Explanation.txt",
    "content": "Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. \r\nHe asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. \r\nIn the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system.\r\n\r\nSince the number n on the board was small, Vova quickly guessed which x could be in the textbook. \r\nNow he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. \r\nWrite such a program for Vova.\r\n\r\n----------------------------------------------\r\n\r\nThe maximum sum of digits of any number within the range is 81. \r\nSo, for any n, we only need to check from (n - 81) to see if any number satisfies the condition.\r\n\r\n----------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int MAX_DIGIT_SUM = 81;\r\n    int x = max(0, n - MAX_DIGIT_SUM);\r\n\r\n    vector <int> answer;\r\n    while(x <= n)\r\n    {\r\n        if(x + digit_sum(x) == n)\r\n            answer.push_back(x);\r\n\r\n        x++;\r\n    }\r\n\r\n    printf(\"%d\\n\", answer.size());\r\n    for(int i = 0; i < answer.size(); i++)\r\n        printf(\"%d \", answer[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Cupboards Explanation.txt",
    "content": "\r\nKeep track of the open doors on the left and right. \r\nThe number of operations on either side is whichever position occurs less times. \r\nThe answer is the sum of the right and left.\r\n\r\nint main()\r\n{\r\n\tconst int OPEN = 1, CLOSED = 0;\r\n\tint no_of_cupboards;\r\n\tscanf(\"%d\", &no_of_cupboards);\r\n\r\n\tint left_open_doors = 0, left_closed_doors = 0;\r\n\tint right_open_doors = 0, right_closed_doors = 0;\r\n\r\n    while(no_of_cupboards--)\r\n\t{\r\n\t\tint left, right;\r\n\t\tscanf(\"%d %d\", &left, &right);\r\n\r\n\t\tleft_open_doors += (left == OPEN);\r\n\t\tleft_closed_doors += (left == CLOSED);\r\n\r\n\t\tright_open_doors += (right == OPEN);\r\n\t\tright_closed_doors += (right == CLOSED);\r\n\t}\r\n\r\n\tint minimum_left_operations = min(left_closed_doors, left_open_doors);\r\n\tint minimum_right_operations = min(right_open_doors, right_closed_doors);\r\n\r\n\tprintf(\"%d\\n\", minimum_left_operations + minimum_right_operations);\r\n\r\n\treturn 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Dishonest Sellers Explanation.txt",
    "content": "\r\nHere's the main idea - \r\n\r\nIf we did not have the restriction of buying k from now, we'd buy every item whenever it is cheaper.\r\n\r\nSo, we buy k items from now greedily and the REMAINING n - k items, we choose from whichever day is cheaper. \r\nHow do we choose these k items ?\r\n\r\nIt's not the k items who's cost now is the cheapest.\r\n\r\nLet's say we buy every item on second day, Cost =\r\n\r\nC = B1 + B2 + B3 + ... + Bn.\r\n\r\nNow, we HAVE TO buy some of these on day 1. How do we choose this ?\r\n\r\nLet's say we buy item 1 now.\r\n\r\nCost increases by (A1 - B1). [This may be negative]. i.e. C' = C + (A1 - B1)\r\n\r\nNow, our task is to choose k items to buy now such that we MINIMISE the rise in C.\r\n\r\nSo, what we do is we choose k items from now such that (A1 - B1) is minimum. \r\n\r\nIn short, \r\n\r\n1. Buy k items who's difference (A1 - B1) is minimum.\r\n2. From K+1 to N, buy the item whenever it is cheaper - now or one week later. min{Ai, Bi}\r\n\r\nImportant to note that the difference should NOT be in terms of absolute value. We want to buy the ones with the negative difference now, because it means \r\nit will be more expensive next week.\r\n\r\n---------------------------------------------------------------------------------------------------------------\r\n\r\n#define all(v) (v).begin(), (v).end()\r\n\r\nstruct prices\r\n{\r\n    int now, discount, difference;\r\n};\r\n\r\nbool sort_By_Difference(const prices &A, const prices &B)\r\n{\r\n    return (A.difference < B.difference);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_days, minimum_now_buys;\r\n    scanf(\"%d %d\", &no_of_days, &minimum_now_buys);\r\n\r\n    vector <prices> price(no_of_days);\r\n    for(int i = 0; i < no_of_days; i++)\r\n        scanf(\"%d\", &price[i].now);\r\n\r\n    for(int i = 0; i < no_of_days; i++)\r\n        scanf(\"%d\", &price[i].discount);\r\n\r\n    for(int i = 0; i < no_of_days; i++)\r\n        price[i].difference = price[i].now - price[i].discount;\r\n\r\n    sort(all(price), sort_By_Difference);\r\n\r\n    int money_used = 0;\r\n    for(int i = 0; i < no_of_days; i++)\r\n    {\r\n        if(i < minimum_now_buys)\r\n            money_used += price[i].now;\r\n        else\r\n            money_used += min(price[i].now, price[i].discount);\r\n    }\r\n\r\n    printf(\"%d\\n\", money_used);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Dubstep Explanation.txt",
    "content": "String implementation problem. \r\n\r\nIf you get a WUB at any point of time, \r\n\r\n\tCheck if word is not empty, if it isn't, then print it and clear it.\r\n\r\nOtherwise, add the current letter to word.\r\n\r\nPrint the word at the end if it is empty\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string song;\r\n    cin >> song;\r\n\r\n    string word;\r\n    for(int i = 0; i < song.length(); i++)\r\n    {\r\n        if(i + 2 < song.length() && song[i] == 'W' && song[i + 1] == 'U' && song[i + 2] == 'B')\r\n        {\r\n            i += 2;\r\n            if(!word.empty())\r\n            {\r\n                cout << word << \" \";\r\n                word.clear();\r\n            }\r\n        }\r\n        else\r\n        {\r\n            word += song[i];\r\n        }\r\n    }\r\n\r\n    if(!word.empty())\r\n        cout << word << \" \";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Easy Number Challenge Explanation.txt",
    "content": "\r\nNote - the constraints are pretty small, Since, a, b, c <= 100.\r\n\r\nO(abc) solution will be accepted.\r\n\r\nPrecompute d(n) for all n <= 10^6.\r\n\r\nThe precomputation can be done using a sieve. It is a multiplicative function. If n = p^a n', where gcd(p, n) = 1, \r\n\r\nThen d(n) = (a + 1). d(n').\r\n\r\nUse this to compute d(n).\r\n\r\n----------------------------------------------------\r\n\r\nvoid precompute(vector <int> &number_of_divisors, int LIMIT)\r\n{\r\n    number_of_divisors[1] = 1;\r\n\r\n    vector <int> largest_prime_factor(LIMIT + 1, 0);\r\n    for(int i = 2; i <= LIMIT; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple <= LIMIT; multiple += i)\r\n                largest_prime_factor[multiple] = i;\r\n        }\r\n\r\n        int exponent = 0;\r\n\r\n        int reduced_i = i;\r\n        while(reduced_i%largest_prime_factor[i] == 0)\r\n        {\r\n            reduced_i /= largest_prime_factor[i];\r\n            exponent++;\r\n        }\r\n\r\n        number_of_divisors[i] = (exponent + 1)*number_of_divisors[reduced_i];\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 1e6;\r\n    vector <int> number_of_divisors(LIMIT + 1, 0);\r\n    precompute(number_of_divisors, LIMIT);\r\n\r\n    int a, b, c;\r\n    scanf(\"%d %d %d\", &a, &b, &c);\r\n\r\n    int sum = 0;\r\n    for(int i = 1; i <= a; i++)\r\n    {\r\n        for(int j = 1; j <= b; j++)\r\n        {\r\n            for(int k = 1; k <= c; k++)\r\n            {\r\n                sum += number_of_divisors[i*j*k];\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", sum);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Fox and Snake Explanation.txt",
    "content": " Implementation problem\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        int different_cell = -1;\r\n        char default_char = (i%2 == 0 ? '.' : '#');\r\n\r\n        if(i%2 == 0)\r\n            different_cell = (i%4 == 0 ? 1 : columns);\r\n\r\n        for(int j = 1; j <= columns; j++)\r\n            printf(\"%c\", (j != different_cell ? default_char : '#'));\r\n\r\n        printf(\"\\n\");\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Greg and Array Explanation.txt",
    "content": "A very interesting concept.\r\n\r\n\n\nSuppose you have an array of n elements. \nAnd Q queries, each characterised by - left and right.\r\n\nIn one query, you must add 1 to every number from left to right.\n\nPrint the array after all the queries \n\r\n\r\nThe naive way of doing this.\r\n\n\nfor(int i = 1; i <= Q; i++)\n{\n\t\r\n\tfor(int j = l; j <= R; j++)\n\t\t\r\n\t\tA[j]++;\n}\n\n\r\n\r\nThis is O(NQ)\n\nIf N and Q are both 10^5, then you will 10^10 operations (or thereabouts) --- that's months of time.\n\n\r\n\r\nThere's a better way. Have an array C, that keeps track of the number of operations that start at C\n\n\r\n\r\nfor(int i = 1; i <= Q; i++)\n{\n\t\r\n\tC[l]++;\n\tC[r + 1]--;\n\r\n}\r\n\r\n\n\nfor(int i = 1; i <= N; i++)\n\t\r\n\tA[i] = A[i - 1] + C[i]\n\t\n\r\n\r\nIn other words, the number of queries affecting previous term plus \nthe number of queries starting at that position.\n\n\r\nOf course, if there's a query affecting (i - 1) but not i, then C[i] will accordingly reduce it.\n\nThis is O(N + Q). \r\n\r\nCan be done in under a second with the same constraints.\r\n\r\nThis question is interersting because this logic has to be applied twice. \r\n\r\n1. Apply it on the operations so that you know the number of times each operation is used.\r\n2. After it is known the number of times each operation is used.\r\n\r\nfor(i = 1 to no of operations)\r\n{\r\n\tUpdates[operations[i].left] += use[i]*operations[i].value\r\n\tUpdates[operations[i].right + 1] -= use[i]*operations[i].value\r\n}\r\n\r\nfor(i = 1 to no of elements)\r\n{\r\n\tamount to be added[i] = amount to be added[i - 1] + Udates[i]\r\n}\r\n\r\nAnd then \r\nfor(i = 1 to no of elements)\r\n\telement[i] += amount to be added[i]\r\n\r\n----------------------------------------------------------------------------------------------------------\r\n\r\nstruct operation\r\n{\r\n    int left, right, value;\r\n};\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_operations, no_of_queries;\r\n    scanf(\"%d %d %d\", &no_of_elements, &no_of_operations, &no_of_queries);\r\n\r\n    vector <long long> element(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &element[i]);\r\n\r\n    vector <operation> operations(no_of_operations + 1);\r\n    for(int i = 1; i <= no_of_operations; i++)\r\n        scanf(\"%d %d %d\", &operations[i].left, &operations[i].right, &operations[i].value);\r\n\r\n    vector <int> no_of_operations_starting(no_of_operations + 2, 0);\r\n    while(no_of_queries--)\r\n    {\r\n        int left_operation, right_operation;\r\n        scanf(\"%d %d\", &left_operation, &right_operation);\r\n\r\n        no_of_operations_starting[left_operation]++;\r\n        no_of_operations_starting[right_operation + 1]--;\r\n    }\r\n\r\n    vector <int> no_of_uses(no_of_operations + 1, 0);\r\n    for(int i = 1; i <= no_of_operations; i++)\r\n        no_of_uses[i] = no_of_uses[i - 1] + no_of_operations_starting[i];\r\n\r\n    vector <long long> no_of_updates_starting(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_operations; i++)\r\n    {\r\n        int start_point = operations[i].left, end_point = operations[i].right, d = operations[i].value;\r\n\r\n        no_of_updates_starting[start_point] += no_of_uses[i]*1LL*d;\r\n        no_of_updates_starting[end_point + 1]-= no_of_uses[i]*1LL*d;\r\n    }\r\n\r\n    vector <long long> amount_to_be_added(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        amount_to_be_added[i] = amount_to_be_added[i - 1] + no_of_updates_starting[i];\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        element[i] += amount_to_be_added[i];\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        printf(\"%I64d \", element[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Hacking Cypher Explanation.txt",
    "content": "\r\nI was very proud of myself for being able to do this one.\r\n\r\nFirstly, how do you brute force such a thing ?\r\n\r\nWell, break the string at every possible point and see if the prefix is divisible by a and suffix by b.\r\n\r\nNow, since this is a string of numbers and not a single number, this takes O(n^2).\r\n\r\nUsing Horner's Method, find p(i), where p(i) denotes the remainder of the prefix ending at i with a.\r\nAnd s(i) = suffix of string starting from b with i.\r\n\r\nCheck if there's a point where p(i) = 0, s(i + 1) = 0 and i+1 th digit is not 0. Also ensure the first digit is not 0.\r\n\r\nNow, calculating p(i) is easy\r\np(1) = N(1)%a\r\np(i) = { 10*p(i - 1) + N(i) }%a\r\n\r\ns(last digit) = N(last digit)%b\r\ns(i) = { 10^l *N(i) + s(i + 1) }%b, where l is the numbre of digits from i+1 to the end.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a, b;\r\n    string number;\r\n    cin >> number >> a >> b;\r\n\r\n    int no_of_numbers = number.size();\r\n\r\n    vector <int> remainder_a_till(no_of_numbers);\r\n    remainder_a_till[0] = (number[0] - '0')%a;\r\n\r\n    for(int i = 1 ; number[i] != '\\0'; i++)\r\n    {\r\n        remainder_a_till[i] = (10*remainder_a_till[i - 1] + number[i] - '0')%a;\r\n    }\r\n\r\n\r\n    vector <int> remainder_b_from(no_of_numbers);\r\n    remainder_b_from[no_of_numbers - 1] = (number[no_of_numbers - 1] - '0')%b;\r\n\r\n    for(int i = no_of_numbers - 2, ten_power = 10; i >= 0; i--)\r\n    {\r\n        remainder_b_from[i] = (ten_power*(number[i] - '0') + remainder_b_from[i + 1])%b;\r\n\r\n        ten_power = (ten_power*10)%b;\r\n    }\r\n\r\n    int end_of_a = -1;\r\n    for(int i = 0; i + 1 < no_of_numbers; i++)\r\n    {\r\n        if(remainder_a_till[i] == 0 && remainder_b_from[i + 1] == 0 && number[i + 1] != '0')\r\n            end_of_a = i;\r\n    }\r\n\r\n    if(end_of_a == -1 || number[0] == '0')\r\n    {\r\n        printf(\"NO\\n\");\r\n        return 0;\r\n    }\r\n\r\n    printf(\"YES\\n\");\r\n\r\n    for(int i = 0; i <= end_of_a; i++) printf(\"%c\", number[i]);\r\n\r\n    printf(\"\\n\");\r\n\r\n    for(int i = end_of_a + 1; i < no_of_numbers; i++) printf(\"%c\", number[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/I Wanna Be The Guy Explanation.txt",
    "content": "\r\nJust keep track of the number of levels that have been crossed and check if there's any level not covered.\r\n\r\nint main()\r\n{\r\n    int no_of_levels;\r\n    scanf(\"%d\", &no_of_levels);\r\n\r\n    int crossed_levels[no_of_levels + 1] = {false};\r\n    int x_levels;\r\n    scanf(\"%d\", &x_levels);\r\n\r\n    while(x_levels--)\r\n    {\r\n        int level;\r\n        scanf(\"%d\", &level);\r\n        crossed_levels[level] = true;\r\n    }\r\n\r\n    int y_levels;\r\n    scanf(\"%d\", &y_levels);\r\n\r\n    while(y_levels--)\r\n    {\r\n        int level;\r\n        scanf(\"%d\", &level);\r\n        crossed_levels[level] = true;\r\n    }\r\n\r\n    int possible = true;\r\n    for(int i = 1; i <= no_of_levels; i++)\r\n        if(!crossed_levels[i])\r\n            possible = false;\r\n\r\n    printf(possible ? \"I become the guy.\" : \"Oh, my keyboard!\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/IQ Test Explanation.txt",
    "content": "Just check every 2x2 square if the frequency of either colour >= 3.\r\n\r\nint possible_to_make_square(char square[][5], int x, int y)\r\n{\r\n    int black = (square[x][y] == '#') + (square[x - 1][y] == '#') + (square[x - 1][y - 1] == '#') + (square[x][y - 1] == '#');\r\n    int white = (square[x][y] == '.') + (square[x - 1][y] == '.') + (square[x - 1][y - 1] == '.') + (square[x][y - 1] == '.');\r\n\r\n    return (black >= 3 || white >= 3);\r\n}\r\n\r\nint main()\r\n{\r\n    const int N = 4;\r\n    char square[N + 1][N + 1];\r\n\r\n    for(int i = 0; i < N; i++)\r\n        scanf(\"%s\", square[i]);\r\n\r\n    int is_possible = false;\r\n\r\n    for(int i = 1; i < 4; i++)\r\n    {\r\n        for(int j = 1; j < 4; j++)\r\n        {\r\n            if(possible_to_make_square(square, i, j))\r\n                is_possible = true;\r\n        }\r\n    }\r\n\r\n    printf(is_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Jeff and Periods Explanation.txt",
    "content": "\r\nFor every number, maintain the following information -\r\n\r\nThe last index it occurs, \r\nThe second last index it occurs,\r\nThe difference of it's AP.\r\n\r\nWhenever a new occurence occurs at i, check if i - last = last - second_last\r\nIf not, then an AP is not possible.\r\n\r\nBe careful about the first and second occurence of the number.\r\n\r\n-------------------------------------------------------------------------\r\n\r\nconst int NOT_POSSIBLE = -1, MAX_ELEMENTS = 1e5 + 1;\r\n\r\nstruct number\r\n{\r\n    int last_index, second_last_index, difference;\r\n\r\n    number(){ last_index = second_last_index = 0; difference = NOT_POSSIBLE;}\r\n};\r\n\r\nint main()\r\n{\r\n    number elements[MAX_ELEMENTS];\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int n;\r\n        scanf(\"%d\", &n);\r\n\r\n        if(elements[n].last_index == 0)\r\n        {\r\n            elements[n].last_index = i;\r\n            elements[n].difference = 0;\r\n        }\r\n        else if(elements[n].second_last_index == 0)\r\n        {\r\n            elements[n].second_last_index = elements[n].last_index;\r\n            elements[n].last_index = i;\r\n            elements[n].difference = elements[n].last_index - elements[n].second_last_index;\r\n        }\r\n        else\r\n        {\r\n            if(i - elements[n].last_index == elements[n].difference)\r\n            {\r\n                elements[n].second_last_index = elements[n].last_index;\r\n                elements[n].last_index = i;\r\n            }\r\n            else\r\n            {\r\n                elements[n].difference = NOT_POSSIBLE;\r\n            }\r\n        }\r\n    }\r\n\r\n    int no_of_aps = 0;\r\n    for(int i = 1; i < MAX_ELEMENTS; i++)\r\n        no_of_aps += (elements[i].difference != NOT_POSSIBLE);\r\n\r\n    printf(\"%d\\n\", no_of_aps);\r\n    for(int i = 1; i < MAX_ELEMENTS; i++)\r\n        if(elements[i].difference != NOT_POSSIBLE)\r\n            printf(\"%d %d\\n\", i, elements[i].difference);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Pashmak and Garden Explanation.txt",
    "content": "\r\nOkay, if the x1 = x2, then it means we have a side parallel to y-axis.\r\n\r\nx3 = x1 + d, y3 = y1\r\nx4 = x2 + 3, y4 = y2\r\n\r\nSimilar reasoning if y1 = y2, \r\n\r\nnow, what happens if we have two diagonally opposite points ?\r\n\r\nThen, |x1 - x2| = |y1 - y2|\r\n\r\nThis quantity is the same in squares. We are taking absolute values because it might be anti-diagonal as well.\r\n\r\nint main()\r\n{\r\n    int x_1, x_2, y_1, y_2;\r\n    scanf(\"%d %d %d %d\", &x_1, &y_1, &x_2, &y_2);\r\n\r\n    int x_3, y_3, x_4, y_4;\r\n\r\n    if(x_1 == x_2)\r\n    {\r\n        int distance = abs(y_1 - y_2);\r\n\r\n        x_3 = x_1 + distance; y_3 = y_1;\r\n\r\n        x_4 = x_2 + distance; y_4 = y_2;\r\n    }\r\n    else if(y_1 == y_2)\r\n    {\r\n        int distance = abs(x_1 - x_2);\r\n\r\n        y_3 = y_1 + distance; x_3 = x_1;\r\n\r\n        y_4 = y_2 + distance; x_4 = x_2;\r\n    }\r\n    else if(abs(x_1 - x_2) == abs(y_1 - y_2))\r\n    {\r\n        x_3 = x_1; y_3 = y_2;\r\n\r\n        x_4 = x_2; y_4 = y_1;\r\n    }\r\n    else\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n    printf(\"%d %d %d %d\\n\", x_3, y_3, x_4, y_4);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Primes or Palindromes Explanation.txt",
    "content": "\r\nOkay, the problem is hard because of analysing the limits. I couldn't do that.\r\n\r\nBut, I saw the editorial and it said two things \r\n\r\n1. There is always an answer in the specified range.\r\n2. The answer is always less than 2 million.\r\n\r\nFrom there, it was easy.\r\n\r\nPrecompute pi(n) using a sieve. Precompute the palindromes too.\r\n\r\nThis happens in roughly three linear scans. \r\n\r\nSince, there's only one query, answer it using another linear scan.\r\n\r\n----------------------------------------------------------------------\r\n\r\nint reverse(int n)\r\n{\r\n    int rev = 0;\r\n    while(n)\r\n    {\r\n        rev = rev*10 + n%10;\r\n        n /= 10;\r\n    }\r\n    return rev;\r\n}\r\n\r\nint is_palindrome(int n)\r\n{\r\n    return (n == reverse(n));\r\n}\r\n\r\nvoid precompute(vector <int> &no_of_primes_till, vector <int> &no_of_palindromes_till, int LIMIT)\r\n{\r\n    vector <int> is_prime(LIMIT + 1, true);\r\n    is_prime[0] = is_prime[1] = false;\r\n\r\n    vector <int> primes;\r\n    for(int i = 2; i <= LIMIT; i++)\r\n    {\r\n        if(is_prime[i])\r\n            primes.push_back(i);\r\n\r\n        for(int j = 0; j < primes.size() && i*primes[j] < LIMIT; j++)\r\n        {\r\n            is_prime[i*primes[j]] = false;\r\n\r\n            if(i%primes[j] == 0) break;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= LIMIT; i++)\r\n        no_of_primes_till[i] = no_of_primes_till[i - 1] + is_prime[i];\r\n\r\n    for(int i = 1; i <= LIMIT; i++)\r\n        no_of_palindromes_till[i] = no_of_palindromes_till[i - 1] + is_palindrome(i);\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 2e6;\r\n    vector <int> no_of_primes_till(LIMIT + 1, 0);\r\n    vector <int> no_of_palindromes_till(LIMIT + 1, 0);\r\n    precompute(no_of_primes_till, no_of_palindromes_till, LIMIT);\r\n\r\n    int p, q;\r\n    scanf(\"%d %d\", &p, &q);\r\n\r\n    for(int n = LIMIT; n >= 1; n--)\r\n    {\r\n        if(q*no_of_primes_till[n] <= p*no_of_palindromes_till[n])\r\n        {\r\n            printf(\"%d\\n\", n);\r\n            break;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Quasi Binary Explanation.txt",
    "content": "\r\nHere's the idea ...\r\n\r\nImagine, towers of height - a1, a2, a3, ... an\r\n\r\nNeed to be built. In one move, you are allowed to place exactly one brick in one or more towers at the same level.\r\n\r\nProceed greedily.\r\n\r\nThe number of moves = max{a1, a2, ... , an}\r\n\r\nIf it is 345\r\n\r\n111, 11, 1\r\n\r\nKeep placing bricks in a certain tower till the height is reached.\r\n\r\n-------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int MAX_SIZE = 7;\r\n    vector <int> no_of_bits(MAX_SIZE + 1, 0);\r\n\r\n    int greatest_bit = 0;\r\n\r\n    for(int i = 0; n > 0; i++)\r\n    {\r\n        no_of_bits[i] = n%10;\r\n        n /= 10;\r\n\r\n        greatest_bit = max(greatest_bit, no_of_bits[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", greatest_bit);\r\n\r\n    for(int i = 1; i <= greatest_bit; i++)\r\n    {\r\n        int number = 0;\r\n\r\n        for(int j = no_of_bits.size() - 1; j >= 0; j--)\r\n        {\r\n            number *= 10;\r\n\r\n            if(no_of_bits[j] > 0)\r\n                number++;\r\n\r\n            no_of_bits[j]--;\r\n        }\r\n        printf(\"%d \", number);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Sereja and Bottles Explanation.txt",
    "content": "I kept trying to come up with an O(n) solution but it had lots of bugs. Here's an O(n) solution.\r\n\r\nint main()\r\n{\r\n    int no_of_bottles;\r\n    scanf(\"%d\", &no_of_bottles);\r\n\r\n    vector <int> brand(no_of_bottles + 1, 0);\r\n    vector <int> can_open(no_of_bottles + 1, 0);\r\n\r\n    for(int i = 1; i <= no_of_bottles; i++)\r\n        scanf(\"%d %d\", &brand[i], &can_open[i]);\r\n\r\n    int impossible_bottles = 0;\r\n    for(int i = 1; i <= no_of_bottles; i++)\r\n    {\r\n        int openable = false;\r\n\r\n        for(int j = 1; j <= no_of_bottles; j++)\r\n        {\r\n            if(can_open[j] == brand[i] && i != j)\r\n                openable = true;\r\n        }\r\n\r\n        impossible_bottles += (!openable);\r\n    }\r\n\r\n    printf(\"%d\\n\", impossible_bottles);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Team Olympiad Explanation.txt",
    "content": "Simple implementation\r\nThe number of teams is the minimum of the three categories.\r\n\r\nint main()\r\n{\r\n    vector <int> mathematician;\r\n    vector <int> programmer;\r\n    vector <int> sportsperson;\r\n\r\n    int no_of_players;\r\n    scanf(\"%d\", &no_of_players);\r\n\r\n    for(int i = 1; i <= no_of_players; i++)\r\n    {\r\n        int activity;\r\n        scanf(\"%d\", &activity);\r\n\r\n        switch(activity)\r\n        {\r\n            case 1: mathematician.push_back(i); break;\r\n            case 2: programmer.push_back(i); break;\r\n            case 3: sportsperson.push_back(i); break;\r\n        }\r\n    }\r\n\r\n    int no_of_teams = min_3(mathematician.size(), programmer.size(), sportsperson.size());\r\n    printf(\"%d\\n\", no_of_teams);\r\n\r\n    for(int i = 1; i <= no_of_teams; i++)\r\n        printf(\"%d %d %d\\n\", mathematician[i - 1], programmer[i - 1], sportsperson[i - 1]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/The Fibonacci Segment Explanation.txt",
    "content": "\r\nIt's a longest increasing subsequence problem. Quite interesting.\r\n\r\nLet f(i) denote the longest increasing segement ending at i.\r\n\r\nf(1) = 1,\r\n\r\nf(i) = (A[i] == A[i - 1] + A[i - 2] ? f(i - 1) + 1 : 2)\r\n\r\nAns = max{f(i)}\r\n\r\n------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    vector <int> longest_segment_ending(no_of_elements + 1, 1);\r\n    int longest_segment = 1;\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        if(i == 2)\r\n            longest_segment_ending[i] = 2;\r\n        else\r\n            longest_segment_ending[i] = (element[i] == element[i - 1] + element[i - 2] ? longest_segment_ending[i - 1] + 1 : 2);\r\n\r\n        longest_segment = max(longest_segment, longest_segment_ending[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_segment);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Twins Explanation.txt",
    "content": "\r\nSort the array and choose the largest elements until the sum of the coins taken, is greater than the remaining sum.\r\n\r\nint main()\r\n{\r\n    int no_of_coins;\r\n    scanf(\"%d\", &no_of_coins);\r\n\r\n    int total = 0;\r\n    vector <int> coin(no_of_coins);\r\n    for(int i = 0; i < no_of_coins; i++)\r\n    {\r\n        scanf(\"%d\", &coin[i]);\r\n        total += coin[i];\r\n    }\r\n\r\n    sort(all(coin));\r\n\r\n    int no_of_coins_taken = 0, sum_of_taken = 0;\r\n    for(int i = no_of_coins - 1; i >= 0 && sum_of_taken <= total ; i--)\r\n    {   \r\n        sum_of_taken += coin[i];\r\n        total -= coin[i];\r\n\r\n        no_of_coins_taken++;  \r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_coins_taken);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 16/Valera and Tubes Explanation.txt",
    "content": "\r\nHere was my idea -\r\n\r\nEach tube has exactly 2 cells and the last tube has all the remaining cells.\r\nCrawl around the cell like a snake.\r\n\r\nIf you're at a corner, change the row.\r\nDon't visit a visited square twice.\r\n\r\n--------------------------------------------\r\n\r\nconst int MAX_ROWS = 301, MAX_COLUMNS = 301;\r\nint visited[MAX_ROWS][MAX_COLUMNS] = {{false}};\r\n\r\nvoid get_next(int &x, int &y, int columns)\r\n{\r\n    if( (y == 1 && visited[x][y + 1]) || (y == columns && visited[x][y - 1]) )\r\n        x++;\r\n    else\r\n        if(y < columns && !visited[x][y + 1])\r\n            y++;\r\n        else\r\n            y--;\r\n}\r\n\r\nint main()\r\n{\r\n    int rows, columns, no_of_tubes;\r\n    scanf(\"%d %d %d\", &rows, &columns, &no_of_tubes);\r\n\r\n    vector <vector <pair <int, int> > >tubes(no_of_tubes + 1);\r\n    int x = 1, y = 1, i = 1;\r\n\r\n    while(x <= rows)\r\n    {\r\n        tubes[i].push_back(make_pair(x, y));\r\n\r\n        if(i != no_of_tubes && tubes[i].size() == 2)\r\n            i++;\r\n\r\n        visited[x][y] = true;\r\n        get_next(x, y, columns);\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_tubes; i++)\r\n    {\r\n        printf(\"%d \", tubes[i].size());\r\n\r\n        for(int j = 0; j < tubes[i].size(); j++)\r\n            printf(\"%d %d \", tubes[i][j].first, tubes[i][j].second);\r\n\r\n        printf(\"\\n\");\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/Xenia and Bit Operations.txt",
    "content": "Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. \nTo better understand how they work, Xenia decided to calculate some value v for a.\n\nNamely, it takes several iterations to calculate value v. \nAt the first iteration, Xenia writes a new sequence a1 or a2, a3 or a4, ..., a2n - 1 or a2n, consisting of 2n - 1 elements. \nIn other words, she writes down the bit-wise OR of adjacent elements of sequence a. \nAt the second iteration, Xenia writes the bitwise exclusive OR of adjacent elements of the sequence obtained after the first iteration. \nAt the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. \nAnd so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is v.\n\nLet's consider an example. Suppose that sequence a = (1, 2, 3, 4). Then let's write down all the transformations (1, 2, 3, 4)  →  (1 or 2 = 3, 3 or 4 = 7)  →  (3 xor 7 = 4). \nThe result is v = 4.\n\nYou are given Xenia's initial sequence. But to calculate value v for a given sequence would be too easy, so you are given additional m queries. \nEach query is a pair of integers p, b. Query p, b means that you need to perform the assignment ap = b. \nAfter each query, you need to print the new value v for the new sequence a.\n\n-----------------------------------------------\n\nBuild a segment trees. The leaves are the elements themselves. Each level we do either OR or XOR on the children nodes.\n\nIf there are an even number of levels, the first operation is XOR ... Else it is OR.\n\nTo do an update, we must trace a path from the root to the leaf. This is O(n), where n is the number of levels. \nOr O(log n), if n is the number of elements.\n\n--------------------------------------------\n\nint tree[3*MAX_SIZE];\nint element[MAX_SIZE];\n\nint perform(int a, int operation, int b)\n{\n    switch(operation)\n    {\n        case OR  :  return (a|b);\n        case XOR :  return (a^b);\n    }\n}\n\nint other(int operation)\n{\n    return (operation^1);\n}\n\nvoid build(int node, int start, int end, int operation)\n{\n    if(start == end)\n    {\n        tree[node] = element[start];\n        return;\n    }\n\n    int mid = (start + end)/2;\n\n    build(2*node, start, mid, other(operation));\n    build(2*node + 1, mid + 1, end, other(operation));\n\n    tree[node] = perform(tree[2*node], operation, tree[2*node + 1]);\n}\n\nvoid update(int node, int start, int end, int index, int value, int operation)\n{\n    if(start == end)\n    {\n        tree[node] = element[index] = value;\n        return;\n    }\n\n    int mid = (start + end)/2;\n\n    if(index >= start && index <= mid)\n    {\n        update(2*node, start, mid, index, value, other(operation));\n    }\n    else if(index > mid && index <= end)\n    {\n        update(2*node + 1, mid + 1, end, index, value, other(operation));\n    }\n\n    tree[node] = perform(tree[2*node], operation, tree[2*node + 1]);\n}\n\nint main()\n{\n    int n, no_of_queries;\n    scanf(\"%d %d\", &n, &no_of_queries);\n\n    int no_of_elements = (1 << n);\n    for(int i = 1; i <= no_of_elements; i++)\n        scanf(\"%d\", &element[i]);\n\n    int first_operation = (n%2 == 0 ? XOR : OR);\n    build(1, 1, no_of_elements, first_operation);\n\n    while(no_of_queries--)\n    {\n        int index, value;\n        scanf(\"%d %d\", &index, &value);\n\n        update(1, 1, no_of_elements, index, value, first_operation);\n        printf(\"%d\\n\", tree[1]);\n    }\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 16/Xenia and Ringroad Explanation.txt",
    "content": "Simple implementation\r\n\r\nint get_travel_time(int previous, int current, int no_of_houses)\r\n{\r\n    return (previous <= current ? current - previous : no_of_houses - previous + current);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_houses, no_of_tasks;\r\n    scanf(\"%d %d\", &no_of_houses, &no_of_tasks);\r\n\r\n    int previous_house = 1;\r\n    long long total_time = 0;\r\n    while(no_of_tasks--)\r\n    {\r\n        int current_house;\r\n        scanf(\"%d\", &current_house);\r\n\r\n        total_time += get_travel_time(previous_house, current_house, no_of_houses);\r\n\r\n        previous_house = current_house;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 16/k-String Explanation.txt",
    "content": "The frequency of every letter must be a multiple of k.\r\n\r\nPut frequency[i]/k copies of every alphabet onto the answer string.\r\n\r\nint main()\r\n{\r\n    int k;\r\n    string input;\r\n    cin >> k >> input;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    int frequency[NO_OF_ALPHABETS] = {0};\r\n\r\n    for(int i = 0; i < input.length(); i++)\r\n        frequency[input[i] - 'a']++;\r\n\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n        if(frequency[i]%k != 0)\r\n        {\r\n            cout << \"-1\";\r\n            return 0;\r\n        }\r\n\r\n    string smaller_string;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        for(int j = 0; j < frequency[i]/k; j++)\r\n            smaller_string += ('a' + i);\r\n    }\r\n\r\n    for(int i = 1; i <= k; i++)\r\n        cout << smaller_string;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Adding Digits Explanation.txt",
    "content": "Check if any single digit from 0 to 9 can be appended at the end of a, to make a = 0 (mod b)\r\n\r\nIf you get such a digit, pad it with 0s afterwards.\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a, b, no_of_operations;\r\n    scanf(\"%d %d %d\", &a, &b, &no_of_operations);\r\n\r\n    int appended_digit = -1;\r\n    for(int digit = 0; digit <= 9; digit++)\r\n    {\r\n        if((a*10 + digit)%b == 0)\r\n        {\r\n            appended_digit = digit;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(appended_digit == -1)\r\n    {\r\n        printf(\"-1\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"%d%d\", a, appended_digit);\r\n        for(int i = 2; i <= no_of_operations; i++) printf(\"0\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Christmas Spruce Explanation.txt",
    "content": "\r\nKeep track of the number of children of each vertex.\r\n\r\nno of children[parent[i]]++\r\n\r\nThen go through all the vertices again. If it has 0 children, then increase the number of leaf children of it's parent.\r\n\r\nno of leaf children[parent[i]]++\r\n\r\nNow, check if there's any non-leaf vertex that has fewer than 3 leaf children.\r\n\r\n---------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d\", &no_of_vertices);\r\n\r\n    int no_of_children[no_of_vertices + 1] = {0};\r\n    int parent[no_of_vertices + 1];\r\n\r\n    for(int i = 2; i <= no_of_vertices; i++)\r\n    {\r\n        scanf(\"%d\", &parent[i]);\r\n\r\n        no_of_children[parent[i]]++;\r\n    }\r\n\r\n    int no_of_leaf_children[no_of_vertices + 1] = {0};\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(no_of_children[i] == 0)\r\n        {\r\n            no_of_leaf_children[parent[i]]++;\r\n        }\r\n    }\r\n\r\n    int is_spruce = true;\r\n    for(int i = 1; i<= no_of_vertices; i++)\r\n    {\r\n        if(no_of_children[i] > 0 && no_of_leaf_children[i] < 3)\r\n        {\r\n            is_spruce = false;\r\n            break;\r\n        }\r\n    }\r\n\r\n    printf(is_spruce ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Dreamoon and Wi-Fi Explanation.txt",
    "content": "\r\nCalculate the final destination you're supposed to be at.\r\n\r\nCalculate the steps you will take for sure (The one's that aren't question mark.)\r\n\r\nLet the actual destination be D, let the current position be x.\r\n\r\nRemaining steps = D - x\r\n\r\nNow let's say there are Q question marks.\r\n\r\nFOr all i, from 1 to Q, \r\n\r\nCheck if i(+) + (Q - i)(-) takes you to the destination.\r\n\r\nLet's say r plus signs and Q-r minus signs take you to the destination.\r\n\r\nNow, the question is how many strings of length Q have exactly r plus signs.\r\n\r\nThis = Choose(Q, r)\r\n\r\nTotal number of strings = 2^Q\r\n\r\nProbability = Choose(Q, r)/2^Q\r\n\r\n--------------------------------------------------------------------\r\n\r\nint choose(int n, int r)\r\n{\r\n    if(r > n)\r\n        return 0;\r\n\r\n    int answer = 1;\r\n\r\n    for(int i = 0; i < r; i++)\r\n        answer = (answer*(n - i))/(i + 1);\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    const int MAX_LENGTH = 11;\r\n    char sent_commands[MAX_LENGTH], received_commands[MAX_LENGTH];\r\n    scanf(\"%s %s\", sent_commands, received_commands);\r\n\r\n    int destination = 0;\r\n    for(int i = 0; sent_commands[i] != '\\0'; i++)\r\n        destination += (sent_commands[i] == '+' ? 1 : -1);\r\n\r\n    int reached = 0, unrecognised_symbols = 0;\r\n    for(int i = 0; received_commands[i] != '\\0'; i++)\r\n    {\r\n        if(received_commands[i] == '?')\r\n            unrecognised_symbols++;\r\n        else\r\n            reached += (received_commands[i] == '+' ? 1 : -1);\r\n    }\r\n\r\n    int remaining = destination - reached;\r\n\r\n    int no_of_plus = 0, no_of_minus = unrecognised_symbols;\r\n\r\n    while(no_of_plus - no_of_minus != remaining)\r\n    {\r\n        no_of_plus++;\r\n        no_of_minus--;\r\n    }\r\n\r\n    int no_of_ways = choose(unrecognised_symbols, no_of_plus);\r\n    int total_ways = (1 << unrecognised_symbols);\r\n\r\n    double probability = (no_of_ways*1.0f)/(total_ways*1.0f);\r\n    printf(\"%.9lf\", probability);\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Exams Explanation.txt",
    "content": "Be greedy. Score 2 marks on all the exams.\r\n\r\nAnd then there will be k - 2n marks left to score.\r\n\r\nIf (k - 2n) >= n, then every exam gets more than 2 marks.\r\n\r\nElse, give 1 mark to (k - 2n) exams and n - (k - 2n) will remain with only 2 marks.\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_exams, minimum_marks;\r\n    scanf(\"%d %d\", &no_of_exams, &minimum_marks);\r\n\r\n    int marks_scored = 2*no_of_exams;\r\n    int remaining_marks = minimum_marks - marks_scored;\r\n\r\n    int exams_with_2_marks = (remaining_marks >= no_of_exams ? 0 : no_of_exams - remaining_marks);\r\n\r\n    printf(\"%d\\n\", exams_with_2_marks);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 17/Garden Explanation.txt",
    "content": "\r\nint main()\r\n{\r\n    int n, length;\r\n    scanf(\"%d %d\", &n, &length);\r\n\r\n    int ans = 1e9;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int a_i;\r\n        scanf(\"%d\", &a_i);\r\n\r\n        if(length%a_i == 0)\r\n            ans = min(ans, length/a_i);\r\n    }\r\n\r\n    printf(\"%d\\n\", ans);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Jamie and Alarm Snooze Explanation.txt",
    "content": "\r\nDecrement by x till you get a lucky number. \r\n\r\nWhile decrementing, check if minutes has < 0. If it is, then add 60 to the number of minutes, because 60 = 0 in a clock. \r\n\r\nSO 0 - x, = 60 - x\r\n\r\nIf hour < 0, then add 24, because 24 = 0 ... So 0 - x hours = 24 - x hours\r\n\r\n-------------------------------------------------\r\n\r\nint is_lucky(int n)\r\n{\r\n    while(n)\r\n    {\r\n        if(n%10 == 7)\r\n            return true;\r\n\r\n        n = n/10;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int decrement_time, hour, minute;\r\n    scanf(\"%d %d %d\", &decrement_time, &hour, &minute);\r\n\r\n    int no_of_hits = 0;\r\n\r\n    while(!is_lucky(hour) && !is_lucky(minute))\r\n    {\r\n        const int NO_OF_MINUTES_IN_HOUR = 60, NO_OF_HOURS_IN_DAY = 24;\r\n\r\n        minute -= decrement_time;\r\n\r\n        if(minute < 0)\r\n        {\r\n            minute += NO_OF_MINUTES_IN_HOUR;\r\n            hour--;\r\n        }\r\n\r\n        if(hour < 0)\r\n        {\r\n            hour += NO_OF_HOURS_IN_DAY;\r\n        }\r\n\r\n        no_of_hits++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_hits);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Jamie and Interesting Graph Explanation.txt",
    "content": "\r\nHere was my idea ... \r\n\r\nThe number of edges has to be at least n-1 to ensure it's connected so do this first .\r\n\r\n\r\n1 -> 2 -> 3 -> ... n-1 -> n\r\n\r\nMake these n-1 edges first. Make each edge = 1, from (1, 2) to (n - 2, n - 1). \r\n\r\nThe sum of all edges till here = n - 2.\r\n\r\nThe final (n - 1, n) edge has the minimum integer w, such that w + (n - 2) is prime.\r\n\r\nI want to ensure that is the MST too. \r\n\r\nSo, till here I have ensured the graph is connected, path from 1 to n is prime, MST weight is prime. \r\n\r\nNow, all I have to do is add the remaining edges ensuring there's no multi edges and no shorter path or no lighter MST. \r\n\r\nfor(u = 1 to n - 2)\r\n\tfor(v = u + 2 to n)\r\n\t\tadd(u, v, MST)\r\n\r\ntill the number of edges is the required number.\r\n\r\nAfter constructing the MST, every pair of vertices has a weight = MST to ensure there's no shorter path.\r\n\r\nv starts from u + 2, because the path from (u, u + 1) has already been constructed while making the MST.\r\n\r\n\r\n---------------------------------------------------\r\n\r\nint is_prime(int n)\r\n{\r\n    if(n <= 1)\r\n        return false;\r\n\r\n    for(int i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint find_nearest_prime(int n)\r\n{\r\n    int ans = n + 1;\r\n    while(!is_prime(ans))\r\n        ans++;\r\n\r\n    return ans;\r\n}\r\n\r\nint main()\r\n{\r\n    int n, no_of_edges;\r\n    scanf(\"%d %d\", &n, &no_of_edges);\r\n\r\n    int cost_to_n = find_nearest_prime(n - 2) - (n - 2);\r\n\r\n    int mst_cost = cost_to_n + (n - 2);\r\n    int min_path = mst_cost;\r\n\r\n    printf(\"%d %d\\n\", mst_cost, min_path);\r\n\r\n    for(int i = 1; i < n - 1; i++)\r\n        printf(\"%d %d %d\\n\", i, i + 1, 1);\r\n\r\n    printf(\"%d %d %d\\n\", n - 1, n, cost_to_n);\r\n\r\n    int edges = n - 1;\r\n\r\n    for(int u = 1; u <= n - 1 && edges < no_of_edges; u++)\r\n    {\r\n        for(int v = u + 2; v <= n && edges < no_of_edges; v++)\r\n        {\r\n            printf(\"%d %d %d\\n\", u, v, mst_cost);\r\n            edges++;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Kolya and Tanya Explanation.txt",
    "content": "\r\nThere are 20 good arrangements, 7 bad arrangements.\r\n\r\nNow, there are n triplets.\r\n\r\nA triplet may be either good or bad.... We are interested in configurations where at least one triplet is good.\r\n\r\nC(n, 1) 20^1 7^(n - 1) + C(n, 2) 20^2 7^(n - 2) + ... + C(n, n) 20^n\r\n\r\nThis = (20 + 7)^n - C(n, 0) 7^n = 27^n - 7^n\r\n\r\n7^n is when all triplets have a bad arrangement\r\n\r\nSince the whole thing happens via mod\r\n\r\nAns = 27^n + MOD - 7^n\r\n\r\n----------------------------------------------------------\r\n\r\nlong long power_mod(long long x, int power, int MOD)\r\n{\r\n    long long result = 1;\r\n\r\n    while(power)\r\n    {\r\n        if(power%2 == 1)\r\n            result = (result*x)%MOD;\r\n\r\n        x = (x*x)%MOD;\r\n        power = power >> 1;\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long no_of_ways = power_mod(27, n, MOD) + (MOD - power_mod(7, n, MOD));\r\n\r\n    no_of_ways %= MOD;\r\n\r\n    printf(\"%I64d\\n\", no_of_ways);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Mashmokh and ACM Explanation.txt",
    "content": "\r\nLet f(x, k) be the number of good sequences of length k where the first number is x.\r\n\r\nNow if the first element is x, then the second element can be {x, 2x, 3x, .... (n/x) x } \r\n\r\nf(x, k) = f(x, k - 1) + f(2x, k - 1) + f(3x, k - 1) + f(4x, k - 1) + .... f((n/x).x, k - 1)\r\n\r\nAnd f(x, 1) = 1, for all x, \r\n\r\nHowever, I didn't know how to do it iteratively so I did it recursively.\r\n\r\nImportant to note that \r\n\r\nfor(int i = 1; x*i <= n; i++) //This loop runs in O(log n) time\r\n\tf(x, k) += f(x*i, k - 1)\r\n\r\nSo over all complexity is O(nk log n)\r\n\r\nImportant to note that if you fix an element x, and want to find the PREVIOUS element and go through all divisors of x,\r\n\r\nit would be O(nk sqrt(n)), which isn't enough to pass the time limit. O(log n) is better than O(sqrt n)\r\n\r\nAnswer = f(1, k) + f(2, k) + ... + f(n, k)\r\n\r\n[The first number can be anything from 1 to n]\r\n\r\n--------------------------------------------------------------\r\n\r\nRecursive implementation - \r\n\r\nconst int N = 2001, MOD = 1e9 + 7;\r\nint no_of_sequences[N][N], max_number;\r\n\r\nlong long get(int first_number, int length)\r\n{   \r\n    if(length == 1)\r\n        no_of_sequences[first_number][1] = 1;\r\n\r\n    if(no_of_sequences[first_number][length] != -1)\r\n        return no_of_sequences[first_number][length];\r\n\r\n    no_of_sequences[first_number][length] = 0;\r\n    for(int i = 1; first_number*i <= max_number; i++)\r\n    {   \r\n        no_of_sequences[first_number][length] += get(first_number*i, length - 1);\r\n        no_of_sequences[first_number][length] %= MOD;\r\n    }\r\n    \r\n    return no_of_sequences[first_number][length];\r\n}\r\n\r\nint main()\r\n{\r\n    memset(no_of_sequences, -1, sizeof(no_of_sequences));\r\n\r\n    int length;\r\n    scanf(\"%d %d\", &max_number, &length);\r\n\r\n    long long answer = 0;\r\n    for(int first_number = 1; first_number <= max_number; first_number++)\r\n        answer = (answer + get(first_number, length) )%MOD;\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n\r\n------------------------------------------------\r\n\r\nIterative implementation - \r\n\r\nint main()\r\n{\r\n    const int MOD = 1e9 + 7;\r\n\r\n    int max_number, length;\r\n    scanf(\"%d %d\", &max_number, &length);\r\n\r\n    for(int first_number = 1; first_number <= max_number; first_number++)\r\n        no_of_sequences[first_number][1] = 1;\r\n\r\n    for(int l = 2; l <= length; l++)\r\n    {\r\n        for(int first_number = 1; first_number <= max_number; first_number++)\r\n        {\r\n            no_of_sequences[first_number][l] = 0;\r\n\r\n            for(int i = 1; first_number*i <= max_number; i++)\r\n            {\r\n                no_of_sequences[first_number][l] += no_of_sequences[first_number*i][l - 1];\r\n            }\r\n\r\n            no_of_sequences[first_number][l] %= MOD;\r\n        }\r\n    }\r\n\r\n    long long answer = 0;\r\n    for(int first_number = 1; first_number <= max_number; first_number++)\r\n        answer += no_of_sequences[first_number][length];\r\n\r\n    answer %= MOD;\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n\r\n----------------------------------------------------\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Maxmium Splitting Explanation.txt",
    "content": "\r\nThe smallest composite number is 4. \r\n\r\nIf a number is a multiple of 4, then we can write it as a series of 4. \r\nWe can't do better since if we used another composite number, we'd have to reduce the number of summands\r\n\r\nWhat if n = 1 (mod 4) What is the smallest number = 1 (mod 4) that is composite ? 9\r\n\r\n1 and 5 cannot be written as sum of composites.\r\n\r\nn = 1 (mod 4)\r\nSo, we write it as 9 + (n - 9), (n - 9) can be written as a series of 4s.\r\n\r\nn = 2 (mod 4)\r\nSimilarly, 6 + (n - 6) \r\n\r\nn = 3 (mod 4)\r\nAnd 15 + (n - 15) = (9 + 6) + (n - 15)\r\n\r\nNow, this completes our proof that every composite number can be written as \r\n\r\nn = 4a + 6b + 9c.\r\n\r\nFact 1 - Every composite integer can be written as n = 4a + 6b + 9c\r\n\r\nNow, we want to maximise the number of summands. Let's say for sum n, we use a composite number m, other than 4, 6 and 9.\r\n\r\nUsing the same process for m, we can replace m with 4s, 6s and 9s and do better.\r\n\r\nFact 2 - This proves that the maximum summands of n will have ONLY 4s, 6s and 9s.\r\n\r\nFact 3 - When n has the maximum number of summands, there will be at most one 6 and one 9.\r\n\r\n6 + 6 = 4 + 4 + 4\r\n9 + 9 = 6 + 6 + 6 = 4 + 4 + 4 + 6\r\n\r\nIt is never optimal to use more than one 6 or one 9 in the summation.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int n;\r\n        scanf(\"%d\", &n);\r\n\r\n        int no_of_parts = -1;\r\n\r\n        if( !(n <= 3 || n == 5 || n == 7 || n == 11) )\r\n        {\r\n            switch(n%4)\r\n            {\r\n                case 0: no_of_parts = n/4; break;\r\n                case 1: no_of_parts = (n - 9)/4 + 1; break;\r\n                case 2: no_of_parts = (n - 6)/4 + 1; break;\r\n                case 3: no_of_parts = (n - 15)/4 + 2; break;\r\n            }\r\n        }\r\n\r\n        printf(\"%d\\n\", no_of_parts);\r\n    }\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Minimum Sum Explanation.txt",
    "content": "\r\nThis problem can be solved by looking at the sum in a different way.\r\n\r\nFind the contribution of each of the 10 digits.\r\n\r\nFor example, 345 = 3 x 100 + 4 x 10 + 5\r\n\r\nWe know the contribution of each of the digits.\r\n\r\nKeep track of the contribution of each digit in all the numbers together.\r\n\r\nAlso, keep track each digit whether it is a first digit or not.\r\n\r\nNow, the biggest coefficient gets assigned the smallest legal value it can take.\r\n\r\nAnd so on.\r\n\r\n------------------------------------------------------------------------\r\n\r\nstruct code\r\n{\r\n    int is_first_digit, coefficient;\r\n\r\n    code(){\r\n        is_first_digit = false, coefficient = 0;\r\n    }\r\n};\r\n\r\nint compare(const code &A, const code &B)\r\n{\r\n    return (A.coefficient < B.coefficient);\r\n}\r\n\r\nint main()\r\n{\r\n    const int NO_OF_DIGITS = 10;\r\n    vector <code> letter(NO_OF_DIGITS);\r\n\r\n    int no_of_numbers;\r\n    scanf(\"%d\", &no_of_numbers);\r\n\r\n    while(no_of_numbers--)\r\n    {\r\n        string number;\r\n        cin >> number;\r\n\r\n        letter[number[0] - 'a'].is_first_digit = true;\r\n\r\n        int power_of_10 = 1;\r\n\r\n        for(int i = number.size() - 1; i >= 0; i--)\r\n        {\r\n            letter[number[i] - 'a'].coefficient += power_of_10;\r\n            power_of_10 *= 10;\r\n        }\r\n    }\r\n\r\n    sort(all(letter), compare);\r\n\r\n    vector <int> assigned(NO_OF_DIGITS, false);\r\n\r\n    int sum = 0;\r\n\r\n    for(int i = NO_OF_DIGITS - 1; i >= 0; i--)\r\n    {\r\n        int digit = (letter[i].is_first_digit ? 1 : 0);\r\n\r\n        while(assigned[digit])\r\n            digit++;\r\n\r\n        assigned[digit] = true;\r\n\r\n        sum += letter[i].coefficient*digit;\r\n    }\r\n\r\n    printf(\"%d\\n\", sum);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 17/Modular Exponentiation Explanation.txt",
    "content": "\r\nIf x < y, then x (mod y) = x itself.\r\n\r\nNow, in this problem m (mod 2^n) m and n can be upto 10^8, 2^n overflows integer data type at value 32.\r\n\r\nAll we need to notice that if 2^n > 10^8, then the answer will always be m as m is never greater than 10^8.\r\n\r\nThis happens quite quickly. (At n = 28 itself).\r\n\r\n----------------------------------------------------\r\n\r\n#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, m;\r\n    scanf(\"%d %d\", &n, &m);\r\n\r\n    int answer = (n > 31 ? m : m%(1 << n));\r\n    printf(\"%d \", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/New Year and Domino Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTjxl\r\n\r\nVery neat problem ... Let f(i, j) be the number of dominos that can be placed from (1, 1) to (i, j)\r\n\r\nThe main insight is that the horizontal and vertical dominos should be handled seperately.\r\n\r\nUsing the principle of inclusion and exclusion,\r\n\r\nv(i, j) = v(i - 1, j) + v(i, j - 1) - v(i - 1, j - 1)\r\n\r\nh(i, j) = h(i - 1, j) + h(i, j - 1) - h(i - 1, j - 1)\r\n\r\nNow, to answer a query\r\n\r\nH = H(r2, c2) - H(r2, c1) - H(r1 - 1, c2) + H(r1 - 1, c1)\r\n\r\nV = V(r2, c2) - V(r2, c1 - 1) - V(r1, c2) + V(r1, c1 - 1)\r\n\r\nAns = H + V\r\n\r\n------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n\r\n    char cell[rows + 1][columns + 2];\r\n    for(int i = 1; i <= rows; i++)\r\n        scanf(\"%s\", cell[i] + 1);\r\n\r\n    int horizontal_dominos[rows + 1][columns + 2] = {{0}};\r\n    int vertical_dominos[rows + 1][columns + 2] = {{0}};\r\n    \r\n    memset(vertical_dominos, 0, sizeof(vertical_dominos));\r\n    memset(horizontal_dominos, 0, sizeof(horizontal_dominos));\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns + 1; j++)\r\n        {\r\n            horizontal_dominos[i][j] = (cell[i][j] == '.' && cell[i][j - 1] == '.');\r\n\r\n            horizontal_dominos[i][j] += horizontal_dominos[i - 1][j] + horizontal_dominos[i][j - 1] - horizontal_dominos[i - 1][j - 1];\r\n\r\n            vertical_dominos[i][j] = (cell[i][j] == '.' && cell[i - 1][j] == '.');\r\n\r\n            vertical_dominos[i][j] += vertical_dominos[i][j - 1] + vertical_dominos[i - 1][j] - vertical_dominos[i - 1][j - 1];\r\n        }\r\n    }\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int row_1, column_1, row_2, column_2;\r\n        scanf(\"%d %d %d %d\", &row_1, &column_1, &row_2, &column_2);\r\n\r\n        int total_horizontal = horizontal_dominos[row_2][column_2]\r\n                              - horizontal_dominos[row_2][column_1] - horizontal_dominos[row_1 - 1][column_2]\r\n                              +horizontal_dominos[row_1 - 1][column_1];\r\n\r\n\r\n        int total_vertical = vertical_dominos[row_2][column_2]\r\n                           - vertical_dominos[row_2][column_1 - 1] - vertical_dominos[row_1][column_2]\r\n                           + vertical_dominos[row_1][column_1 - 1];\r\n\r\n        int total_dominos = total_horizontal + total_vertical;\r\n\r\n        printf(\"%d\\n\", total_dominos);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/New Year's Eve Explanation.txt",
    "content": "There are only two cases that matter. k = 1, k > 1.\r\n\r\nCase 1 :\r\n\r\nIf k = 1, then any number we choose in the set will be the XOR.\r\nWe want to maximise the XOR, so we choose the maximum number we can. We choose n.\r\n\r\nCase 2:\r\n\r\nNow, notice that if we take XOR(a, b, c .... , n)         \r\nThe answer can never have more bits than the largest number in the set since XOR never creates new bits.\r\n\r\nSo, any XOR we take will not have more bits than n, as n is the largest number we have.\r\n\r\nLet n = 10000111001... 0\r\n\r\nThe first bit is forced to be 1.\r\nNow, since the maximum number of bits is fixed, the maximum answer we can get is\r\n\r\n111111 ... 1 (As many 1s as the number of bits in n)\r\n\r\nThe question is can we always get this number ? Answer is yes.\r\n\r\nWe need a number x, such that n^x = 1111 ... 1\r\n\r\nFor this, we only need a number x with a 1 in whichever position n has a 0, and a 0 in whichever position n has a 1.\r\n\r\nSo, if n = 10000111001... 0, \r\nx = 01111000110.... 1\r\n\r\nNow, notice that the first bit of n has to be 1. So, the first bit of x has to be 0.\r\n\r\nIf the first bit of x is 0, then it means x < n.\r\n\r\nIf x < n, then we can always choose x and n as the question allows us to choose any number less than n.\r\n\r\nk = 1, answer = n\r\nk > 1, answer = 1111...1 = 1 0...0000000 - 1 = 2^(no of bits in n) - 1"
  },
  {
    "path": "Explanations/Explanations 17/Palindrome Pairs Explanation.txt",
    "content": "\r\n\r\nKeep track of the number of palindromes ending exactly at i, and all the palindromes that start from i onwards.\r\n\r\nAns = sum(PE(i)*(PS(i + 1) + PS(i + 2) + ... + PS(n))\r\n\r\nWhere PE(i) is the number of palindromes ending exactly at i,\r\nPS(i) is the number of palindromes starting exactly at i\r\n\r\nNow, the suffix sums of PS can be precomputed so that it can be done in O(n) time.\r\n\r\nFind all palindromic substrings in O(n^2) time\r\n\r\nIf A[i] = A[j], AND (i + 1 == j OR P[i + 1][j - 1] = true)\r\n\r\nThen P[i][j] = true\r\n\r\nUse this and compute all palindromes and keep track of PE and PS.\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    int length = A.size();\r\n\r\n    int is_palindrome[length + 1][length + 1] = {{false}};\r\n\r\n    vector <int> palindrome_starts(length + 1, 0);\r\n    vector <int> palindrome_ends(length + 1, 0);\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        is_palindrome[i][i] = true;\r\n        palindrome_starts[i] = palindrome_ends[i] = 1;\r\n    }\r\n\r\n    for(int substring_length = 2; substring_length < length; substring_length++)\r\n    {\r\n\r\n        for(int start = 0, end = start + substring_length - 1; end < length; start++, end++)\r\n        {\r\n\r\n            if(A[start] == A[end] && (substring_length == 2 || is_palindrome[start + 1][end - 1]))\r\n            {\r\n                is_palindrome[start][end] = true;\r\n                palindrome_starts[start]++;\r\n                palindrome_ends[end]++;\r\n            }\r\n        }\r\n    }\r\n\r\n    vector <int> palindromes_from(length + 1, 0);\r\n    for(int i = length - 1; i >= 0; i--)\r\n        palindromes_from[i] = palindromes_from[i + 1] + palindrome_starts[i];\r\n\r\n    long long palindromic_pairs = 0;\r\n\r\n    for(int i = 0; i < length; i++)\r\n        palindromic_pairs += palindrome_ends[i]*1LL*palindromes_from[i + 1];\r\n\r\n    printf(\"%I64d\\n\", palindromic_pairs);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Perfect Number Explanation.txt",
    "content": "\r\nI brute forced it. Number of operations comes to about 1e7, which passes in this case. \r\n\r\nI optimised it a little bit by only checking numbers = 1 (mod 9).\r\n\r\n----------------------------------------\r\n\r\nint sum_of_digits(int n)\r\n{\r\n    int sum = 0;\r\n\r\n    while(n)\r\n    {\r\n        sum += n%10;\r\n        n /= 10;\r\n    }\r\n\r\n    return sum;\r\n}\r\n\r\nint main()\r\n{\r\n    vector <int> perfect_number;\r\n\r\n    for(int i = 19; perfect_number.size() <= 1e4; i+=9)\r\n    {\r\n        if(sum_of_digits(i) == 10)\r\n            perfect_number.push_back(i);\r\n    }\r\n\r\n    int k;\r\n    scanf(\"%d\", &k);\r\n    printf(\"%d\\n\", perfect_number[k - 1]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 17/QAQ Explanation.txt",
    "content": "\r\nLet P[i] denote the number of Q's till position i\r\nLet S[i] denote the number of Q's from position i\r\n\r\nFor every A in the string the answer increases by P[i]*S[i]\r\n\r\n----------------------------------------------\r\n\r\nint main()\r\n{\r\n    const int N = 101;\r\n    char input[N];\r\n    scanf(\"%s\", input);\r\n\r\n    int length = strlen(input);\r\n\r\n    int no_of_Q_till[length] = {0};\r\n    no_of_Q_till[0] = (input[0] == 'Q');\r\n    for(int i = 1; i < length; i++)\r\n        no_of_Q_till[i] = no_of_Q_till[i - 1] + (input[i] == 'Q');\r\n\r\n    int no_of_Q_after[length] = {0};\r\n    no_of_Q_after[length - 1] = (input[length - 1] == 'Q');\r\n    for(int i = length - 2; i >= 0; i--)\r\n        no_of_Q_after[i] = no_of_Q_after[i + 1] + (input[i] == 'Q');\r\n\r\n    int no_of_QAQ = 0;\r\n    for(int i = 0; i < length; i++)\r\n        if(input[i] == 'A')\r\n            no_of_QAQ += no_of_Q_till[i]*no_of_Q_after[i];\r\n\r\n    printf(\"%d\\n\", no_of_QAQ);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Seat Arrangements Explanation.txt",
    "content": "\r\nLet up(i, j) represent the consecutive dots up ending at (i, j)\r\nLet left(i, j) represent the consecutive dots left ending at(i, j)\r\n\r\nLet f(i, j) represent the number of ways to do this from (1, 1) to (i, j)\r\n\r\nf(i, j) = (up(i, j) >= k) + (left(i, j) >= k) + f(i - 1, j) + f(i, j - 1) - f(i - 1, j - 1)\r\n\r\nUsing the principle of inclusion and exclusion. \r\n\r\nK = 1 is a special case, because it is overcounting. \r\n\r\nFor k = 1, the answer is the number of dots in the grid. \r\n\r\nI got WA in the contest because I gave the array insufficient memory and didn't allocate memory for the null character.\r\n\r\nActually, after the contest I realised that the rectangle DP is unnecessary. It is enough to count the number of points where the number of consecutive seats\r\nis >= k, in both the up and left direction.\r\n\r\nFirst, I learnt from the editorial that if strings are involved, as much as possible, try to deal with numbers instead to avoid the nasty mistake due to the null character.\r\n\r\nThen, I learnt that instead of handling k = 1 seperately, just divide by 2 in the end.\r\n\r\nThen, I learnt that it's better to not use a DP and just count the points. \r\n\r\nThree very important things (Use numbers instead of strings whenever possible, handle k = 1 elegantly and no need of rectangular DP)\r\n\r\n------------------------------------------------------------------\r\n\r\n#include <cstdio>\r\n#include <cstring>\r\n\r\nint main()\r\n{\r\n    int no_of_rows, no_of_columns, k;\r\n    scanf(\"%d %d %d\", &no_of_rows, &no_of_columns, &k);\r\n\r\n    char seat[no_of_rows + 1][no_of_columns + 2];\r\n    for(int row = 1; row <= no_of_rows; row++)\r\n        scanf(\"%s\", seat[row] + 1);\r\n\r\n    int up_empty_seats[no_of_rows + 1][no_of_columns + 1];\r\n    memset(up_empty_seats, 0, sizeof(up_empty_seats));\r\n\r\n    int left_empty_seats[no_of_rows + 1][no_of_columns + 1];\r\n    memset(left_empty_seats, 0, sizeof(left_empty_seats));\r\n\r\n    int total_seatings = 0;\r\n\r\n    for(int row = 1; row <= no_of_rows; row++)\r\n    {\r\n        for(int column = 1; column <= no_of_columns; column++)\r\n        {\r\n            up_empty_seats[row][column] = (seat[row][column] == '.' ? 1 + up_empty_seats[row - 1][column] : 0);\r\n            left_empty_seats[row][column] = (seat[row][column] == '.' ? 1 + left_empty_seats[row][column - 1] : 0);\r\n\r\n            total_seatings += (up_empty_seats[row][column] >= k) + (left_empty_seats[row][column] >= k);\r\n        }\r\n    }\r\n\r\n    if(k == 1)\r\n        total_seatings = total_seatings >> 1;\r\n\r\n    printf(\"%d\\n\", total_seatings);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Supermarket Explanation.txt",
    "content": "\r\nIt costs a/b to buy one. It costs am/b to buy m. Find the minimum. It is always optimal to buy all apples from the same market.\r\n\r\nBe careful for type casting.\r\n\r\n--------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, m;\r\n    scanf(\"%d %d\", &n, &m);\r\n\r\n    double ans = 1E9;\r\n    while(n--)\r\n    {\r\n        int a, b;\r\n        scanf(\"%d %d\", &a, &b); \r\n\r\n        ans = min(ans, (a*1.0*m)/(b*1.0));\r\n    }\r\n\r\n    printf(\"%lf\\n\", ans);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Swap Adjacent Elements Explanation.txt",
    "content": "\r\nClaim - It is possible to sort the permutation if and only if, for every i such that p(i) =/= i, \r\n\r\nthere exists a series of consecutive 1s in between i and p(i) allowing the element p(i) to be swapped one-by-one and placed at position p(i) from position i.\r\n\r\nProof - We can easily see that if i =/= p(i) and there is no stream of one's in between i and p(i), we can never get an array in order as there will always be some \r\nelement p(i) that can never travel to position p(i).\r\n\r\nFor example, Consider this\r\n\r\n1 2 7 4 5 6 3\r\n\r\n0 0 1 1 0 1 \r\n\r\nSince 7 is not in it's place and there is no continuous stream of 1s from 3 to 7, it is impossible for 7 to travel all the way to 3. \r\n\r\n----------------------------------------------------\r\n\r\nNow, to prove the other way around - i.e. it is always possible to sort an array if there exists a stream of 1s in between every i and p(i) where i =/= p(i)\r\n\r\nI will prove that if the condition of stream of 1s in between every i and p(i) is satisfied, then it is always possible to place the SMALLEST out of order element in it's \r\nright place. \r\n\r\nChoose the smallest element x, such that for all y < x, p(y) = y. In other words, pick the smallest element that is not in it's right position. \r\n\r\n{This means that the array is sorted from A[1, 2, .... x - 1]}\r\n\r\nLet x be located at position i. (P(x) = i). \r\n\r\nNow, we can conclude that x < i. Because all y < x, P(y) = y, so P(x) can't be < x. It has to be > x.\r\n\r\nBased on the condition, it means there is a string of consecutive 1s from x to (i - 1), allowing the travel. \r\n\r\nSince it is already established that there is a stream of 1s in between x and (i - 1). We perform the swaps one by one, \r\ntill x moves all the way from position i to position x\r\n\r\nA[1, 2, ... x] The unsorted array is from A[x + 1, ... n]. \r\n\r\nNow, the smallest element that is out of order either lies in between x and i or it doesn't. \r\n\r\nEither way, the condition of it having a string of 1s in between it's current and true position remains invariant. \r\n\r\nBecause if it lies outside [x, i), then it was never disturbed. \r\n\r\nIf it did, then it still remains somewhere in the stream of 1s in between x and i. If it had a string of 1s in the beginning, it still does now, because it is still connected\r\n\r\nSo, we keep placing the minimum element out-of-order in it's right place till the entire array is sorted.\r\n\r\n---------------------------------------------------------------\r\n\r\nHere's what I did - Maintain a prefix sum of the number of 1s till i. \r\n\r\nFor every i, such that p(i) != i\r\n\r\nRight = Max{p(i), i}\r\nLeft = Min{p(i), i}\r\n\r\nNow, there should be continuous 1s from Left to (Right - 1).\r\n\r\nThe expected number of 1s = (Right - 1) - (Left - 1)\r\n\r\nThe number of 1s present = Prefix(Right - 1) - Prefix(Left - 1)\r\n\r\nIf these two numbers are not equal, then it means there is some element which can't go it's true position. \r\n\r\nIf these two numbers are equal for all i, such that i =/= p(i), then it means that the array can always be sorted by placing the minimum out-of-order element in it's right place.\r\n\r\n------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> permutation(n + 1, 0);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &permutation[i]);\r\n\r\n    vector <int> ones_till(n + 1, 0);\r\n    for(int i = 1; i <= n - 1; i++)\r\n    {\r\n        int digit;\r\n        scanf(\"%1d\", &digit);\r\n\r\n        ones_till[i] = (digit == 1) + ones_till[i - 1];\r\n    }\r\n\r\n    int is_sortable = true;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        if(permutation[i] != i)\r\n        {\r\n            int right = max(i, permutation[i]);\r\n            int left = min(i, permutation[i]);\r\n\r\n            int distance = (right - 1) - (left - 1);\r\n\r\n            if(ones_till[right - 1] - ones_till[left - 1] != distance)\r\n                is_sortable = false;\r\n        }\r\n    }\r\n\r\n    printf(is_sortable ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Tea Queue Explanation.txt",
    "content": "\r\nThis problem is made a lot easier, because the inputs are sorted in terms of their l_i's \r\n\r\nOtherwise, we'd need to use structures and call a custom sort. \r\n\r\nHere's what we do, \r\n\r\nFirst initial time = left[1]\r\n\r\nFor each person that arrives, \r\n\r\n\tset current time to max{current time, left[i]} [If current time < left[i], then the current customer will be served. He'll just have to wait till left[i]. \r\n\t\t\t\t\t\t\tSo, directly set the current time to left[i]. If current time > left[i], let it be.]\r\n\t\r\n\t(check if current time <= right[i])\r\n\r\n\t\tif it is, then service time[i] = current time, current time++\r\n\r\nNote - I made the mistake of increasing service time regardless of whether the person was served. That was a mistake. Incrememnt time only if he has been served.\r\n\r\nFor example,\r\n\r\n1 4\r\n1 1\r\n\r\nThe first person is served at moment 1. Now, the time is 2. The second person is not served. This means that he has left the queue. the time REMAINS 2 for the third customer\r\n\r\nIt does NOT increase to 3 even if he didn't take the tea. Only the serviced customers increment the current time.\r\n\r\n---------------------------------------------------------------------\r\n\r\nvoid solve()\r\n{\r\n    int number_of_students;\r\n    scanf(\"%d\", &number_of_students);\r\n\r\n    vector <int> left(number_of_students + 1);\r\n    vector <int> right(number_of_students + 1);\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        scanf(\"%d %d\", &left[i], &right[i]);\r\n\r\n    vector <int> served_time(number_of_students + 1, 0);\r\n\r\n    for(int current_time = left[1], student = 1; student <= number_of_students; student++)\r\n    {\r\n            current_time = max(current_time, left[student]);\r\n\r\n            if(current_time <= right[student])\r\n            {\r\n                served_time[student] = current_time++;\r\n            }\r\n    }\r\n\r\n    for(int i = 1; i <= number_of_students; i++)\r\n        printf(\"%d \", served_time[i]);\r\n\r\n    printf(\"\\n\");\r\n}"
  },
  {
    "path": "Explanations/Explanations 17/Testing Pants for Sadness Explanation.txt",
    "content": "\r\nLet's say we have crossed x levels, how many clicks to we make on level x+1 with k options ?\r\n\r\nWe have already crossed x levels, so we make 1 click, which will be wrong in the worst case.\r\n\r\nNow, after that to reach level x + 1, we will need to make x clicks. \r\n\r\nSo, for each of the remaining k - 1 options, we will need x clicks to get there and one more click for the option itself.\r\n\r\nSo, number of clicks at level x + 1 = 1 + (x + 1)(k - 1)\r\n\r\nFirst option requires one click and all remaining options require x + 1 clicks.\r\n\r\n\r\nSo, if we are now at level i,\r\n\r\nClicks += 1 + i(k - 1)\r\n\r\n---------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_questions;\r\n    scanf(\"%d\", &no_of_questions);\r\n\r\n    long long no_of_clicks = 0;\r\n\r\n    for(int i = 1; i <= no_of_questions; i++)\r\n    {\r\n        int no_of_options;\r\n        scanf(\"%d\", &no_of_options);\r\n\r\n        no_of_clicks += 1 + i*1LL*(no_of_options - 1);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_clicks);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 17/The World is a Theatre Explanation.txt",
    "content": "Answer is sum( C(boys, i)* C(girls, actors - i) ), i = 4 to actors - 1\n\nPrecompute using Pascal's triangle.\n\n-------------------------------------------------\n\nint main()\n{\n    const int N = 60;\n    long long combinations[N + 1][N + 1];\n\n    combinations[0][0] = 1;\n\n    for(int n = 1; n <= N; n++)\n    {\n        for(int r = 0; r <= n; r++)\n        {\n            if(r == 0 || r == n)\n                combinations[n][r] = 1;\n            else\n                combinations[n][r] = combinations[n - 1][r] + combinations[n - 1][r - 1];\n        }\n    }\n\n\n    int no_of_actors, boys, girls;\n    scanf(\"%d %d %d\", &boys, &girls, &no_of_actors);\n\n    long long no_of_ways = 0;\n    for(int i = 4; i < no_of_actors; i++)\n        no_of_ways += combinations[boys][i]*combinations[girls][no_of_actors - i];\n\n    printf(\"%I64d\\n\", no_of_ways);\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 17/Tricky Alchemy Explanation.txt",
    "content": "Count the number of required yellow crystals and required green crystals.\r\n\r\nIf we have more than required, it's 0.\r\n\r\n----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int yellow, blue;\r\n    scanf(\"%d %d\", &yellow, &blue);\r\n\r\n    int x, y, z;\r\n    scanf(\"%d %d %d\", &x, &y, &z);\r\n\r\n    long long required_yellow = 2LL*x + y;\r\n    long long required_blue = y + 3LL*z;\r\n\r\n    long long required = max(0LL, required_yellow - yellow) + max(0LL, required_blue - blue);\r\n    printf(\"%I64d\\n\", required);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 17/Water the Gardens Explanation.txt",
    "content": "\r\nNow, the time taken to water the patch of grass in between 1 and tap[1]\r\n\r\nis tap[1] - 1 = tap[1].\r\n\r\nThe time taken to water the patch of grass from the last tap to the end is = N - (tap.back() - 1);\r\n\r\nThe time taken to water the patch of grass in between tap[i] and tap[i + 1] is ceil[distance/2], where distance = tap[i + 1] - (tap[i] - 1)\r\n\r\nThis is because the number of unwatered patches of grass in between tap[i] and tap[i + 1] reduces by 2 each second. So, the distance shrinks by 2 each second.\r\n\r\nIf this number is odd, add one more second. \r\n\r\nThe time taken = max{First patch, all middle patches, Last patch}\r\n\r\n(It's already sorted)\r\n\r\n---------------------------------------------------------------------\r\n\r\nvoid solve()\r\n{\r\n    int number_of_taps, number_of_beds;\r\n    scanf(\"%d %d\", &number_of_beds, &number_of_taps);\r\n\r\n    vector <int> tap(number_of_taps + 1, 0);\r\n    for(int i = 1; i <= number_of_taps; i++)\r\n        scanf(\"%d\", &tap[i]);\r\n\r\n    int time = tap[1];\r\n\r\n    for(int i = 1; i < number_of_taps; i++)\r\n    {\r\n        int distance = tap[i + 1] - tap[i] + 1;\r\n\r\n        int time_for_this_patch = distance/2 + distance%2 ;\r\n\r\n        time = max(time, time_for_this_patch);\r\n    }\r\n\r\n    time = max(time, number_of_beds - tap.back() + 1);\r\n\r\n    printf(\"%d\\n\", time);\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Art Union Explanation.txt",
    "content": "\r\nLet f(i, j) denote the time at which painting i is finished by painter j. \r\n\r\nNote that a painting can only start by a painter, provided, that painter j has finished painting i - 1, and painter j - 1 has finished painter j\r\n\r\nSo, f(i, j) = max{ f(i - 1, j), f(i, j - 1) } + time[i][j]\r\n\r\n-------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_paintings, number_of_painters;\r\n    scanf(\"%d %d\", &number_of_paintings, &number_of_painters);\r\n\r\n    int time[number_of_paintings + 1][number_of_painters + 1];\r\n    for(int i = 1; i <= number_of_paintings; i++)\r\n        for(int j = 1; j <= number_of_painters; j++)\r\n            scanf(\"%d\", &time[i][j]);\r\n\r\n    int time_for[number_of_paintings + 1][number_of_painters + 1];\r\n    memset(time_for, 0, sizeof(time_for));\r\n\r\n    for(int painter_i = 1; painter_i <= number_of_painters; painter_i++)\r\n    {\r\n        for(int painting = 1; painting <= number_of_paintings; painting++)\r\n        {\r\n            time_for[painting][painter_i] = max(time_for[painting - 1][painter_i], time_for[painting][painter_i - 1]) +\r\n                                            time[painting][painter_i];\r\n        }\r\n    }\r\n\r\n    int all_painters = number_of_painters;\r\n\r\n    for(int i = 1; i <= number_of_paintings; i++)\r\n        printf(\"%d \", time_for[i][all_painters]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Bear and Colours Explanation.txt",
    "content": "Quite interesting question. I read it yesterday and the solution and was surprised to see O(n^2) pass. \r\n\r\nLet's say the question said find the number of intervals, starting from 1, where each colour is winning, \r\n\r\nHow to do this ?\r\n\r\nkeep frequency of each ball, \r\n\r\nwhenevver you update frequency of a ball, check if it is now greater than the maximum frequency \r\n\r\nint winner = 0;\r\n\r\nfor(int i = 1; i <= N; i++)\r\n\tfrequency[colour[i]]++\r\n\r\n\tif(frequency[colour[i]] > frequency[winner])\r\n\t\twinner = colour[i]\r\n\r\n\twinning_intervals[winner]++ -> This line is important\r\n\r\nNow, just do this for every possible start, not just 1. \r\n\r\nThe elegant trick here is to update winning interval every time and the realisation that you only need to compare the frequency of the updated colour with the winner.\r\n\r\n-------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_balls;\r\n    scanf(\"%d\", &no_of_balls);\r\n\r\n    vector <int> colour(no_of_balls + 1, 0);\r\n    for(int i = 1; i <= no_of_balls; i++)\r\n        scanf(\"%d\", &colour[i]);\r\n\r\n    vector <int> no_of_winning_intervals(no_of_balls + 1);\r\n    for(int start = 1; start <= no_of_balls; start++)\r\n    {\r\n        vector <int> frequency(no_of_balls + 1, 0);\r\n        int winner = 0;\r\n\r\n        for(int i = start; i <= no_of_balls; i++)\r\n        {\r\n            frequency[colour[i]]++;\r\n\r\n            if(frequency[colour[i]] > frequency[winner] || (frequency[colour[i]] == frequency[winner] && colour[i] < winner))\r\n                winner = colour[i];\r\n\r\n            no_of_winning_intervals[winner]++;\r\n        }\r\n    }\r\n\r\n    for(int ball_i = 1; ball_i <= no_of_balls; ball_i++)\r\n        printf(\"%d \", no_of_winning_intervals[ball_i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Cave Painting Explanation.txt",
    "content": "\r\nLet us try to examine the properties of n, if it had a different remainder with every number from 1 to k.\r\n\r\nn = 0 (mod 1)\r\n\r\nThis means \r\n\r\nn = 1 (mod 2) No other option.\r\n\r\nSimilarly, \r\n\r\nn = 2 (mod 3)\r\n\r\nn = 3 (mod 4)\r\n\r\nAnd so on. \r\n\r\nAt every stage, n = -1 (mod i)\r\n\r\nThis means, (n + 1) = 0 (mod i)\r\n\r\nThis means that (n + 1) must be divisible by every number from 1 to i.\r\n\r\nI made the mistake of thinking that it means (n + 1) should be i!, and then a multiple of i!, but that's incorrect. \r\n\r\nIt's a common mistake. If you mark multiples of A and B, multiples of LCM(A, B) will be marked twice, not AB. LCM(A, B) = AB, when they are coprime. \r\n\r\nSo, actually (n + 1) should be a multiple of all numbers from 1 to i, means it should be divisibly by LCM(1, ... , i)\r\n\r\nI checked how fast the sequence grows and when i = 43, it is > 10^18. So in the contest, I precomputed all LCM's from 1 to 42, and then if k < 43 and (n + 1)%lcm(43) == 0,\r\n\r\nAnswer is yes\r\n\r\n------------------------------------------------------------------------------\r\n\r\n#include <cstdio>\r\n\r\nint main()\r\n{\r\n    long long n, k;\r\n    scanf(\"%I64d %I64d\", &n, &k);\r\n\r\n    long long lcm_1_till[45];\r\n    lcm_1_till[1] = 1;\r\n\r\n    for(int i = 2; i < 43; i++)\r\n    {\r\n        int ii = i;\r\n        long long extra = 1, lcm_i_minus_1 = lcm_1_till[i - 1];\r\n\r\n        for(int j = 2; j <= ii; j++)\r\n        {\r\n            while(ii%j == 0)\r\n            {\r\n                ii /= j;\r\n                if(lcm_i_minus_1%j == 0)\r\n                    lcm_i_minus_1 /= j;\r\n                else\r\n                    extra *= j;\r\n\r\n            }\r\n        }\r\n\r\n        lcm_1_till[i] = lcm_1_till[i - 1]*extra;\r\n    }\r\n\r\n    printf( k < 43 && (n + 1)%lcm_1_till[k] == 0 ? \"Yes\\n\" : \"No\\n\");\r\n\r\n    return 0;\r\n}\r\n\r\n-------------------------------------------------------------------------------\r\n\r\nAfter the contest, and reading the editorial, I made it cleaner by realising that no need of precomputing, k < 43, so you can check every number from 1 to 42, provided\r\n\r\nk < 43\r\n\r\nint main()\r\n{\r\n    long long n, k;\r\n    scanf(\"%I64d %I64d\", &n, &k);\r\n\r\n    const int LIMIT = 43;\r\n    int divisible_by_lcm = true;\r\n\r\n    if(k < LIMIT)\r\n    {\r\n        for(int i = 1; i <= k; i++)\r\n        {\r\n            if( (n + 1)%i != 0)\r\n            {\r\n                divisible_by_lcm = false;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(k < LIMIT && divisible_by_lcm ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Cloning Toys Explanation.txt",
    "content": "\r\nSlightly tricky problem and the case of 0 originals needs to be handled seperately. \r\n\r\nSo, if you want to have Y originals, then it means you have to create Y - 1  new originals. \r\n\r\nWhen you do this, you are forced to make Y - 1 new copies as well. \r\n\r\nThere is no other way of generating originals. Then you may make new copies, each new copy gives you two new pieces. \r\n\r\nSo, here are the conditions - \r\n\r\n1. At least one new original\r\n2. Copies >= Original\r\n3. (Copies - originals) is even.\r\n\r\nI got this in the contest, however I missed out on the case where originals = 0 ?\r\n\r\nWhen you don't want any new originals, what do you do ? \r\n\r\nIs the answer always no ? Actually, this is what the above algorithm says, but it's wrong. \r\n\r\nIf you make 0 originals, the answer is no, EXCEPT when you want 0 copies as well. \r\n\r\nFor example, if you want 1 original and 0 copies, that means you don't have to do anything. \r\n\r\nI missed this trick during the contest. \r\n\r\n0 originals is a special case.\r\n\r\n1. Yes, if copies = 0\r\n2. No, otherwise.\r\n\r\n-------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int originals, copies;\r\n    scanf(\"%d %d\", &copies, &originals);\r\n\r\n    originals--;\r\n\r\n    printf( (originals == 0 && copies == 0) || (originals >= 1 && copies >= originals && (copies - originals)%2 == 0) ? \"Yes\\n\" : \"No\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Eternal Victory Explanation.txt",
    "content": "\r\nThink of the path travelled in terms of the edges travelled. \r\n\r\nWhat if we had only one vertex and all of it's children were leafs ? \r\n\r\nThen cost = w1 + w2 + ... + wn .... Now, all except one of these leaves are visited twice. \r\n\r\nSo, the best we can do is visit the maximum weight only once. Cost = 2(w1 + w2 + ... + wn) - wmax\r\n\r\nNow, we don't necessarily have all children as leaves. \r\n\r\nBut, notice that from the root, we must visit every leaf. The cost to one leaf is f(L)\r\n\r\nf(L1) + f(L2) + ... + f(Ln)\r\n\r\nAll except one leaf is visited twice. Let us visit the leaf with the maximum cost once. \r\n\r\nTotal cost = 2*sum of edges - f(max)\r\n\r\nThis is an elegant way of putting it. \r\n\r\nA very important corner case, which fortunately is elaborated in the example itself - What if there is only one leaf ?\r\nThen, no edge will be visited twice as we don't need to come back to any vertex and visit the other vertices and \r\nthe answer is merely the sum of all edges. \r\n--------------------------------------------------------------------------------------------------------\r\n\r\nvoid dfs(int v, int parent_v)\r\n{\r\n        max_distance[v] = 0;\r\n\r\n        for(int i = 0; i < tree[v].size(); i++)\r\n        {\r\n            int child_v = tree[v][i].first;\r\n            int child_distance = tree[v][i].second;\r\n\r\n            if(child_v == parent_v)\r\n                continue;\r\n\r\n            dfs(child_v, v);\r\n\r\n            max_distance[v] = max(max_distance[v], child_distance + max_distance[child_v]);\r\n        }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_cities;\r\n    scanf(\"%d\", &no_of_cities);\r\n\r\n    long long sum_of_edges = 0;\r\n\r\n    for(int i = 1; i < no_of_cities; i++)\r\n    {\r\n        int x, y, weight;\r\n        scanf(\"%d %d %d\", &x, &y, &weight);\r\n\r\n        tree[x].push_back(make_pair(y, weight));\r\n        tree[y].push_back(make_pair(x, weight));\r\n\r\n        sum_of_edges += weight;\r\n    }\r\n\r\n    dfs(1, 0);\r\n\r\n    long long total_travel_distance = (sum_of_edges == max_distance[1] ? sum_of_edges : 2*sum_of_edges - max_distance[1]);\r\n\r\n    printf(\"%I64d\\n\", total_travel_distance);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Hard Problem Explanation.txt",
    "content": "\r\n-----------------------------------------\r\n\r\nHere's the main idea. \r\n\r\nAssume the first i elements of the list are already sorted. How can you place string (i + 1) at the end of this list ?\r\n\r\nThere are two options - Either you place it reversed, or un-reversed.\r\n\r\nf(i, R) = Minimum cost for the first i strings with last string reversed.\r\n\r\nf(i, U) = Minimum cost for the first i strings with last string unreversed.\r\n\r\n\r\nif(s[i] >= s[i - 1]) f(i, U) = f(i - 1, U)\r\n\r\nif(s[i] >= R(s[i - 1]) f(i, U) = min{f(i, U), f(i - 1, R)}\r\n\r\nif(R(s[i]) >= s[i - 1]) f(i, R) = c[i] + f(i - 1, U)\r\n\r\nif(R(s[i]) >= R(s[i - 1])) f(i, R) = min{f(i, R), c[i] + f(i - 1, R)}\r\n\r\nAnswer = min{f(N, R), f(N, U)}\r\n\r\nCheck if answer >= oo, in which case it's not possible.\r\n\r\n------------------------------------------------------------------------------\r\n\r\nstring rev(string s)\r\n{\r\n    reverse(all(s));\r\n\r\n    return s;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_strings;\r\n    scanf(\"%d\", &no_of_strings);\r\n\r\n    vector <int> cost(no_of_strings + 1);\r\n    for(int i = 1; i <= no_of_strings; i++)\r\n        scanf(\"%d\", &cost[i]);\r\n\r\n    vector <string> s(no_of_strings + 1);\r\n    for(int i = 1; i <= no_of_strings; i++)\r\n        cin >> s[i];\r\n\r\n    const long long oo = 1e16;\r\n    const int WITHOUT_REVERSING = 0, REVERSING = 1;\r\n    long long minimum_till[no_of_strings + 1][2];\r\n    minimum_till[0][REVERSING] = minimum_till[0][WITHOUT_REVERSING] = 0;\r\n\r\n    for(int i = 1; i <= no_of_strings; i++)\r\n    {\r\n        minimum_till[i][REVERSING] = minimum_till[i][WITHOUT_REVERSING] = oo;\r\n\r\n        if(s[i] >= s[i - 1])\r\n            minimum_till[i][WITHOUT_REVERSING] = minimum_till[i - 1][WITHOUT_REVERSING];\r\n\r\n        if(s[i] >= rev(s[i - 1]))\r\n            minimum_till[i][WITHOUT_REVERSING] = min(minimum_till[i][WITHOUT_REVERSING], minimum_till[i - 1][REVERSING]);\r\n\r\n        if(rev(s[i]) >= s[i - 1])\r\n            minimum_till[i][REVERSING] = cost[i] + minimum_till[i - 1][WITHOUT_REVERSING];\r\n\r\n        if(rev(s[i]) >= rev(s[i - 1]))\r\n            minimum_till[i][REVERSING] = min(minimum_till[i][REVERSING], cost[i] + minimum_till[i - 1][REVERSING]);\r\n\r\n    }\r\n\r\n    long long answer = min(minimum_till[no_of_strings][REVERSING], minimum_till[no_of_strings][WITHOUT_REVERSING]);\r\n\r\n    printf(\"%I64d\\n\", answer >= oo ? -1 : answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Joystick Explanation.txt",
    "content": "\r\nAt each point charge the joystick with smaller charge.\r\n\r\nStop when the smaller charge is <= 0 and the larger charge <= 1\r\n\r\nFor it to continue, one of them must be > 1 and the other >= 1\r\n\r\nint main()\r\n{\r\n    int charge_a, charge_b;\r\n    scanf(\"%d %d\", &charge_a, &charge_b);\r\n\r\n    int no_of_minutes = 0;\r\n\r\n    while(max(charge_a, charge_b) > 1 && min(charge_a, charge_b) > 0)\r\n    {\r\n        if(charge_a < charge_b)\r\n            charge_a++, charge_b -= 2;\r\n        else\r\n            charge_a -= 2, charge_b++;\r\n\r\n        no_of_minutes++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_minutes);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/K-Special Tables Explanation.txt",
    "content": " \r\nI was going to give up on this problem and then I told myself that if I can't solve it, I should at least come up with a bad heuristic or a brute force.\r\n\r\nAnd, then I got it !\r\n\r\nSimple, I will fill the largest elements from the end till I reach A[k],\r\n\r\nA[k] < A[k + 1] < A[k + 2]  < A[n]\r\n\r\nA[k] is the largest element possible, but there are enough elements left over.\r\n\r\nSo, now theres two dimensions and a matrix. What to do now ?\r\n\r\nSame thing, fill in the largest elements from the end of the row till you reach the k-th column. Now, I want the next row k to be the maximum possible. For this, I want to save my large elements. So, I will fill columns 1 to k-1 from the beginning of the list.\r\n\r\nNext column, again I will start from the greatest unused element from N to K, and then smallest unused elements from 1 to K - 1.\r\n\r\nIn short, use two pointers - one to the front, other to the back. Fill in each row greedily. Fill from the back pointer from A[N] to A[k] and with the front pointer from A[1] to A[k - 1].\r\n\r\nI was delighted to find N = 500, the solution will pass, and it did !\r\n\r\n--------------------------------\r\n\r\n-----------------------------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int N, k;\r\n    scanf(\"%d %d\", &N, &k);\r\n\r\n    int special_table[N + 1][N + 1];\r\n    int front_ptr = 1, back_ptr = N*N;\r\n\r\n    for(int row = 1; row <= N; row++)\r\n    {\r\n        for(int column = N; column >= k; column--)\r\n            special_table[row][column] = back_ptr--;\r\n\r\n        for(int column = 1; column < k; column++)\r\n            special_table[row][column] = front_ptr++;\r\n    }\r\n\r\n    int k_column_sum = 0;\r\n\r\n\r\n    for(int row = 1; row <= N; row++)\r\n        k_column_sum += special_table[row][k];\r\n\r\n    printf(\"%d\\n\", k_column_sum);\r\n\r\n    for(int row = 1; row <= N; row++)\r\n    {\r\n        for(int column = 1; column <= N; column++)\r\n        {\r\n            printf(\"%d \", special_table[row][column]);\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Lucky Sum Explanation.txt",
    "content": "\r\nLet us consider lucky numbers of at most 10 digits. \r\n\r\nEach digit can have either 4 or 7. \r\n\r\nSo fill up each of the 10 digits in 2 ways. There are 2^10 = 1024 lucky numbers. \r\n\r\nPrecompute all of them, and sort them. This won't take too much time. \r\n\r\nThen, find the sum of next_lucky(i) till i = R, and i = L - 1, and then subtract the two values. \r\n\r\nFor convenience, let 0 also be a lucky number, \r\n\r\nIf x and y are consecutive lucky numbers, then each term from x to y-1, contributes y to the sum.\r\n\r\nIf y and z are consecutive lucky numbers, then each term from y to z - 1, contributes z to the sum. \r\n\r\nThe trick is when we have reached limit. \r\n\r\nIn that case, the range = limit - last lucky\r\n\r\nSO, in general range = min(limit, next lucky) - last lucky\r\n\r\nEach member of this range contributes (next lucky) to the sum.\r\n\r\n-----------------------------------------------------------------------------------------------------------\r\n\r\nvoid compute(vector <long long> &lucky_numbers, long long last_lucky_number)\r\n{\r\n    lucky_numbers.push_back(last_lucky_number);\r\n\r\n    if(last_lucky_number > 1e10)\r\n        return ;\r\n\r\n    compute(lucky_numbers, last_lucky_number*10 + 4);\r\n    compute(lucky_numbers, last_lucky_number*10 + 7);\r\n}\r\n\r\nlong long get_answer(vector <long long> &lucky_numbers, int limit)\r\n{\r\n    long long answer = 0;\r\n\r\n    for(int i = 1; i < lucky_numbers.size() && lucky_numbers[i - 1] < limit; i++)\r\n    {\r\n        long long next_lucky_number = lucky_numbers[i];\r\n        long long range = min(limit, lucky_numbers[i]) - lucky_numbers[i - 1];\r\n\r\n        answer += next_lucky_number*range;\r\n    }\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    vector <long long> lucky_numbers;\r\n    compute(lucky_numbers, 0);\r\n\r\n    sort(all(lucky_numbers));\r\n\r\n    int left, right;\r\n    scanf(\"%d %d\", &left, &right);\r\n\r\n    long long answer = get_answer(lucky_numbers, right) - get_answer(lucky_numbers, left - 1);\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Magic Forest Explanation.txt",
    "content": "\r\nA common technique in going over triples is in trying to go over doubles and then force the third variable.\r\n\r\na^b^c = 0\r\n\r\na^a^b^c = a^0\r\n\r\nb^0^b^c = b^a^0\r\n\r\nc = b^a\r\n\r\nSo, we fix (a, b) and find c, and then check if a non-degenerate triangle is possible.\r\n\r\nTo avoid overcounting, make sure c >= b >= a\r\n\r\n------------------------------------\r\n\r\nint is_nondegenerate_triangle(int a, int b, int c)\r\n{\r\n    return (a + b > c);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int no_of_triangles = 0;\r\n    for(int a = 1; a <= n; a++)\r\n    {\r\n        for(int b = a; b <= n; b++)\r\n        {\r\n            int c = a^b;\r\n\r\n            if(c >= b && c <= n && is_nondegenerate_triangle(a, b, c))\r\n                no_of_triangles++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_triangles);\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Marvolo Gaunt's Ring Alternate Solution Explanation.txt",
    "content": "\r\nNow, this is a different DP from the previous one. \r\n\r\nFix q on a certain i, then p can take any value <= i and r can take any value >= i.\r\n\r\nWhat is the best possible match for both ? \r\n\r\nif p is maximum, then match it with the largest number in that range. Else with the smallest number in that range.\r\n\r\n---------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    long long p, q, r;\r\n    scanf(\"%d %I64d %I64d %I64d\", &no_of_elements, &p, &q, &r);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> left_min(no_of_elements + 1);\r\n    vector <int> left_max(no_of_elements + 1);\r\n    left_min[1] = left_max[1] = A[1];\r\n\r\n    for(int i = 2; i <= no_of_elements; i++)\r\n    {\r\n        left_min[i] = min(left_min[i - 1], A[i]);\r\n        left_max[i] = max(left_max[i - 1], A[i]);\r\n    }\r\n\r\n    vector <int> right_min(no_of_elements + 1);\r\n    vector <int> right_max(no_of_elements + 1);\r\n    right_min[no_of_elements] = right_max[no_of_elements] = A[no_of_elements];\r\n\r\n    for(int i = no_of_elements - 1; i >= 1; i--)\r\n    {\r\n        right_max[i] = max(right_max[i + 1], A[i]);\r\n        right_min[i] = min(right_min[i + 1], A[i]);\r\n    }\r\n\r\n    long long ans = p*A[1] + q*A[1] + r*A[1];\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        long long y = q*A[i];\r\n        long long x = (p > 0 ? p*left_max[i] : p*left_min[i]);\r\n        long long z = (r > 0 ? r*right_max[i] : r*right_min[i]);\r\n\r\n        ans = max(ans, x + y + z);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", ans);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Marvolo Gaunt's Ring Explanation.txt",
    "content": "\r\nLet f(i, P) represent the greatest value p*a[i] can take if you're allowed to choose till i\r\n\r\nf(i, Q) represent the greatest value of q*a[i]. f(i, Q) = max{f(i - 1, Q), q*a[i] + f(i, P)}\r\n\r\nf(i, R) represent the greatest value of r*a[i]. f(i, R) = max{f(i - 1, R), r*a[i] + f(i, q)}\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    long long p, q, r;\r\n    scanf(\"%d %I64d %I64d %I64d\", &no_of_elements, &p, &q, &r);\r\n\r\n    vector <int> a(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &a[i]);\r\n\r\n    vector <long long> max_P(no_of_elements);\r\n    max_P[0] = p*a[0];\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        max_P[i] = max(max_P[i - 1], p*a[i]);\r\n\r\n    vector <long long> max_Q(no_of_elements);\r\n    max_Q[0] = q*a[0] + p*a[0];\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        max_Q[i] = max(max_Q[i - 1], q*a[i] + max_P[i]);\r\n\r\n    vector <long long> max_R(no_of_elements);\r\n    max_R[0] = r*a[0] + q*a[0] + p*a[0];\r\n    for(int i = 1; i < no_of_elements; i++)\r\n        max_R[i] = max(max_R[i - 1], r*a[i] + max_Q[i]);\r\n\r\n\r\n    printf(\"%I64d\\n\", max_R[no_of_elements - 1]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Not Equal on a Segment Explanation.txt",
    "content": "\r\nVery powerful idea. \r\n\r\nFor every i, let f(i) denote the first index on the left such that A[f(i)] =/= A[i], (un equal element)\r\n\r\nf(i) = (A[i - 1] =/= A[i] ? i - 1: f(i - 1))\r\n\r\nNow, in a query, either x = r, or not\r\n\r\nIf x =/= r, then r is the answer\r\n\r\nIf x = r, then check if f(r) >= l, then f(r) is the answer.\r\n\r\nOtherwise, -1 is the answer.\r\n\r\nThe above can be precomputed in one pass.\r\n\r\n---------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_elements, number_of_queries;\r\n    scanf(\"%d %d\", &number_of_elements, &number_of_queries);\r\n\r\n    vector <int> A(number_of_elements + 1, 0);\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> first_unequal_position_left(number_of_elements + 1, 0);\r\n    for(int i = 1; i <= number_of_elements; i++)\r\n        first_unequal_position_left[i] = (A[i] != A[i - 1] ? i - 1 : first_unequal_position_left[i - 1]);\r\n\r\n    while(number_of_queries--)\r\n    {\r\n        int left, right, x;\r\n        scanf(\"%d %d %d\", &left, &right, &x);\r\n\r\n        int answer;\r\n\r\n        if(A[right] != x)\r\n            answer = right;\r\n        else if(A[right] == x)\r\n            answer = (first_unequal_position_left[right] >= left ? first_unequal_position_left[right] : -1);\r\n\r\n        printf(\"%d\\n\", answer);\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Perfect Squares Explanation.txt",
    "content": "\r\nKeep a boolean vector of all squares. Sort the array given and then find the first element that is either negative or not a square.\r\n\r\n0 is a square. Forgot to include this in the contest.\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> A(n);\r\n\r\n    for(int i = 0; i < n; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    vector <int> is_square(1e6 + 1, false);\r\n    for(int i = 0; i*i <= 1e6; i++)\r\n        is_square[i*i] = true;\r\n\r\n    int answer;\r\n\r\n    for(int i = n - 1; i >= 0; i--)\r\n    {\r\n        if(A[i] < 0 || !is_square[A[i]])\r\n        {\r\n            answer = A[i];\r\n            break;\r\n        }\r\n    }\r\n\r\n\r\n    printf(\"%d \", answer);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Petya and Inequiations Explanation.txt",
    "content": "\r\nTry to find the maximum value of the sum of squares - \r\n\r\nTurns out this happens when all the elements except one = 1, and the last element = Y - (n - 1)\r\n\r\nLet us say there is another arrangement where we have at most (n - 2) ones. I will show that you can always do better by making it (n - 1) 1's \r\n\r\nChoose the largest and second largest element - Let it be a and b. Without loss of generality, a < b, and a > b > 1\r\n\r\nSum of squares = a^2 + b^2 = X\r\n\r\nNow, let us make the two numbers 1, (b + a - 1)\r\n\r\nKeeping the sum invariant.\r\n\r\nLet us examine the sum of squares now\r\n\r\n1^2 + (b + a - 1)^2\r\n\r\n= 1 + a^2 + b^2 + 1 - 2a - 2b + 2ab\r\n\r\n= (a^2 + b^2) + 2(1 + ab - a - b)\r\n\r\n= X + 2( 1  + ab - a - b)\r\n\r\nNow, all I have to do is show that (1 + ab - a - b) is positive\r\n\r\nWhen a and b are two positive integers > 1, their product is always greater than their sum.\r\n\r\nxy - x - y + 1 = x(y - 1) - y + 1 = (x - 1)(y - 1), both terms are positive, so (x - 1)(y - 1) > 0\r\n\r\nThis completes the proof ---------\r\n\r\nNow, get the maximum possible sum of squares for a given sum = 1^2 + 1^2 + ... + (Y - (N - 1))^2\r\n\r\nTest cases I missed - What happens when N > Y.\r\n\r\n--------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, sum_limit;\r\n    long long square_sum_lower_bound;\r\n    scanf(\"%d %I64d %d\", &n, &square_sum_lower_bound, &sum_limit);\r\n\r\n    long long largest_element = sum_limit - (n - 1);\r\n    long long max_square_sum = (n - 1) + largest_element*largest_element;\r\n\r\n    if(max_square_sum < square_sum_lower_bound || n > sum_limit)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n        printf(\"%I64d\\n\", (i == n ? largest_element : 1));\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Polo the Penguin and Matrix Explanation.txt",
    "content": "\r\nFirst, I thought of binary search where try to find the minimum number of moves all elements can be equalised. \r\n\r\nBut, then that was not so easy. It's not easy to answer the question, - \"Can the matrix be equalised in at most x moves ?\"\r\n\r\nIt's easier to answer the question - \"Can the matrix be equalised to element x ?\"\r\n\r\nThen, I thought of taking the frequency of all elements, and then the answer is yes, if (frequency[x - d] + frequency[x] + frequency[x + d]) = N*M\r\n\r\nBut then I realised that the you can add D any number of times to a number, not just once. \r\n\r\nThen, I realised the remainder with D is invariant under the operation of adding or subtracting D\r\n\r\nx = x + D = x - D (mod D)\r\n\r\nIf all the numbers are not congruent mod D, then we can never equalise them. \r\n\r\nNow, the question is that you have 10^4 elements ... Which element do they have the least distance. \r\n\r\nTurns out this is the median. \r\n\r\nIf we equalise all elements to something other than the median, then there are more elements from one side than the other. \r\n\r\nWe can do better by setting it to the median. \r\n\r\n(Let the other element by x, and let us say it takes s steps to go from x to the median.)\r\n\r\nNow, if x < m, then there are more elements to the right of x (R) than to the left (L)\r\n\r\nIf we now set the equal point to the median, we add L(s) steps and reduce R(s) steps. \r\n\r\nSo total new steps = s(L - R)\r\n\r\nL < R, so this is a negative number. Which means we have reduced the steps. \r\n\r\n-----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_rows, no_of_columns, difference;\r\n    scanf(\"%d %d %d\", &no_of_rows, &no_of_columns, &difference);\r\n\r\n    vector <int> A(no_of_rows*no_of_columns, 0);\r\n\r\n    set <int> remainder;\r\n\r\n    int possible = true;\r\n    for(int i = 0; i < no_of_rows*no_of_columns; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n\r\n        remainder.insert(A[i]%difference);\r\n    }\r\n\r\n    if(remainder.size() > 1)\r\n        possible = false;\r\n\r\n    sort(all(A));\r\n\r\n    int middle = A.size()/2;\r\n    int median = A[middle];\r\n\r\n    int minimum_no_of_moves = 0;\r\n    for(int i = 0; i < A.size(); i++)\r\n        minimum_no_of_moves += abs(A[i] - median)/difference;\r\n\r\n    printf(\"%d\\n\", possible ? minimum_no_of_moves : -1);\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Polo the Penguin and Strings Explanation.txt",
    "content": "\r\nWhat's the smallest answer of length 1 ? - a\r\n\r\nLength 2 ? has to be ab.\r\n\r\nLength 3 ? Answer should be either aba or abc, depending on whether you want 3 distinct characters.\r\n\r\nThe answer can be constructed in the following way - \r\n\r\nFirst, fill it up with alternating a's and b's.\r\n\r\nababababa....aba\r\n\r\nThen, from the back start putting the largest letters in the end in alphabetical order.\r\n\r\nFor example, N = 7, K = 4\r\n\r\nababacd\r\n\r\nThis is the smallest string, because if we put c or d in any other position where we have a or b, we get a larger string. \r\n\r\nIn fact, if we swap any two characters of this string, we will either get a larger string or violate the condition S[i] =/= S[i - 1]\r\n\r\nNow, when is it not possible ?\r\n\r\nWhen N < K and when K = 1, and N > 1. I missed the second case.\r\n\r\nIf N > 1, then we are forced to put the same character in multiple positions and will violate the condition.\r\n\r\n-----------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length, distinct_letters;\r\n    scanf(\"%d %d\", &length, &distinct_letters);\r\n\r\n    if(length < distinct_letters || (length > 1 && distinct_letters == 1))\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    string answer;\r\n    for(int i = 0; i < length; i++)\r\n        answer += ('a' + i%2);\r\n\r\n    for(int i = length - 1, letter = distinct_letters - 1; letter >= 2; i--, letter--)\r\n        answer[i] = ('a' + letter);\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Replacement Explanation.txt",
    "content": "\r\nN = 1, is a special case. Let us solve it first. \r\n\r\nIf N = 1, then \r\n\r\nif A[i] = 1, then Answer = 2\r\n\r\nelse, Answer = 1\r\n\r\n-------------------------------------------------------\r\n\r\nNow, let N > 1\r\n\r\nThe smallest digit that can occupy the first position  = 1. \r\n\r\nLet us consider the sorted array.\r\n\r\nFor all other positions k, \r\n\r\nThere must be k-1 smaller numbers ... A[1], A[2], ... , A[k - 1].\r\n\r\nIf A[k] > A[k - 1], then we can replace A[k] with another copy of A[k - 1]\r\n\r\nNo element smaller than A[k - 1] can occupy the position K.\r\n\r\nIf A[k] = A[k - 1], then we replace any number from (k + 1 to N) or from (1, k - 2) to maintain the order. It doesn't matter which. \r\n\r\nSince nothing smaller than A[k - 1] can occupy A[k], we are done. \r\n\r\nHowever, there's a special case here - What if A[n] = 1 ? \r\n\r\nThen, we can't replace any other number, and A[n] =/= A[n - 1] as the array would remain unchanged. \r\n\r\nIf the array consists of all 1's then the last 1, will become = 2\r\n\r\n----------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> element(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    sort(all(element));\r\n\r\n    if(no_of_elements == 1)\r\n    {\r\n        printf(\"%d\", element[0] == 1 ? 2 : 1);\r\n        return 0;\r\n    }\r\n\r\n    printf(\"1 \");\r\n    for(int i = 1; i < no_of_elements - 1; i++)\r\n        printf(\"%d \", element[i - 1]);\r\n\r\n    if(element[no_of_elements - 1] == 1)\r\n        printf(\"2\");\r\n    else\r\n        printf(\"%d\", element[no_of_elements - 2]);\r\n\r\n\r\n    return 0;\r\n}\r\n \r\n\r\n----------------------------------------------------------------------------\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Robot Vaccuum Cleaner Explanation.txt",
    "content": "\r\nThis is a custom sorting question \r\n\r\nLet f(A) denote the number of sh subsquences in A. \r\n\r\nThis question requires a similar approach to segment trees. How do we calculate f(A + B) if we know f(A) and f(B) ? What information do we need ?\r\n\r\nAny sh subsequence will either be completely in A, or completely in B or start in A and end in B.\r\n\r\nThen, f(A + B) = f(A) + f(B) + s[A]*h[B]\r\n\r\nWe put A before B, if we get more sh sequences than if we put B before A. \r\n\r\nThis is determined by s[A]*h[B] > S[B]*h[A].\r\n\r\nIf in the final order, the strings are concatenated in an order and there's a string A before B, where f(A + B) < f(B + A), \r\n\r\nswapping A and B can give us a higher number of subsequences. \r\n\r\n---------------------------------------------------------------------------------\r\n\r\nstruct info\r\n{\r\n    long long no_of_s, no_of_h;\r\n    string text;\r\n};\r\n\r\nint compare(const info &A, const info &B)\r\n{\r\n    long long no_of_new_sh_if_A_front = A.no_of_s*B.no_of_h;\r\n    long long no_of_new_sh_if_B_front = B.no_of_s*A.no_of_h;\r\n\r\n    if(no_of_new_sh_if_A_front > no_of_new_sh_if_B_front)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_strings;\r\n    cin >> no_of_strings;\r\n\r\n    vector <info> A(no_of_strings);\r\n    for(int i = 0; i < no_of_strings; i++)\r\n    {\r\n        cin >> A[i].text;\r\n\r\n        A[i].no_of_s = 0;\r\n        A[i].no_of_h = 0;\r\n\r\n        for(int j = 0; j < A[i].text.size(); j++)\r\n        {\r\n            A[i].no_of_s += (A[i].text[j] == 's');\r\n            A[i].no_of_h += (A[i].text[j] == 'h');\r\n        }\r\n    }\r\n\r\n    sort(all(A), compare);\r\n\r\n    string final_text;\r\n    for(int i = 0; i < no_of_strings; i++)\r\n        final_text += A[i].text;\r\n\r\n    long long no_of_s_till_here = 0, no_of_sh = 0;\r\n    for(int i = 0; i < final_text.size(); i++)\r\n    {\r\n        no_of_s_till_here += (final_text[i] == 's');\r\n\r\n        if(final_text[i] == 'h')\r\n            no_of_sh += no_of_s_till_here;\r\n    }\r\n\r\n    cout << no_of_sh;\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Rumour Explanation.txt",
    "content": "\r\nWhat I did was took each connected component of a graph and put it inside a vector. \r\n\r\nThen, I found the minimum of each connected component. \r\n\r\nDo DFS to mark all the connected components.\r\n\r\n----------------------------------------------------------------------------------------------\r\n\r\nvoid dfs_and_mark_component(int v, int component_no)\r\n{\r\n    visited[v] = true;\r\n    component[component_no].push_back(v);\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(!visited[child])\r\n            dfs_and_mark_component(child, component_no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_people, no_of_friendships;\r\n    scanf(\"%d %d\", &no_of_people, &no_of_friendships);\r\n\r\n    vector <int> gold(no_of_people + 1, 0);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &gold[i]);\r\n\r\n    for(int i = 1; i <= no_of_friendships; i++)\r\n    {\r\n        int person_1, person_2;\r\n        scanf(\"%d %d\", &person_1, &person_2);\r\n\r\n        graph[person_1].push_back(person_2);\r\n        graph[person_2].push_back(person_1);\r\n    }\r\n\r\n    memset(visited, false, sizeof(visited));\r\n\r\n    int component_no = 1;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            dfs_and_mark_component(i, component_no++);\r\n        }\r\n    }\r\n\r\n    long long total_cost = 0;\r\n\r\n    for(int component_i = 1; component_i < component_no; component_i++)\r\n    {\r\n        long long min_cost_for_this_component = 1e15;\r\n\r\n        for(int v = 0; v < component[component_i].size(); v++)\r\n        {\r\n            int person = component[component_i][v];\r\n\r\n            min_cost_for_this_component = min(min_cost_for_this_component, gold[person]);\r\n        }\r\n\r\n        total_cost += min_cost_for_this_component;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Search for Pretty Integers Explanation.txt",
    "content": "\r\nIf there's a single digit that occurs in both lists, then the answer is the smallest such number. \r\n\r\nElse it is the smallest single digit number that occurs in A with the smallest single digit with B or the other way around.\r\n\r\n--------------------------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int list_1_size, list_2_size;\r\n    scanf(\"%d %d\", &list_1_size, &list_2_size);\r\n\r\n    vector <int> in_A(10, false);\r\n    for(int i = 1; i <= list_1_size; i++)\r\n    {\r\n        int a_i;\r\n        scanf(\"%d\", &a_i);\r\n\r\n        in_A[a_i] = true;\r\n    }\r\n\r\n    vector <int> in_B(10, false);\r\n    for(int i = 1; i <= list_2_size; i++)\r\n    {\r\n        int b_i;\r\n        scanf(\"%d\", &b_i);\r\n\r\n        in_B[b_i] = true;\r\n    }\r\n\r\n    int answer = -1;\r\n\r\n    for(int i = 1; i <= 9; i++)\r\n    {\r\n        if(in_A[i] && in_B[i])\r\n        {\r\n            answer = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(answer != -1)\r\n    {\r\n        printf(\"%d\\n\", answer);\r\n        return 0;\r\n    }\r\n\r\n    for(int i = 1; i <= 9 && answer == -1; i++)\r\n    {\r\n        for(int j = i + 1; j <= 9; j++)\r\n        {\r\n            if( (in_A[i] && in_B[j]) || (in_A[j] && in_B[i]) )\r\n            {\r\n                answer = 10*i + j;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Tom Riddle's Diary Explanation.txt",
    "content": "\r\nPut all the names in a set. \r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_people;\r\n    scanf(\"%d\", &no_of_people);\r\n\r\n    set <string> people;\r\n    while(no_of_people--)\r\n    {\r\n        string current_possesser;\r\n        cin >> current_possesser;\r\n\r\n        printf(people.count(current_possesser) == 1 ? \"YES\\n\" : \"NO\\n\");\r\n        people.insert(current_possesser);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 18/Two Substrings Explanation.txt",
    "content": "\r\nStore the positions where AB and BA occur. \r\n\r\nTry to compare the further AB and BA\r\n\r\nCheck if the last AB and the first BA overlap \r\n\r\nAnd if the first BA and the last AB overlap. \r\n\r\nIf they don't, we are done. \r\n\r\nIf the first AB overlaps with the last BA - ABA\r\n\r\nAnd the first BA overlaps with the last AB, then that would mean the first BA comes after the last BA which is not possible. \r\n\r\nThe only possibility is if it's like - ABAB\r\n\r\nThere's only one BA. And it overlaps so it's not possible.\r\n\r\n------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    vector <int> ab;\r\n    vector <int> ba;\r\n\r\n    for(int i = 0; i < A.size() - 1; i++)\r\n    {\r\n        if(A[i] == 'A' && A[i + 1] == 'B')\r\n            ab.push_back(i);\r\n\r\n        if(A[i] == 'B' && A[i + 1] == 'A')\r\n            ba.push_back(i);\r\n    }\r\n\r\n    if(ab.size() == 0 || ba.size() == 0 || !(ab[0] + 1 < ba.back() || ba[0] + 1 < ab.back()))\r\n       cout << \"NO\\n\";\r\n    else\r\n        cout << \"YES\\n\";\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Vladik and Fractions Explanation.txt",
    "content": "\r\nThis one calls for some inspired factorisation. But, that need not be the case if you know the history of Egyptian fractions. \r\n\r\nThe Egyptians had found a trick to write any unit fraction\r\n\r\n1/a as an infinite chain of unit fractions by using this - \r\n\r\n\r\n1/a = 1/(a + 1) + 1/a(a + 1)\r\n\r\nIt's the reverse of telescoping a series, where an infinite series was bought down to one or two fractions. \r\n\r\nIf you know the historical trick, the factorisation will not appear too difficult. \r\n\r\n2/n \r\n\r\n= 1/n + 1/n \r\n\r\n= 1/n + ( 1/(n + 1) + 1/n(n + 1) \r\n\r\nWhen n = 1, it is not possible because 1/n is = 1\r\n\r\n-------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int x = n;\r\n    int y = n + 1;\r\n    int z = n*(n + 1);\r\n\r\n    printf(n == 1 ? \"-1\\n\" : \"%d %d %d\\n\", x, y, z);\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 18/Woodcutter.txt",
    "content": "\nSince we have three options for every tree, store the answer for each of them, \n\nf(i, straight), f(i, right), f(i, left)\n\nf(i, straight) = max{f(i - 1, ...)}\n\nf(i, right) = 1 + f(i, straight) {if right is possible)\n\nf(i, left) = 1 + max{f(i - 1, straight), f(i - 1, left)} \n\nif possible then, f(i, left) = max{f(i, left), 1 + f(i - 1, right)}\n\n--------------------------------------------------------------------------\n\n#include <cstdio>\n\n#define max(a, b) (a > b ? a : b)\n#define max_3(a, b, c) max(a, max(b, c))\n\nint main()\n{\n    int no_of_trees;\n    scanf(\"%d\", &no_of_trees);\n\n    long long height[no_of_trees + 1];\n    long long x[no_of_trees + 1];\n    for(int i = 1; i <= no_of_trees; i++)\n        scanf(\"%I64d %I64d\", &x[i], &height[i]);\n\n    const int RIGHT = 1, STRAIGHT = 0, LEFT = 2;\n    int max_cut[no_of_trees + 1][3];\n    max_cut[0][RIGHT] = max_cut[0][STRAIGHT] = max_cut[0][LEFT] = 0;\n\n    for(int i = 1; i <= no_of_trees; i++)\n    {\n        max_cut[i][STRAIGHT] = max_3(max_cut[i - 1][LEFT], max_cut[i - 1][STRAIGHT], max_cut[i - 1][RIGHT]);\n\n        max_cut[i][LEFT] = max_cut[i][RIGHT] = max_cut[i][STRAIGHT];\n\n        if(i == 1 || x[i] - height[i] > x[i - 1])\n            max_cut[i][LEFT] = 1 + max(max_cut[i - 1][LEFT], max_cut[i - 1][STRAIGHT]);\n\n        if(height[i - 1] + height[i] + x[i - 1] < x[i])\n            max_cut[i][LEFT] = max(max_cut[i][LEFT], 1 + max_cut[i - 1][RIGHT]);\n\n        if(i == no_of_trees || height[i] + x[i] < x[i + 1])\n            max_cut[i][RIGHT] = 1 + max_cut[i][STRAIGHT];\n\n    }\n\n    int answer = max_3(max_cut[no_of_trees][RIGHT], max_cut[no_of_trees][STRAIGHT], max_cut[no_of_trees][LEFT]);\n\n    printf(\"%d\\n\", answer);\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 19/A Compatipble Pair Explanation.txt",
    "content": "\r\nIt's not as simple as multiplying the second largest number from A with the largest from B. \r\n\r\nThere are negative numbers as well, and the case of most negative x most negative must also be considered. \r\n\r\nWhat I did was iterate through all products. Find the largest product = A[i], B[j]\r\n\r\nNow exclude this A[i], what is the maximum product now ?\r\n\r\nTwo O(nm) scans.\r\n\r\n-----------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a_elements, b_elements;\r\n    scanf(\"%d %d\", &a_elements, &b_elements);\r\n\r\n    vector <long long> A(a_elements);\r\n    for(int i =0; i < a_elements; i++) scanf(\"%I64d\", &A[i]);\r\n\r\n    vector <long long> B(b_elements);\r\n    for(int i = 0; i < b_elements; i++) scanf(\"%I64d\", &B[i]);\r\n\r\n    long long max_product = -1e18;\r\n    int best_choice_A;\r\n    for(int i = 0; i < a_elements; i++)\r\n    {\r\n        for(int j = 0; j < b_elements; j++)\r\n        {\r\n            if(A[i]*1LL*B[j] > max_product)\r\n            {\r\n                best_choice_A = i;\r\n                max_product = A[i]*1LL*B[j];\r\n            }\r\n        }\r\n    }\r\n\r\n    long long max_product_without_best_A = -1e18;\r\n    for(int i = 0; i < a_elements; i++)\r\n    {\r\n        if(i == best_choice_A)\r\n            continue;\r\n\r\n        for(int j = 0; j < b_elements; j++)\r\n        {\r\n            max_product_without_best_A = max(max_product_without_best_A, A[i]*1LL*B[j]);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", max_product_without_best_A);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/A Prosperous Lot Explanation.txt",
    "content": "\r\nSome numbers have 0 loops, some have 1, some have 2. \r\n\r\nYou are allowed only 18 digits. So you can reach at most 36 loops. \r\n\r\nWhile no of loops >= 2, print a digit with 2 loops, and then print a digit with 1 loop. \r\n\r\nIn the contest, I made the mistake of choosing the 1 loop digit as 0. They want a positive integer, so k = 1, gives WA. \r\n\r\nIt didn't strike me. \r\n\r\n---------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_loops;\r\n    scanf(\"%d\", &no_of_loops);\r\n\r\n    const int MAX_LOOPS = 36;\r\n\r\n    if(no_of_loops > MAX_LOOPS)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    while(no_of_loops >= 2)\r\n    {\r\n        printf(\"8\");\r\n        no_of_loops -= 2;\r\n    }\r\n\r\n    if(no_of_loops == 1)\r\n        printf(\"9\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 19/Almost Identity Permutations Explanation.txt",
    "content": "\r\nThe key to note here is that k is very small. \r\n\r\nFirst we must choose k spots out of n. \r\n\r\nNow, we can fill these k spots in derangement(k) number of ways. \r\n\r\nHow to find a recurrence for d(n) ?\r\n\r\nConsider we have n numbers .... \r\n\r\nNow, let us place n at position i. (There are (n - 1) choices for this.)\r\n\r\nThere are two possibilities for i - Either it is at position n, or it is at some other position.\r\n\r\nNow if i is placed at position n, then the remaining (n - 2) numbers must be deranged ... given by d(n - 2).\r\n\r\nWhat if i is placed at some position other than n ? \r\n\r\nThen notice now that we have a situation where every element has exactly one spot it cannot fill. \r\n\r\n(1 cannot be in 1, \r\n2 cannot be in 2, \r\n3 cannot be in 3, \r\n.\r\n.\r\ni - 1 cannot be in i - 1\r\ni cannot be in N\r\ni + 1 cannot be in i + 1\r\n. \r\n.\r\nN - 1 cannot be in N - 1)\r\n\r\nWe have i-1 elements and i - 1 positions to fill them, and each element cannot occupy one spot. \r\n\r\nTotal answer = (n - 1)(d(n - 1) + d(n - 2))\r\n\r\n(n - 1) choices to place n, and then accordingly d(n - 1) or d(n - 2)\r\n\r\nFor convenience, when 0 elements are out of place, I want to add 1 to the answer for this question so define d(0) = 1\r\n\r\n------------------------------------------------------------------\r\n\r\nlong long choose(int n, int r)\r\n{\r\n    if(r == 0 || r == n)\r\n        return 1;\r\n    if(r == 1 || r == n - 1)\r\n        return n;\r\n\r\n    return choose(n - 1, r) + choose(n - 1, r - 1);\r\n}\r\n\r\nlong long derangements(int n)\r\n{\r\n    if(n == 0)\r\n        return 1;\r\n    if(n == 1)\r\n        return 0;\r\n    if(n == 2)\r\n        return 1;\r\n\r\n    return (n - 1)*(derangements(n - 1) + derangements(n - 2));\r\n}\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    scanf(\"%d %d\", &n, &k);\r\n\r\n    long long answer = 0;\r\n    for(int i = 0; i <= k; i++)\r\n    {\r\n        answer += choose(n, i)*derangements(i);\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Amr and Large Array Explanation.txt",
    "content": "\r\nFirstly, keep track of the left most, right most and frequency of each element. \r\n\r\nIf the frequency of each element = max frequency, then the subarray required to have only that element as the largest frequency element = right[i] - left[i] + 1\r\n\r\nThen, we're done.\r\n\r\n----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    const int LIMIT = 1e6;\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    vector <int> frequency(LIMIT + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(int i = 1; i <= LIMIT; i++)\r\n        max_frequency = max(max_frequency, frequency[i]);\r\n\r\n    vector <int> rightmost_occurence(LIMIT + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        rightmost_occurence[A[i]] = i;\r\n\r\n    vector <int> leftmost_occurence(LIMIT + 1, 0);\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n        leftmost_occurence[A[i]] = i;\r\n\r\n    int minimum_segment_length = no_of_elements + 1;\r\n    int answer;\r\n    for(int i = 1; i <= LIMIT; i++)\r\n    {\r\n        if(frequency[i] == max_frequency)\r\n        {\r\n            int subsegment_length = rightmost_occurence[i] - (leftmost_occurence[i] - 1);\r\n\r\n            if(subsegment_length < minimum_segment_length)\r\n            {\r\n                answer = i;\r\n                minimum_segment_length = subsegment_length;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%d %d\\n\", leftmost_occurence[answer], rightmost_occurence[answer]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Beautiful Sets of Points Explanation.txt",
    "content": "\r\nThe distance between two points is an integer, if and only if at least one of their coordinates are equal.\r\n\r\n(I was going to go for (0, 0) (1, 1) ... (m, m), but (0, 0) is restricted.)\r\n\r\nSo, you can go for the other diagonal ... (0, m - 0), (1, m - 1) ... etc.\r\n\r\nThe distance in between any (x, y) and (y, x) = root(2) x something, so it's never an integer\r\n\r\n---------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int m, n;\r\n    scanf(\"%d %d\", &m, &n);\r\n\r\n    int limit = min(m, n) + 1;\r\n    printf(\"%d\\n\", limit);\r\n\r\n    for(int i = 0; i < limit; i++)\r\n        printf(\"%d %d\\n\", i, limit - i - 1);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Buggy Robot Explanation.txt",
    "content": "\r\nFor the robot to finish at the starting position, the left and right  ... and the up and down .. directions must neutralise each other. \r\n\r\nSo, the max = 2*min{L, R} + 2*min{U, D}\r\n\r\nThis allows for neutralisation in both horizontal and vertical directions.\r\n\r\n--------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_instructions;\r\n    string instructions;\r\n    cin >> no_of_instructions >> instructions;\r\n\r\n    int lefts = 0, rights = 0, ups = 0, downs = 0;\r\n\r\n    for(int i = 0; i < no_of_instructions; i++)\r\n    {\r\n        lefts  += (instructions[i] == 'L');\r\n        rights += (instructions[i] == 'R');\r\n        downs  += (instructions[i] == 'D');\r\n        ups    += (instructions[i] == 'U');\r\n    }\r\n\r\n    int max_correct_instructions = 2*min(lefts, rights) + 2*min(ups, downs);\r\n    cout << max_correct_instructions;\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 19/Cellular Network Explanation.txt",
    "content": "\r\nBoth the cities and the towers are given in ascending order. \r\n\r\nTake each city and perform binary search to find the nearest tower.\r\n\r\nPerform lower bound(city) and it gives the leftmost occurence of city, if city occurs and otherwise returns the first tower to it's left. \r\n\r\n(If city is not present in towers, then upper bound and lower bound both perform exactly the same - point to the first position where the element can be inserted\r\nwithout breaking the order. (Suppose you search for 4, and the list has (3, 5) ... Both will point to 5)\r\n\r\nSo, we need to compare with wherever lower bound points and one position less than that.\r\n\r\n(Don't forget to do bound checking to see it doesn't exceed the limit. If lower bound points to after the last element, then don't compare with it.\r\n\r\nIf lower bound points to 0, then don't compare with -1.)\r\n\r\n\r\nNearest tower = min(left, right)\r\n\r\nThe nearest distance = max(nearest tower).\r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int number_of_cities, number_of_towers;\r\n    scanf(\"%d %d\", &number_of_cities, &number_of_towers);\r\n\r\n    vector <int> city(number_of_cities);\r\n    for(int i = 0; i < number_of_cities; i++)\r\n        scanf(\"%d\", &city[i]);\r\n\r\n    vector <int> tower(number_of_towers);\r\n    for(int i = 0; i <  number_of_towers; i++)\r\n        scanf(\"%d\", &tower[i]);\r\n\r\n    int min_range = 0;\r\n\r\n    for(int i = 0; i < number_of_cities; i++)\r\n    {\r\n        int position = lower_bound(all(tower), city[i]) - tower.begin();\r\n\r\n        int closest_tower = 2e9;\r\n\r\n        if(position != number_of_towers) closest_tower = min(closest_tower, abs(tower[position] - city[i]));\r\n\r\n        if(position != 0) closest_tower = min(closest_tower, abs(tower[position - 1] - city[i]));\r\n\r\n        min_range = max(min_range, closest_tower);\r\n    }\r\n\r\n    printf(\"%d\\n\", min_range);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Coder Explanation.txt",
    "content": "\r\nBe greedy while distributing the pieces. \r\n\r\nFill them up in alternating positions. \r\n\r\nNotice that in any two consecutive rows, we will have exactly N pieces. \r\n\r\n. C . C .\r\nC . C . C\r\n\r\nIn this way - If it was an odd number, then \r\n\r\nC . C . C\r\n. C . C .\r\nC . C . C\r\n\r\nSo, number of pieces = (n/2)*n + ceil(n/2) (if n is odd)\r\n\r\n-----------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_rows;\r\n    scanf(\"%d\", &no_of_rows);\r\n\r\n    int maximum_pieces = (no_of_rows)*(no_of_rows/2) + (no_of_rows%2)*(no_of_rows/2 + no_of_rows%2);\r\n    printf(\"%d\\n\", maximum_pieces);\r\n\r\n    for(int i = 1; i <= no_of_rows; i++)\r\n    {\r\n        if(i%2 == 1)\r\n        {\r\n            for(int j = 1; j <= no_of_rows; j++)\r\n                printf(\"%c\", j%2 == 0 ? '.' : 'C');\r\n        }\r\n        else\r\n        {\r\n            for(int j = 1; j <= no_of_rows; j++)\r\n                printf(\"%c\", j%2 == 0 ? 'C' : '.');\r\n        }\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Diversity Explanation.txt",
    "content": "\r\nThe idea is to keep one character of each letter and then be able to change the others. \r\n\r\nThe minimum changes = 0, if we already have more than k characters\r\n\r\n= k - distinct characters, otherwise\r\n\r\nCheck if minimum changes > changeable characters\r\n\r\n------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    char string[MAX_LENGTH];\r\n    int min_distinct_characters;\r\n    scanf(\"%s %d\", string, &min_distinct_characters);\r\n\r\n    int frequency[NO_OF_ALPHABETS] = {0};\r\n    for(int i = 0; string[i] != '\\0'; i++)\r\n    {\r\n        frequency[string[i] - 'a']++;\r\n    }\r\n\r\n    int no_of_distinct_characters = 0, no_of_changeable_characters = 0;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(frequency[i] > 0)\r\n        {\r\n            no_of_distinct_characters++;\r\n            no_of_changeable_characters += (frequency[i] - 1); //Keep one character\r\n        }\r\n    }\r\n\r\n    int minimum_changes = max(min_distinct_characters - no_of_distinct_characters, 0); //printf(\"NO of changes = %d\\n\", no_of_changeable_characters);\r\n\r\n    printf(minimum_changes > no_of_changeable_characters ? \"impossible\\n\" : \"%d\\n\",minimum_changes);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 19/Hamster Farm Explanation.txt",
    "content": "If you take box_i, number of remaining hamsters = Hamsters%box_i ... No of boxes = Hamsters/box_i\r\n\r\nMinimise the remainder.\r\n\r\n-----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long no_of_hamsters;\r\n    int no_of_boxes;\r\n    scanf(\"%I64d %d\", &no_of_hamsters, &no_of_boxes);\r\n\r\n    long long leftover_hamsters = 1e18, boxes_bought;\r\n    int box_type;\r\n\r\n    for(int i = 1; i <= no_of_boxes; i++)\r\n    {\r\n        long long box_i;\r\n        scanf(\"%I64d\", &box_i);\r\n\r\n        if(no_of_hamsters%box_i < leftover_hamsters)\r\n        {\r\n            leftover_hamsters = no_of_hamsters%box_i;\r\n            boxes_bought = no_of_hamsters/box_i;\r\n            box_type = i;\r\n        }\r\n    }\r\n\r\n    printf(\"%d %I64d\\n\", box_type, boxes_bought);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/K-Dominant Character Explanation.txt",
    "content": "\r\nAt first, I thought that if a string is K-dominant, it is also (K + 1)-dominant. \r\n\r\nIf it is not K-dominant, it is not (K - 1)-dominant either.\r\n\r\nThis suggests binary search, How to check if a string is x dominant ?\r\n\r\nDo 26 O(n) scans. For each alphabet, check if it occurs at least once in every substring of length x. \r\n\r\nNow, if there's at least one alphabet that satisfies this, the string is x-dominant.\r\n\r\n--------------------------------------------------------------\r\n\r\nint is_possible(int k, int length)\r\n{\r\n    for(int alphabet = 0; alphabet < NO_OF_LETTERS; alphabet++)\r\n    {\r\n        int alphabet_occurs_in_every_segment = true;\r\n\r\n        for(int left = 1, right = k; right <= length; left++, right++)\r\n        {\r\n            int alphabet_frequency_here = frequency[alphabet][right] - frequency[alphabet][left - 1];\r\n\r\n            if(alphabet_frequency_here == 0)\r\n                alphabet_occurs_in_every_segment = false;\r\n        }\r\n\r\n        if(alphabet_occurs_in_every_segment)\r\n            return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\n---------------------------------------------------------------\r\n\r\nDo binary search for this -\r\n\r\nint answer, start = 1, end = length;\r\n\r\n    while(start <= end)\r\n    {\r\n        int mid = (start + end) >> 1;\r\n\r\n        if(is_possible(mid, length))\r\n        {\r\n            if(!is_possible(mid - 1, length))\r\n            {\r\n                answer = mid;\r\n                break;\r\n            }\r\n            else\r\n            {\r\n                end = mid - 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            start = mid;\r\n        }\r\n    }\r\n\r\n------------------------------------------------------------------------------------\r\n\r\nProblem is this might take about 20 x 26 O(n) scans. \r\n\r\nThis is too much !\r\n\r\nHere's how we reduce it. \r\n\r\nThe idea of solving it seperately for each alphabet is correct, \r\n\r\nFor a given alphabet i, how do we find the minimum length k, such that the string is k-dominant for character i.\r\n\r\nThe minimum length is the maximum distance S, between any two consecutive occurences of i.\r\n\r\nIf k > S, then by definition we will have an i on the segment S. If K < S, then there is at least one segment which does not have i. \r\n\r\nNow, we find the k for all alphabets, and the minimum k is our answer !\r\n\r\n-------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_LETTERS = 26;\r\n    int length = S.size(), answer = S.size();\r\n\r\n    for(int alphabet = 0; alphabet < NO_OF_LETTERS; alphabet++)\r\n    {\r\n        int last_occurence = -1, largest_gap_for_this_alphabet = 0;\r\n\r\n        for(int i = 0; S[i] != '\\0'; i++)\r\n        {\r\n            if(S[i] == 'a' + alphabet)\r\n            {\r\n                largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, i - last_occurence);\r\n                last_occurence = i;\r\n            }\r\n        }\r\n\r\n        largest_gap_for_this_alphabet = max(largest_gap_for_this_alphabet, length - last_occurence);\r\n\r\n        answer = min(answer, largest_gap_for_this_alphabet);\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Little Artem and Grasshopper Explanation.txt",
    "content": "\r\nThey are asking you to emulate the grasshopper and perform DFS. \r\n\r\nIf you ever visit a previously visited square, you are stuck in a loop.\r\n\r\n-------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_strips;\r\n    char strip[NO_OF_STRIPS];\r\n    scanf(\"%d %s\", &no_of_strips, strip);\r\n\r\n    int jump[no_of_strips + 1];\r\n    int visited[no_of_strips + 1] = {false};\r\n\r\n    for(int i = 0; i < no_of_strips; i++)\r\n        scanf(\"%d\", &jump[i]);\r\n\r\n    int square = 0, stuck_forever;\r\n\r\n    while(true)\r\n    {\r\n        if(visited[square] == true)\r\n        {\r\n            stuck_forever = true;\r\n            break;\r\n        }\r\n\r\n        visited[square] = true;\r\n\r\n        if(strip[square] == '<')\r\n        {\r\n            if(square - jump[square] < 0)\r\n            {\r\n                stuck_forever = false;\r\n                break;\r\n            }\r\n\r\n            square -= jump[square];\r\n        }\r\n        else\r\n        {\r\n            if(square + jump[square] >= no_of_strips)\r\n            {\r\n                stuck_forever = false;\r\n                break;\r\n            }\r\n\r\n            square += jump[square];\r\n        }\r\n    }\r\n\r\n    printf(stuck_forever ? \"INFINITE\\n\" : \"FINITE\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Longest K Good Segment Explanation.txt",
    "content": "\r\nUse a sliding window (Two pointers). \r\n\r\nNotice that the window end increases by one each time \r\n\r\nSo, if S[l, l + 1, l + 2, ... , r] is a good segment and S[l, l + 1, .... , r, r + 1] is not a good segment, \r\n\r\nThen it means A[r + 1] is the (K + 1)th distinct character.\r\n\r\nPush L forward while the number of distince characters is more than k.\r\n\r\nWhen we do it like this, notice each character is visited at most two times (Once by L, once by R)\r\n\r\nSo, complexity = O(n)\r\n\r\nNotice we don't need to check S[l + 1, l + 2] S[l + 1, l + 2, l + 3], etc ... Because we know we have S[l, l + 1, .... , r]\r\n\r\nNo need of checking smaller segments. \r\n\r\n-------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, k;\r\n    scanf(\"%d %d\", &no_of_elements, &k);\r\n\r\n    vector <int> element(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &element[i]);\r\n\r\n    const int MAX = 1e6 + 1;\r\n    vector <int> frequency(MAX, 0);\r\n\r\n    int left = 1, right = 1, best_left, best_right, distinct_elements = 0, maximum_length = 0;\r\n    while(right <= no_of_elements)\r\n    {\r\n        frequency[element[right]]++;\r\n        distinct_elements += (frequency[element[right]] == 1);\r\n\r\n        while(distinct_elements > k)\r\n        {\r\n            frequency[element[left]]--;\r\n            distinct_elements -= (frequency[element[left]] == 0);\r\n            left++;\r\n        }\r\n\r\n        int current_segment_length = right - (left - 1);\r\n        if(current_segment_length > maximum_length)\r\n        {\r\n            maximum_length = current_segment_length;\r\n            best_left = left;\r\n            best_right = right;\r\n        }\r\n\r\n        right++;\r\n\r\n    }\r\n\r\n    printf(\"%d %d\\n\", best_left, best_right);\r\n    return 0;\r\n}\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Love Triangle Explanation.txt",
    "content": "\r\nThis problem is made a lot simpler because nobody likes himself. \r\n\r\nSo, if A-> B and B-> A, ... A does not like A .... So, this is not a traingle.\r\n\r\nA-> A never occurs either.\r\n\r\n\r\nNow, for every i, find p(i) and p(p(i)) ... If p(p(p(i))) = i, then we have a triangle ! Else we do not.\r\n\r\n------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_planes;\r\n    scanf(\"%d\", &no_of_planes);\r\n\r\n    vector <int> liked_by(no_of_planes + 1);\r\n    for(int i = 1; i <= no_of_planes; i++)\r\n        scanf(\"%d\", &liked_by[i]);\r\n\r\n    int love_triangle_exists = false;\r\n    for(int i = 1; i <= no_of_planes; i++)\r\n    {\r\n        int a = i;\r\n        int b = liked_by[a];\r\n        int c = liked_by[b];\r\n\r\n        if(a == liked_by[c])\r\n        {\r\n            love_triangle_exists = true;\r\n        }\r\n    }\r\n\r\n    printf(love_triangle_exists ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Nuts Explanation.txt",
    "content": "\r\nOne of those brute force questions where it's quite confusing to emulate the process. \r\n\r\nWhile you have dividers left, make as many divisions as allowed in the box. \r\n\r\nSee how many nuts you have stored till here and if you need more boxes. \r\n\r\n-------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int k, total_nuts, dividers, capacity;\r\n    scanf(\"%d %d %d %d\", &k, &total_nuts, &dividers, &capacity);\r\n\r\n    int boxes_used = 0, nuts_stored_till_here = 0;\r\n\r\n    while(nuts_stored_till_here < total_nuts)\r\n    {\r\n        boxes_used++;\r\n\r\n        int dividers_used_in_this_box = min(dividers, k - 1);\r\n        int nuts_in_this_box = (dividers_used_in_this_box + 1)*capacity;\r\n\r\n\r\n        dividers -= dividers_used_in_this_box;\r\n        nuts_stored_till_here += nuts_in_this_box;\r\n    }\r\n\r\n    printf(\"%d\\n\", boxes_used);\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Palindrome Transformation Explanation.txt",
    "content": "\r\nWe need to notice a few things. \r\n\r\nFirstly, it's always possible to make the string a palindrome. \r\n\r\nSecondly, it's enough to make one half of the string equal to the other half. \r\n\r\nThirdly, we have to make every element equal to it's reflection. That is, make A[i] = A[n - i - 1]\r\n\r\nFourthly, the number of vertical moves to make A[i] and A[n - i - 1] equal = min{A[i] - A[n - i - 1], 26 - A[i] + A[n - i - 1]}\r\n\r\nSo, we go over every pair of elements that is not equal and calculate the vertical moves required to make them equal.\r\n\r\nFifthly, calculate the leftmost and rightmost position of the cursor in the first half that is not equal to it's reflection.\r\n\r\nAnd then horizontal moves is whichever is minimum - (Cursor -> Leftmost->Rightmost or Cursor->Rightmost->Leftmost)\r\n\r\n--------------------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    string A;\r\n    int cursor;\r\n    cin >> n >> cursor >> A;\r\n\r\n    cursor--;\r\n    n--;\r\n\r\n    cursor = min(cursor, n - cursor);\r\n\r\n    int middle = n/2;\r\n\r\n    int leftmost = cursor, rightmost = cursor;\r\n    for(int i = cursor; i <= middle; i++)\r\n        if(A[i] != A[n - i])\r\n            rightmost = i;\r\n\r\n    for(int i = cursor; i >= 0; i--)\r\n        if(A[i] != A[n - i])\r\n            leftmost = i;\r\n\r\n    int vertical_moves = 0;\r\n    for(int i = leftmost; i <= rightmost; i++)\r\n        vertical_moves += min(abs(A[i] - A[n - i]), 26 - abs(A[i] - A[n - i]));\r\n\r\n\r\n    int horizontal_moves = min((cursor - leftmost) + (rightmost - leftmost), (rightmost - cursor) + (rightmost - leftmost));\r\n\r\n    int total_moves = horizontal_moves + vertical_moves;\r\n    cout << total_moves;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 19/Palindromic Supersequence Explanation.txt",
    "content": "\r\nThe simplest way to do this is to concatenate A with it's reverse. It is always guaranteed to be a palindrome.\r\n\r\nAlso, length is at most 2 x 10^3 <= 10^4\r\n\r\n---------------------------------------------------------------------------\r\n\r\nstring reverse(string A)\r\n{\r\n    string rev;\r\n\r\n    for(int i = A.size() - 1; i >= 0; i--)\r\n        rev += A[i];\r\n\r\n    return rev;\r\n}\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    string A_rev = reverse(A);\r\n    string B = A_rev + A;\r\n\r\n    cout << B;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Recursive Queries Explanation.txt",
    "content": "\r\nFirstly, for all n >= 10, f(n) < n. \r\n\r\nWhy is this important ?\r\n\r\nSo, g(n) = g(f(n)) ... We can calculate this bottom-up.\r\n\r\n--------------------------------------------------\r\n\r\nI didn't prove it during the contest. The editorial had a nice proof.\r\n\r\nLet N = n1 n2 n3 ... nk\r\n\r\nSo, product is at most = n1 x n2 x ... x nk\r\n\r\nNow, N = nk + 10n(k - 1) + ... + 10^(k - 1)n1\r\n\r\nNow, each nk is at most 9. \r\n\r\nProduct of digits <= 9^(k -1)n1 < 10^(k - 1)n1 < N\r\n\r\n-------------------------------------------------------\r\n\r\nThe key to note is that in the query [L, R, k], k is small < 10. \r\n\r\nSo, we precompute g(i, k) for all i <= 10^6 and all k < 10. This allows us to answer the query in O(1) time. \r\n\r\nHere is the main idea ... Since f(n) < n ... Whenever we are at i, we have all values of g(x), where x < i. \r\n\r\nWe simply find g(f(i))\r\n\r\nNow, while storing the answer ..., Here's what we do -\r\n\r\nLet answer(i, k) be the number of numbers in the range [1, i] for which g(i) = k. \r\n\r\nIf we know this, how can we calculate g(i + 1, k) ? \r\n\r\nThere are two possibilities - Either g(i + 1) = k, or g(i + 1) =/= k\r\n\r\nIf g(i + 1) =/= k, then Answer(i + 1, k) = Answer(i, k)\r\n\r\nIf g(i + 1) = k, then Answer(i + 1, k)  = Answer(i, k) + 1\r\n\r\nDo this for all k from 1 to 9.\r\n\r\nThis idea of precomputing the answers using a 2D array, I had come across in some SPOJ question a long time back. \r\n\r\n----------------------------------------------------------------\r\n\r\nconst int LIMIT = 1e6 + 5;\r\nint answer[LIMIT][10];\r\n\r\nint non_zero_digit_product(int n)\r\n{\r\n    int product = 1;\r\n\r\n    while(n)\r\n    {\r\n        product *= (n%10 != 0 ? n%10 : 1);\r\n        n /= 10;\r\n    }\r\n\r\n    return product;\r\n}\r\n\r\nvoid precompute()\r\n{\r\n    vector <int> g(LIMIT, 0);\r\n    for(int i = 1; i < LIMIT; i++)\r\n        g[i] = (i < 10 ? i : g[non_zero_digit_product(i)]);\r\n\r\n    for(int i = 1; i < LIMIT; i++)\r\n        answer[i][0] = 0;\r\n\r\n    for(int i = 1; i < LIMIT; i++)\r\n    {\r\n        for(int digit = 1; digit < 10; digit++)\r\n        {\r\n            answer[i][digit] = answer[i - 1][digit];\r\n        }\r\n\r\n        if(g[i] < 10)\r\n            answer[i][g[i]]++;\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    precompute();\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int left, right, k;\r\n        scanf(\"%d %d %d\", &left, &right, &k);\r\n\r\n        printf(\"%d\\n\", answer[right][k] - answer[left - 1][k]);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Run For Your Prize Explanation.txt",
    "content": "\r\nA takes the first i items, and B takes the remaining items from (I + 1) to N\r\n\r\nPrecompute the time taken by A for first i, and for B from (I + 1) to N\r\n\r\nFind the minimum value of A[i] + B[i + 1].\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> items(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &items[i]);\r\n\r\n    const int A_POSITION = 1;\r\n    vector <int> time_A(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) time_A[i] = (items[i] - A_POSITION);\r\n\r\n    const int B_POSITION = 1e6;\r\n    vector <int> time_B(no_of_elements + 2, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) time_B[i] = (B_POSITION - items[i]);\r\n\r\n    int minimum_time = B_POSITION + A_POSITION;\r\n\r\n    for(int i = 0; i <= no_of_elements; i++)\r\n    {\r\n        int time_if_A_picks_first_i = max(time_A[i], time_B[i + 1]);\r\n        minimum_time = min(minimum_time, time_if_A_picks_first_i);\r\n    }\r\n\r\n    printf(\"%d\\n\", minimum_time);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 19/Simple Strings Explanation.txt",
    "content": "\r\nHere's what we do. Be greedy. \r\n\r\nIf A[i] =/= A[i - 1], \r\n\r\nput A[i] into the answer, \r\n\r\nIf A[i] == A[i - 1], then put in some character other than A[i - 1] and A[i + 1]. \r\n\r\nOtherwise, put in A[i].\r\n\r\n-----------------------------------\r\n\r\nchar some_char_other_than(char a, char b)\r\n{\r\n    for(char ch = 'a'; ch <= 'z' ; ch++)\r\n        if(ch != a && ch != b)\r\n            return ch;\r\n}\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    string answer;\r\n    answer += A[0];\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        char predecessor = answer[answer.size() - 1];\r\n        char successor = (i + 1 == A.size() ? predecessor : A[i + 1]);\r\n\r\n        if(A[i] == predecessor)\r\n        {\r\n            answer += some_char_other_than(predecessor, successor);\r\n        }\r\n        else\r\n        {\r\n            answer += A[i];\r\n        }\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/The Useless Toy Explanation.txt",
    "content": "\r\nMake a map, that maps all possible positions the toy can take to an integer number. \r\n\r\nNotice that the number of spins is periodic about 4. We only need to consider the number of spins mod 4. \r\n\r\nThe answer is undefined if we can reach a position either both clockwise and anticlockwise, or never at all.\r\n\r\n-----------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    map <char, int> positions;\r\n\r\n    positions['v'] = 0;\r\n    positions['<'] = 1;\r\n    positions['^'] = 2;\r\n    positions['>'] = 3;\r\n\r\n    char start_position, end_position;\r\n    int no_of_spins;\r\n\r\n    scanf(\"%c %c %d\", &start_position, &end_position, &no_of_spins);\r\n    int first_position = positions[start_position];\r\n    int final_position = positions[end_position];\r\n\r\n    if( (first_position + no_of_spins%4)%4 == final_position && (first_position + (4 - no_of_spins%4))%4 == final_position)\r\n        printf(\"undefined\\n\");\r\n    else if( (first_position + no_of_spins%4)%4 == final_position)\r\n        printf(\"cw\\n\");\r\n    else if( (first_position + (4 - no_of_spins%4))%4 == final_position)\r\n        printf(\"ccw\\n\");\r\n    else\r\n        printf(\"undefined\\n\");\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Vasya and Socks Explanation.txt",
    "content": "Just simulate the process.\r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int socks, new_sock_day;\r\n    scanf(\"%d %d\", &socks, &new_sock_day);\r\n\r\n    int no_of_days = 0;\r\n\r\n    while(socks > 0)\r\n    {\r\n        no_of_days++;\r\n\r\n        if(no_of_days%new_sock_day == 0)\r\n            socks++;\r\n\r\n        socks--;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_days);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 19/Watchmen Explanation.txt",
    "content": "\nWe can see that if x1 = x2, or y1 = y2, then Euclidean distance = Manhattan distance. \n\nNow, by squaring both sides, it can be seen that Euclidean distance = Manhattan distance only if one or both of the coordinates are equal.\n\nWe need to count the number of pairs which have the same x, the number of pairs with the same y and \nsubtract the number of pairs with the same (x, y) because they're counted twice.\n\nO(n log n)\n\n---------------------------------------------------------------------------------------\n\nint main()\n{\n    int no_of_watchmen;\n    scanf(\"%d\", &no_of_watchmen);\n\n    map <int, int> x_frequency;\n    map <int, int> y_frequency;\n    map <pair<int, int>, int> x_and_y_frequency;\n\n    for(int i = 1; i <= no_of_watchmen; i++)\n    {\n        int x, y;\n        scanf(\"%d %d\", &x, &y);\n\n        x_frequency[x]++;\n        y_frequency[y]++;\n        x_and_y_frequency[make_pair(x,y)]++;\n    }\n\n    long long same_x_pairs = 0;\n    for(map <int, int> :: iterator it = x_frequency.begin(); it != x_frequency.end(); it++)\n    {\n        long long current_frequency = it->second;\n\n        same_x_pairs += (current_frequency*(current_frequency - 1))/2;\n    }\n\n    long long same_y_pairs = 0;\n    for(map <int, int> :: iterator it = y_frequency.begin(); it != y_frequency.end(); it++)\n    {\n        long long current_frequency = it->second;\n\n        same_y_pairs += (current_frequency*(current_frequency - 1))/2;\n    }\n\n    long long same_x_and_y_pairs = 0;\n    for(map <pair <int,int>, int> :: iterator it = x_and_y_frequency.begin(); it != x_and_y_frequency.end(); it++)\n    {\n        long long current_frequency = it->second;\n\n        same_x_and_y_pairs += (current_frequency*(current_frequency - 1))/2;\n    }\n\n    long long answer = same_x_pairs + same_y_pairs - same_x_and_y_pairs;\n    printf(\"%I64d\\n\", answer);\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Explanations/Explanations 19/Word Correction Explanation.txt",
    "content": "\r\nInsert a character from text to final text, only if final text last character is not a vowel.\r\n\r\n--------------------------------------------------------\r\n\r\nint is_vowel(char ch)\r\n{\r\n    switch(ch)\r\n    {\r\n        case 'a':\r\n        case 'e':\r\n        case 'i':\r\n        case 'o':\r\n        case 'u':\r\n        case 'y': return true;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string text;\r\n    cin >> length >> text;\r\n\r\n    string final_text;\r\n    final_text += text[0];\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        if(is_vowel(text[i]) && is_vowel(final_text[final_text.size() - 1]))\r\n        {\r\n               continue;\r\n        }\r\n\r\n        final_text += text[i];\r\n    }\r\n\r\n    cout << final_text;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Alena and the Heater Explanation.txt",
    "content": "\r\nNow, it's given that this is always possible. \r\n\r\nJust choose L and R greedily. \r\n\r\nIf B[i] == B[i - 1], don't do anything. \r\n\r\nOtherwise if B[i] = 1 and B[i - 1] = 0, since it's guaranteed that it's always possible, it's guranateed last 4 values of B are all 0s. Don't waste time checking.\r\n\r\nNow, among all such possibilities make the smallest L possible. L = 1 + max(A[i], A[i - 1], A[i - 2], A[i - 3], A[i - 4]) for this i, \r\n\r\nDo the same thing for all parts where B[i] = 0 and B[i - 1] = 1, and choose the maximum R possible, R = min(A[i], ... A[i - 4]) - 1 for this i.\r\n\r\n-----------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    vector <int> A(length + 1);\r\n    for(int i = 0; i < length; i++) cin >> A[i];\r\n\r\n    string B;\r\n    cin >> B;\r\n\r\n    int left = -1e9, right = 1e9;\r\n\r\n    for(int i = 4; i < length; i++)\r\n    {\r\n        if(B[i] == B[i - 1])\r\n            continue;\r\n\r\n        if(B[i] == '1')\r\n            left = max(left, max_5(A[i], A[i - 1], A[i - 2], A[i - 3], A[i - 4]) + 1);\r\n\r\n        if(B[i] == '0')\r\n            right = min(right, min_5(A[i], A[i - 1], A[i - 2], A[i - 3], A[i - 4]) - 1);\r\n    }\r\n\r\n    cout << left << \" \" << right;\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Fafa and Ancient Alphabet Explanation.txt",
    "content": "\r\nLet f(i, G) be the number of ways to fill up positions from i to N such that  A > B\r\n\r\nThe idea is that if you fill position i for equality, then at some point in between (i + 1, N) ... A > B\r\n\r\nIf you fill i such that A[i] > B[i], what comes after doesn't really matter.\r\n\r\n-----------------------------------------------------------------------------------------\r\n\r\nWhen do you say that A > B ? (For example, why do we say that 112345 is greater that 112333 ?\r\n\r\nThis is how we compare. First, we check if the lengths are equal. If they aren't the longer number is greater. \r\n\r\nIf they are equal, then there must be some position i, for which A[i] =/= B[i], and all j < i A[j] = B[j]\r\n\r\nThat is, there is some FIRST position where the strings aren't equal. The strings share a prefix before that. \r\n\r\n(In this case, it is 1123 - this is the common prefix. Note that if we were comparing 2562 and 7891, then the length of the common \r\nprefix is 0 Becasue the first unequal position is the first !)\r\n\r\nNow, we want to place a character at the i-th position of A, or B, or both, or neither (If they are both non-zero). \r\n\r\nHow do we do this ?\r\n\r\nSuppose A[i] = 0, and we fill a character at A[i] so that A[i] = B[i]\r\n\r\nFor instance, \r\nA =  0 1 2\r\nB =  5 1 0\r\n\r\nSuppose we fill A[1] = 5, then it means strings A and B are equal till position 1, and the number of ways of making A > B\r\n\r\nis equal to the number of ways of making A > B, by filling characters from (i + 1). There has to be SOME position after i + 1, after which A > B. So, we simply add f(i + 1, G) as that is exactly the information it contains.\r\n\r\nSo, f(i, G) = f(i + 1, G)\r\n\r\nIf we set A[i] = 6, then A is already greater than B .... And the 0s after position i can be filled by any of the m digits, and\r\nA will still be greater than B.\r\n\r\nf(i, G) = (M - B[i])*f(i + 1, ANY_WAY)\r\n\r\nBecause there are (M - B[i]) ways of filling position i so that A[i] > B[i]\r\n\r\nAnd only one way of filling A[i] so that A[i] = B[i]\r\n\r\nUltimately, f(i, G) = f(i + 1, G) + (M - B[i])*f(i + 1, ANY_WAY)\r\n\r\nI have just shown the case of A[i] = 0 and B[i] =/= 0.\r\n\r\nA similar analysis can be done to all possibilities. Just think how can we fill A[i] and B[i] ... How can we fill them for A = B, (In that case, count f(i + 1, G) and How can we fill them for A > B\r\n\r\n------------------------------------------------------------------------------------------\r\n\r\nf(i, A) be all the number of ways to fill up positions from i to N.\r\n\r\nif A[i] = 0 and B[i] = 0, \r\n\r\n\tthen we can fill up the same character in both A and B. We get C(M, 2) f(i + 1, A) or equal here M f(i + 1, G)\r\n\r\nif A[i] = 0\r\n\r\n\tf(i, G) = (M - B[i]) f(i + 1, A) + 1. f(i + 1, G)\r\n\r\nif B[i] = 0\r\n\r\n\tf(i, G) = (A[i] - 1) f(i + 1, A) + 1. f(i + 1, G)\r\n\r\nif A[i] > B[i]\r\n\r\n\tf(i, G) = f(i + 1, A)\r\n\r\nif A[i] < B[i]\r\n\r\n\tf(i, G) = 0\r\n\r\nif A[i] = B[i]\r\n\r\n\tf(i, G) = f(i + 1, G)\r\n\r\n----------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    const int MOD = 1e9 + 7;\r\n\r\n    int length, no_of_alphabets;\r\n    scanf(\"%d %d\", &length, &no_of_alphabets);\r\n\r\n    vector <int> A(length + 1);\r\n    for(int i = 1; i <= length; i++) scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> B(length + 1);\r\n    for(int i = 1; i <= length; i++) scanf(\"%d\", &B[i]);\r\n\r\n    int no_of_zeroes = 0;\r\n    for(int i = 1; i <= length; i++) no_of_zeroes += (A[i] == 0) + (B[i] == 0);\r\n\r\n    const int ANY_WAY = 0, GREATER = 1;\r\n    typedef vector <long long> v_ll;\r\n    vector <v_ll> no_of_ways(length + 5, v_ll(2, 1));\r\n\r\n    no_of_ways[length + 1][ANY_WAY] = 1;\r\n    no_of_ways[length + 1][GREATER] = 0;\r\n\r\n    for(int i = length; i >= 1; i--)\r\n    {\r\n        no_of_ways[i][ANY_WAY] = no_of_ways[i + 1][ANY_WAY];\r\n\r\n        if(A[i] == 0) no_of_ways[i][ANY_WAY] = (no_of_ways[i][ANY_WAY]*no_of_alphabets)%MOD;\r\n        if(B[i] == 0) no_of_ways[i][ANY_WAY] = (no_of_ways[i][ANY_WAY]*no_of_alphabets)%MOD;\r\n\r\n        if(A[i] == 0 && B[i] == 0)\r\n        {\r\n            long long choose_different_alphabets = choose_2(no_of_alphabets);\r\n            long long choose_same_alphabet = no_of_alphabets;\r\n\r\n            no_of_ways[i][GREATER] = choose_different_alphabets*no_of_ways[i + 1][ANY_WAY] + choose_same_alphabet*no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(A[i] == 0)\r\n        {\r\n            no_of_ways[i][GREATER] = (no_of_alphabets - B[i])*no_of_ways[i + 1][ANY_WAY] + no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(B[i] == 0)\r\n        {\r\n            no_of_ways[i][GREATER] = (A[i] - 1)*no_of_ways[i + 1][ANY_WAY] + no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(A[i] > B[i])\r\n        {\r\n            no_of_ways[i][GREATER] = no_of_ways[i + 1][ANY_WAY];\r\n        }\r\n        else if(A[i] == B[i])\r\n        {\r\n            no_of_ways[i][GREATER] = no_of_ways[i + 1][GREATER];\r\n        }\r\n        else if(A[i] < B[i])\r\n        {\r\n            no_of_ways[i][GREATER] = 0;\r\n        }\r\n\r\n        no_of_ways[i][ANY_WAY] %= MOD;\r\n        no_of_ways[i][GREATER] %= MOD;\r\n    }\r\n\r\n    long long numerator = no_of_ways[1][GREATER];\r\n    long long denominator = power(no_of_alphabets, no_of_zeroes, MOD);\r\n\r\n    long long answer = numerator*inverse(denominator, MOD);\r\n    answer %= MOD;\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Fafa and His Company Explanation.txt",
    "content": "\r\nNow, find the number of i, such that i | (n - i), excluding i = n.\r\n\r\nThis can be done in O(n)\r\n\r\nHowever, whenever i | (n - i) => i | n\r\n\r\nSo, count all of n's factors instead. It can be done in root(n).\r\n\r\n-------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int answer = 1;\r\n    for(int i = 2; i*i <= n; i++)\r\n        if(n%i == 0)\r\n            answer += (i*i == n ? 1 : 2);\r\n\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Fafa and the Gates Explanation.txt",
    "content": "\r\nOne way to do is keep track of the current half and then change x and y accordingly. \r\n\r\nBut, a much simpler way is to notice that you are at the line y = x, only when the number of R and U is equal\r\n\r\n\r\nFuther, you cross over, when you make the same step as you did to reach there. \r\n\r\nIf you reached y = x, using R, then you must be in the top half. Taking another R takes you to the lower half.\r\n\r\nIf you reached y = x, using L, then you must be in the lower half. Taking another U takes you to the upper half.\r\n\r\n\r\n------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_steps;\r\n    string steps;\r\n    cin >> no_of_steps >> steps;\r\n\r\n    int x = 0, y = 0, no_of_changes = 0;\r\n\r\n    for(int i = 0; i < no_of_steps - 1; i++)\r\n    {\r\n        if(steps[i] == 'U') y++;\r\n        if(steps[i] == 'R') x++;\r\n\r\n        no_of_changes += (x == y && steps[i] == steps[i + 1]);\r\n    }\r\n\r\n    cout << no_of_changes;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Fixing Typos Explanation.txt",
    "content": "\r\nBe greedy while constructing the string. \r\n\r\nInsert a character at the back of the string only if it doesn't violate the conditions.\r\n\r\nThis is optimal because the string we have so far is a legal string. \r\n\r\n----------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string A;\r\n    cin >> A;\r\n\r\n    string answer;\r\n\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        char last_character, second_last_character, third_last_character;\r\n\r\n        if(answer.size() >= 1) last_character = answer[answer.size() - 1];\r\n        if(answer.size() >= 2) second_last_character = answer[answer.size() - 2];\r\n        if(answer.size() >= 3) third_last_character = answer[answer.size() - 3];\r\n\r\n        if(answer.size() >= 2 && A[i] == last_character && last_character == second_last_character)\r\n            continue;\r\n\r\n        if(answer.size() >= 3 && A[i] == last_character && second_last_character == third_last_character)\r\n            continue;\r\n\r\n        answer += A[i];\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Gargari and Bishops Explanation.txt",
    "content": "\r\nFirstly, notice that if we colour the board black and white like a chess board, then two bishops of the same colour will always attack one common square at least.\r\n\r\nSo, we must place the bishops on different colours. \r\n\r\nWe must find the best black and the best white bishop. \r\n\r\nNow, to do this, notice that if you put a bishop on square (x, y), you will get all the points in the principal and secondary diagonal that passes through that square.\r\n\r\nPrecompute the diagonal sums. \r\n\r\nI was going to colour the squares like this - \r\n\r\n1 2 3 4\r\n5 1 2 3\r\n6 5 1 2\r\n7 6 5 1\r\n\r\nBut, the editorial made some brilliant observations. We don't need to explicitly colour the squares. \r\n\r\nThe secondary diagonal has the invariant (x + y)\r\n\r\nThe principal diagonal has the invariant (x - y). However, we want to avoid negative numbers and use array indices, so use (x - y + n).\r\n\r\nWe also need not colour the board black and white physically. \r\n\r\nNotice that all white squares have even (x + y), and all black squares must have odd (x + y), since black squares are always at a distance of 1 from a white square.\r\n\r\n----------------------------------------------------------------------------------------------------\r\n\r\nint colour(int x, int y)\r\n{\r\n    int sum = x + y;\r\n\r\n    return (sum%2 == 0 ? WHITE : BLACK);\r\n}\r\n\r\nint get_principal_diagonal_no(int x, int y, int n)\r\n{\r\n    return (x - y + n);\r\n}\r\n\r\nint get_secondary_diagonal_no(int x, int y)\r\n{\r\n    return (x + y);\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    memset(principal_diagonal_sum, 0, sizeof(principal_diagonal_sum));\r\n    memset(secondary_diagonal_sum, 0, sizeof(secondary_diagonal_sum));\r\n\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            scanf(\"%d\", &points[x][y]);\r\n\r\n            int principal_diagonal_no = get_principal_diagonal_no(x, y, n);\r\n            int secondary_diagonal_no = get_secondary_diagonal_no(x, y);\r\n\r\n            principal_diagonal_sum[principal_diagonal_no] += points[x][y];\r\n            secondary_diagonal_sum[secondary_diagonal_no] += points[x][y];\r\n        }\r\n    }\r\n\r\n    int white_x, white_y; long long white_best = 0;\r\n    int black_x, black_y; long long black_best = 0;\r\n\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            int principal_diagonal_no = get_principal_diagonal_no(x, y, n);\r\n            int secondary_diagonal_no = get_secondary_diagonal_no(x, y);\r\n            long long bishop_score = principal_diagonal_sum[principal_diagonal_no] + secondary_diagonal_sum[secondary_diagonal_no] - points[x][y];\r\n\r\n            if(colour(x, y) == WHITE)\r\n            {\r\n                if(bishop_score >= white_best)\r\n                {\r\n                    white_best = bishop_score, white_x = x, white_y = y;\r\n                }\r\n            }\r\n            else if(colour(x, y) == BLACK)\r\n            {\r\n                if(bishop_score >= black_best)\r\n                {\r\n                    black_best = bishop_score, black_x = x, black_y = y;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    long long best = black_best + white_best;\r\n    printf(\"%I64d\\n\", best);\r\n    printf(\"%d %d %d %d\", white_x, white_y, black_x, black_y);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Gargari and Permutations Alternate Solution Explanation.txt",
    "content": "\r\nLet f(i) be the maximum subsequence that can be constructed from the first i elements of the first vector. \r\n\r\nNow, f(i) = 1, at least. Because a subsequence of 1 is always possible. \r\n\r\nFor, all j < i\r\n\r\nLet Current = A[i], Previous = A[j], \r\n\r\nIf Previous comes before Current in all permutations, then f(i) = f(j) + 1\r\n\r\nChoose the best possible j\r\n\r\nAnswer = max{f(i)}\r\n\r\nThis is not as inspired as thinking in terms of a graph, but it gets the job done nonetheless. \r\n\r\n----------------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_permutations, length;\r\n    scanf(\"%d %d\", &length, &no_of_permutations);\r\n\r\n    for(int k = 1; k <= no_of_permutations; k++)\r\n    {\r\n        for(int i = 1; i <= length; i++)\r\n        {\r\n            scanf(\"%d\", &P[k][i]);\r\n            int element = P[k][i];\r\n            position[k][element] = i;\r\n        }\r\n    }\r\n\r\n    int answer = 1;\r\n\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        maximum_length_till[i] = 1;\r\n\r\n        for(int j = 1; j < i; j++)\r\n        {\r\n            int current = P[1][i], previous = P[1][j];\r\n            int previous_always_before_current = true;\r\n\r\n            for(int k = 1; k <= no_of_permutations; k++)\r\n            {\r\n                if(position[k][previous] > position[k][current])\r\n                {\r\n                    previous_always_before_current = false;\r\n                }\r\n            }\r\n\r\n            if(previous_always_before_current)\r\n            {\r\n                maximum_length_till[i] = max(maximum_length_till[i], 1 + maximum_length_till[j]);\r\n            }\r\n        }\r\n\r\n        answer = max(answer, maximum_length_till[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Gargari and Permutations Explanation.txt",
    "content": "\r\nHere's the main idea. \r\n\r\nIf a-b-c is a common subsequence, then a occurs before b and b occurs before c in all the permutations. \r\n\r\nSo, here's what we do. \r\n\r\nDraw an edge in between (i, j) if i comes before j in all the permutations. \r\n\r\nNow, in this graph, find the length of the longest path. \r\n\r\n--------------------------------------------------------------------------------------------------------------------\r\n\r\nint get_longest_path(int v)\r\n{\r\n    if(longest_path[v] != -1)\r\n        return longest_path[v];\r\n\r\n    longest_path[v] = 1;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        longest_path[v] = max(longest_path[v], 1 + get_longest_path(child));\r\n    }\r\n\r\n    return longest_path[v];\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_permutations, length;\r\n    scanf(\"%d %d\", &length, &no_of_permutations);\r\n\r\n    for(int k = 1; k <= no_of_permutations; k++)\r\n    {\r\n        for(int i = 1; i <= length; i++)\r\n        {\r\n            int element;\r\n            scanf(\"%d\", &element);\r\n            position[k][element] = i;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= length; i++)\r\n    {\r\n        for(int j = i + 1; j <= length; j++)\r\n        {\r\n            int i_always_before_j = true, j_always_before_i = true;\r\n\r\n            for(int k = 1; k <= no_of_permutations; k++)\r\n            {\r\n                if(position[k][i] > position[k][j])\r\n                {\r\n                    i_always_before_j = false;\r\n                }\r\n                if(position[k][j] > position[k][i])\r\n                {\r\n                    j_always_before_i = false;\r\n                }\r\n            }\r\n\r\n            if(i_always_before_j)\r\n            {\r\n                graph[i].push_back(j);\r\n            }\r\n            if(j_always_before_i)\r\n            {\r\n                graph[j].push_back(i);\r\n            }\r\n        }\r\n    }\r\n\r\n    memset(longest_path, -1, sizeof(longest_path));\r\n    int graph_longest_path = 0;\r\n    for(int i = 1; i <= length; i++)\r\n        graph_longest_path = max(graph_longest_path, get_longest_path(i));\r\n\r\n    printf(\"%d\\n\", graph_longest_path);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Hard Process Explanation.txt",
    "content": "\r\nHere's the trick. \r\n\r\nMaintain two pointers, [L, R]. \r\n\r\nWe want the largest segment with at most k 0s. \r\n\r\nnow, to do this fix L and let R go as far as possible till it has at most k 0s. \r\n\r\nOnce there are more than K 0's, then\r\n\r\nIncrement L till there are <= K 0's. \r\n\r\nNow, if R is at position X, when no of 0's = K + 1, \r\n\r\nThere is no need to start checking all segments from [L + 1, L + 2], [L + 1, L + 3], .... [L + 1, X] and so on and so forth. \r\n\r\nWe know that [L, X - 1] was a good segment. And all these segments are smaller than it. \r\n\r\nWe only need to check larger segments. So for every possible left from [L, X- 1], we check only larger intervals, [L + 1, X + 1] and so on. \r\n\r\nIf we know [L, X - 1] is a good segment, there is no need to check intervals smaller than that. \r\n\r\n---------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, max_zeroes;\r\n    scanf(\"%d %d\", &no_of_elements, &max_zeroes);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int no_of_0s = 0;\r\n    int change_left = 0, change_right = 0, left = 1, right = 1, max_window_size = 0;\r\n\r\n    while(right <= no_of_elements)\r\n    {\r\n        if(A[right] == 0)\r\n            no_of_0s++;\r\n\r\n        while(no_of_0s > max_zeroes)\r\n        {\r\n            if(A[left] == 0)\r\n                no_of_0s--;\r\n\r\n            left++;\r\n        }\r\n\r\n        int window_size = right - (left - 1);\r\n        if(window_size > max_window_size)\r\n        {\r\n            max_window_size = window_size, change_left = left, change_right = right;\r\n        }\r\n\r\n        right++;\r\n    }\r\n\r\n    for(int i = change_left; i <= change_right; i++) A[i] = 1;\r\n\r\n    printf(\"%d\\n\", max_window_size);\r\n    for(int i = 1; i <= no_of_elements; i++) printf(\"%d \", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Lisa and Dima Explanation.txt",
    "content": "\r\nIf n is a prime number, then k = 1\r\n\r\nElse, we need to check if n can be written as the sum of two prime numbers. \r\nThe sum of two odd numbers is never a prime number. So, one of the summands must be even, which means = 2.\r\n\r\n2 + (n - 2)\r\n\r\nWe need to check if (n - 2) is prime. \r\n\r\nOtherwise, we will always have answer with 3. \r\nWhy ?\r\nTake any odd prime p < n. Notice that (n - p) is an even number. \r\nBy Goldbach's conjecture, any even number in the specified range can be written as the sum of two prime numbers. \r\n\r\nNow, how do we find these three primes ?\r\nWe need to use the fact that the prime gap is never too large till 10^9. It is at most 300. \r\n\r\nSo, given N, ... We search for a prime number from [N, N - 300] .... We are guranteed to get a prime number. \r\n\r\nNow, we take the difference, N - p, which is an even number less than 300. \r\nWe can check with brute force how to sum up to 300 with two prime numbers.\r\n\r\n-----------------------------------------------------------------------------------------------------------------------\r\n\r\nvoid break_into_sum_of_primes(int N, int &prime_1, int &prime_2)\r\n{\r\n    vector <int> is_prime(N + 1, true);\r\n    sieve(is_prime);\r\n\r\n    for(int i = 2; i <= N; i++)\r\n    {\r\n        if(is_prime[i] && is_prime[N - i])\r\n        {\r\n            prime_1 = i;\r\n            prime_2 = N - i;\r\n            return;\r\n        }\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    if(is_prime(n))\r\n    {\r\n        printf(\"1\\n%d\\n\", n);\r\n        return 0;\r\n    }\r\n\r\n    if(is_prime(n - 2))\r\n    {\r\n        printf(\"2\\n%d %d\", 2, n - 2);\r\n        return 0;\r\n    }\r\n\r\n    int prime_1, prime_2, prime_3;\r\n\r\n    for(int i = n - 4; ; i--)\r\n    {\r\n        if(is_prime(i))\r\n        {\r\n            prime_3 = i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    break_into_sum_of_primes(n - prime_3, prime_1, prime_2);\r\n    printf(\"3\\n%d %d %d\\n\", prime_1, prime_2, prime_3);\r\n\r\n   return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Love Rescue Explanation.txt",
    "content": "\r\nDraw an edge in between any two alphabets that occur in the same position of different strings. \r\n\r\ni.e.  ... if A[i] =/= B[i], draw an edge in between them\r\n\r\nWe will have a graph. What we must do is make sure all the components stay connected but minimise the number of edges required. \r\n\r\nIf x can be reached from y in the original graph, it must be true for the new graph as well.\r\n\r\nNow, how do we do this ?\r\n\r\nFirstly, if a component has v vertices, it requires a minimum of (v - 1) edges to stay connected.\r\n\r\nIn the contest, I thought I was only allowed to delete edges, but it turns out you can construct your own graph just ensuring the same components are connected !\r\n\r\n(It's possible to do this by finding the MST of every component, but it's not required.)\r\n\r\nI made two solutions. In the first solution, every component had a sink, S that had an edge will all members of the component.\r\n\r\nIn the other solution, every component member had either 1 or 2 edges, depending on whether it was the first/last, or intermediate vertex.\r\n\r\nVery interesting question.\r\n    \r\n-----------------------------------------------------------------\r\n\r\nconst int MAX_N = 26;\r\nvector <int> graph[MAX_N];\r\nvector <int> visited(MAX_N, false);\r\nvector <int> component[MAX_N] ;\r\n\r\nvoid mark(int v, int component_no)\r\n{\r\n    visited[v] = true;\r\n    component[component_no].push_back(v); \r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(!visited[child])\r\n            mark(child, component_no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string A, B;\r\n    cin >> length >> A >> B;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        if(A[i] != B[i])\r\n        {\r\n            graph[A[i] - 'a'].push_back(B[i] - 'a');\r\n            graph[B[i] - 'a'].push_back(A[i] - 'a');\r\n        }\r\n    }\r\n\r\n    int component_no = 0, no_of_edges = 0;\r\n    for(int i = 0; i < MAX_N; i++)\r\n    {\r\n        if(graph[i].size() != 0 && !visited[i])\r\n        {\r\n            mark(i, component_no);\r\n            no_of_edges += component[component_no].size() - 1;\r\n\r\n            component_no++;\r\n        }\r\n    }\r\n\r\n    cout << no_of_edges << \"\\n\";\r\n    for(int i = 0; i < component_no; i++)\r\n    {\r\n        for(int j = 1; j < component[i].size(); j++)\r\n        {\r\n            cout << char('a' + component[i][j - 1]) << \" \" << char('a' + component[i][j]) << \"\\n\";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n----------------------------------------------------------------\r\n\r\nThe other solution with the sink would be printed like this - \r\n\r\nfor(int i = 0; i < component_no; i++)\r\n    {\r\n        for(int j = 1; j < component[i].size(); j++)\r\n        {\r\n            cout << char('a' + component[i][0]) << \" \" << char('a' + component[i][j]) << \"\\n\";\r\n        }\r\n    }"
  },
  {
    "path": "Explanations/Explanations 20/Mashmok and Numbers Explanation.txt",
    "content": "\r\nNotice that the smallest score possible is n/2 ... By making all consecutive numbers coprime.\r\n\r\nThe last (n - 2) numbers are such that gcd(A[i], A[i + 1])  = 1.\r\n\r\nSo, the minimum contribution = (n - 2)/2\r\n\r\nSo, make the gcd of the first two numbers T = S - (n - 2)/2. \r\n\r\nI used T, 2T\r\n\r\nNow, Score = 0, is possible only for n = 1\r\nn = 1 cannot reach any other score.\r\n\r\n-------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, score;\r\n    scanf(\"%d %d\", &n, &score);\r\n\r\n    int minimum_score = n/2;\r\n\r\n    if(n == 1 && score == 0) {printf(\"1\\n\"); return ;}\r\n    \r\n    if(n == 1 || score < minimum_score)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    int score_except_last_two = (n - 2)/2;\r\n    int second_term = score - score_except_last_two;\r\n\r\n    printf(\"%d %d \", second_term, 2*second_term);\r\n\r\n    for(int i = 3; i <= n; i++) printf(\"%d \", 2*second_term + i);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Non-Secret Cypher Explanation.txt",
    "content": "\r\nFor each element L, find the smallest R such that A[L, ... , R] is a good subarray. \r\n\r\nNotice that all subarrays starting at L and ending at least at R are good. There are N - R + 1 such arrays. \r\n\r\nSo, add (N - R + 1) to the answer. \r\n\r\nNotice that subarrays ending at R and starting at most by L are also good subarrays. There are L such arrays. \r\nNow, we don't add L to the answer because we'd be overcounting.\r\n\r\nWhen we are at L, we have already considered all subarrays starting at any position smaller than L. \r\n\r\nSo, don't count twice. \r\nWe should fix one end, either L or R and then find the other end.\r\n\r\n------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, no_of_equal_elements;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_equal_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int left = 1, right = 1;\r\n    long long no_of_subarrays = 0;\r\n\r\n    map <int, int> frequency;\r\n\r\n    while(right <= no_of_elements)\r\n    {\r\n        frequency[A[right]]++;\r\n\r\n        while(frequency[A[right]] == no_of_equal_elements)\r\n        {\r\n            no_of_subarrays += (no_of_elements - right + 1);\r\n\r\n            frequency[A[left]]--;\r\n            left++;\r\n        }\r\n\r\n        right++;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_subarrays);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Olympiad Explanation.txt",
    "content": "The number of awards is equal to the number of positive numbers greater than 0. \r\n\r\nNow, it can be done in O(n), but I used a set and did it in O(n log n)\r\n\r\n---------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    set <int> awards;\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int score;\r\n        scanf(\"%d\", &score);\r\n\r\n        if(score > 0) awards.insert(score);\r\n    }\r\n\r\n    printf(\"%u\\n\", awards.size());\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Partition Explanation.txt",
    "content": "\r\nNow, I would have done this by maintaining a sum of all positive numbers, P, sum of all negative numbers N\r\n\r\nAnd then P - N.\r\n\r\nBut the editorial solution was even more elegant. \r\n\r\nSum over abs(A[i])\r\n\r\nIt's a beautiful one-step observation that eschews some work. I loved it. I loved the element of surprise and how the two steps are combined. \r\n\r\n-----------------------------------------------------------------------------------\r\n\r\n#define abs(x) (x > 0 ? x : -x)\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    int answer = 0;\r\n    while(no_of_elements--)\r\n    {\r\n        int element;\r\n        scanf(\"%d\", &element);\r\n\r\n        answer += abs(element);\r\n    }\r\n\r\n    printf(\"%d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Petya and His Friends Alternate Solution Explanation.txt",
    "content": "\r\nBlog Link - http://qr.ae/TUTYGd\r\n\r\nRaziman told me about this brilliant solution. It was so creative, I had to code it myself !\r\nI loved it so much. \r\n\r\nHere's the idea ... \r\n\r\nWrite down all numbers from 1 to N in binary. \r\n\r\nFor each bit, associate prime P[i] if the bit is set, and prime Q[i] if bit is unset. \r\n\r\nFor example, we will associate 2 with all numbers which have the first bit set and 3 with all numbers which have the first bit unset.\r\n\r\nEvery pair of numbers which have a common bit, have a common factor. \r\n\r\nHave we covered all pairs ? No. \r\n\r\nWhat pairs are remaining, ... The pairs in which no two numbers have a common bit set. \r\n\r\nSo, for all (I, (n - 1)^I), we will associate another prime. \r\n\r\nAfter this, we have ensured that all pairs of numbers have a common prime factor (at least).\r\n\r\nNo prime divides all numbers. So, we are done ! This approach is beautiful and creative !\r\n\r\n--------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 300;\r\n    vector <int> primes;\r\n    precompute(primes, LIMIT);\r\n\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    if(n == 2)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    int N = nearest_power_of_2_greater_than(n);\r\n    vector <long long> A(N + 5, 1);\r\n\r\n    int first_free_prime = 0;\r\n\r\n    for(int bit = 0; (1 << bit) < N; bit++)\r\n    {\r\n        int set_bit_prime = primes[first_free_prime++];\r\n        int unset_bit_prime = primes[first_free_prime++];\r\n\r\n        for(int i = 1; i <= N; i++)\r\n        {\r\n            if(is_bit_set(i, bit))\r\n                A[i] *= set_bit_prime;\r\n            else\r\n                A[i] *= unset_bit_prime;\r\n        }\r\n    }\r\n\r\n    for(int i = 1; 2*i <= N; i++, first_free_prime++)\r\n    {\r\n        A[i]   *= primes[first_free_prime];\r\n        A[(N - 1)^i] *= primes[first_free_prime];\r\n    }\r\n\r\n    for(int i = 1; i <= n; i++)\r\n        printf(\"%I64d\\n\", A[i]);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Petya and His Friends Explanation.txt",
    "content": "Here was my solution, \n\nFirst assign every element other than A[2], a factor of 2. \n\nNow, assign every element other than A[3] a factor of 3.\n\nNow, assign every element other than A[1], a factor of 5. \n\nSince, gcd(A[1], A[2], A[3]) = 1, the gcd of the entire array = 1\n\nFirst three elements = (2 x 3, 3 x 5, 2 x 5, 2 x 3 x 5, 2 x 3 x 5 ... )\n\nNow, the first three elements are (6, 15, 10)\n\nNow, after that append 0's to every number from A[4] onwards just to make sure the numbers are different. \n\nSolution = (6, 15, 10, 60, 600, 6000, 60000, etc)\n\nImportant to know the corner case. No solution for N = 2\n\n---------------------------------------------------------------\n\nint main()\n{\n    int n;\n    scanf(\"%d\", &n);\n\n    if(n == 2)\n    {\n        printf(\"-1\\n\");\n        return 0;\n    }\n\n    printf(\"6\\n10\\n15\\n\");\n    for(int i = 4; i <= n; i++)\n    {\n        printf(\"6\"); for(int zero = 1; zero <= i - 4 + 1; zero++) printf(\"0\");\n        printf(\"\\n\");\n    }\n    return 0;\n}\n\n\n"
  },
  {
    "path": "Explanations/Explanations 20/Phone Numbers Explanation.txt",
    "content": "\r\nIf the length of the answer string is greater than |S|, then simply print S and then append the smallest character of (S) at the end. \r\n\r\nOtherwise k <= n. \r\n\r\nNow, we want to match the longest prefix possible. \r\n\r\nIF A > S ... then it means for some i, A[i] > S[i] and before that A[j] = S[j]\r\n\r\nWe want to maximise this i ... So we find the first i from the end for which a character greater than S[i] is available. \r\n\r\nA = S[1, ... , i] + first available greater character(S[i]) + smallest character of S (till length becomes k)\r\n\r\n--------------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length, answer_length;\r\n    string A;\r\n    cin >> length >> answer_length >> A;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> present(NO_OF_ALPHABETS, false);\r\n    for(int i = 0; i < A.size(); i++) present[A[i] - 'a'] = true;\r\n\r\n    char smallest_alphabet;\r\n    for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n    {\r\n        if(present[i])\r\n        {\r\n            smallest_alphabet = 'a' + i;\r\n            break;\r\n        }\r\n    }\r\n\r\n    if(answer_length > length)\r\n    {\r\n        cout << A;\r\n        for(int i = A.size(); i < answer_length; i++) cout << smallest_alphabet;\r\n\r\n        return 0;\r\n    }\r\n\r\n    int first_change_point;\r\n    char char_at_first_change_point;\r\n    for(int i = answer_length - 1; i >= 0; i--)\r\n    {\r\n        int greater_char_available = false;\r\n\r\n        for(char alphabet = A[i] + 1; alphabet <= 'z'; alphabet++)\r\n        {\r\n            if(present[alphabet - 'a'])\r\n            {\r\n                greater_char_available = true;\r\n\r\n                first_change_point = i;\r\n                char_at_first_change_point = alphabet;\r\n\r\n                break;\r\n            }\r\n        }\r\n\r\n        if(greater_char_available) break;\r\n    }\r\n\r\n    for(int i = 0; i < first_change_point; i++) cout << A[i];\r\n    cout << char_at_first_change_point;\r\n    for(int i = first_change_point + 1; i < answer_length; i++) cout << smallest_alphabet;\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Pocket Book Explanation.txt",
    "content": "\r\nLet's say you want string \r\n\r\nS[1],S[2], ... , S[m]\r\n\r\nThen first, swap string 1, with string X with prefix length = m, X is whichever string the character S[m] is from. \r\n\r\nThen do the same for S[m - 1], and so on. \r\n\r\nYou can get any combination that is possible. \r\n\r\nThe answer = product of distinct characters at each position. \r\n\r\nNow, I missed it. However, I have seen similar constructive type problems. The idea occurs in some Digit DPs too. Fix every character from right to left. \r\nI don't know why I didn't realise this. Maybe I wasn't interpreting this as a constructive problem and asking myself how to construct a string. \r\n\r\n---------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_names, length;\r\n    cin >> no_of_names >> length;\r\n\r\n    set <int> distinct_characters[length];\r\n\r\n    while(no_of_names--)\r\n    {\r\n        string name;\r\n        cin >> name;\r\n\r\n        for(int i = 0; i < length; i++)\r\n            distinct_characters[i].insert(name[i]);\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long total_strings = 1;\r\n\r\n    for(int i = 0; i < length; i++)\r\n    {\r\n        total_strings = (total_strings*distinct_characters[i].size())%MOD;\r\n    }\r\n\r\n    cout << total_strings;\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Points on the Line Explanation.txt",
    "content": "\r\nFirst sort the sequence.\r\n\r\nFor each i, calculate how many elements would need to be removed if A[i] was the first element. \r\n\r\nWe remove (i - 1) elements from the back ... Let j be the first element position that A[j] - A[i] > d\r\n\r\nIn that case, we need to remove all elements from j to n. This is given by n - (j - 1) = n - j + 1\r\n\r\nNote that in case j = n + 1, this formula still works and we will remove 0 elements.\r\n\r\n----------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n, d;\r\n    scanf(\"%d %d\", &n, &d);\r\n\r\n    vector <int> A(n + 1, 0);\r\n    for(int i = 1; i <= n; i++) scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int removed_elements = n;\r\n\r\n    for(int i = 1; i <= n; i++)\r\n    {\r\n        int removed_elements_to_start_at_i = i - 1, j = i;\r\n\r\n        while(j <= n && A[j] - A[i] <= d)\r\n            j++;\r\n\r\n        removed_elements_to_start_at_i += (n - j + 1);\r\n\r\n        removed_elements = min(removed_elements, removed_elements_to_start_at_i);\r\n    }\r\n\r\n    printf(\"%d\\n\", removed_elements);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/Protect Sheep Explanation.txt",
    "content": "\r\nIf there are a wolf and a sheep in adjacent cells, the answer is no. Else it is always yes.\r\n\r\n---------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n    char pasture[rows + 5][columns + 5];\r\n\r\n    for(int r = 1; r <= rows; r++)\r\n        scanf(\"%s\", pasture[r] + 1);\r\n\r\n    int is_possible = true;\r\n\r\n    for(int r = 1; r <= rows; r++)\r\n    {\r\n        for(int c = 1; c <= columns; c++)\r\n        {\r\n            if(pasture[r][c] == 'W')\r\n            {\r\n                if(pasture[r + 1][c] == 'S' || pasture[r][c + 1] == 'S' || pasture[r - 1][c] == 'S' || pasture[r][c - 1] == 'S')\r\n                {\r\n                    is_possible = false;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    if(!is_possible)\r\n    {\r\n        printf(\"No\\n\");\r\n        return 0;\r\n    }\r\n\r\n    printf(\"Yes\\n\");\r\n    for(int r = 1; r <= rows; r++)\r\n    {\r\n        for(int c = 1; c <= columns; c++)\r\n        {\r\n            char current_cell = (pasture[r][c] == '.' ? 'D' : pasture[r][c]);\r\n\r\n            printf(\"%c\", current_cell);\r\n        }\r\n        printf(\"\\n\");\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 20/String Transformation Explanation.txt",
    "content": "\r\nBe greedy. Try to get each character, as early as possible. \r\n\r\nLet, last = 'a' - 1\r\n\r\nat first. \r\n\r\nNow, scan through the string. \r\n\r\nIf S[i] <= last + 1, \r\n\r\nThen S[i] = last + 1, last = S[i]\r\n\r\n\r\nAt the end, check if last = 'z'.\r\n\r\n----------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    int last_found = 'a' - 1;\r\n\r\n    for(int i = 0; i < S.size() && last_found < 'z'; i++)\r\n    {\r\n        if(S[i] <= last_found + 1)\r\n        {\r\n            S[i] = last_found + 1;\r\n            last_found = S[i];\r\n        }\r\n    }\r\n\r\n    cout << (last_found == 'z' ? S : \"-1\");\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Sum and Replace Explanation.txt",
    "content": "\r\nNow, it happens that d(n) is a function that converges rapidly. Every number will ultimately be reduced to 2. \r\nIn the given range every number goes to 2 in at most 6 times. After that d(2) = 2 and d(1) = 1\r\n\r\nHow do we use this fact ? We can't use lazy propagation for a function like number of divisors. \r\n\r\nHere's what we do ... Use a segment tree for sum and another one for max. \r\n\r\nWhile performing an update check if the max of any node is <= 2. If it is, then we can ignore it as it won't change with the update.\r\n\r\nWe can afford to go to every leaf node and avoid nodes who's max <= 2. \r\nIn the worst case, we will do 6 O(n) scans ! Which is perfectly fine ! It's very reasonable. \r\n\r\nThis is an important trick to note in functions which converge rapidly. We can afford to change each element one-by-one and ignore nodes which have already hit the converged\r\npoint. \r\nWe won't be doing too many updates ... That's the main thing to learn here.\r\n\r\nAgain the idea of a segment tree is to break the query interval into intervals that either lie completely with an interval or ones that lie completely outside the interval.\r\n\r\n---------------------------------------------------------\r\n\r\nvoid precompute_divisors()\r\n{\r\n    vector <int> largest_prime_factor(MAX_N, 0);\r\n    no_of_divisors[1] = 1;\r\n\r\n    for(int i = 2; i < MAX_N; i++)\r\n    {\r\n        if(largest_prime_factor[i] == 0)\r\n        {\r\n            for(int multiple = i; multiple < MAX_N; multiple += i)\r\n            {\r\n                largest_prime_factor[multiple] = i;\r\n            }\r\n        }\r\n\r\n        int exponent = 0, reduced_i = i;\r\n\r\n        while(reduced_i%largest_prime_factor[i] == 0)\r\n        {\r\n            reduced_i /= largest_prime_factor[i];\r\n            exponent++;\r\n        }\r\n\r\n        no_of_divisors[i] = (exponent + 1)*no_of_divisors[reduced_i];\r\n    }\r\n}\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n}\r\n\r\nlong long get_sum(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left)\r\n        return 0;\r\n\r\n    if(query_left <= left && right <= query_right)\r\n        return sum_tree[n];\r\n\r\n    int mid = (left + right) >> 1;\r\n    long long left_sum = get_sum(LEFT(n), left, mid, query_left, query_right);\r\n    long long right_sum = get_sum(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    return (left_sum + right_sum);\r\n}\r\n\r\nvoid update(int n, int left, int right, int query_left, int query_right)\r\n{\r\n    if(query_right < left || right < query_left || max_tree[n] <= 2)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        A[left] = no_of_divisors[A[left]];\r\n        max_tree[n] = sum_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    update(LEFT(n), left, mid, query_left, query_right);\r\n    update(RIGHT(n), mid + 1, right, query_left, query_right);\r\n\r\n    max_tree[n] = max(max_tree[LEFT(n)], max_tree[RIGHT(n)]);\r\n    sum_tree[n] = sum_tree[LEFT(n)] + sum_tree[RIGHT(n)];\r\n}\r\n\r\nint main()\r\n{\r\n    precompute_divisors();\r\n\r\n    int no_of_elements, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        const int SUM = 2, REPLACE = 1;\r\n        int query_type, left, right;\r\n        scanf(\"%d %d %d\", &query_type, &left, &right);\r\n\r\n        if(query_type == SUM)\r\n        {\r\n            long long sum = get_sum(1, 1, no_of_elements, left, right);\r\n            printf(\"%I64d\\n\", sum);\r\n        }\r\n        else if(query_type == REPLACE)\r\n        {\r\n            update(1, 1, no_of_elements, left, right);\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Vile Grasshoppers Explanation.txt",
    "content": "\r\nWe need to find the greatest number upto y, such that it is not divisible by any number from [2, p]. \r\n\r\nHere's a very important fact - Upto 10^9, the distance between consecutive primes is never more than 300 or so. \r\nNotice that any prime number P, is automatically co prime to every number [2, p]\r\n\r\nThis is a very important fact. This allows us to start from y, and keep decrementing 1 till we find a number who's smallest factor is > p. \r\n(We will never do more than 300 factorisation checks)\r\n\r\nAs for the factorisation itself ... we go from [2, min{p, root(i)}]. Either way, it's quite reasonable. Never more than 10^5. \r\n\r\n-------------------------------------------------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int p, y;\r\n    scanf(\"%d %d\", &p, &y);\r\n\r\n    int answer = y;\r\n\r\n    while(answer > p)\r\n    {\r\n        int coprime_till_p = true;\r\n\r\n        for(int i = 2; i <= p && i*i <= y; i++)\r\n        {\r\n            if(answer%i == 0)\r\n            {\r\n                coprime_till_p = false;\r\n                break;\r\n            }\r\n        }\r\n\r\n        if(coprime_till_p) break;\r\n\r\n        answer--;\r\n    }\r\n\r\n\r\n    printf(\"%d\\n\", answer == p ? -1 : answer);\r\n    return 0;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 20/Weird Subtraction Process Explanation.txt",
    "content": "Constraints are too big too simulate. The main observation is that if \r\n\r\na >= 2b, \r\n\r\nThen, we will keep subtracting a with 2b, till a < 2b. \r\n\r\nIn other words, a = a (mod 2b)\r\n\r\nThis is similar to the Euclidean GCD algorithm. A very beautiful problem, and a very beautiful logic.\r\n\r\n----------------------------------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long a, b;\r\n    cin >> a >> b;\r\n\r\n    while(a != 0 && b != 0 && (a >= 2*b || b >= 2*a))\r\n    {\r\n        if(a >= 2*b)\r\n        {\r\n            a %= (2*b);\r\n        }\r\n        else if(b >= 2*a)\r\n        {\r\n            b %= (2*a);\r\n        }\r\n    }\r\n\r\n    cout << a << \" \" << b;\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Aramic Script Bitmask Solution.txt",
    "content": "Maintain a binary string of length 26. \r\n\r\nConstruct a binary string with each given string as follows :\r\nThe i-th bit is set if the i-th alphabet is present in the string and 0 otherwise. Strings which have the same 'root' have the same mask. \r\n\r\nCount the number of distinct masks. \r\n\r\n------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <int> mask;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        int current_mask = 0;\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            current_mask |= (1 << (word[i] - 'a'));\r\n\r\n        mask.insert(current_mask);\r\n    }\r\n\r\n    cout << mask.size();\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Aramic Script Explanation.txt",
    "content": "For each string, keep track of which alphabets were used. \r\n\r\nAnd then make another string X, consisting of exactly one occurence of each of it's alphabets in alphabetical order. \r\n\r\nThis ensures strings which have the same root are mapped to the same X. \r\n\r\nCount the number of distinct X.\r\n\r\n----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_words;\r\n    cin >> no_of_words;\r\n\r\n    set <string> distinct_words;\r\n\r\n    while(no_of_words--)\r\n    {\r\n        string word;\r\n        cin >> word;\r\n\r\n        const int NO_OF_ALPHABETS = 26;\r\n        vector <int> present(NO_OF_ALPHABETS, false);\r\n\r\n        for(int i = 0; i < word.size(); i++)\r\n            present[word[i] - 'a'] = true;\r\n\r\n        string root;\r\n        for(int i = 0; i < NO_OF_ALPHABETS; i++)\r\n            if(present[i])\r\n                root += (char)('a' + i);\r\n\r\n        distinct_words.insert(root);\r\n    }\r\n\r\n    cout << distinct_words.size();\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Arithmetic Progression Explanation.txt",
    "content": "There are a lot of different cases to handle in this one !\r\n\r\nFirstly, if n = 1, then there are an infinite number of solutions.\r\n\r\n-----------------------------------------------\r\n\r\nThen, let us say there are n integers already in AP with d > 0, \r\n\r\nThen we can add two cards, one at A[0] - d, and A[0] + d. \r\n\r\nThe only exception is when n = 2, in that case, we can add a middle element too ! (This is an exception because doing this changes the d.) We can do this only if the middle elements is an integer.\r\n\r\n------------------------------------------------\r\n\r\nWhat to do if AP with d = 0 ? \r\n\r\nThen only one card can be inserted. \r\n\r\n-----------------------------------------------\r\n\r\nNow, the tricky case, what to do if it's not an AP, but every pair of consecutive numbers EXCEPT 1 is at a difference of d.\r\n\r\nWe have to check that if A[i] and A[i + 1] are not at a difference of d, \r\n\r\nThen A[i + 1] - A[i] = 2d\r\n\r\nSo we can insert a card in between them !\r\n\r\n---------------------------------------------\r\n\r\nWhile checking the d of the sequence, check the minimum d, because adding new elements decreases the d but never increases it. \r\n\r\n---------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_cards;\r\n    scanf(\"%d\", &no_of_cards);\r\n\r\n    vector <int> card(no_of_cards);\r\n    for(int i = 0; i < no_of_cards; i++) scanf(\"%d\", &card[i]);\r\n\r\n    if(no_of_cards == 1)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    vector <int> new_cards;\r\n\r\n    if(no_of_cards == 2 && (card[0] != card[1]) && (card[0] + card[1])%2 == 0)\r\n    {\r\n        new_cards.push_back( (card[0] + card[1])/2 );\r\n    }\r\n\r\n    sort(all(card));\r\n\r\n    int min_difference = card[1] - card[0];\r\n    for(int i = 2; i < no_of_cards; i++)\r\n        min_difference = min(min_difference, card[i] - card[i - 1]);\r\n\r\n    int ap_possible = true, new_middle_cards = 0;\r\n    for(int i = 1; i < no_of_cards; i++)\r\n    {\r\n        if(card[i] - card[i - 1] != min_difference)\r\n        {\r\n            if(card[i] - card[i - 1] == 2*min_difference)\r\n            {\r\n                new_middle_cards++;\r\n            }\r\n            else\r\n            {\r\n                ap_possible = false;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(ap_possible)\r\n    {\r\n        if(min_difference == 0)\r\n        {\r\n            new_cards.push_back(card[0]);\r\n        }\r\n        else if(new_middle_cards == 0)\r\n        {\r\n            new_cards.push_back(card[0] - min_difference);\r\n            new_cards.push_back(card[no_of_cards - 1] + min_difference);\r\n        }\r\n        else if(new_middle_cards == 1)\r\n        {\r\n            for(int i = 1; i < no_of_cards; i++)\r\n                if(card[i] - card[i - 1] == 2*min_difference)\r\n                    new_cards.push_back(card[i - 1] + min_difference);\r\n        }\r\n    }\r\n\r\n    sort(all(new_cards));\r\n\r\n    printf(\"%d\\n\", new_cards.size());\r\n    for(int i = 0; i < new_cards.size(); i++)\r\n        printf(\"%d \", new_cards[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Bash and a Tough Math Puzzle Explanation.txt",
    "content": "\r\nIf the gcd(L, R) is a multiple of x, then all we have to do is change any one element in the range to x. \r\n\r\nIf there is at most one element in the range which is not a multiple of x, we set it to x to make the gcd = x\r\n\r\nIf there are two elements which are not multiples of x, then it is impossible. \r\n\r\n--------------------------------\r\n\r\nSo, here's the idea - \r\n\r\n1. Look for the first element which is not a multiple of x. Let it be A[p]. \r\n\t\r\n\tIf it doesn't exist, then it is possible to make gcd = x.\r\n\r\n2. Look for the first element which is not a multiple of x in [p + 1, R]. \r\n\r\n\tIf it doesn't exist, then it is possible to make gcd = x.\r\n\r\n\tIf it exists, then answer is NO.\r\n\r\n----------------------------------------------\r\n\r\nNow, how to find the first element that is not a multiple of x ? \r\n\r\nMaintain a GCD-segment tree. \r\n\r\nIf the gcd of a node is a multiple of x, then don't look further. \r\n\r\nIf the gcd is not a multiple of x, then \r\n\r\n1. If it is a leaf node, then return the position of the leaf. \r\n2. Look in the left subtree first. If it is found in the left subtree, return the position.\r\n3. If it is not found in the left subtree, look in the right subtree. \r\n\r\n-----------------------------------------------------------------------------------------------------\r\n\r\nint gcd(int a, int b)\r\n{\r\n    if(a == 0 || b == 0)\r\n        return (a + b);\r\n    else\r\n        return gcd(min(a, b), max(a, b)%min(a, b));\r\n}\r\n\r\nvoid build(int n, int left, int right)\r\n{\r\n    if(left == right)\r\n    {\r\n        gcd_tree[n] = A[left];\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    build(LEFT(n), left, mid);\r\n    build(RIGHT(n), mid + 1, right);\r\n\r\n    gcd_tree[n] = gcd(gcd_tree[LEFT(n)], gcd_tree[RIGHT(n)]);\r\n}\r\n\r\nvoid update(int n, int left, int right, int index, int value)\r\n{\r\n    if(right < index || index < left)\r\n        return;\r\n\r\n    if(left == right)\r\n    {\r\n        gcd_tree[n] = value;\r\n        return;\r\n    }\r\n\r\n    int mid = (left + right) >> 1;\r\n    update(LEFT(n), left, mid, index, value);\r\n    update(RIGHT(n), mid + 1, right, index, value);\r\n\r\n    gcd_tree[n] = gcd(gcd_tree[LEFT(n)], gcd_tree[RIGHT(n)]);\r\n}\r\n\r\nint get_first_indivisible_element(int n, int left, int right, int query_left, int query_right, int x)\r\n{\r\n    if(gcd_tree[n]%x == 0 || right < query_left || query_right < left || right < left || query_right < query_left)\r\n        return NOT_FOUND;\r\n\r\n    if(left == right) //Leaf node and it's not divisible. So, it has to be this element.\r\n        return left;\r\n\r\n    int mid = (left + right) >> 1;\r\n\r\n    int left_answer = get_first_indivisible_element(LEFT(n), left, mid, query_left, query_right, x);\r\n\r\n    if(left_answer != NOT_FOUND)\r\n        return left_answer;\r\n\r\n    int right_answer = get_first_indivisible_element(RIGHT(n), mid + 1, right, query_left, query_right, x);\r\n\r\n    return right_answer;\r\n}\r\n\r\nvoid solve()\r\n{\r\n    const int GUESS_GCD = 1, UPDATE = 2;\r\n\r\n    int query_type;\r\n    scanf(\"%d \", &query_type);\r\n\r\n    if(query_type == GUESS_GCD)\r\n    {\r\n        int left, right, x;\r\n        scanf(\"%d %d %d\", &left, &right, &x);\r\n\r\n        int first_indivisible_element = get_first_indivisible_element(1, 1, no_of_elements, left, right, x);\r\n\r\n        if(first_indivisible_element == NOT_FOUND) //Entire range divisible by x.\r\n        {\r\n            printf(\"YES\\n\");\r\n        }\r\n        else if(first_indivisible_element != NOT_FOUND) //If 2 elements are not divisible by x, answer is NO. Else, if it is <= 1, answer is YES\r\n        {\r\n            int second_indivisible_element = get_first_indivisible_element(1, 1, no_of_elements, first_indivisible_element + 1, right, x);\r\n\r\n            printf(second_indivisible_element == NOT_FOUND ? \"YES\\n\" : \"NO\\n\");\r\n        }\r\n    }\r\n    else if(query_type == UPDATE)\r\n    {\r\n        int index, value;\r\n        scanf(\"%d %d\", &index, &value);\r\n\r\n        update(1, 1, no_of_elements, index, value);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    build(1, 1, no_of_elements);\r\n\r\n    int no_of_queries;\r\n    scanf(\"%d\", &no_of_queries);\r\n\r\n    while(no_of_queries--)\r\n        solve();\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Consecutive Subsequences Explanation.txt",
    "content": "Let f(A[i]) denote the longest sequence ending at A[i]. \r\n\r\nNow, A[i] is appended to the sequence ending at A[i] - 1\r\n\r\nSo, f(A[i]) = 1 + f(A[i] - 1)\r\n\r\nAs n is large use maps. Don't use unordered maps as unordered maps have worst case complexity O(n) so the algorithm degrades to O(n^2) and causes TLE.\r\n\r\n------------------------------\r\n\r\nI've solved two problems seperately. First, find the longest sequence length and the last element. \r\n\r\nThen collect the indices. \r\n\r\nIf I know the longest sequence has length L, and last element X\r\n\r\nThen I need to store the index of (X - L + 1) (X - L + 2) ... (X -1) (X)\r\n\r\nAt first the index list is empty. I store the index of element (X - L + 1). Then, after that store the index of i, where\r\nA[i] = A[index.back()] + 1\r\n\r\nBecause we know that i must be the index of the element that is one more than the last element in the list.\r\n\r\n----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    int last_element, longest_sequence = 0;\r\n\r\n    map <int, int> answer_with_last_element;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n       answer_with_last_element[A[i]] = 1 + answer_with_last_element[A[i] - 1];\r\n\r\n\r\n        if(answer_with_last_element[A[i]] > longest_sequence)\r\n        {\r\n            longest_sequence = answer_with_last_element[A[i]];\r\n            last_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <int> index;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(index.size() == 0)\r\n        {\r\n            if(A[i] == last_element - longest_sequence + 1)\r\n                index.push_back(i);\r\n        }\r\n        else if(A[i] == A[index.back()] + 1)\r\n        {\r\n            index.push_back(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", longest_sequence);\r\n    for(int i = 0; i < longest_sequence; i++) printf(\"%d \", index[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Cyclic Components Explanation.txt",
    "content": "Store each component in a seperate vector. \r\n\r\nIn the contest, I used a more complicated solution. But there's an easier solution with an observation - \r\n\r\nA component is a cycle if each vertex has degree 2. \r\n\r\nThis can be proven through induction. \r\n\r\n---------------------------------------------------------\r\n\r\nvoid dfs_and_mark_component(int v, int no)\r\n{\r\n    component[no].push_back(v);\r\n    component_no[v] = no;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(component_no[child] == UNMARKED)\r\n            dfs_and_mark_component(child, no);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, no_of_edges;\r\n    scanf(\"%d %d\", &no_of_vertices, &no_of_edges);\r\n\r\n    for(int i = 1; i <= no_of_edges; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    memset(component_no, UNMARKED, sizeof(component_no));\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(component_no[i] == UNMARKED)\r\n            dfs_and_mark_component(i, no_of_components++);\r\n    }\r\n\r\n    int no_of_cycles = 0;\r\n\r\n    for(int i = 0; i < no_of_components; i++)\r\n    {\r\n        int is_cycle = true;\r\n\r\n        for(int j = 0; j < component[i].size(); j++)\r\n        {\r\n            int v = component[i][j];\r\n\r\n            if(graph[v].size() != 2)\r\n            {\r\n                is_cycle = false;\r\n            }\r\n        }\r\n\r\n        no_of_cycles += (is_cycle == true);\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_cycles);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Divide by Three Multiply by Two Alternate Solution Explanation.txt",
    "content": "http://qr.ae/TUTyWZ\r\n\r\nFor any x, we cannot have both (2x and x/3) in the array. \r\n\r\nThis is because from x, we can go either to 2x or to x/3. \r\n\r\nIf we go to 2x, we can never reach x/3 as we can never divide by 2. \r\nSimilar reasoning for x/3. \r\n\r\nFor any element A[i], the chain from A[i] is uniquely determined. \r\n\r\nAll we need to do is find the first element. \r\n\r\nThis is the element x, for which x/2 and 3x are both absent from the array. \r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    map <ULL, int> present;\r\n    vector <ULL> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%I64u\", &A[i]);\r\n        present[A[i]] = true;\r\n    }\r\n\r\n    ULL first_element;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int comes_from_multiplication = (A[i]%2 == 0 && present[A[i]/2]);\r\n        int comes_from_division = (A[i] <= 1e18 && present[3*A[i]]);\r\n\r\n        if(!comes_from_multiplication && !comes_from_division)\r\n        {\r\n            first_element = A[i];\r\n        }\r\n    }\r\n\r\n    vector <ULL> solution;\r\n    solution.push_back(first_element);\r\n    while(solution.size() < no_of_elements)\r\n    {\r\n        ULL last_element = solution.back();\r\n        if(last_element%3 == 0 && present[last_element/3])\r\n        {\r\n               solution.push_back(last_element/3);\r\n        }\r\n        else\r\n        {\r\n            solution.push_back(2*last_element);\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", solution[i]);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Divide by Three, Multiply by Two Explanation.txt",
    "content": "http://qr.ae/TUTyWZ\r\n\r\nNotice that Exp(3) only decreases from left to right. \r\n\r\nExp(2) only increases. \r\n\r\n-Exp(3) only increases. \r\n\r\nThis means Exp(2) - Exp(3) increases from left to right. \r\n\r\nIn going from one element to another, only one of these values changes by 1. \r\n\r\nSO, the quantity Exp(2) - Exp(3) is a monotonic and increases by 1 for each element. \r\n\r\nThe beautiful solution is to simply sort the array according to (Exp(2) - Exp(3))\r\n\r\n-------------------------------------\r\n\r\nstruct info\r\n{\r\n    int two, three;\r\n    unsigned long long number;\r\n};\r\n\r\nint compare(const info &A, const info &B)\r\n{\r\n    if(A.two - A.three < B.two - B.three)\r\n        return true;\r\n    else\r\n        return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <info> A(no_of_elements);\r\n\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        unsigned long long element;\r\n        scanf(\"%I64u\", &element);\r\n\r\n        A[i].number = element;\r\n        A[i].two = 0, A[i].three = 0;\r\n\r\n        while(element%2 == 0) A[i].two++, element /= 2;\r\n        while(element%3 == 0) A[i].three++, element /= 3;\r\n    }\r\n\r\n    sort(all(A), compare);\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%I64u \", A[i].number);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Dreamoon and Sets Explanation.txt",
    "content": "For the explanation, refer to this blog post - \r\n\r\nhttps://mathprogrammer.quora.com/4147697-1?share=fcd3169f&srid=F7Hz\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_sets, k;\r\n    scanf(\"%d %d\", &no_of_sets, &k);\r\n\r\n    int maximum_number = (6*(no_of_sets - 1) + 5)*k;\r\n    printf(\"%d\\n\", maximum_number);\r\n\r\n    for(int i = 0; i < no_of_sets; i++)\r\n    {\r\n        const int NO_OF_TERMS = 4;\r\n        int mod[NO_OF_TERMS] = {1, 2, 3, 5};\r\n\r\n        for(int m = 0; m < NO_OF_TERMS; m++)\r\n        {\r\n            int term = (6*i + mod[m])*k;\r\n            printf(\"%d \", term);\r\n        }\r\n        printf(\"\\n\");\r\n\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/File Name Explanation.txt",
    "content": "For every character i, check if the previous two characters were x, if it was, then remove it. \r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    int removable_characters = 0;\r\n    for(int i = 2; i < length; i++)\r\n       removable_characters += (S[i] == 'x' && S[i - 1] == 'x' && S[i - 2] == 'x');\r\n\r\n    cout << removable_characters;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Fox and Box Accumulation Explanation.txt",
    "content": "Let us make the observation - \r\n\r\nIf p piles are possible, then it is possible to make p + 1 piles as well, if p + 1 <= N, \r\n\r\nWe do this by simply taking the top of any one pile and making a new pile. \r\n\r\nIf p piles are not possible, then even p - 1 piles are not possible. \r\n\r\n-------------------------------------\r\n\r\nWe are looking for a number P, such that P piles are possible but P - 1 piles are not !\r\n\r\nWe can do this by binary search !\r\n\r\n------------------------------------------\r\n\r\nYou have a number P, how do you check if P piles are possible ? \r\n\r\nFirstly, we shall choose the P boxes with the highest strength and then make a pile with each box as the first stone. We only keep track of the strength of the box on top of each pile.\r\n\r\nNow, we take each of the remaining boxes, starting from the one with the greatest strength and place it over the pile which has the highest strength box on top. \r\n\r\nThe new top = min(top - 1, new box)\r\n\r\nWe can place a new box on a pile as long as the strength of that pile's top > 0. \r\n\r\nIf we have been able to place all the boxes, then the answer is Yes to P.\r\nElse the answer is No.\r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_cards;\r\n    scanf(\"%d\", &no_of_cards);\r\n\r\n    vector <int> card(no_of_cards);\r\n    for(int i = 0; i < no_of_cards; i++) scanf(\"%d\", &card[i]);\r\n\r\n    if(no_of_cards == 1)\r\n    {\r\n        printf(\"-1\\n\");\r\n        return 0;\r\n    }\r\n\r\n    vector <int> new_cards;\r\n\r\n    if(no_of_cards == 2 && (card[0] != card[1]) && (card[0] + card[1])%2 == 0)\r\n    {\r\n        new_cards.push_back( (card[0] + card[1])/2 );\r\n    }\r\n\r\n    sort(all(card));\r\n\r\n    int min_difference = card[1] - card[0];\r\n    for(int i = 2; i < no_of_cards; i++)\r\n        min_difference = min(min_difference, card[i] - card[i - 1]);\r\n\r\n    int ap_possible = true, new_middle_cards = 0;\r\n    for(int i = 1; i < no_of_cards; i++)\r\n    {\r\n        if(card[i] - card[i - 1] != min_difference)\r\n        {\r\n            if(card[i] - card[i - 1] == 2*min_difference)\r\n            {\r\n                new_middle_cards++;\r\n            }\r\n            else\r\n            {\r\n                ap_possible = false;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(ap_possible)\r\n    {\r\n        if(min_difference == 0)\r\n        {\r\n            new_cards.push_back(card[0]);\r\n        }\r\n        else if(new_middle_cards == 0)\r\n        {\r\n            new_cards.push_back(card[0] - min_difference);\r\n            new_cards.push_back(card[no_of_cards - 1] + min_difference);\r\n        }\r\n        else if(new_middle_cards == 1)\r\n        {\r\n            for(int i = 1; i < no_of_cards; i++)\r\n                if(card[i] - card[i - 1] == 2*min_difference)\r\n                    new_cards.push_back(card[i - 1] + min_difference);\r\n        }\r\n    }\r\n\r\n    sort(all(new_cards));\r\n\r\n    printf(\"%d\\n\", new_cards.size());\r\n    for(int i = 0; i < new_cards.size(); i++)\r\n        printf(\"%d \", new_cards[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Ghosts Explanation.txt",
    "content": "Unlike most problems, this problems specifically asks us to overcount rather than avoid it. Each collision must be counted two times - once for each ghost. \r\n\r\nNow, the equation for the motion of a ghost = P + VT, where V is velocity, T is time and P is position. We have two dimensions and the equations need to be applied seperately on both. \r\n\r\nNow the trick is in noticing that two ghosts will intersect if the time for their x coordinates to be equal is the same as the Y.\r\n\r\nX1 + Vx1T = X2 + Vx2T\r\nX1 - X2 = T(Vx2 - Vx1)\r\nT = (X1 - X2)/(Vx2 - Vx1)\r\n\r\nAnd Y1 + Vy1T = Y2 + Vy2T\r\n\r\nY1 - Y2 = T(Vy2 - Vy1)\r\n\r\nT = (Y1 - Y2)/(Vy2 - Vy1)\r\n\r\n(X1 - X2)/(Vx2 - Vx1) = (Y1 - Y2)/(Vy2 - Vy1)\r\n\r\n(X1 - X2)/(Vx2 - Vx1) = (aX1 + b - aX2 - b)/(Vy2 - Vy1)\r\n\r\n(X1 - X2)/(Vx2 - Vx1) = a(X1 - X2)/(Vy2 - Vy1)\r\n\r\n1/(Vx2 - Vx1) = a/(Vy2 - Vy1)\r\n\r\nVy2 - Vy1 = aVx2 - aVx1\r\n\r\n-------------------------------\r\n\r\naVx1 - Vy1 = aVx2 - Vy2\r\n\r\nThis shows that ghosts which have the same aVx - Vy intersect at some point.\r\n\r\nHowever, we need to notice that if two ghosts are parallel (V1 = V2) then they never meet. \r\n\r\n---------------------------------\r\n\r\nTake each ghost. That ghost intersects with all ghosts who have aVx - Vy value, but not with those that have the same V. (Parallel)\r\n\r\nA very elegant way to keep track of slopes is to maintain a map of pairs. {Vx, Vy}. \r\n\r\nMaintain another map for {aVx - Vy}\r\n\r\n------------------------------------------\r\n\r\nMultiply the number of collisions by 2 at the end.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_points, a, b;\r\n    scanf(\"%d %d %d\", &no_of_points, &a, &b);\r\n\r\n    long long total_collisions = 0;\r\n    map < pair<int, int>, int > slope_count;\r\n    map <long long, int> intersections;\r\n\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        int x, vx, vy;\r\n        scanf(\"%d %d %d\", &x, &vx, &vy);\r\n\r\n        total_collisions += intersections[a*1LL*vx - vy] - slope_count[make_pair(vx, vy)]; //Parallel points don't meet.\r\n\r\n        slope_count[make_pair(vx, vy)]++;\r\n        intersections[a*1LL*vx - vy]++;\r\n    }\r\n\r\n    total_collisions *= 2;\r\n\r\n    printf(\"%I64d\\n\", total_collisions);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Less or Equal Explanation.txt",
    "content": "Let us sort the array. \r\n\r\nThe question is asking for any number in the range [A[k], A[k + 1] - 1]\r\n\r\nThis is not possible when A[k] = A[k + 1]\r\n\r\nOtherwise, just output A[k]\r\n\r\nThe special case is k = 0, when we must output a number smaller than all the elements of the array.\r\n\r\nIf A[1] = 1, then we cannot output any number as we must output a number that is at least 1. \r\nElse, we simply output 1.\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements, position;\r\n    scanf(\"%d %d\", &no_of_elements, &position);\r\n\r\n    vector <int> A(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    sort(all(A));\r\n\r\n    int answer;\r\n    if(position == 0)\r\n    {\r\n        answer = (A[1] > 1 ? 1 : -1);\r\n    }\r\n    else\r\n    {\r\n        answer = (position < no_of_elements && A[position] == A[position + 1] ? -1 : A[position]);\r\n    }\r\n    printf(\"%d\\n\", answer);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Little Girl and Maximum XOR Explanation.txt",
    "content": "Let L = 000110011\r\n\r\nR = 0001101111\r\n\r\nNotice that there must be some position p, where R[p] = 1, and L[p] = 0\r\n\r\nand for all i < p, R[p] = L[p]\r\n\r\nThe key observation here is that all numbers in between [L, R] will all have the same value for all those bits before p. The XOR of any two numbers will give 0. It doesnt contribute anything.\r\n\r\nNow, the largest possible XOR we can get is a number with p 1s since all the bits before that will always be 0 in any pair we choose.\r\n\r\nNow, Ill prove its always possible to get a number with p 1s.\r\n\r\nLet A match the common prefix of L and R.\r\n\r\nA[p] = 0, and let all positions after this = 1\r\n\r\nA is smaller than R for sure since R[p] = 1. It is >= L. It cant be smaller than L because it matches L till position P and from then has all 1s.\r\n\r\nLet B match the common prefix of L and R till p.\r\n\r\nB[p] = 1, and then all positions after that have 0.\r\n\r\nB is greater than L because B[p] = 1 > L[p]\r\n\r\nB is <= R because it matches R till position P and from there has all 0s.\r\n\r\n(A xor B) = a string of 1s.\r\n\r\nWe dont even need to find out what the numbers are ! \r\n\r\n----------------------------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    if(left == right)\r\n    {\r\n        printf(\"0\\n\");\r\n        return 0;\r\n    }\r\n\r\n    int largest_unequal_bit_position;\r\n\r\n    for(int i = 0; left > 0 || right > 0; i++)\r\n    {\r\n        if(left%2 != right%2)\r\n            largest_unequal_bit_position = i;\r\n\r\n        left >>= 1;\r\n        right >>= 1;\r\n    }\r\n\r\n    long long answer = all_ones(largest_unequal_bit_position); //This gives a number consisting of n 1's in binary\r\n    printf(\"%I64d\\n\", answer);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Lucky Sum of Digits Explanation.txt",
    "content": "Now, whenever x is possible, x + 4 is also possible\n\nAll numbers greater than 18 are possible\n\nsince (18, 19, 20, 21) are all possible. \n\nNow, we want to minimise the number of summands, so we maximise the number of 7s. \n\nLet N = 4x + 7y\n\nWe start with y = floor(n/7) and check if there exists an x. \n\nPrint x 4s followed by y 7s for the answer.\n\n--------------------------------------------------------------------------------------------\n\nint main()\n{\n    int sum;\n    scanf(\"%d\", &sum);\n\n    int possible = false;\n    int no_of_4s = 0, no_of_7s = sum/7;\n\n    while(no_of_7s >= 0)\n    {\n        if( (sum - 7*no_of_7s)%4 == 0)\n        {\n            no_of_4s = (sum - 7*no_of_7s)/4;\n            possible = true;\n            break;\n        }\n        no_of_7s--;\n    }\n\n    if(!possible)\n    {\n        printf(\"-1\\n\");\n        return 0;\n    }\n\n    for(int i = 1; i <= no_of_4s; i++) printf(\"4\");\n    for(int i = 1; i <= no_of_7s; i++) printf(\"7\");\n\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 21/Mahmoud and Ehab and Another Array Construction Test Explanation.txt",
    "content": "\r\nBlog Link - http://qr.ae/TUTAnY\r\n\r\nIf all the elements are pairwise coprime, then it means that no prime number occurs in the prime factorisation of two numbers.\r\n\r\nLet us keep an array Used[]\r\n\r\nUsed[x] = true, if prime factor x occurs in the factorisation of some A[i]. \r\nUsed[x] = false, otherwise. \r\n\r\nNow, we go through each A[i], \r\n\r\nIf all of A[i]'s prime factors are unused, then mark all of them and add A[i] to the solution. \r\n\r\nIf we get an A[i], which has at least one used prime factor, \r\n\r\nThen, x = A[i], \r\n\r\nwhile(all_prime_factors_unused(x))\r\n\tx++\r\n\r\nAnd then insert x to the solution. \r\n\r\nNow, we have lexicographically larger B. \r\n\r\nFrom here, onwards, we must print the smallest numbers that are not used. \r\n\r\nThese numbers must be prime. \r\n\r\nLet us suppose we have a composite numbe C. We can get a smaller number by replacing C with any of it's prime factors. \r\n\r\nSo, here's the overall algorithm.\r\n\r\n1. Push as many A[i] as possible. \r\n2. If an A[i] is not possible, x = A[i] + 1, keep incrementing till x is possible.\r\n3. After x, print the smallest unused primes. \r\n\r\n-----------------------------------------------------------------------------------------------\r\n\r\nvoid sieve(vector <int> &is_prime, int LIMIT)\r\n{\r\n    is_prime[0] = is_prime[1] = false;\r\n    for(long long i = 2; i*i <= LIMIT; i++)\r\n    {\r\n        if(is_prime[i])\r\n        {\r\n            for(long long multiple = i*i; multiple <= LIMIT; multiple += i)\r\n            {\r\n                is_prime[multiple] = false;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nint all_prime_factors_available(int n, vector <int> &used)\r\n{\r\n    for(int p = 2; p*p <= n; p++)\r\n    {\r\n        while(n%p == 0)\r\n        {\r\n            if(used[p] == true) return false;\r\n\r\n            n /= p;\r\n        }\r\n    }\r\n\r\n    if(n > 1 && used[n]) return false;\r\n\r\n    return true;\r\n}\r\n\r\nvoid mark_prime_factors(int n, vector <int> &used)\r\n{\r\n    for(int p = 2; p*p <= n; p++)\r\n    {\r\n        while(n%p == 0)\r\n        {\r\n            used[p] = true;\r\n\r\n            n /= p;\r\n        }\r\n    }\r\n\r\n    if(n > 1)\r\n        used[n] = true;\r\n}\r\n\r\nint main()\r\n{\r\n    const int LIMIT = 2e6;\r\n    vector <int> is_prime(LIMIT, true);\r\n    sieve(is_prime, LIMIT);\r\n\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> original(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &original[i]);\r\n\r\n    vector <int> solution;\r\n\r\n    vector <int> used(LIMIT, false);\r\n    for(int i = 0; i < no_of_elements; i++)\r\n    {\r\n        if(all_prime_factors_available(original[i], used))\r\n        {\r\n            solution.push_back(original[i]);\r\n\r\n            mark_prime_factors(original[i], used);\r\n        }\r\n        else\r\n        {\r\n            int x = original[i] + 1;\r\n            while(!all_prime_factors_available(x, used))\r\n                x++;\r\n\r\n            mark_prime_factors(x, used);\r\n\r\n            solution.push_back(x);\r\n            break;\r\n        }\r\n    }\r\n\r\n    for(int i = 2; i < LIMIT && solution.size() < no_of_elements; i++)\r\n    {   \r\n        if(!used[i] && is_prime[i])\r\n            solution.push_back(i);\r\n    }\r\n\r\n    for(int i = 0; i < no_of_elements; i++) printf(\"%d \", solution[i]);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Mahmoud and Ehab and Even Odd Game Explanation.txt",
    "content": "If n is even, then Mahmoud takes n and wins. \r\n\r\nIf n is odd, no matter what even number takes, he leaves an odd number for Ehab. Ehab then takes it and wins. \r\n\r\n-----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n    printf(n%2 == 0 ? \"Mahmoud\\n\" : \"Ehab\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Mahmoud and a Triangle Explanation.txt",
    "content": "\r\nLet us sort the sides. \r\n\r\nS[1] < S[2] < ... < S[n]\r\n\r\nLet us try to make S[i] the largest side of the triangle and match S[i] with S[i - 1], S[i - 2]\r\n\r\nIf we get a triangle, we are done. \r\n\r\nElse, S[i] >= S[i - 1] + S[i - 2]\r\n\r\nReplacing S[i - 1] or S[i - 2] by any other side will only give a smaller sum. \r\n\r\nSo, this means there is no triangle with S[i] as the largest side. \r\n\r\nWe need to do one O(n) scan after O(n log n) sorting to check if we can construct a triangle with each S[i] as the largest side. \r\n\r\n---------------------------------------------\r\n\r\nNote - There is an important optimisation here. \r\n\r\nLet us try to construct the smallest sequence of numbers which don't allow a triangle formation. \r\n\r\nFirst two numbers = 1, 1\r\n\r\nThe third number must satisfy S[i] >= S[i - 1] + S[i - 2]\r\n\r\nWe want the smallest possible S[i], So S[i] = S[i - 1] + S[i - 2]\r\n\r\nThis gives us the Fibonacci numbers. They grow quite rapidly and there are only 45 of them till 10^9. \r\n\r\nThis means that if there are more than 45 numbers, there must be some i in the series such that \r\n\r\nS[i] < Fibo[i] and for all j < i, S[j] >= Fibo[j]\r\n\r\nFibo[i] = Fibo[i - 1] + Fibo[i - 2] <= S[i - 1] + S[i - 2]\r\n\r\nS[i] < Fibo[i] <= S[i - 1] + S[i - 2]\r\n\r\nS[i] < S[i - 1] + S[i - 2]\r\n\r\n------------------------------------------------------------------------\r\n\r\nIf there are more than 45 numbers, the answer will always be yes ! Else, O(n log n + n). Actually O(n^3) naive solution is also possible among 45 numbers.\r\n\r\nint main()\r\n{\r\n    int no_of_sides;\r\n    cin >> no_of_sides;\r\n\r\n    const int FIBO_LIMIT_MAX_SIDES = 45;\r\n    if(no_of_sides > FIBO_LIMIT_MAX_SIDES)\r\n    {\r\n        cout << \"YES\\n\";\r\n        return 0;\r\n    }\r\n\r\n    vector <int> side(no_of_sides);\r\n    for(int i = 0; i < no_of_sides; i++) cin >> side[i];\r\n\r\n    sort(all(side));\r\n\r\n    int triangle_possible = false;\r\n    for(int i = no_of_sides - 1; i >= 2; i--)\r\n    {\r\n        if(side[i] < side[i - 1] + side[i - 2])\r\n        {\r\n            triangle_possible = true;\r\n            break;\r\n        }\r\n    }\r\n\r\n    cout << (triangle_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Make a Square Alternate Solution Explanation.txt",
    "content": "\r\nThis is more brute force. \r\n\r\nGenerate all squares less than N. \r\n\r\nCheck if each square is a subsequence of N. \r\n\r\nChoose the square which preserves the maximum digits. \r\n\r\nIt generalises less quickly than the bitmasks solution.\r\n\r\n---------------------------------------------------------------\r\n\r\nint is_subsequence(int sequence, int n)\r\n{\r\n    while(sequence > 0 && n > 0)\r\n    {\r\n        if(n%10 == sequence%10)\r\n        {\r\n            sequence /= 10;\r\n\r\n            if(sequence == 0)\r\n                return true;\r\n        }\r\n\r\n        n /= 10;\r\n    }\r\n\r\n    return false;\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int digit_count = no_of_digits(n), maximum_digits = 0;\r\n\r\n    for(int i = 0; square(i) <= n; i++)\r\n    {\r\n        if(is_subsequence(square(i), n) && no_of_digits(square(i)) > maximum_digits)\r\n        {\r\n            maximum_digits = no_of_digits(square(i));\r\n        }\r\n    }\r\n\r\n    int deleted_digits = digit_count - maximum_digits;\r\n    printf(deleted_digits == digit_count ? \"-1\\n\" : \"%d\\n\", deleted_digits);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Make a Square Explanation.txt",
    "content": "\r\nUse bitmasks. \r\n\r\nThe number will not have more than 10 digits. Have a bitmask of the same length as N. \r\n\r\nFor every mask, choose only those digits of N in which position the bit is set in mask.\r\n\r\nCheck if each mask is a square. And then check how many digits are deleted. Choose the square with the minimum deleted digits (or maximum preserved digits).\r\n\r\nI made a mistake here where leading 0s were included. Had to put in another condition to stop leading zeroes from being considered.\r\n\r\n\r\nThere's another approach. You can simply generate all squares upto 10^9 (About 3x10^4). And check if each square is a subsequence of n.\r\n\r\nThis approach generalises more easier. If n <= 10^18, we can't check all squares till 10^9, but we can still check all bitmasks till 2^18. \r\n\r\n----------------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    int digit_count = no_of_digits(n), maximum_digits = 0;\r\n    int digit[11];\r\n\r\n    for(int i = 0; i < digit_count; i++, n /= 10)\r\n        digit[i] = n%10;\r\n\r\n    for(int mask = (1 << digit_count) - 1; mask > 0; mask--)\r\n    {\r\n        int number = 0;\r\n\r\n        for(int i = digit_count - 1; i >= 0; i--)\r\n        {\r\n            if(is_bit_set(mask, i))\r\n                number = number*10 + digit[i];\r\n        }\r\n\r\n        if(is_square(number) && no_of_digits(number) > maximum_digits)\r\n            maximum_digits = no_of_digits(number);\r\n    }\r\n\r\n\r\n    int deleted_digits = digit_count - maximum_digits;\r\n    printf(deleted_digits == digit_count ? \"-1\\n\" : \"%d\\n\", deleted_digits);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Mancala Explanation.txt",
    "content": "There are only 14 hold. The problem is small enough to simulate. \r\n\r\nTake each hole. Calculate the answer if this hole was redistributed. And keep track of the best hole. \r\n\r\nHow to calculate the answer if a particular hole is distributed ? \r\n\r\nWell, let's say hole[i] has S stones. \r\n\r\nAnd let S = 14q + r, \r\nq is the quotient, r is the remainder, 0 <= r < 14\r\n\r\nNow, first of all set hole[i] = 0. \r\n\r\nThen all 14 holes will get an additional q stones. \r\n\r\nThen simulate the process of distributing the left out r stones. \r\n(Start from (i + 1) and give one stone to all holes till you run out of stones.)\r\n\r\nAfter this do an O(n) scan to find out the hole with the maximum number of stones. \r\n\r\nThis requires 3 O(n) scans.\r\n\r\nWe do this for all 14 holes. So 42 O(n) scans.\r\n\r\n------------------------------------------------------------\r\n\r\nlong long score_by_distributing(int chosen, vector <long long> stone, int no_of_holes)\r\n{\r\n    int quotient = stone[chosen]/no_of_holes, remainder = stone[chosen]%no_of_holes;\r\n\r\n    stone[chosen] = 0;\r\n\r\n    int current = chosen;\r\n    do\r\n    {\r\n        stone[current] += quotient;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n    while(current != chosen);\r\n\r\n    current = (chosen + 1)%no_of_holes;\r\n    while(remainder > 0)\r\n    {\r\n        stone[current]++;\r\n        remainder--;\r\n\r\n        current = (current + 1)%no_of_holes;\r\n    }\r\n\r\n    long long score = 0;\r\n    for(int i = 0; i < stone.size(); i++)\r\n        if(stone[i]%2 == 0)\r\n            score += stone[i];\r\n\r\n    return score;\r\n}\r\n\r\nint main()\r\n{\r\n    const int NO_OF_HOLES = 14;\r\n    vector <long long> stone(NO_OF_HOLES);\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        cin >> stone[i];\r\n\r\n    long long maximum_score = 0;\r\n    for(int i = 0; i < NO_OF_HOLES; i++)\r\n        maximum_score = max(maximum_score, score_by_distributing(i, stone, NO_OF_HOLES));\r\n\r\n    cout << maximum_score;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Pairs of Lines Explanation.txt",
    "content": "\r\nNotice that if there are upto 4 points, an answer is always possible. \r\n\r\nLet us take the first 3 points. By the Pigeonhole principle, at least 2 of these points have to lie on the same line. (3 points, 2 lines)\r\n\r\nLet us say P1, P2 are on the same line. (We need to check all 3 cases.)\r\n\r\nThen go through all the remaining points, If point i, is not on the same line as P1, P2, then put Pi in a Vector L2. \r\n\r\nAt the end check if all points on L2 lie on the same line. \r\n\r\nFor checking if a list of points lie on the same line, all we have to do is \r\n\r\ncheck_on_line(P[0], P[1], P[i]), for all i in the list. \r\n\r\n----------------------------------------------------------------------------------------------\r\n\r\nstruct Point{\r\n\r\nlong long x, y;\r\n\r\n};\r\n\r\nint is_on_line(Point a, Point b, Point c)\r\n{\r\n    //Checking slope product to avoid division\r\n    return ( (c.y - b.y)*(b.x - a.x) == (b.y - a.y)*(c.x - b.x) );\r\n}\r\n\r\nint check_line(vector <Point> &line)\r\n{\r\n    for(int i = 2; i < line.size(); i++)\r\n        if(!is_on_line(line[0], line[1], line[i]))\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint check_one_line_passing_through(int a, int b, vector <Point> &P)\r\n{\r\n    vector <Point> line_2;\r\n\r\n    for(int i = 1; i < P.size(); i++)\r\n    {\r\n        if(!is_on_line(P[a], P[b], P[i]))\r\n           line_2.push_back(P[i]);\r\n    }\r\n\r\n    int two_lines_possible = check_line(line_2);\r\n    return two_lines_possible;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <Point> P(no_of_points + 1);\r\n    for(int i = 1; i <= no_of_points; i++)\r\n        scanf(\"%I64d %I64d\", &P[i].x, &P[i].y);\r\n\r\n    int two_lines_possible = (no_of_points <= 4 || check_one_line_passing_through(1, 2, P)\r\n                              || check_one_line_passing_through(2, 3, P) || check_one_line_passing_through(3, 1, P));\r\n\r\n    printf(two_lines_possible ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 21/Two Gram Explanation.txt",
    "content": "There are only (n - 1) two-grams. \r\n\r\nKeep track of the frequency of each two-gram. \r\n\r\nThe most frequent two-gram is the answer.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    map <string, int> frequency;\r\n    int max_frequency = 0;\r\n    string answer;\r\n\r\n    for(int i = 0; i + 1 < length; i++)\r\n    {\r\n        string two_gram = S.substr(i, 2);\r\n        frequency[two_gram]++;\r\n\r\n        if(frequency[two_gram] > max_frequency)\r\n            max_frequency = frequency[two_gram], answer = two_gram;\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Valhalla Siege Explanation.txt",
    "content": "To kill i soldiers, we need to shoot S[1] + S[2] + ... + S[i] arrows. \r\n\r\nMaintain a prefix sum array. \r\n\r\nKeep track of the total number of arrows shot so far. If total_arrows >= S[n], then total_arrows = 0\r\n\r\nAfter that use binary search and find the smallest position i, such that total_arrows < S[i]. (i - 1) soldiers would have been dead at that time and the remaining N - i are alive. \r\n\r\n-----------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_soldiers, no_of_queries;\r\n    scanf(\"%d %d\", &no_of_soldiers, &no_of_queries);\r\n\r\n    vector <long long> strength(no_of_soldiers + 1);\r\n    for(int i = 1; i <= no_of_soldiers; i++)\r\n        scanf(\"%I64d\", &strength[i]);\r\n\r\n    vector <long long> sum(no_of_soldiers + 1, 0);\r\n    for(int i = 1; i <= no_of_soldiers; i++)\r\n        sum[i] = sum[i - 1] + strength[i];\r\n\r\n    long long total_arrows = 0;\r\n    while(no_of_queries--)\r\n    {\r\n        long long arrows;\r\n        scanf(\"%I64d\", &arrows);\r\n\r\n        total_arrows += arrows;\r\n\r\n        if(total_arrows >= sum[no_of_soldiers])\r\n            total_arrows = 0;\r\n\r\n        int no_of_dead_soldiers = upper_bound(all(sum), total_arrows) - sum.begin() - 1;\r\n\r\n        int no_of_alive_soldiers = no_of_soldiers - no_of_dead_soldiers;\r\n\r\n        printf(\"%d\\n\", no_of_alive_soldiers);\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 21/Wrong Subtraction Explanation.txt",
    "content": "The process is simple enough to simulate. \r\n\r\n----------------------------------\r\n\r\n#include <cstdio>\r\n\r\nint main()\r\n{\r\n    int n, no_of_operations;\r\n    scanf(\"%d %d\", &n, &no_of_operations);\r\n\r\n    while(no_of_operations--)\r\n    {\r\n        n = (n%10 == 0 ? n/10 : n - 1);\r\n    }\r\n\r\n    printf(\"%d\\n\", n);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/AND Graph Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUT6oy\r\n\r\nBasically,X&Y = 0, if Y is any submask of X's complement. \r\n\r\nSo perform DFS. Start from X\r\n\r\nFrom X visit all of the submasks of the complement of Y.\r\n\r\nMark N visited if you have visited all of it's submasks.\r\n\r\nIf any of the submasks are also present in the array, then visit all the submasks of it's complement as well !\r\n\r\nDo this recursively till all integers which can be reached starting from X (in the same component).\r\n\r\n------------------------------------------\r\n\r\nvoid dfs(int mask, int no_of_bits)\r\n{\r\n    if(visited[mask])\r\n        return;\r\n\r\n    visited[mask] = true;\r\n\r\n    for(int bit = 0; bit < no_of_bits; bit++)\r\n    {\r\n        if(mask&(1LL << bit))\r\n        {\r\n            int submask = mask - (1LL << bit);\r\n            dfs(submask, no_of_bits);\r\n        }\r\n    }\r\n\r\n    if(is_present[mask])\r\n        dfs(complement(mask, no_of_bits), no_of_bits);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_bits, no_of_vertices;\r\n    scanf(\"%d %d\", &no_of_bits, &no_of_vertices);\r\n\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        int x;\r\n        scanf(\"%d\", &x);\r\n        is_present[x] = true;\r\n    }\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 0; i < (1LL << no_of_bits); i++)\r\n    {\r\n        if(is_present[i] && !visited[i])\r\n        {\r\n            dfs(complement(i, no_of_bits), no_of_bits);\r\n            no_of_components++;\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_components);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 22/Almost Arithmetic Progression Explanation.txt",
    "content": "Any AP is uniquely determined by it's first two elements. \r\n\r\nLet us check all possible first two elements\r\n\r\nA[0] +/- 1 \r\nA[1] +/- 1\r\n\r\nFor each of the 9 possible first two terms, check if an AP with that difference is possible with only adding or subtracting one to each element. \r\n\r\nIf it's possible, then |term1 + k*d - A[k]| <= 1\r\n\r\nIf it is greater then it is not possible. \r\n\r\nIf |term1 + k*d - A[k]| = 1, no of operations++\r\n\r\nKeep track of the total no of operations and minimum total in all 9 configurations.\r\n\r\nIn my program, if it's not possible, I set the number of operations to oo.\r\n\r\n--------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements);\r\n    for(int i = 0; i < no_of_elements; i++) scanf(\"%d\", &A[i]);\r\n\r\n    const int oo = 1e7;\r\n    int add[3] = {-1, 0, 1}, min_operations = oo;\r\n\r\n    for(int i = 0; i < 3; i++)\r\n    {\r\n        int term_1 = A[0] + add[i];\r\n\r\n        for(int j = 0; j < 3; j++)\r\n        {\r\n            int term_2 = A[1] + add[j];\r\n\r\n            int difference = term_2 - term_1;\r\n\r\n            int no_of_operations = (term_1 != A[0]) + (term_2 != A[1]);\r\n\r\n            for(int k = 2; k < no_of_elements; k++)\r\n            {\r\n                if(abs(term_1 + k*difference - A[k]) == 1)\r\n                {\r\n                    no_of_operations++;\r\n                }\r\n                else if(abs(term_1 + k*difference - A[k]) > 1)\r\n                {\r\n                    no_of_operations = oo;\r\n                }\r\n            }\r\n\r\n            min_operations = min(min_operations, no_of_operations);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", min_operations >= oo ? -1 : min_operations);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Antipalindrome Alternate Solution Explanation.txt",
    "content": "The constraints are small enough to allow for an O(n^3) solution where all substrings are checked but there's an elegant O(n) solution !\r\n\r\nCase 1:\r\n\r\n\tS is not a palindrome, then answer = n.\r\n\r\nCase 2:\r\n\r\n\tS is a palindrome. \r\n\r\n\tthen we check S[1, ... , n - 1] and S[2, ... n]\r\n\r\n\tIf either of these strings are not a palindrome, then the answer = n - 1\r\n\r\nCase 3:\r\n\r\n\tS, S[1, ... , n - 1] and S[2, ... , n] are all palindromes. \r\n\r\nIn that case, \r\n\r\nNotice \r\n\r\nS[1] = S[n], from 1\r\n \r\nS[2] = S[n], from 3\r\n\r\nAlso, S[2] = S[n - 1], from 1\r\n\r\nAnd S[1] = S[n - 1], from 2\r\n\r\nSo, this implies S[1] = S[2] = S[n - 1] = S[n - 2]\r\n\r\nSimilarly, we see from 1, that S[i] = S[n - i]\r\nAnd S[i] = S[n - 1 - i]\r\n\r\nSo, S[n - i] = S[n - 1 - i]\r\n\r\nWe continually apply the above inequality to show that all characters are the same. \r\n\r\nIf that's the case, then ANY substring will be a palindrome. \r\n\r\n--------------------------------\r\n\r\nTherefore, the answer is either n, n - 1 or 0.\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n    int length = S.size();\r\n\r\n    if(!is_palindrome(S, 0, length - 1))\r\n        cout << length;\r\n    else if(!is_palindrome(S, 0, length - 2) || !is_palindrome(S, 1, length - 1))\r\n        cout << length - 1;\r\n    else\r\n        cout << \"0\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Antipalindrome Explanation.txt",
    "content": "N is very small. Check all choose(N, 2) substrings if they're palindromes, starting from the longest substrings.\r\n\r\nThis is O(N^3). \r\n\r\n---------------------------------------\r\n\r\nint is_palindrome(string S)\r\n{\r\n    for(int i = 0; i < S.size(); i++)\r\n        if(S[i] != S[S.size() - 1 - i])\r\n            return false;\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    for(int length = S.size(); length >= 1; length--)\r\n    {\r\n        for(int i = 0; i + length - 1 < S.size(); i++)\r\n        {\r\n            if(!is_palindrome(S.substr(i, length)))\r\n            {\r\n                cout << length;\r\n                return 0;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << \"0\";\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Ball Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpFlU\r\n\r\nYou have N triplets (A, B, C). \r\n\r\nSort the triplets by A. \r\n\r\nMaintain an array S, where the index is B and the value is C. Initially C is empty. \r\n\r\nProcess triplets in descending order of A. \r\n\r\nCheck if max{S[B[i] + 1, B[i] + 2, ... , N]} > C_i, \r\n\r\nIf yes, then we have found a triplet j such that \r\n\r\nA_j > A_i, because it was processed first. \r\nB_j > B_i, because we have queried in the range > B_i\r\nC_j > C_i, as we have just found out !\r\n\r\nWe compress the coordinates of B and maintain a segment tree over S. Otherwise, it once again degrades to O(n^2). But, with our beautiful segment tree, it's now O(n log n).\r\n\r\n------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_ladies;\r\n    scanf(\"%d\", &no_of_ladies);\r\n\r\n    vector <info> lady(no_of_ladies + 1);\r\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].beauty);\r\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].richness);\r\n    for(int i = 1; i <= no_of_ladies; i++) scanf(\"%d\", &lady[i].intellect);\r\n\r\n    sort(all(lady), sort_by_beauty);\r\n\r\n    vector <int> intelligence(no_of_ladies + 1, 0);\r\n    for(int i = 1; i <= no_of_ladies; i++) intelligence[i] = lady[i].intellect;\r\n\r\n    sort(all(intelligence));\r\n    map <int, int> iq_rank;\r\n\r\n    for(int i = 1; i <= no_of_ladies; i++)\r\n    {\r\n        iq_rank[intelligence[i]] = (intelligence[i] == intelligence[i - 1] ? iq_rank[intelligence[i - 1]] : i);\r\n    }\r\n\r\n    memset(max_tree, 0, sizeof(max_tree));\r\n\r\n    int suicides = 0;\r\n\r\n    for(int i = no_of_ladies; i >= 1; )\r\n    {\r\n        int j;\r\n\r\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\r\n        {\r\n            int max_richness_with_other_2_greater = get_max_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect] + 1, no_of_ladies);\r\n\r\n            if(max_richness_with_other_2_greater > lady[j].richness)\r\n                suicides++;\r\n        }\r\n\r\n        for(j = i; j >= 1 && lady[j].beauty == lady[i].beauty; j--)\r\n        {\r\n            insert_richness(1, 1, no_of_ladies, iq_rank[lady[j].intellect], lady[j].richness);\r\n        }\r\n\r\n        i = j;\r\n    }\r\n\r\n    printf(\"%d\", suicides);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Bits Explanation.txt",
    "content": "Blog Link - \r\n\r\nThe basic idea is that if L and R have different number of digits, than the answer consists of no_of_bits(R) - 1 ones.\r\n\r\nIf R is a string of all ones, then the answer is R.\r\n\r\nIf L and R have the same number of digits, then search for the first bit i, where L[i] = 0 and R[i] = 1, \r\nA will have the same prefix upto (i + 1). \r\n\r\nThen if R is a string of all ones from I till 0, then A[i] = A[i - 1] = ... = A[0] = 1, in other words A = R\r\n\r\nElse, A[i] = 0, and then A[i - 1] = A[i - 2] = ... = A[0] = 1\r\n\r\n\r\n---------------------------\r\n\r\nvoid solve()\r\n{\r\n    long long left, right;\r\n    scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n    long long answer = 0;\r\n\r\n    if(all_ones(no_of_bits(right)) == right)\r\n    {\r\n        answer = right;\r\n    }\r\n    else if(no_of_bits(left) != no_of_bits(right))\r\n    {\r\n        answer = all_ones(no_of_bits(right) - 1);\r\n    }\r\n    else if(no_of_bits(left) == no_of_bits(right))\r\n    {\r\n        for(int bit = 63; bit >= 0; bit--)\r\n        {\r\n            if(is_set(left, bit) && is_set(right, bit))\r\n            {\r\n                answer |= (1LL << bit);\r\n            }\r\n            else if(!is_set(left, bit) && is_set(right, bit)) //If L[i] = 0, and R[i] = 1\r\n            {\r\n                answer |= all_ones(bit); //Setting the current bit to 0, and then padding with 1s till the end.\r\n\r\n                if((answer|(1LL << bit)) <= right) //Checking if the current bit can also be 1\r\n                    answer |= (1LL << bit);\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Bookshelves Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTmQ6\r\n\r\nLet us answer, a related question. \r\n\r\nIf given a number x, how do we determine if it is possible to divide the numbers into K segments such that the bitwise AND of the sum of the K segments = x ? \r\n\r\nEach segment[L, R] has to obey the following property - \r\n\r\n(Sum[R] - Sum[L - 1])&x = x, \r\n\r\ni.e. all the bits that are set in x, must be set in the sum from [L, ... , R] for each of the K segments !\r\n\r\nWe can check this with dynamic programming. \r\n\r\nLet f(n, k) = true, if it is possible for the bitwise-AND of the sums of the first K segments = x, with the last segment ending on n.\r\nAnd f(n, k) = false, otherwise. \r\n\r\nf(R, K) = true, if there exists some L < R, such that \r\n\r\nSum[L ... R]&x = x and f(L - 1, K - 1) = true.\r\n\r\nIt takes us O(N^2 K) time to answer one such question. \r\n\r\nNow, let us be greedy and start from i = 60, and check if answer + 2^i is possible, if it is then the answer = answer + 2^i.\r\n\r\nThis is always optimal.\r\n\r\nOverall Complexity = O(log(max{A}) N^2 K)\r\n\r\n-----------------------------------------------\r\n\r\nint is_possible(LL goal)\r\n{\r\n    memset(possible, false, sizeof(possible));\r\n\r\n    possible[0][0] = true;\r\n\r\n    for(int part = 1; part <= no_of_parts; part++)\r\n    {\r\n        for(int right = 1; right <= no_of_elements; right++)\r\n        {\r\n            for(int left = 0; left < right; left++)\r\n            {\r\n                if( possible[left][part - 1] && ( ( (sum[right] - sum[left])&goal ) == goal ) )\r\n                {\r\n                    possible[right][part] = true;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    return possible[no_of_elements][no_of_parts];\r\n}\r\n\r\nint main()\r\n{\r\n    scanf(\"%d %d\", &no_of_elements, &no_of_parts);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%I64d\", &A[i]);\r\n\r\n    sum[0] = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        sum[i] = sum[i - 1] + A[i];\r\n\r\n    LL answer = 0;\r\n\r\n    for(int bit = MAX_BIT; bit >= 0; bit--)\r\n    {\r\n        if(is_possible(answer|(1LL << bit)))\r\n        {\r\n            answer |= (1LL << bit);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 22/Businessman Problems Explanation.txt",
    "content": "For every item x, \r\n\r\nwe add max{A_cost[x], B_cost[x]}\r\n\r\nIf x does not exist in either A or B, then it is 0. \r\n\r\nWe can use maps to do this !\r\n\r\nWhile reading A_cost, just read in cost[x].\r\n\r\nWhile reading B_cost, then cost[x] = max{cost[x], cost}\r\n\r\n-------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int a_elements;\r\n    scanf(\"%d\", &a_elements);\r\n\r\n    map <int, int> cost;\r\n    for(int i = 1; i <= a_elements; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n        cost[element_i] = cost_i;\r\n    }\r\n\r\n    int b_elements;\r\n    scanf(\"%d\", &b_elements);\r\n\r\n    for(int i = 1; i <= b_elements; i++)\r\n    {\r\n        int element_i, cost_i;\r\n        scanf(\"%d %d\", &element_i, &cost_i);\r\n\r\n        cost[element_i] = max(cost[element_i], cost_i);\r\n    }\r\n\r\n    long long total_cost = 0;\r\n    for(map <int, int> :: iterator it = cost.begin(); it != cost.end(); it++)\r\n    {\r\n        total_cost += it->second;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", total_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Chess Placing Explanation.txt",
    "content": "There are only two possibilities. At the end, either all the squares are on black squares or they're all on white squares. \r\n\r\nCalculate the number of moves if all pieces are on black squares, and if all the pieces are on white squares and the answer is the minimum of these two. \r\n\r\nTo calculate the minimum number of moves to put all pieces on squares of the same colour, it is always best to put on square i, the piece closest to it. \r\n\r\nSo Ans = |P[i] - 2i|, to put all pieces on even squares. \r\n\r\nOf course, the pieces must be sorted before this. \r\n\r\nThe proof is that if P[i] is the closest to 2i, if we replace P[i] by any piece > P[i], then we increase the number of moves. \r\n\r\n-----------------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    vector <int> A(n/2 + 1);\r\n    for(int i = 1; 2*i <= n; i++)\r\n        cin >> A[i];\r\n\r\n    sort(all(A));\r\n\r\n    int black_moves = 0;\r\n    for(int i = 1; 2*i <= n; i++)\r\n        black_moves += abs(A[i] - (2*i - 1));\r\n\r\n    int white_moves = 0;\r\n    for(int i = 1; 2*i <= n; i++)\r\n        white_moves += abs(A[i] - 2*i);\r\n\r\n    int minimum_moves = min(black_moves, white_moves);\r\n    cout << minimum_moves;\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Correct Solution Explanation.txt",
    "content": "If you are given N, the answer is all the digits of N in ascending order. \r\n\r\nIf N[0] = 0, then swap it with the first non zero number. (There's always a non zero digit, if the number of digits > 1 as there is no number consisting of multiple zeroes. However, a single 0 is a special case. Be careful. If it's only 0, then there's no non zero digit to replace it with.)\r\n\r\nCompare the answer with B.\r\n\r\n--------------------------------------------------------------\r\n\r\nstring solve(string S)\r\n{\r\n    vector <char> digits;\r\n    for(int i = 0; i < S.size(); i++)\r\n        digits.push_back(S[i]);\r\n\r\n    sort(all(digits));\r\n\r\n    if(digits[0] == '0')\r\n    {\r\n        int first_nonzero = 1;\r\n        while(first_nonzero < digits.size() && digits[first_nonzero] == '0')\r\n            first_nonzero++;\r\n\r\n        swap(digits[0], digits[first_nonzero]);\r\n    }\r\n\r\n    string answer;\r\n    for(int i = 0; i < digits.size(); i++)\r\n        answer += digits[i];\r\n\r\n    return answer;\r\n}\r\n\r\nint main()\r\n{\r\n    string A, B;\r\n    cin >> A >> B;\r\n\r\n    string answer = solve(A);\r\n\r\n    cout << ((answer == B) ? \"OK\\n\" : \"WRONG_ANSWER\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Couting Kangaroos is Fun Explanation.txt",
    "content": "At most N/2 kangaroos can hold a kangaroo. \r\n\r\nSo, it is always optimal for the lighter kangaroos to be held by the heavier kangaroos. This is exactly what we do. Divide into two sets of size N/2. \r\n\r\nAnd then greedily try to match them.\r\n\r\n-----------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_kangaroos;\r\n    scanf(\"%d\", &no_of_kangaroos);\r\n\r\n    vector <int> kangaroo_size(no_of_kangaroos);\r\n    for(int i = 0; i < no_of_kangaroos; i++)\r\n        scanf(\"%d\", &kangaroo_size[i]);\r\n\r\n    sort(all(kangaroo_size));\r\n\r\n    int no_of_pairs = 0;\r\n    int front_i = 0, back_i = no_of_kangaroos/2;\r\n    for( ; front_i < no_of_kangaroos/2 && back_i < no_of_kangaroos; front_i++)\r\n    {\r\n        while(back_i < no_of_kangaroos)\r\n        {\r\n            if(kangaroo_size[front_i]*2 <= kangaroo_size[back_i])\r\n            {\r\n                back_i++;\r\n                no_of_pairs++;\r\n                break;\r\n            }\r\n            else\r\n            {\r\n                back_i++;\r\n            }\r\n        }\r\n    }\r\n\r\n    int no_of_visible_kangaroos = no_of_pairs + (no_of_kangaroos - 2*no_of_pairs);\r\n    printf(\"%d\\n\", no_of_visible_kangaroos);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Fruits Explanation.txt",
    "content": "Keep track of the frequency of each fruit. \r\n\r\nTo minimise prices, the most frequent fruits, get the lowest prices. \r\n\r\nTo maximise prices, the most frequent fruits get the highest prices.\r\n\r\n------------------------------\r\n\r\nsort(all(fruit_frequency));\r\n    reverse(all(fruit_frequency));\r\n\r\n    long long min_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        min_price += price[i]*1LL*fruit_frequency[i];\r\n\r\n    reverse(all(price));\r\n    long long max_price = 0;\r\n    for(int i = 0; i < fruit_frequency.size(); i++)\r\n        max_price += price[i]*1LL*fruit_frequency[i];"
  },
  {
    "path": "Explanations/Explanations 22/High Schooll Become Human Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUTQHH\r\n\r\nYou can either compare the logarithms. \r\n\r\nOr, if x^y > y^x, then \r\n\r\ny log x > x log y\r\n\r\n(log x)/x > (log y)/y\r\n\r\nNow, (log x)/x has a derivative of (1 - log x)/x^2\r\n\r\nThe derivative = 0, at x = e\r\n\r\nDerivative < 0, x > e, which means it is a monotonically decreasing function when x > e\r\n\r\nIf x, y > e\r\n\r\nAnd x < y\r\n\r\nThen, (log x)/x > (log y)/y\r\n\r\nx^y > y^x\r\n\r\n----------------------\r\n\r\nAlso, x^y = y^x, whenever x = y, and x = 2, y = 4\r\n\r\nThe remaining cases can be handled by hand.\r\n\r\n------------------------------------------------------\r\n\r\nint main()\r\n{\r\n    long long x, y;\r\n    scanf(\"%I64d %I64d\", &x, &y);\r\n\r\n    if(x == y || (min(x, y) == 2 && max(x, y) == 4))\r\n    {\r\n        printf(\"=\");\r\n    }\r\n    else if(min(x, y) == 1)\r\n    {\r\n        printf(x == 1 ? \"<\" : \">\");\r\n    }\r\n    else if(min(x, y) == 2)\r\n    {\r\n        if(x == 2)\r\n        {\r\n            printf(y < 4 ? \"<\" : \">\");\r\n        }\r\n        else if(y == 2)\r\n        {\r\n            printf(x < 4? \">\" : \"<\");\r\n        }\r\n    }\r\n    else if(min(x, y) >= 3) //Both greater than e\r\n    {\r\n        printf(x < y ? \">\" : \"<\");\r\n    }\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 22/Infinity Gauntlet Explanation.txt",
    "content": "Have a map of all the colours and their powers. \r\n\r\nAnd then have a map of which colours have been used. \r\n\r\nIf a colour has not been used, then display it.\r\n\r\n-------------------------------------\r\n\r\nint main()\r\n{\r\n    map <string, string> power;\r\n    power[\"red\"] = \"Reality\";\r\n    power[\"purple\"] = \"Power\";\r\n    power[\"green\"] = \"Time\";\r\n    power[\"yellow\"] = \"Mind\";\r\n    power[\"orange\"] = \"Soul\";\r\n    power[\"blue\"] = \"Space\";\r\n\r\n    map <string, int> present;\r\n\r\n    int no_of_names;\r\n    cin >> no_of_names;\r\n\r\n    while(no_of_names--)\r\n    {\r\n        string colour;\r\n        cin >> colour;\r\n\r\n        present[colour] = true;\r\n    }\r\n\r\n    vector <string> answer;\r\n    for(map <string, string> :: iterator it = power.begin(); it != power.end(); it++)\r\n    {\r\n        if(!present[it->first])\r\n            answer.push_back(it->second);\r\n    }\r\n\r\n    cout << answer.size() << \"\\n\";\r\n    for(int i = 0; i < answer.size(); i++)\r\n        cout << answer[i] << \"\\n\";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Knights of a Polygonal Table Explanation.txt",
    "content": "Sort the knights, first by their power. \r\n\r\nAnd then maintain a priority queue of the k highest coins so far. k is at most 10. So, this works.\r\n\r\nAs each knight can only kill knights that are less powerful than him, we insert coins into the priority queue only AFTER processing all knights of the same power. \r\n\r\nSo when we're at knight i, we have processed all knights that have less than power of this knight i. \r\n\r\nAll of the coins of the first (i - 1) are in a priority queue. This allows us to get the maximum in O(1) time. \r\n\r\n-----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_knights, max_coins;\r\n    scanf(\"%d %d\", &no_of_knights, &max_coins);\r\n\r\n    vector <knight> knights(no_of_knights + 1);\r\n    for(int i = 1; i <= no_of_knights; i++) knights[i].position = i;\r\n    for(int i = 1; i <= no_of_knights; i++) scanf(\"%d\", &knights[i].power);\r\n    for(int i = 1; i <= no_of_knights; i++) scanf(\"%d\", &knights[i].coin);\r\n\r\n    sort(all(knights), sort_by_power);\r\n\r\n    vector <long long> answer(no_of_knights + 1, 0);\r\n    multiset <int> best_coin;\r\n\r\n    for(int i = 1; i <= no_of_knights; i++)\r\n    {\r\n        if(knights[i].power == knights[i - 1].power)\r\n        {\r\n            answer[knights[i].position] = answer[knights[i - 1].position] - knights[i - 1].coin + knights[i].coin;\r\n        }\r\n        else\r\n        {\r\n            int c = 1;\r\n            answer[knights[i].position] = knights[i].coin;\r\n\r\n            for(multiset <int> :: reverse_iterator it = best_coin.rbegin(); it != best_coin.rend() && c <= max_coins; it++, c++)\r\n            {\r\n                answer[knights[i].position] += *it;\r\n            }\r\n        }\r\n\r\n        best_coin.insert(knights[i].coin);\r\n    }\r\n\r\n\r\n    for(int i = 1; i <= no_of_knights; i++)\r\n        printf(\"%I64d \", answer[i]);\r\n\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 22/Letters Explanation.txt",
    "content": "Maintain a prefix sum array of the array. \n\nThen do binary search to find the first i, such that S[i] >= x and S[i - 1] < x\n\ni is the dorm no\nAnd x - S[i - 1] is the room no\n\nI used upper bound here quite clearly. upper bound(x) returns the first element which is GREATER than x. \nSo upper bound(x - 1) does the trick quite nicely !\n\n-----------------------------------------------\n\nint main()\n{\n    int no_of_elements, no_of_queries;\n    scanf(\"%d %d\", &no_of_elements, &no_of_queries);\n\n    vector <long long> A(no_of_elements + 1);\n    vector <long long > sum_till(no_of_elements + 1, 0);\n\n    for(int i = 1; i <= no_of_elements; i++)\n    {\n        scanf(\"%I64d\", &A[i]);\n        sum_till[i] = sum_till[i - 1] + A[i];\n    }\n\n    while(no_of_queries--)\n    {\n        long long x;\n        scanf(\"%I64d\", &x);\n\n        int dorm_no = upper_bound(all(sum_till), x - 1) - sum_till.begin();\n        long long room_no = x - sum_till[dorm_no - 1];\n\n        printf(\"%d %I64d\\n\", dorm_no, room_no);\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "Explanations/Explanations 22/Local Extrema Explanation.txt",
    "content": "Go from 2 to N - 1 and check in O(n).\r\n\r\nint is_extrema(int mid, int start, int end)\r\n{\r\n    return ((start < mid && end < mid) || (mid < start && mid < end));\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    int local_extrema = 0;\r\n    for(int i = 2; i < no_of_elements; i++)\r\n        local_extrema += is_extrema(A[i], A[i - 1], A[i + 1]);\r\n\r\n    printf(\"%d\\n\", local_extrema);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Remove Duplicates Explanation.txt",
    "content": "Read the integers right to left and keep track of what has been used so far. \r\n\r\nPut that into the solution and then print the solution in reverse. \r\n\r\n----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    const int MAX = 1015;\r\n    vector <int> used(MAX, false);\r\n    vector <int> ans;\r\n\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        if(!used[A[i]])\r\n        {\r\n            used[A[i]] = true;\r\n            ans.push_back(A[i]);\r\n        }\r\n    }\r\n\r\n    reverse(all(ans));\r\n\r\n    printf(\"%d\\n\", ans.size());\r\n    for(int i = 0; i < ans.size(); i++) printf(\"%d \", ans[i]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Super Agent Explanation.txt",
    "content": "There are only 9 points and 4 pairs. Check all of them.\r\n\r\nint main()\r\n{\r\n    const int N = 3;\r\n    char grid[N + 2][N + 2];\r\n    for(int i = 1; i <= N; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    int symmetric = (grid[1][1] == grid[3][3]) && (grid[1][2] == grid[3][2]) && (grid[1][3] == grid[3][1]) && (grid[2][3] == grid[2][1]);\r\n    printf(symmetric ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Switches and Lamps Explanation.txt",
    "content": "Count the number of switches that each lamp is connected to. \r\n\r\n(In other words, find the sum of each column.)\r\n\r\nThe go through all switches and check if there is any switch that can be ignored. \r\n\r\nA switch can be ignored, if each of it's connected lamp has another switch connected to it. \r\n\r\ni.e. If Switch[i][j] = 1, and lamp[j] > 1, then the i-th switch can be ignored. \r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_switches, no_of_lamps;\r\n    cin >> no_of_switches >> no_of_lamps;\r\n\r\n    vector <string> switches(no_of_switches);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        cin >> switches[i];\r\n\r\n    vector <int> no_of_switches_for(no_of_lamps, 0);\r\n    for(int i = 0; i < no_of_switches; i++)\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n            no_of_switches_for[lamp] += (switches[i][lamp] == '1');\r\n\r\n    int one_ignorable = false;\r\n\r\n    for(int i = 0; i < no_of_switches; i++)\r\n    {\r\n        int can_ignore_this_one = true;\r\n\r\n        for(int lamp = 0; lamp < no_of_lamps; lamp++)\r\n        {\r\n            if(switches[i][lamp] == '1' && no_of_switches_for[lamp] == 1)\r\n                can_ignore_this_one = false;\r\n        }\r\n\r\n        if(can_ignore_this_one)\r\n            one_ignorable = true;\r\n    }\r\n\r\n    cout << (one_ignorable ? \"YES\\n\" : \"NO\\n\");\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Three Displays Explanation.txt",
    "content": "\r\nThis is the O(n^2) solution. Iterate over all possible middle elements. \r\n\r\nIf A[i] is the middle element, then go from (i + 1) to N. \r\nCheck if S[r] > A[i], if yes then best right[i] = min{best right[i], C[r]}\r\n\r\nDo the same thing towards the left as well. \r\n\r\nBest cost = min{Best cost, best left[i] + A[i] + best right[i]}\r\n\r\nWe perform an O(n) scan for every possible mid element. \r\n\r\nHence, O(n^2)\r\n\r\n----------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <int> text_size(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &text_size[i]);\r\n\r\n    vector <int> cost(no_of_displays + 1);\r\n    for(int i = 1; i <= no_of_displays; i++) scanf(\"%d\", &cost[i]);\r\n\r\n    const long long oo = 1e10;\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n\r\n    long long best_cost = oo;\r\n\r\n    for(int mid = 1; mid <= no_of_displays; mid++)\r\n    {\r\n        for(int right = mid + 1; right <= no_of_displays; right++)\r\n        {\r\n            if(text_size[mid] < text_size[right])\r\n                best_right[mid] = min(best_right[mid], cost[right]);\r\n        }\r\n\r\n        for(int left = 1; left < mid; left++)\r\n        {\r\n            if(text_size[left] < text_size[mid])\r\n                best_left[mid] = min(best_left[mid], cost[left]);\r\n        }\r\n\r\n        best_cost = min(best_cost, best_right[mid] + cost[mid] + best_left[mid]);\r\n    }\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Three Displays Segment Tree Solution Explanation.txt",
    "content": "This is actually a beautiful technique. There are plenty of problems where segment trees can make O(n^2) to O(n log n).\r\n\r\nHere's what we do. \r\n\r\nWhile processing element i, ensure that we have already processed all elements which have a smaller font size. Now find the minimum cost in the range [1, Position(i) - 1]. \r\n\r\n(To avoid a clash, ensure that you have not processed elements which have equal font size but who's positions lie to the left of Position(i) because we should not be considering their cost.)\r\n\r\nSo, we sort by font size, \r\nIf font size is equal, then the rightmost element comes first. \r\n\r\nOne by one, we insert the costs into segment tree at Position(i). \r\nAnd then query the minimum in [1, Position(i) - 1].\r\nAs we have ensured rightmost element comes first for equal font sizes, elements with equal font size to the left of an element will not effect it's query as it's not been inserted yet. \r\n\r\nWhile finding the best right, we do the opposite. We insert elements in the reverse order that we did for the left and then find the minimum in the range [Position(i) + 1, N].\r\n\r\n---------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_displays;\r\n    scanf(\"%d\", &no_of_displays);\r\n\r\n    vector <info> A(no_of_displays + 1);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        A[i].position = i;\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].font_size);\r\n\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        scanf(\"%d\", &A[i].cost);\r\n\r\n    sort(A.begin() + 1, A.end(), compare_by_size);\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_left(no_of_displays + 1, oo);\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_left[i] = get_min(1, 1, no_of_displays, 1, A[i].position - 1);\r\n    }\r\n\r\n    build_min_tree(1, 1, no_of_displays);\r\n    vector <long long> best_right(no_of_displays + 1, oo);\r\n    for(int i = no_of_displays; i >= 1; i--)\r\n    {\r\n        update_min(1, 1, no_of_displays, A[i].position, A[i].cost);\r\n\r\n        best_right[i] = get_min(1, 1, no_of_displays, A[i].position + 1, no_of_displays);\r\n    }\r\n\r\n    long long best_cost = oo;\r\n    for(int i = 1; i <= no_of_displays; i++)\r\n        best_cost = min(best_cost, best_left[i] + A[i].cost + best_right[i]);\r\n\r\n    printf(best_cost >= oo ? \"-1\\n\" : \"%I64d\\n\", best_cost);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Tufurama Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpORd\r\n\r\nMaintain an array S of 1s and 0s. \r\n\r\nWe want the number of pairs such that i < j, A[i] >= j and A[j] >= i\r\n\r\nFor each i, sum over S in [i + 1, A[i]]\r\n\r\nAfter step i, delete all occurences of i in the array and set S[p] = 0, if A[p] = i\r\n\r\nThis ensures that at step i, all elements < i are deleted so only >= i are present.\r\n\r\n-----------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    vector <int> index[no_of_elements + 1];\r\n\r\n    memset(sum_tree, 0, sizeof(sum_tree));\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        A[i] = min(A[i], no_of_elements);\r\n\r\n        update(1, 1, no_of_elements, i, 1);\r\n\r\n        index[A[i]].push_back(i);\r\n    }\r\n\r\n    long long answer = 0;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        answer += get_sum(1, 1, no_of_elements, i + 1, A[i]);\r\n\r\n        for(int j = 0; j < index[i].size(); j++)\r\n        {\r\n            update(1, 1, no_of_elements, index[i][j], 0);\r\n        }\r\n    }\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 22/Useful Decomposition Explanation.txt",
    "content": "We root the tree at a vertex V, and we make a path from V to each of it's leaves. \r\n\r\nWe can always decompose a tree, unless V has some descendant that has more than one child. \r\n\r\nSo, here's what we do \r\n\r\n1. If the graph has more than one vertex which has 3 or more edges, then it is not possible. \r\n\r\n2. If the graph has exactly one vertex which has 3 or more edges, then we root the tree at that vertex. \r\nIf the graph has no such vertex, then it means every vertex has at most two edges (one parent and one child). We can arbitrarily root the graph at any of these vertices, then.\r\n\r\nOnce we have a root, then make a path from the root the leaf vertex by going through each of the root's children.\r\n\r\nNote - You don't need to minimise the number of paths. Otherwise, the root is the vertex which has degree > 2, or the vertex with degree = 1, if all vertices have degree <= 2\r\n\r\nLet us suppose we were asked to minimise or maximise the number of paths. \r\n\r\nCall a vertex a root if it's degree > 2.\r\n\r\nCase 1 : There is atleast one vertex with degree > 2\r\n\r\nIf there is more than one root, then the solution stays the same as a decomposition is not possible. If there was exactly one root, then we have to make it the root and the solution stays the same. Making any other vertex the root will not satisfy the given conditions.\r\n\r\nCase 2 : All vertices have degree <= 2\r\n\r\nTo minimise the number of paths, we must choose a leaf vertex since it has only one child and it will result in 1 simple path from one leaf to another.\r\n\r\nFor maximising the number of paths, we will have to pick any non-leaf vertex which has a degree of 2. There will be two paths, one to each leaf.\r\n\r\n\r\n----------------------------------------\r\n\r\nint dfs_leaf_from(int v, int parent)\r\n{\r\n    if(graph[v].size() == 1)\r\n        return v;\r\n\r\n    for(int i = 0; i < graph[v].size(); i++)\r\n    {\r\n        int child = graph[v][i];\r\n\r\n        if(child == parent) continue;\r\n\r\n        return dfs_leaf_from(child, v);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_vertices;\r\n    scanf(\"%d\", &no_of_vertices);\r\n\r\n    for(int i = 1; i < no_of_vertices; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        graph[u].push_back(v);\r\n        graph[v].push_back(u);\r\n    }\r\n\r\n    int no_of_roots = 0, root = 1;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n    {\r\n        if(graph[i].size() > 2)\r\n        {\r\n            no_of_roots++;\r\n            root = i;\r\n        }\r\n    }\r\n\r\n    if(no_of_roots > 1)\r\n    {\r\n        printf(\"No\\n\");\r\n        return 0;\r\n    }\r\n\r\n    printf(\"Yes\\n\");\r\n\r\n    int no_of_paths = graph[root].size();\r\n\r\n    printf(\"%d\\n\", no_of_paths);\r\n\r\n    for(int i = 0; i < graph[root].size(); i++)\r\n    {\r\n        int child = graph[root][i];\r\n\r\n        int leaf = dfs_leaf_from(child, root);\r\n\r\n        printf(\"%d %d\\n\", root, leaf);\r\n    }\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 23/An Impassioned Circulation of Affection Explanation.txt",
    "content": "We compute the answer for every range. \r\n\r\nFor every range [L, R], we find the answer for every alphabet. We can do this because there are only 26 alphabets. \r\n\r\nAnother thing to take care for is that f(c, r) = max{f(c, r), f(c, r - 1)}\r\n\r\nwhere f(c, r) is the length of the maximum substring of 'c' with at most r replacements.\r\n\r\n---------------\r\n\r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    for(int ch = 0; ch < MAX_ALPHABETS; ch++)\r\n    {\r\n        for(int left = 0; left < length; left++)\r\n        {\r\n            int replacements = 0;\r\n\r\n            for(int right = left; right < length; right++)\r\n            {\r\n                replacements += (S[right] != 'a' + ch);\r\n\r\n                maximum_segment[ch][replacements] = max(maximum_segment[ch][replacements], right - left + 1);\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int ch = 0; ch < MAX_ALPHABETS; ch++)\r\n    {\r\n        for(int replacements = 1; replacements <= length; replacements++)\r\n        {\r\n            maximum_segment[ch][replacements] = max(maximum_segment[ch][replacements], maximum_segment[ch][replacements - 1]);\r\n        }\r\n    }\r\n\r\n    int no_of_queries;\r\n    cin >> no_of_queries;\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int max_replacements;\r\n        char character;\r\n\r\n        cin >> max_replacements >> character;\r\n        cout << maximum_segment[character - 'a'][max_replacements] << '\\n';\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Another Problem on Strings Explanation.txt",
    "content": "Let us consider the range S[L, ... , R]. The sum is Sum[R] - Sum[L - 1]\r\n\r\nNow for a given R, how many L's exist such that Sum[R] - Sum[L - 1] = k ? \r\n\r\nIt is equal to the number of Ls such that Sum[L - 1] = Sum[R] - k\r\n\r\nLet us maintain the frequency of all sums. Then at each i, add Sum_frequency[Sum[i] - k] to the answer.\r\n\r\n-----------------\r\n\r\nint main()\r\n{\r\n    int target_no_of_1s;\r\n    scanf(\"%d\", &target_no_of_1s);\r\n\r\n    const int MAX = 1e6 + 3;\r\n    char S[MAX];\r\n    scanf(\"%s\", S);\r\n\r\n    vector <int> sum(MAX, 0);\r\n    sum[0] = (S[0] == '1');\r\n    for(int i = 1; S[i] != '\\0'; i++)\r\n        sum[i] = sum[i - 1] + (S[i] == '1');\r\n\r\n    vector <int> sum_frequency(MAX, 0);\r\n    sum_frequency[0] = 1; //Empty string\r\n\r\n    long long no_of_good_substrings = 0;\r\n    for(int i = 0; S[i] != '\\0'; i++)\r\n    {\r\n        if(sum[i] >= target_no_of_1s)\r\n            no_of_good_substrings += (sum_frequency[sum[i] - target_no_of_1s]);\r\n\r\n        sum_frequency[sum[i]]++;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_good_substrings);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Babaei and Birthday Cake Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUGuqG\r\n\r\nLet us do this ... Firstly, calculate the volumes of all the cylinders. \r\n\r\nLet the volumes be v_1, v_2, ... , v_n\r\n\r\nfor(int i = 1; i <= no_of_cylinders; i++)\r\n    {\r\n        int radius, height;\r\n        scanf(\"%d %d\", &radius, &height);\r\n\r\n        const double PI = 3.14159;\r\n\r\n        volume[i] = (PI*radius*radius*1LL*height);\r\n        sorted_volume[i] = volume[i];\r\n    }\r\n\r\n-----------------------------\r\n\r\nLet us sort the volumes and give each volume a rank indicating it's position in the sorted list. \r\n\r\n    sort(all(sorted_volume));\r\n\r\n    map <double, int> rank;\r\n    for(int i = 1; i <= no_of_cylinders; i++)\r\n        rank[sorted_volume[i]] = i;\r\n\r\n---------------------------\r\n\r\nNow, let f(i) represent the maximum volume possible if the last cylinder used was the one with RANK i.\r\n\r\nThen what is the recurrence for i ? \r\n\r\nf(i) = V(i) + max{f(j)}\r\n\r\nwhere \r\n\r\n1. j < i\r\n2. V(j) < V(i)\r\n\r\nIn other words, \r\n\r\n1. j < i\r\n2. Rank(V(j)) < Rank(V(i))\r\n\r\nHow do we find out this j ? We can obviously do so in O(n^2) time. But, that will not fit in the time limit and there is a more insightful way of doing it !\r\n\r\nLet us maintain a maximum segment tree over an array Z.  \r\n\r\n1. Process the volumes in the order that it is given. \r\n2. After processing, insert f(i) into Z at the position Rank(V(i)). \r\nZ[Rank(V(i))] = f(i)\r\n\r\nWe will add f(i) = V(i) + max{Z[1, ... , Rank[V(i)] - 1]}\r\n\r\nWe know that this is the j we want because \r\n\r\n1. j < i because we have processed V(j) already and inserted it into Z. \r\n2. Rank(V(j)) < Rank(V(i)) because we are only searching in that range.\r\n3. Among all such j which satsifies both conditions, we have chosen the one that maximises f(i).\r\n\r\nmap <double, double> answer_with_last;\r\n\r\n    for(int i = 1; i <= no_of_cylinders; i++)\r\n    {\r\n        answer_with_last[volume[i]] = volume[i] + get_max(1, 1, no_of_cylinders, 1, rank[volume[i]] - 1);\r\n\r\n        insert(1, 1, no_of_cylinders, answer_with_last[volume[i]], rank[volume[i]]);\r\n    }\r\n\r\n--------------------------\r\n\r\nNow, the answer is the maximum value of f(i) in the array.\r\n\r\ndouble answer = 0;\r\n\r\nfor(int i = 1; i <= no_of_cylinders; i++)\r\n    answer = max(answer, answer_with_last[volume[i]]);\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 23/Bear and Prime Numbers Explanation.txt",
    "content": "The numbers are only until 10^7. \r\n\r\nFor each prime till 10^7, keep track of it's number of multiples. \r\n\r\nDon't do this by factorising each integer. Rather go over all it's multiples frequencies. Similar to sieving.\r\n\r\nvector <int> no_of_multiples(MAX_N + 1, 0);\r\n    for(int i = 1; i <= MAX_N; i++)\r\n    {\r\n        if(!is_prime[i]) continue;\r\n\r\n        for(int multiple = i; multiple <= MAX_N; multiple += i)\r\n        {\r\n            no_of_multiples[i] += frequency[multiple];\r\n        }\r\n    }\r\n\r\n-----------------------------\r\n\r\nNow build a prefix sum for this. Answer queries in O(1) time. \r\n\r\nvector <int> answer(MAX_N + 1, 0);\r\n    for(int i = 1; i <= MAX_N; i++)\r\n        answer[i] = answer[i - 1] + no_of_multiples[i];\r\n\r\n-------------------------\r\n\r\nThere's a catch. Both left and right should be at most 10^7, not 10^9. Because all the numbers are guaranteed to be less than 10^7.\r\n\r\n    while(no_of_queries--)\r\n    {\r\n        int left, right;\r\n        scanf(\"%d %d\", &left, &right);\r\n\r\n        right = min(right, MAX_N);\r\n        left = min(left, MAX_N);\r\n\r\n        printf(\"%d\\n\", answer[right] - answer[left - 1]);\r\n    }"
  },
  {
    "path": "Explanations/Explanations 23/Cirriculum Vitae Explanation.txt",
    "content": "We need the longest sequence of the form - 000... 111\r\n\r\n--------\r\n\r\nint main()\r\n{\r\n    int no_of_games;\r\n    scanf(\"%d\", &no_of_games);\r\n\r\n    vector <int> won(no_of_games + 1);\r\n    for(int i = 1; i <= no_of_games; i++)\r\n        scanf(\"%d\", &won[i]);\r\n\r\n    vector <int> wins_from(no_of_games + 2, 0);\r\n    for(int i = no_of_games; i >= 1; i--)\r\n        wins_from[i] = wins_from[i + 1] + (won[i]);\r\n\r\n    int final_no_of_games = 0;\r\n    int losses_so_far = 0;\r\n    for(int i = 1; i <= no_of_games; i++)\r\n    {\r\n        losses_so_far += (!won[i]);\r\n\r\n        final_no_of_games = max(final_no_of_games, losses_so_far + wins_from[i]);\r\n    }\r\n\r\n    printf(\"%d\\n\", final_no_of_games);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Classy Numbers Explanation.txt",
    "content": "The number of such numbers is quite small. We can precompute all of them and then perform binary search for each query :)\r\n\r\n-----------\r\n\r\nvoid precompute(int position, int non_zero_count, long long current_num)\r\n{\r\n    if(non_zero_count > 3)\r\n        return;\r\n\r\n    if(position == MAX_DIGITS)\r\n    {\r\n        classy_numbers.push_back(current_num);\r\n        return;\r\n    }\r\n\r\n    for(int digit = 0; digit <= 9; digit++)\r\n    {\r\n        precompute(position + 1, non_zero_count + (digit != 0), current_num*10 + digit);\r\n    }\r\n}\r\n\r\n---------------\r\n\r\nint main()\r\n{\r\n    precompute(0, 0, 0);\r\n    classy_numbers.push_back(1e18); //This has 19 digits\r\n\r\n    int no_of_tests;\r\n    scanf(\"%d\", &no_of_tests);\r\n\r\n    while(no_of_tests--)\r\n    {\r\n        long long left, right;\r\n        scanf(\"%I64d %I64d\", &left, &right);\r\n\r\n        int classy_number_count = upper_bound(all(classy_numbers), right) - lower_bound(all(classy_numbers), left);\r\n        printf(\"%d\\n\", classy_number_count);\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Counting Arrays Explanation.txt",
    "content": "Firstly, let us try to count the number of ways to factorise into positive integers. \r\n\r\nThis is equal to the number of ways of distributing each prime factor into y factors. \r\n\r\nWe use stars and bars for each prime. \r\n\r\nint x, no_of_summands;\r\n    cin >> x >> no_of_summands;\r\n\r\n    map <int, int> prime_exponents;\r\n    factorise(x, prime_exponents);\r\n\r\n    long long answer = 1;\r\n    for(map <int, int> :: iterator it = prime_exponents.begin(); it != prime_exponents.end(); it++)\r\n    {\r\n        int exponent = it->second;\r\n\r\n        answer *= choose(no_of_summands + exponent - 1, no_of_summands - 1);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n-----------------------------\r\n\r\nNow, after this we need to make an even number of integers even. \r\n\r\nC(n, 0) + C(n, 2) + ... C(n, 2m), where 2m <= n and 2m + 1 >= n\r\n\r\nThis is equal to 2^{n - 1}\r\n\r\nlong long ways_to_distribute_signs = power_mod(2, no_of_summands - 1);\r\n\r\n    answer = (answer*ways_to_distribute_signs)%MOD;%= MOD;"
  },
  {
    "path": "Explanations/Explanations 23/Crazy Town Explanation.txt",
    "content": "I thought of a complicated solution where I create a graph and draw an edge if two regions share a border, and perform BFS  but the solution was stunningly simple.\r\n\r\nDraw a line from source to destination. The line crosses how many lines ?\r\n\r\nIt crosses every line such that the source and destination are on different sides !\r\n\r\nThat's it ! \r\n\r\nThat's all that needs to be checked ! Beautiful geometry problem, indeed !\r\n\r\n------------------------------------------\r\n\r\nint main()\r\n{\r\n    int start_x, start_y, end_x, end_y;\r\n    scanf(\"%d %d %d %d\", &start_x, &start_y, &end_x, &end_y);\r\n\r\n    int no_of_lines;\r\n    scanf(\"%d\", &no_of_lines);\r\n\r\n    int crossed_lines = 0;\r\n    while(no_of_lines--)\r\n    {\r\n        long long a, b, c;\r\n        scanf(\"%I64d %I64d %I64d\", &a, &b, &c);\r\n\r\n        long long start_side = a*start_x + b*start_y + c;\r\n        long long end_side = a*end_x + b*end_y + c;\r\n\r\n        if( (start_side > 0 && end_side < 0) || (start_side < 0 && end_side > 0) )\r\n            crossed_lines++;\r\n    }\r\n\r\n    printf(\"%d\\n\", crossed_lines);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Find Maximum Explanation.txt",
    "content": "Every integer smaller than m has some matching prefix, and then has a 0 where m has a 1. \r\n\r\nFor example if m = 100010010\r\n\r\nThen Some numbers will have same first four bits and fifth bits = 0\r\n\r\n10000 ..... and can have anything after that.\r\n\r\nSince all the numbers are positive integers. \r\n\r\nWe will set a 1 to a 0 and then activate all integers after that. \r\n\r\nSo in this case, we will check\r\n\r\n011111111\r\n100001111\r\n100010001\r\n\r\nAnd of course, we will have to check m itself !\r\n\r\n-------------------------\r\n\r\nint main()\r\n{\r\n    int n;\r\n    scanf(\"%d\", &n);\r\n\r\n    vector <int> A(n + 1);\r\n    for(int i = 1; i <= n; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <long long> prefix_sum(n + 1, 0);\r\n    for(int i = 1; i <= n; i++)\r\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\r\n\r\n    const int MAX_N = 1e5 + 5;\r\n    char S[MAX_N];\r\n    scanf(\"%s\", S + 1);\r\n\r\n    long long answer = 0, set_bit_sum = 0;\r\n\r\n    for(int i = n; i > 0; i--)\r\n    {\r\n        if(S[i] == '1')\r\n        {\r\n            answer = max(answer, set_bit_sum + prefix_sum[i - 1]);\r\n\r\n            set_bit_sum += A[i];\r\n        }\r\n    }\r\n\r\n    answer = max(answer, set_bit_sum);\r\n\r\n    printf(\"%I64d\\n\", answer);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Fish Explanation.txt",
    "content": "Blog Link - http://qr.ae/TUpa1S\n\nMaintain a mask for all fish that are alive at a given moment. \n\n---------------------------------\n\nfor(int mask = max_mask; mask >= 1; mask--)\n    {\n        for(int eating_fish = 0; eating_fish < no_of_fish; eating_fish++)\n        {\n            if(is_alive(mask, eating_fish)) //Eating fish is alive\n            {\n                for(int victim_fish = 0; victim_fish < no_of_fish; victim_fish++)\n                {\n                    if(is_alive(mask, victim_fish) && eating_fish != victim_fish)\n                    {\n                        int mask_without_victim = kill(mask, victim_fish);\n\n                        int no_of_alive_fish = no_of_set_bits(mask);\n                        int no_of_combinations = choose_2(no_of_alive_fish);\n\n                        probability[mask_without_victim] += (probability[mask]*eat_probability[eating_fish][victim_fish])/no_of_combinations;\n                    }\n                }\n            }\n        }\n    }\n\n"
  },
  {
    "path": "Explanations/Explanations 23/Garbage Disposal Explanation.txt",
    "content": "Let us be greedy and only use a bag when we need to. \r\n\r\n------------------\r\n\r\nint main()\r\n{\r\n    int no_of_days, k;\r\n    cin >> no_of_days >> k;\r\n\r\n    vector <long long> A(no_of_days + 1);\r\n    for(int i = 1; i <= no_of_days; i++)\r\n        cin >> A[i];\r\n\r\n    long long minimum_bags = 0;\r\n\r\n    for(int i = 1; i <= no_of_days; i++)\r\n    {\r\n        minimum_bags += A[i]/k;\r\n        A[i] %= k;\r\n\r\n        if(A[i] > 0)\r\n        {\r\n            minimum_bags++;\r\n\r\n            if(i + 1 <= no_of_days)\r\n                A[i + 1] = max(0LL, A[i + 1] - (k - A[i]));\r\n        }\r\n    }\r\n\r\n    cout << minimum_bags;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Guest from the Past Explanation.txt",
    "content": "int main()\r\n{\r\n    long long money, plastic_bottle_price, glass_bottle_price, return_amount;\r\n    scanf(\"%I64d %I64d %I64d %I64d\", &money, &plastic_bottle_price, &glass_bottle_price, &return_amount);\r\n\r\n    long long effective_glass_bottle_price = glass_bottle_price - return_amount;\r\n    long long no_of_bottles = 0;\r\n\r\n    if(plastic_bottle_price <= effective_glass_bottle_price || glass_bottle_price > money)\r\n    {\r\n        no_of_bottles = money/plastic_bottle_price;\r\n    }\r\n    else if(effective_glass_bottle_price < plastic_bottle_price && glass_bottle_price <= money)\r\n    {\r\n        no_of_bottles = (money - return_amount)/effective_glass_bottle_price;\r\n\r\n        long long remaining_money = money - no_of_bottles*effective_glass_bottle_price;\r\n        long long remaining_bottles = remaining_money/plastic_bottle_price;\r\n\r\n        no_of_bottles += remaining_bottles;\r\n    }\r\n\r\n    printf(\"%I64d\\n\", no_of_bottles);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Ice Skater Explanation.txt",
    "content": "We can go from one point to another if either the x-coordinate or y-coordinate is the same. \r\n\r\nLet us make a graph with the points as vertices and draw an edge between two points if one can be reached from the other. \r\n\r\nThis graph will have a set of connected components. We need to connect all these components together. \r\n\r\nTo connect any two components we need exactly one new point.\r\n(For example with the x-coordinate of some point of one component and the y-coordinate of some point of the other component.)\r\n\r\nAnswer = C - 1\r\n\r\n---------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_points;\r\n    scanf(\"%d\", &no_of_points);\r\n\r\n    vector <int> X(no_of_points + 1);\r\n    vector <int> Y(no_of_points + 1);\r\n    for(int i = 1; i <= no_of_points; i++)\r\n        scanf(\"%d %d\", &X[i], &Y[i]);\r\n\r\n    int no_of_components = 0;\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        for(int j = 1; j < i; j++)\r\n        {\r\n            if(X[i] == X[j] || Y[i] == Y[j])\r\n            {\r\n                graph[i].push_back(j);\r\n                graph[j].push_back(i);\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_points; i++)\r\n    {\r\n        if(!visited[i])\r\n        {\r\n            no_of_components++;\r\n\r\n            dfs(i);\r\n        }\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_components - 1);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 23/Lazyland Explanation.txt",
    "content": "If a number occurs only one time, then there is no point in persuading the person to change as that would not increase the number of distinct values. \r\n\r\nSuppose some number occurs more than once. We can persuade anyone except the person with the greatest time to change. \r\n\r\nWe can maintain an array A, which has all the times which can be persuaded. \r\n\r\nLook at all the people who can be persuaded and choose the people with the smallest time. This corresponds with the smallest integers of A.\r\n\r\n---------------\r\n\r\nint main()\r\n{\r\n    int no_of_people, distinct_targets;\r\n    scanf(\"%d %d\", &no_of_people, &distinct_targets);\r\n\r\n    vector <int> A(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> time(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &time[i]);\r\n\r\n    map <int, int> max_time_for_task;\r\n    vector <int> free_time;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        if(max_time_for_task[A[i]] != 0)\r\n            free_time.push_back(min(time[i], max_time_for_task[A[i]]));\r\n\r\n        max_time_for_task[A[i]] = max(max_time_for_task[A[i]], time[i]);\r\n    }\r\n\r\n    sort(all(free_time));\r\n\r\n    int distinct_numbers = max_time_for_task.size();\r\n    int required_new_distinct_numbers = distinct_targets - distinct_numbers;\r\n\r\n    long long total_time = 0;\r\n    for(int i = 0; i < required_new_distinct_numbers; i++)\r\n        total_time += free_time[i];\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 23/Lesha and Array Splitting Explanation.txt",
    "content": "If the array only has 0s, then there is no answer. \r\n\r\nElse, find any valid i, where A[1, ... , i] and A[i + 1, ... n] are both non-zero sums. \r\n\r\nIf the sum of the entire array is not 0, then give the full array. \r\n\r\nElse if the sum is 0, but there are non-zero elements, there must be two parts of non-zero sum which negate each other :)\r\n\r\n--------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> prefix_sum(no_of_elements + 1, 0);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        prefix_sum[i] = prefix_sum[i - 1] + A[i];\r\n\r\n    vector <int> suffix_sum(no_of_elements + 2, 0);\r\n    for(int i = no_of_elements; i>= 1; i--)\r\n        suffix_sum[i] = suffix_sum[i + 1] + A[i];\r\n\r\n    int all_zeroes = true;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] != 0)\r\n            all_zeroes = false;\r\n    }\r\n\r\n    if(all_zeroes)\r\n    {\r\n        printf(\"NO\\n\");\r\n    }\r\n    else\r\n    {\r\n        printf(\"YES\\n\");\r\n\r\n        if(no_of_elements == 1 || prefix_sum[no_of_elements] != 0)\r\n        {\r\n            printf(\"1\\n1 %d\\n\", no_of_elements);\r\n        }\r\n        else\r\n        {\r\n            int division_point;\r\n            for(int i = 1; i < no_of_elements; i++)\r\n            {\r\n                if(prefix_sum[i] != 0 && suffix_sum[i + 1] != 0)\r\n                {\r\n                    division_point = i;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            printf(\"2\\n\");\r\n            printf(\"1 %d\\n\", division_point);\r\n            printf(\"%d %d\\n\", division_point + 1, no_of_elements);\r\n        }\r\n    }\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Lost Array Explanation.txt",
    "content": "If Array X is the answer, then it must satisfy this property -  \r\n\r\n X[i (mod k)] = A[i + 1] - A[i]\r\n\r\nFor every i, we will need to check that X[i (mod k)] satisfies this property. \r\n\r\nOne way of doing this is constructing an array where \r\n\r\nX[i] = A[i + 1] - A[i]\r\n\r\nIf X[i (mod k)] = A[i + 1] - A[i], \r\n\r\nThen A[i + 1] - A[i] = A[j + 1] - A[j]\r\n\r\nif i = j (mod k)\r\n\r\n-----------------\r\n\r\nThen, we will check here if \r\n\r\nX[0] = X[k] = X[2k] = X[3k]\r\nX[1] = X[k + 1] = X[2k + 1] = X[3k + 1]\r\nX[2] = X[k + 2] = X[2k + 2] = X[3k + 2]\r\nX[3] = X[k + 3] = X[2k + 3] = X[3k + 3]\r\n\r\nand so on\r\n\r\n\r\n-------------------\r\n\r\nWe go through all numbers from 1 to N and check which lengths are possible. \r\n\r\nvector <int> answer;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(is_possible(X, i))\r\n        {\r\n            answer.push_back(i);\r\n        }\r\n    }\r\n\r\n------------------\r\n\r\nThis is how we check if it is possible. \r\n\r\nint is_possible(vector <int> &A, int k)\r\n{\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if(A[i] != A[(i%k)])\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Maze Explanation.txt",
    "content": "There are S free cells\r\n\r\nWe will use DFS to visit S - K cells. \r\n\r\nThe remaining K will be marked as walls\r\n\r\n-------------------------------------\r\n\r\nvoid dfs(int r, int c, int target)\r\n{\r\n    if(no_of_visits >= target)\r\n        return;\r\n\r\n    visited[r][c] = true;\r\n\r\n    no_of_visits++;\r\n\r\n    const int NO_OF_NEIGHBOURS = 4;\r\n    int next_x[NO_OF_NEIGHBOURS] = {-1, 0, 0, 1};\r\n    int next_y[NO_OF_NEIGHBOURS] = {0, 1, -1, 0};\r\n\r\n    for(int i = 0; i < NO_OF_NEIGHBOURS; i++)\r\n    {\r\n        int next_r = r + next_x[i], next_c = c + next_y[i];\r\n\r\n        if(0 < next_r && next_r <= rows && 0 < next_c && next_c <= columns &&\r\n           !visited[next_r][next_c] && grid[next_r][next_c] == '.')\r\n        {\r\n            dfs(next_r, next_c, target);\r\n        }\r\n    }\r\n}\r\n\r\n-----------------\r\n\r\nfor(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            if(grid[i][j] == '.')\r\n            {\r\n                dfs(i, j, total_free - k);\r\n\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            printf(\"%c\", (grid[i][j] == '.' && !visited[i][j]) ? 'X' : grid[i][j]);\r\n        }\r\n\r\n        printf(\"\\n\");\r\n    }\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 23/Minesweeper Explanation.txt",
    "content": "int neighbour_bomb_count(int x, int y)\r\n{\r\n    const int NO_OF_NEIGHBOURS = 8;\r\n    int step_x[NO_OF_NEIGHBOURS] = {-1, 0, 1, -1, 1, - 1, 0, 1};\r\n    int step_y[NO_OF_NEIGHBOURS] = {-1, -1, -1, 0, 0, 1, 1, 1};\r\n\r\n    int no_of_bombs = 0;\r\n    for(int i = 0; i < NO_OF_NEIGHBOURS; i++)\r\n    {\r\n        no_of_bombs += (grid[x + step_x[i]][y + step_y[i]] == BOMB);\r\n    }\r\n\r\n    return no_of_bombs;\r\n}\r\n\r\nint main()\r\n{\r\n    int rows, columns;\r\n    scanf(\"%d %d\", &rows, &columns);\r\n\r\n    for(int i = 1; i <= rows; i++)\r\n        scanf(\"%s\", grid[i] + 1);\r\n\r\n    int valid = true;\r\n    for(int i = 1; i <= rows; i++)\r\n    {\r\n        for(int j = 1; j <= columns; j++)\r\n        {\r\n            if(grid[i][j] == EMPTY)\r\n            {\r\n                if(neighbour_bomb_count(i, j) != 0)\r\n                    valid = false;\r\n            }\r\n            else if('0' <= grid[i][j] && grid[i][j] <= '9')\r\n            {\r\n                if(neighbour_bomb_count(i, j) != grid[i][j] - '0')\r\n                    valid = false;\r\n            }\r\n        }\r\n    }\r\n\r\n    printf(valid ? \"YES\\n\" : \"NO\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Minimum Diameter Tree Explanation.txt",
    "content": "Notice that the diameter is always between two leaf vertices. \r\n\r\n(Suppose by contradiction that the diamater is in between two non-leafs u-v. Then we can extend both u and v to their nearest leaves - l1 and l2. \r\n\r\nThe path between l1 and l2 cannot weigh less than u-v because it contains u-v.)\r\n\r\n------------\r\n\r\nThe diameter will always be between two leafs. So, let us set all non-leaf edges to 0 and make all leaf edges equal. \r\n\r\nIf we don't make them equal, then some diameters will always be more than others. \r\n\r\n------------\r\n\r\nWe set every leaf = S/no_of_leaves.\r\n\r\n---------\r\n\r\nint main()\r\n{\r\n    int no_of_vertices, total_weight;\r\n    scanf(\"%d %d\", &no_of_vertices, &total_weight);\r\n\r\n    vector <int> degree(no_of_vertices + 1, 0);\r\n    for(int i = 1; i <= no_of_vertices - 1; i++)\r\n    {\r\n        int u, v;\r\n        scanf(\"%d %d\", &u, &v);\r\n\r\n        degree[u]++;\r\n        degree[v]++;\r\n    }\r\n\r\n    int no_of_leafs = 0;\r\n    for(int i = 1; i <= no_of_vertices; i++)\r\n        no_of_leafs += (degree[i] == 1);\r\n\r\n    double leaf_weight = ( (double) total_weight)/ no_of_leafs;\r\n    double diameter = leaf_weight*2;\r\n\r\n    printf(\"%.12f\\n\", diameter);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/No To Palindromes Explanation.txt",
    "content": "Fact - To avoid palindromic substrings, it is sufficient to avoid palindromic substrings of length 2 and 3. \r\n\r\n-------------\r\n\r\nWe will start from the rightmost position and then look for the first position where we can update S[i] and ensure 2 and 3 length palindromes are avoided. S[i] should not be equal to S[i - 1] and S[i - 2].\r\n\r\nfor(int i = length - 1; first_greater_position == NOT_FOUND && i >= 0; i--)\r\n    {\r\n        for(char new_ch = S[i] + 1; new_ch <= 'a' + max_alphabet - 1; new_ch++)\r\n        {\r\n            int possible = true;\r\n            for(int j = i - 1; j >= max(i - 2, 0); j--)\r\n            {\r\n                if(new_ch == S[j])\r\n                    possible = false;\r\n            }\r\n\r\n            if(possible)\r\n            {\r\n                first_greater_position = i;\r\n                replacement = new_ch;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    if(first_greater_position == NOT_FOUND)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return 0;\r\n    }\r\n\r\n------------\r\n\r\nNow we must make the suffix as small as possible. We only need to use a, b and c.\r\n\r\nAs long as k >= 3, we can always do this. \r\n\r\nIf k < 3, then we cannot have a string of length longer than 2. And it would have been caught by the previous part of the program. :)\r\n\r\nstring next_good_string;\r\n    for(int i = 0 ; i < first_greater_position; i++)\r\n        next_good_string += S[i];\r\n\r\n    next_good_string += replacement;\r\n\r\n    for(int i = first_greater_position + 1; i < length; i++)\r\n    {\r\n        char current_char;\r\n\r\n        for(current_char = 'a'; current_char <= 'c'; current_char++)\r\n        {\r\n            if( (i - 1 >= 0 && next_good_string[i - 1] == current_char) ||\r\n                (i - 2 >= 0 && next_good_string[i - 2] == current_char) )\r\n            {\r\n                continue;\r\n            }\r\n            else\r\n            {\r\n                next_good_string += current_char;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 23/On Number of Decompositions into Multipliers Explanation.txt",
    "content": "Let us notice that if N is a prime number we can't break it down further and can only assign it to one of k places. \r\n\r\n------------------------\r\n\r\nIf N = p^m, \r\n\r\nThen it is equal to the number of ways of writing m as the result of m summands. \r\n\r\nThis is like stars and bars. \r\n\r\nThe answer is C(m + k - 1, k - 1)\r\n\r\n----------------------------------\r\n\r\nEach prime is independent.\r\n\r\nWe will break down N into it's prime factors and solve seperately for each prime exponent.\r\n\r\n--------------------------------\r\n\r\nint main()\r\n{\r\n    sieve();\r\n    precompute();\r\n\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    map <int, int> prime_exponents;\r\n\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int element;\r\n        cin >> element;\r\n\r\n        factorise(element, prime_exponents);\r\n    }\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long answer = 1;\r\n    for(map <int, int> :: iterator it = prime_exponents.begin(); it != prime_exponents.end(); it++)\r\n    {\r\n        int exponent = it->second;\r\n\r\n        answer *= choose(no_of_elements + exponent - 1, no_of_elements - 1);\r\n\r\n        answer %= MOD;\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/Summarise to Powers of Two Explanation.txt",
    "content": "For every element of the array, check if there exists (2^p - A[i]), for 30 powers of 2. \r\n\r\nThe special case is when (2^p - A[i]) = A[i], In that case, the frequency of the complement must be 2, not 1. \r\n\r\n------------------------------------------------\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    scanf(\"%d\", &no_of_elements);\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    map <int, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        scanf(\"%d\", &A[i]);\r\n        frequency[A[i]]++;\r\n    }\r\n\r\n    int no_of_deletions = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        int complement_exists = false;\r\n\r\n        for(int power = 0; power <= 32; power++)\r\n        {\r\n            int complement = (1LL << power) - A[i];\r\n\r\n            if(complement == A[i])\r\n            {\r\n                if(frequency[A[i]] >= 2)\r\n                    complement_exists = true;\r\n            }\r\n            else if(frequency.find(complement) != frequency.end())\r\n            {\r\n                complement_exists = true;\r\n            }\r\n        }\r\n\r\n        if(!complement_exists)\r\n            no_of_deletions++;\r\n    }\r\n\r\n    printf(\"%d\\n\", no_of_deletions);\r\n    return 0;"
  },
  {
    "path": "Explanations/Explanations 23/The Fair Nut and String Explanation.txt",
    "content": "Every alphabet other than 'a' and 'b' does not matter. We might as well delete it. \r\n\r\nWhenever we have a block of 'a' ... We may choose a single 'a' from it or not choose any 'a'. \r\n\r\nEach block is independent. The answer is Prod(Block_size + 1) - 1\r\n\r\nWe subtract 1 because we have also counted the empty sequence. \r\n\r\n--------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int MOD = 1e9 + 7;\r\n    long long total_sequences = 1, current_block_of_a = 0;\r\n    for(int i = 0; i <= S.size(); i++)\r\n    {\r\n        if(S[i] == 'a')\r\n        {\r\n            current_block_of_a++;\r\n        }\r\n        else if(i == S.size() || S[i] == 'b')\r\n        {\r\n            total_sequences = (total_sequences*(current_block_of_a + 1))%MOD;\r\n\r\n            current_block_of_a = 0;\r\n        }\r\n    }\r\n\r\n    total_sequences = (total_sequences + MOD - 1)%MOD;\r\n    cout << total_sequences;\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 23/The Meaningless Game Explanation.txt",
    "content": "The sum of the prime exponents of numbers in both A and B should be a multiple of 3. \r\n\r\nLet A win X points in total and let B win Y points in total. \r\n\r\nThen A = X^2 Y and B = X^2 Y\r\n\r\nNow we notice that AB = (XY)^3\r\n\r\nWe can compute the first million cubes to find the cube roots till 10^{18}.\r\n\r\nAfter finding XY = (AB)^(1/3)\r\n\r\nA = X (XY) and B = Y (XY)\r\n\r\nNow we can simply find X and Y and then we check if the A and B are consistent.\r\n\r\n----------------\r\n\r\nint main()\r\n{\r\n    int no_of_people, distinct_targets;\r\n    scanf(\"%d %d\", &no_of_people, &distinct_targets);\r\n\r\n    vector <int> A(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &A[i]);\r\n\r\n    vector <int> time(no_of_people + 1);\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        scanf(\"%d\", &time[i]);\r\n\r\n    map <int, int> max_time_for_task;\r\n    vector <int> free_time;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n    {\r\n        if(max_time_for_task[A[i]] != 0)\r\n            free_time.push_back(min(time[i], max_time_for_task[A[i]]));\r\n\r\n        max_time_for_task[A[i]] = max(max_time_for_task[A[i]], time[i]);\r\n    }\r\n\r\n    sort(all(free_time));\r\n\r\n    int distinct_numbers = max_time_for_task.size();\r\n    int required_new_distinct_numbers = distinct_targets - distinct_numbers;\r\n\r\n    long long total_time = 0;\r\n    for(int i = 0; i < required_new_distinct_numbers; i++)\r\n        total_time += free_time[i];\r\n\r\n    printf(\"%I64d\\n\", total_time);\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 24/Brutality Explanation.txt",
    "content": "Suppose there was only one alphabet. Then what is the answer ? \r\n\r\nThe answer is the k highest numbers. \r\n\r\nNow we have to treat every block of consecutive characters independently. \r\n\r\nFor each block, maintain the costs. Sort it and take the k greatest numbers as the answer. \r\n\r\nA block ends either when you have reached the end of the string or when S[i] != S[i - 1].\r\n\r\n----\r\n\r\nint main()\r\n{\r\n    int length, max_elements;\r\n    cin >> length >> max_elements;\r\n\r\n    vector <int> A(length);\r\n    for(int i = 0; i < length; i++)\r\n        cin >> A[i];\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    long long total = 0;\r\n    vector <int> last_pressed_costs;\r\n\r\n    for(int i = 0; i <= length; i++)\r\n    {\r\n        if(i == length ||S[i] != S[i - 1])\r\n        {\r\n            sort(all(last_pressed_costs));\r\n\r\n            reverse(all(last_pressed_costs));\r\n\r\n            for(int j = 0; j < min(max_elements, last_pressed_costs.size()); j++)\r\n            {\r\n                total += last_pressed_costs[j];\r\n            }\r\n\r\n            last_pressed_costs.clear();\r\n        }\r\n\r\n        if(i == length) continue;\r\n\r\n        last_pressed_costs.push_back(A[i]);\r\n\r\n    }\r\n\r\n    cout << total;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Connect Explanation.txt",
    "content": "Let us do DFS and put two cells in the same component if they lie on land and are reachable without crossing water. \r\n\r\nIf the Start and Finish points are in the same component, the answer is 0. \r\n\r\nElse, make a vector of all the points in the starting component and all the points in the finish component and find the minimum distance between these points.\r\n\r\nActually, we do not need to handle the 0 case seperately. \r\n\r\nSimply make a component of all points in the start and finish point and find the distance between every pair of points between them. If it's the same component, the distance will be 0.\r\n\r\n-------------\r\n\r\nint calculate_distance(Point P, Point Q)\r\n{\r\n    return (P.x - Q.x)*(P.x - Q.x) + (P.y - Q.y)*(P.y - Q.y);\r\n}\r\n\r\nint is_outside(int x, int y, int n)\r\n{\r\n    return (x < 1 || n < x || y < 1 || n < y);\r\n}\r\n\r\nvoid dfs(int x, int y, int n, int number)\r\n{\r\n    if(is_water[x][y] || is_outside(x, y, n) || component_no[x][y] != 0)\r\n        return;\r\n\r\n    component_no[x][y] = number;\r\n\r\n    for(int i = 0; i < NO_OF_NEIGHBOURS; i++)\r\n    {\r\n        dfs(x + next_x[i], y + next_y[i], n, number);\r\n    }\r\n}\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    Point start, finish;\r\n    cin >> start.x >> start.y >> finish.x >> finish.y;\r\n\r\n    memset(is_water, false, sizeof(is_water));\r\n    for(int i = 0; i < n; i++)\r\n    {\r\n        string row;\r\n        cin >> row;\r\n\r\n        for(int j = 0; j < n; j++)\r\n        {\r\n            if(row[j] == '1')\r\n            {\r\n                is_water[i + 1][j + 1] = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    memset(component_no, 0, sizeof(component_no));\r\n    int last_component_no = 0;\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            if(component_no[x][y] == 0)\r\n            {\r\n                dfs(x, y, n, ++last_component_no);\r\n            }\r\n        }\r\n    }\r\n\r\n    vector <Point> start_component, finish_component;\r\n    for(int x = 1; x <= n; x++)\r\n    {\r\n        for(int y = 1; y <= n; y++)\r\n        {\r\n            if(component_no[x][y] == component_no[start.x][start.y])\r\n                start_component.push_back(Point(x, y));\r\n\r\n            if(component_no[x][y] == component_no[finish.x][finish.y])\r\n                finish_component.push_back(Point(x, y));\r\n        }\r\n    }\r\n\r\n    int distance = oo;\r\n    for(int i = 0; i < start_component.size(); i++)\r\n    {\r\n        for(int j = 0; j < finish_component.size(); j++)\r\n        {\r\n            distance = min(distance, calculate_distance(start_component[i], finish_component[j]));\r\n        }\r\n    }\r\n\r\n    cout << distance;\r\n    return 0;\r\n}\r\n\r\n"
  },
  {
    "path": "Explanations/Explanations 24/Div Times Mod Explanation.txt",
    "content": "Let us iterate over the divisors of n. \r\n\r\nFor each pair of factors (f1, f2) such that f1 x f2 = n, \r\n\r\nOne will be the quotient and one will the remainder. \r\n\r\nWe need to check if the remainder is smaller than k, of course. \r\n\r\nAnd then among all such values we set x to the minimum. \r\n\r\n-------------\r\n\r\nint main()\r\n{\r\n    int n, k;\r\n    cin >> n >> k;\r\n\r\n    const int oo = 1e9;\r\n    int answer = oo;\r\n\r\n    for(int i = 1; i*i <= n; i++)\r\n    {\r\n        if(n%i == 0)\r\n        {\r\n            int quotient = i, remainder = n/i;\r\n\r\n            if(remainder < k)\r\n                answer = min(answer, quotient*k + remainder);\r\n\r\n            quotient = n/i, remainder = i;\r\n            if(remainder < k)\r\n                answer = min(answer, quotient*k + remainder);\r\n        }\r\n    }\r\n\r\n    cout << answer;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Diverse Garland Explanation.txt",
    "content": "Greedy Solution works.\r\n\r\nWe will from from i = 1 to N\r\n\r\nWhenever S[i] = S[i - 1], we will change S[i]'s colour. \r\n\r\n\r\nNote that if we change whenever S[i] = S[i + 1], then it might not be optimal as swapping S[i] when it is different from S[i + 1] might solve at most one position's problem. \r\n\r\nBut swapping when S[i] = S[i - 1] can solve two positions' problems.\r\n\r\n---\r\n\r\nI kept a string called colour \"RGB\" for convenience in knowing what to swap. \r\n\r\nSimilar to the C of this contest, where I kept 6 string - RGB, RBG, BGR, BRG, GRB, GBR\r\n\r\nAnd counted number of replacements for each string S[i] = R[i%3].\r\n\r\n---\r\n \r\nint main()\r\n{\r\n    int length;\r\n    string S;\r\n    cin >> length >> S;\r\n\r\n    string colour = \"RGB\";\r\n    int replacements = 0;\r\n\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        if(S[i] == S[i - 1])\r\n        {\r\n            for(int j = 0; j < colour.size(); j++)\r\n            {\r\n                if( (i + 1 == length && colour[j] != S[i - 1]) || (colour[j] != S[i + 1] && colour[j] != S[i - 1]) )\r\n                {\r\n                    replacements++;\r\n                    S[i] = colour[j];\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << replacements << \"\\n\" << S;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Division and Union Explanation.txt",
    "content": "Let us sort the segments by their endings. \r\n\r\nThen for some segment Si, we know that all segments from [i + 1, ... , n] have their endings after Si. \r\n\r\nIf we know that the smallest beginning is also after Si, then we can place [1, 2, ... , i] in one group and the remaining segments in the other group. \r\n\r\nAlternatively, we could also sort by beginnings and then check for some i, if the largest ending in [1, 2, ... , i - 1] is before the beginning of Si. \r\n\r\nIf no such segment i exists, then it means the segments are all connected and two such groups are not possible.\r\n\r\n-----\r\n\r\nvoid solve()\r\n{\r\n    int no_of_segments;\r\n    cin >> no_of_segments;\r\n\r\n    vector <line> L;\r\n    for(int i = 0; i < no_of_segments; i++)\r\n    {\r\n        int left, right;\r\n        cin >> left >> right;\r\n\r\n        L.push_back(line(left, right, i));\r\n    }\r\n\r\n    sort(all(L));\r\n\r\n    vector <int> minimum_left_from(no_of_segments);\r\n    for(int i = no_of_segments - 1; i >= 0; i--)\r\n    {\r\n        if(i == no_of_segments - 1)\r\n            minimum_left_from[i] = L[i].left;\r\n        else\r\n            minimum_left_from[i] = min(minimum_left_from[i + 1], L[i].left);\r\n    }\r\n\r\n    const int NOT_FOUND = -1;\r\n    int first_group_ending = NOT_FOUND;\r\n\r\n    for(int i = 0; i < no_of_segments - 1; i++)\r\n    {\r\n        if(L[i].right < minimum_left_from[i + 1])\r\n            first_group_ending = i;\r\n    }\r\n\r\n    if(first_group_ending == NOT_FOUND)\r\n    {\r\n        cout << NOT_FOUND << \"\\n\";\r\n        return ;\r\n    }\r\n\r\n    vector <int> group(no_of_segments);\r\n    for(int i = 0; i < no_of_segments; i++)\r\n        group[L[i].position] = (i <= first_group_ending ? 1 : 2);\r\n\r\n    for(int i = 0; i < no_of_segments; i++)\r\n        cout << group[i] << \" \";\r\n\r\n    cout << \"\\n\";\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Finite or Not Explanation.txt",
    "content": "The fraction is finite, if gcd(p, q) = 1 and q | b^k. \n\nLet us keep dividing denominator by base to determine if there are prime factors in q that are not in b. \n\n-----------------\n\nvoid solve()\n{\n    LL numerator, denominator, base;\n    scanf(\"%I64d %I64d %I64d\", &numerator, &denominator, &base);\n\n    LL gcd_fraction = gcd(numerator, denominator);\n    numerator /= gcd_fraction;\n    denominator /= gcd_fraction;\n\n    base = gcd(base, denominator);\n\n    while(base > 1)\n    {\n        while(denominator%base == 0) denominator /= base;\n\n        base = gcd(base, denominator);\n    }\n\n    printf(denominator == 1 ? \"Finite\\n\" : \"Infinite\\n\");\n}\n"
  },
  {
    "path": "Explanations/Explanations 24/Ilya and Escalator Explanation.txt",
    "content": "Let f(i, j) represent the probability that there are i people at time j. \r\n\r\nf(i, j) = p f(i - 1, j - 1) + (1 - p) f(i, j - 1)\r\n\r\nThe first term represents the case where a person comes on at time j. So there have to be (i - 1) people at time (j - 1). \r\n\r\nThe second term represents the case where no new person steps on at time j. So there have to be (i) people at time (j - 1). \r\n\r\n----\r\n\r\nNow, f(N, j) = f(N, j - 1) + (p) f(N - 1, j - 1)\r\n\r\nThe reason is that if there are N people already on the esclator, no new person can step on so there's no need to multiply it with (1 - p).\r\n\r\n----\r\n\r\nf(0, j) = (i - p) f(0, j - 1)\r\n\r\n-----\r\n\r\nNow to find the expectation, we will sum over i f(i, T).\r\n\r\n-----------\r\n\r\n\r\nint main()\r\n{\r\n    int no_of_people, total_time;\r\n    double new_person_probability;\r\n    cin >> no_of_people >> new_person_probability >> total_time;\r\n\r\n    double no_new_person_probability = 1 - new_person_probability;\r\n\r\n    memset(probability, 0, sizeof(probability));\r\n    probability[0][0] = 1;\r\n\r\n    for(int t = 1; t <= total_time; t++)\r\n    {\r\n        probability[0][t] = no_new_person_probability*probability[0][t - 1];\r\n\r\n        for(int i = 1; i < no_of_people; i++)\r\n        {\r\n            probability[i][t] = new_person_probability*probability[i - 1][t - 1] +\r\n                                no_new_person_probability*probability[i][t - 1];\r\n\r\n        }\r\n\r\n        probability[no_of_people][t] = probability[no_of_people][t - 1] +\r\n                        new_person_probability*probability[no_of_people - 1][t - 1];\r\n    }\r\n\r\n    double expectation = 0;\r\n    for(int i = 1; i <= no_of_people; i++)\r\n        expectation += i*probability[i][total_time];\r\n\r\n    cout << setprecision(7) << expectation;\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Increasing by Modulo Explanation.txt",
    "content": "We can binary search the number of operations required to make the array non-decreasing. \r\n\r\nWe can make A[i] = (A[i], A[i] + x) (mod M). \r\n\r\nThese are the reachable values for A[i]. \r\n\r\nWe will choose the smallest value possible at each step for each A[i], while maintaining the condition that A[i] is not smaller than the prefix minimum. \r\n\r\nIf possible we will make A[i] = the prefix minimum. Otherwise, we will make the minimum = A[i]. \r\n\r\nIf A[i] can't be made >= minimum and is < minimum, then it is not possible in x moves. \r\n\r\n---\r\n\r\nAt each step, we are making the minimum as small as possible. It is never optimal to increase some previous element by more than what we have as that would increase the minimum.\r\n\r\n---\r\n\r\nint possible(int operations, int m, vector <int> &A)\r\n{\r\n    int minimum = 0;\r\n\r\n    for(int i = 1; i < A.size(); i++)\r\n    {\r\n        if( (A[i] <= minimum && A[i] + operations >= minimum) || (A[i] > minimum && A[i] + operations - m >= minimum) )\r\n            continue;\r\n\r\n        if(A[i] < minimum)\r\n            return false;\r\n\r\n        minimum = A[i];\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_elements, m;\r\n    cin >> no_of_elements >> m;\r\n\r\n    vector <int> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    int left = -1, right = m;\r\n    while(right - left > 1)\r\n    {\r\n        int mid = (left + right)/2;\r\n\r\n        if(possible(mid, m, A))\r\n            right = mid;\r\n        else\r\n            left = mid;\r\n    }\r\n\r\n    cout << right;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Nice Garland Explanation.txt",
    "content": "Every position = 0 (mod 3) must have the same colour. \r\n\r\nEvery position = 1 (mod 3) must have the same colour. \r\n\r\nEvery position = 2 (mod 3) must have the same colour. \r\n\r\nWe must distribute RGB into 3 holes. There are 3! = 6 ways of doing this. \r\n\r\nWe will count the number of replacements required in the 6 ways and give the one that minimises it. \r\n\r\n----\r\n\r\nint replacements(string &R, string &S)\r\n{\r\n    int difference_count = 0;\r\n\r\n    for(int i = 0; i < S.size(); i++)\r\n        difference_count += (S[i] != R[i%3]);\r\n\r\n    return difference_count;\r\n}\r\n\r\nint main()\r\n{\r\n    int length;\r\n    cin >> length;\r\n\r\n    string S;\r\n    cin >> S;\r\n\r\n    const int NO_OF_OPTIONS = 6, oo = 1e9;\r\n\r\n    string option[NO_OF_OPTIONS] = {\"RGB\", \"RBG\", \"BRG\", \"BGR\", \"GRB\", \"GBR\"};\r\n\r\n    int minimum_replacement = oo, best_option = 0;\r\n\r\n    for(int i = 0; i < NO_OF_OPTIONS; i++)\r\n    {\r\n        int replacements_here = replacements(option[i], S);\r\n\r\n        if(replacements_here < minimum_replacement)\r\n        {\r\n            minimum_replacement = replacements_here;\r\n            best_option = i;\r\n        }\r\n    }\r\n\r\n    cout << minimum_replacement << \"\\n\";\r\n    for(int i = 0; i < length; i++)\r\n        cout << option[best_option][i%3];\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Planning the Expedition Explanation.txt",
    "content": "Let us use binary search over the number of days.\r\n \r\nIt can be proved that it is a monotonic function. \r\n\r\n---------------\r\n\r\nint possible(vector <int> A, int days, int min_participants)\r\n{\r\n    int participants = 0;\r\n    for(int i = 0; i < A.size(); i++)\r\n    {\r\n        participants += A[i]/days;\r\n        A[i] %= days;\r\n    }\r\n\r\n    return (participants >= min_participants);\r\n}\r\n\r\nint main()\r\n{\r\n    int no_of_participants, no_of_packages;\r\n    scanf(\"%d %d\", &no_of_participants, &no_of_packages);\r\n\r\n    const int MAX = 100;\r\n    vector <int> frequency(MAX + 1, 0);\r\n    for(int i = 1; i <= no_of_packages; i++)\r\n    {\r\n        int type;\r\n        scanf(\"%d\", &type);\r\n\r\n        frequency[type]++;\r\n    }\r\n\r\n    if(no_of_packages < no_of_participants)\r\n    {\r\n        printf(\"0\");\r\n        return 0;\r\n    }\r\n\r\n    int left_days = 1, right_days = MAX;\r\n    while(left_days <= right_days)\r\n    {\r\n        int mid_days = (left_days + right_days) >> 1;\r\n\r\n        if(possible(frequency, mid_days, no_of_participants))\r\n        {\r\n            if(mid_days == right_days || !possible(frequency, mid_days + 1, no_of_participants))\r\n            {\r\n                printf(\"%d\\n\", mid_days);\r\n                return 0;\r\n            }\r\n            else\r\n            {\r\n                left_days = mid_days + 1;\r\n            }\r\n        }\r\n        else\r\n        {\r\n            right_days = mid_days - 1;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Playing Piano Explanation.txt",
    "content": "Let f(i, j) be true if it is possible to play the first i notes using the finger j for the last note.\r\n\r\nWe will first calculate f(i, j). \r\n\r\nIf f(N, j) is true for any j, it is possible other wise it is not. \r\n\r\nFor example, if A[i - 1] < A[i], \r\n\r\nThen f(i, j) is true, if for some j', where j' < j and f(i - 1, j) is true. \r\n\r\nSince j' is a smaller finger, if we can play (i - 1) with j' last, then we can play i notes with j last. \r\n\r\n\r\nfor(int i = 1; i <= no_of_notes; i++)\r\n    {\r\n        for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n        {\r\n            if(i == 1)\r\n            {\r\n                is_possible[i][finger] = true;\r\n                continue;\r\n            }\r\n\r\n            if(notes[i - 1] <= notes[i])\r\n            {\r\n                for(int previous_finger = 1; previous_finger < finger; previous_finger++)\r\n                {\r\n                    if(is_possible[i - 1][previous_finger])\r\n                    {\r\n                        is_possible[i][finger] = true;\r\n                    }\r\n                }\r\n            }\r\n\r\n            if(notes[i - 1] >= notes[i])\r\n            {\r\n                for(int previous_finger = NO_OF_FINGERS; previous_finger > finger; previous_finger--)\r\n                {\r\n                    if(is_possible[i - 1][previous_finger])\r\n                    {\r\n                        is_possible[i][finger] = true;\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n\r\n\r\n\r\n-----\r\n\r\nNow to actually construct the sequence, we must go backwards. \r\n\r\nFor every i, look at A[i] and A[i + 1]. \r\n\r\nCase 1 - A[i] < A[i + 1]. \r\n\r\nThen look at the finger assigned to note (i + 1). Find any smaller finger j, such that f(i, j) is true. Then assign finger j to note i. \r\n\r\nCase 2 - A[i] > A[i + 1]\r\n\r\nThen look at the finger assigned to note (i + 1). Find any greater finger j, such that f(i, j) is true. \r\n\r\nCase 3 - A[i] = A[i + 1]\r\n\r\nAssign any finger j, such that f(i, j) is true and j is not the finger used for the i-th note. \r\n\r\nvector <int> playing_finger(no_of_notes + 1);\r\n    for(int i = no_of_notes; i >= 1; i--)\r\n    {\r\n        if(i == no_of_notes)\r\n        {\r\n            for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n            {\r\n                if(is_possible[i][finger])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n\r\n            continue;\r\n        }\r\n\r\n        if(notes[i] < notes[i + 1])\r\n        {\r\n            for(int finger = playing_finger[i + 1] - 1; finger >= 1; finger--)\r\n            {\r\n                if(is_possible[i][finger])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        if(notes[i] > notes[i + 1])\r\n        {\r\n            for(int finger = playing_finger[i + 1] + 1; finger <= NO_OF_FINGERS; finger++)\r\n            {\r\n                if(is_possible[i][finger])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n\r\n        if(notes[i] == notes[i + 1])\r\n        {\r\n            for(int finger = 1; finger <= NO_OF_FINGERS; finger++)\r\n            {\r\n                if(is_possible[i][finger] && finger != playing_finger[i + 1])\r\n                {\r\n                    playing_finger[i] = finger;\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n    }"
  },
  {
    "path": "Explanations/Explanations 24/Posterized Explanation.txt",
    "content": "int main()\r\n{\r\n    int no_of_colours, group_size;\r\n    scanf(\"%d %d\", &no_of_colours, &group_size);\r\n\r\n    const int MAX_COLOUR = 255;\r\n    vector <int> colour(no_of_colours + 1);\r\n\r\n    for(int i = 1; i <= no_of_colours; i++)\r\n        scanf(\"%d\", &colour[i]);\r\n\r\n    vector <int> key(MAX_COLOUR + 1);\r\n\r\n    vector <int> used(MAX_COLOUR + 1, false);\r\n\r\n    for(int i = 1; i <= no_of_colours; i++)\r\n    {\r\n        int current_colour = colour[i];\r\n\r\n        if(!used[current_colour])\r\n        {\r\n            int first_colour = max(0, current_colour - group_size + 1);\r\n\r\n            while(used[first_colour] && key[first_colour] + group_size - 1 < current_colour)\r\n                first_colour++;\r\n\r\n            if(!used[first_colour])\r\n                key[first_colour] = first_colour, used[first_colour] = true;\r\n\r\n            for(int j = first_colour + 1; j <= current_colour; j++)\r\n            {\r\n                key[j] = key[first_colour];\r\n                used[j] = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 1; i <= no_of_colours; i++)\r\n        printf(\"%d \", key[colour[i]]);\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Powers of Two Explanation.txt",
    "content": "if k < no of bits in n, then it is not possible because the binary representation of a number writes it using the fewest possible powers of 2. \r\n\r\nIf k > n, then it is not possible as we can at most have n ones. \r\n\r\nThese two cases aside, we always have an answer. \r\n\r\nWe will be greedy. As long as we haven't gotten the required number of summands, we simply pick some summand > 1, 2^i remove it and put in 2^{i -1} and 2^{i - 1}.\r\n\r\n-------\r\n\r\nint main()\r\n{\r\n    int n, no_of_summands;\r\n    cin >> n >> no_of_summands;\r\n\r\n    int no_of_summands_made = 0;\r\n    const int MAX_POWER = 32;\r\n    vector <int> frequency(MAX_POWER, 0);\r\n\r\n    for(int i = 0; i < MAX_POWER; i++)\r\n    {\r\n        if(is_bit_set(i, n))\r\n        {\r\n            frequency[i]++;\r\n\r\n            no_of_summands_made++;\r\n        }\r\n    }\r\n\r\n    if(no_of_summands < no_of_summands_made || no_of_summands > n)\r\n    {\r\n        cout << \"NO\\n\";\r\n        return 0;\r\n    }\r\n\r\n    cout << \"YES\\n\";\r\n\r\n    while(no_of_summands_made < no_of_summands)\r\n    {\r\n        for(int i = 1; i < MAX_POWER; i++)\r\n        {\r\n            if(frequency[i] > 0) //Break 2^i into 2^{i - 1} and 2^{i - 1}\r\n            {\r\n                frequency[i]--;\r\n                frequency[i - 1] += 2;\r\n\r\n                no_of_summands_made++;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    for(int i = 0; i < MAX_POWER; i++)\r\n    {\r\n        for(int j = 0; j < frequency[i]; j++)\r\n        {\r\n            cout << (1 << i) << \" \";\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Splitting into Digits Explanation.txt",
    "content": "Print N 1s. This ensures that they sum to N and they are all the same. \r\n\r\n---\r\n\r\nint main()\r\n{\r\n    int n;\r\n    cin >> n;\r\n\r\n    cout << n << \"\\n\";\r\n    for(int i = 1; i <= n; i++) cout << \"1 \";\r\n\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Stages Explanation.txt",
    "content": "int main()\r\n{\r\n    int no_of_letters, required_letters;\r\n    string S;\r\n    cin >> no_of_letters >> required_letters >> S;\r\n\r\n    const int NO_OF_ALPHABETS = 26;\r\n    vector <int> present(NO_OF_ALPHABETS, false);\r\n    for(int i = 0; i < no_of_letters; i++)\r\n        present[S[i] - 'a'] = true;\r\n\r\n    int sum = 0, chosen = 0;\r\n    for(int i = 0; i < NO_OF_ALPHABETS && chosen < required_letters; i++)\r\n    {\r\n        if(present[i])\r\n        {\r\n            chosen++;\r\n\r\n            sum += i + 1;\r\n            i++;\r\n        }\r\n    }\r\n\r\n    cout << (chosen < required_letters ? -1 : sum);\r\n\r\n    return 0;\r\n}\r\n"
  },
  {
    "path": "Explanations/Explanations 24/Tanya and Candies Explanation.txt",
    "content": "Whenever we remove an element, then \r\n\r\neven_sum_till[i - 1] + odd_sum_from[i + 1] = odd_sum_till[i - 1] + even_sum_from[i + 1]. \r\n\r\nThe reason is that removing an element changes the parity of all indices after it. \r\n\r\nWe need to precompute the prefix and suffix sums. \r\n\r\nI did this elegantly with a two dimensional array.\r\n\r\n---------------\r\n\r\nconst int MAX_N = 2e5 + 5, EVEN = 0, ODD = 1;\r\nlong long sum_till[MAX_N][2], sum_from[MAX_N][2];\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <int> A(no_of_elements);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    sum_till[0][ODD] = sum_till[0][EVEN] = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        sum_till[i][ODD] = sum_till[i - 1][ODD];\r\n        sum_till[i][EVEN] = sum_till[i - 1][EVEN];\r\n\r\n        sum_till[i][i%2] += A[i];\r\n    }\r\n\r\n    sum_from[no_of_elements + 1][ODD] = sum_from[no_of_elements + 1][EVEN] = 0;\r\n    for(int i = no_of_elements; i >= 1; i--)\r\n    {\r\n        sum_from[i][ODD] = sum_from[i + 1][ODD];\r\n        sum_from[i][EVEN] = sum_from[i + 1][EVEN];\r\n\r\n        sum_from[i][i%2] += A[i];\r\n    }\r\n\r\n    int no_of_points = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        no_of_points += (sum_till[i - 1][EVEN] + sum_from[i + 1][ODD] == sum_till[i - 1][ODD] + sum_from[i + 1][EVEN]);\r\n    }\r\n\r\n    cout << no_of_points;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/The Way to Home Explanation.txt",
    "content": "Let f(i) denote the minimum number of jumps to reach position i. \r\n\r\nThen f(i) = 1 + min{f(i - 1), f(i - 2), f(i - 3), f(i - 4), ... , f(i - d)}\r\n\r\n---------\r\n\r\nint main()\r\n{\r\n    int length, max_jump;\r\n    cin >> length >> max_jump;\r\n\r\n    string path;\r\n    cin >> path;\r\n\r\n    const int oo = 1e9;\r\n    vector <int> minimum_jumps_to_reach(length, 0);\r\n    minimum_jumps_to_reach[0] = 0;\r\n\r\n    for(int i = 1; i < length; i++)\r\n    {\r\n        minimum_jumps_to_reach[i] = oo;\r\n\r\n        if(path[i] == '0') continue;\r\n\r\n        for(int j = 1; j <= max_jump && i - j >= 0; j++)\r\n        {\r\n            minimum_jumps_to_reach[i] = min(minimum_jumps_to_reach[i], 1 + minimum_jumps_to_reach[i - j]);\r\n        }\r\n    }\r\n\r\n    cout << (minimum_jumps_to_reach[length - 1] == oo ? -1 : minimum_jumps_to_reach[length - 1]);\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Vanya and Label Explanation.txt",
    "content": "If a certain bit is 1, then we only have one option 1. \r\n\r\nIf a certain bit is 0, then we have 3 options. \r\n\r\nGo through every bit of every letter, and the answer is 3^z, where z is the number of 0s.\r\n\r\n--------------------\r\n\r\nint main()\r\n{\r\n    string S;\r\n    cin >> S;\r\n\r\n    long long no_of_ways = 1;\r\n\r\n    const int MOD = 1e9 + 7;\r\n    for(int i = 0; i < S.size(); i++)\r\n    {\r\n        for(int bit = 0; bit < 6; bit++)\r\n        {\r\n            if(!is_bit_set(value(S[i]), bit))\r\n            {\r\n                no_of_ways = (no_of_ways*3)%MOD;\r\n            }\r\n        }\r\n    }\r\n\r\n    cout << no_of_ways;\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Where Do I Turn Explanation.txt",
    "content": "int main()\r\n{\r\n    int a_x, a_y, b_x, b_y, c_x, c_y;\r\n    scanf(\"%d %d %d %d %d %d\", &a_x, &a_y, &b_x, &b_y, &c_x, &c_y);\r\n\r\n    //Checking if (y2 - y1)/(x2-x1) = slope of AB = Slope of BC. Multiplication is done to avoid division by zero error and precision losses.\r\n    if( (c_y - b_y)*1LL*(b_x - a_x) - (b_y - a_y)*1LL*(c_x - b_x) == 0 )\r\n        printf(\"TOWARDS\\n\");\r\n    else if( (c_y - b_y)*1LL*(b_x - a_x) - (b_y - a_y)*1LL*(c_x - b_x) > 0 )\r\n        printf(\"LEFT\\n\");\r\n    else\r\n        printf(\"RIGHT\\n\");\r\n    return 0;\r\n}"
  },
  {
    "path": "Explanations/Explanations 24/Zero Quantity Maximisation Explanation.txt",
    "content": "How do we make C[1] = 0 ? \r\n\r\nWe have to set D = -B[1]/A[1].\r\n\r\nNow, when we set D = -B[1]/A[1] ? Any pair of integers where B[i]/A[i] = B[1]/A[1].\r\n\r\nSo, we simply have to keep track of the frequency of each fraction and find out which comes the highest. \r\n\r\nAlso, a few things to keep in mind - \r\n\r\n1. If (A[i] == 0), then we cannot have a fraction, so we just ignore it. \r\n\r\n2. If(A[i] = B[i] = 0) already, then we will always get a 0 at this position so we need to keep track of the number of such positions.\r\n\r\n--------\r\n\r\nA few things to keep in mind. \r\n\r\nWhile implementing fractions, \r\n\r\n1. Keep track of the fraction in it's reduced form where the numerator and denominator are coprime. \r\n\r\n2. a/b = (-a)/(-b) \r\n\r\n3. (-a)/b = a/(-b). So, try to standardise and maintain only the numerator or only the denominator as negative.\r\n\r\n4. While calculate gcd(a, b) do gcd(|a|, |b|)\r\n\r\n5. Since we are using maps, we need to over load the < operator so that the map knows how to store the fractions. \r\n\r\n6. In maps, two objects are considered equal if !(a < b) && !(b < a).  So while overloading the < operator, don't add <= by mistake.\r\n\r\nHere is the fraction structure.\r\n\r\n--------\r\n\r\nstruct fraction\r\n{\r\n    long long numerator, denominator;\r\n\r\n    fraction(){}\r\n\r\n    fraction(long long N, long long D)\r\n    {\r\n        long long G = __gcd(abs(N), abs(D));\r\n\r\n        numerator = N/G;\r\n        denominator = D/G;\r\n\r\n        if(denominator < 0)\r\n        {\r\n            numerator *= -1;\r\n            denominator *= -1;\r\n        }\r\n    }\r\n\r\n    const int operator <(const fraction &F) const\r\n    {\r\n        return (denominator*F.numerator - numerator*F.denominator < 0);\r\n    }\r\n};\r\n\r\n---------\r\n\r\nThe solution\r\n\r\nint main()\r\n{\r\n    int no_of_elements;\r\n    cin >> no_of_elements;\r\n\r\n    vector <LL> A(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> A[i];\r\n\r\n    vector <LL> B(no_of_elements + 1);\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        cin >> B[i];\r\n\r\n    int both_zeroes = 0;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n        both_zeroes += (A[i] == 0 && B[i] == 0);\r\n\r\n    map <fraction, int> frequency;\r\n    for(int i = 1; i <= no_of_elements; i++)\r\n    {\r\n        if(A[i] == 0)\r\n            continue;\r\n\r\n        frequency[fraction(-B[i], A[i])]++;\r\n    }\r\n\r\n    int max_frequency = 0;\r\n    for(map <fraction, int> :: iterator it = frequency.begin(); it != frequency.end(); it++)\r\n    {\r\n        max_frequency = max(max_frequency, it->second);\r\n    }\r\n\r\n    int answer = max_frequency + both_zeroes;\r\n\r\n    cout << answer;\r\n    return 0;\r\n}"
  },
  {
    "path": "README.md",
    "content": "<img src=\"https://it-edu.com/sites/default/files/codeforceslogo.png\" alt=\"CodeForces\"/>\n\nThis repository is a notebook consisting of all my solutions to questions from CodeForces.\n\nIt is divided into two sections. \nThe folder 'Explanation' consists of text files which document the algorithm and my explanation of the problems.\n\nGrouping is also done because there are significant changes in my programming style over time. \n\nMy handle is `ghoshsai5000`\n"
  }
]