Help Mike in finding the total number of pairs of elements A[i] and A[j] belonging to the given set such that i < j and their sum is divisible by K
+
+To solve the problem in O(K) time limit, we can create an array rem[K]. The array rem[i] will store the number of integers in the set A, such that on dividing by K, you get i as the remainder. rem[i] can be calculated in O(1) time.
+rem[i] = (N-i)/K;
+
+We can sum up all these possibilities to get the required output.
+
+
+
+using namespace std;
+
+#define print(p) cout<>T;
+ while(T--)
+ {
+ cin>>N>>K;
+ long long int arr[K];
+ arr[0] = N/K;
+ for(i=1 ; i< K ; i++)
+ arr[i] = (int)(N-i)/K + 1;
+ if(K%2!=0)
+ {
+ long long int sum = 0;
+ sum = sum + (arr[0]*(arr[0] - 1))/2;
+ for(i=1 ; i< (float)K/2 ; i++)
+ {
+ sum = sum + arr[i]*arr[K-i];
+ }
+ cout<
+
+*A = { x : x is a [natural number](https://en.wikipedia.org/wiki/Natural_number) ≤ N }*
+(i.e), A = {1,2,3,4,5,6,...., N}
+
+Mike has to find the total number of pairs of elements A[i] and A[j] belonging to the given set, such that, i < j and their sum is divisible by K
+
+**Input Format**
+An integer T followed by T lines, each containing a pair of space separated integers N and K.
+
+**Output Format**
+T integers on separate lines. Each integer denotes the answer corresponding to that test case.
+
+**Constraints**
+1<=T<=100
+K<=N<=109
+1<=K<=10000
+
+**Sample Input**
+
+ 2
+ 10 4
+ 7 3
+
+**Sample Output**
+
+ 10
+ 7
+
+**Explanation**
+
+For the 1st test case, there are 10 pairs whose sum is divisible by 4.
+(1,3), (1,7), (2,6), (2,10), (3,5), (3,9), (4,8), (5,7), (6,10) and (7,9)
+
+For the 2nd test case, there are 7 pairs whose sum is divisible by 3.
+(1,2), (1,5), (2,4), (2,7), (3,6), (4,5) and (5,7)
+",code,Help Mike attend the NSA meeting,ai,2013-08-13T09:29:32,2022-09-02T09:54:27,"#
+# Complete the 'solve' function below.
+#
+# The function is expected to return a LONG_INTEGER.
+# The function accepts following parameters:
+# 1. INTEGER n
+# 2. INTEGER k
+#
+
+def solve(n, k):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ t = int(input().strip())
+
+ for t_itr in range(t):
+ first_multiple_input = input().rstrip().split()
+
+ n = int(first_multiple_input[0])
+
+ k = int(first_multiple_input[1])
+
+ result = solve(n, k)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","Harvey Specter has agreed to take Mike Ross to a meeting filled with brilliant scientists at NSA Headquarters. But, as always, it's not going to be easy for Mike. He has to solve a puzzle given by Harvey.
+
+Harvey gives two numbers N and K and defines a set A.
+
+*A = { x : x is a [natural number](https://en.wikipedia.org/wiki/Natural_number) ≤ N }*
+(i.e), A = {1,2,3,4,5,6,...., N}
+
+Mike has to find the total number of pairs of elements A[i] and A[j] belonging to the given set, such that, i < j and their sum is divisible by K
+
+**Input Format**
+An integer T followed by T lines, each containing a pair of space separated integers N and K.
+
+**Output Format**
+T integers on separate lines. Each integer denotes the answer corresponding to that test case.
+
+**Constraints**
+1<=T<=100
+K<=N<=109
+1<=K<=10000
+
+**Sample Input**
+
+ 2
+ 10 4
+ 7 3
+
+**Sample Output**
+
+ 10
+ 7
+
+**Explanation**
+
+For the 1st test case, there are 10 pairs whose sum is divisible by 4.
+(1,3), (1,7), (2,6), (2,10), (3,5), (3,9), (4,8), (5,7), (6,10) and (7,9)
+
+For the 2nd test case, there are 7 pairs whose sum is divisible by 3.
+(1,2), (1,5), (2,4), (2,7), (3,6), (4,5) and (5,7)
+",0.5793650793650794,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""ruby"",""rust"",""scala"",""swift"",""typescript"",""r""]",,,,,Hard,Help Mike - Sept 2020 Editorial,"Problem Statement
+
+Help Mike in finding the total number of pairs of elements A[i] and A[j] belonging to the given set such that i < j and their sum is divisible by K
+
+Difficulty Level Easy-Medium
+
+Required knowledge : Basic Hashing , Maths
+
+Time complexity : O(K) , O(1) will be accepted . O(N/K) or O(N) will go for TLE(time limit exceeded) under given time constraints.
+
+Approach :
+
+To solve the problem in O(K) time limit, we can create an array rem[K]. The array rem[i] will store the number of integers in the set A, such that on dividing by K, you get i as the remainder. rem[i] can be calculated in O(1) time.
+rem[i] = (N-i)/K;
+
+Now, the sum of two integers is divisible by K if:
+
+
+Both numbers are divisible by K and such selection can be made in rem[0](rem[0]-1)/2 ways.
+On dividing first number by K, reminder is p then on dividing second number K, reminder must be K-p . i.e. number of ways can be rem[p]*rem[K-p] where p can belong to 0 to K/2.
+K is even and on dividing both numbers, the reminder is K/2 i.e. rem[K/2]*(rem[K/2]-1)/2 .
+
+
+We can sum up all these possibilities to get the required output.
+
+Problem Setter's code:
+
+#include<bits/stdc++.h>
+
+using namespace std;
+
+#define print(p) cout<<p<<endl;
+int main()
+{
+ int T;
+ long long int N,K,i;
+ cin>>T;
+ while(T--)
+ {
+ cin>>N>>K;
+ long long int arr[K];
+ arr[0] = N/K;
+ for(i=1 ; i< K ; i++)
+ arr[i] = (int)(N-i)/K + 1;
+ if(K%2!=0)
+ {
+ long long int sum = 0;
+ sum = sum + (arr[0]*(arr[0] - 1))/2;
+ for(i=1 ; i< (float)K/2 ; i++)
+ {
+ sum = sum + arr[i]*arr[K-i];
+ }
+ cout<<sum<<endl;
+ }
+ else
+ {
+ long long int sum = 0;
+ sum = sum + (arr[0]*(arr[0] - 1))/2;
+ for(i=1 ; i< K/2 ; i++)
+ {
+ sum = sum + arr[i]*arr[K-i];
+ }
+ sum = sum + (arr[K/2]*(arr[K/2] - 1))/2;
+ cout<<sum<<endl;
+ }
+ }
+ return 0;
+}
+
+
+Problem Tester's Code
+
+#!/usr/bin/py
+import math
+
+T = input()
+1 <= T <= 100
+
+for t in range(T):
+ N, K = map(int, raw_input().strip().split("" ""))
+ assert 1 <= N <= 10**9
+ assert 1 <= K <= 10**4
+ assert K <= N
+
+ n_by_k = math.floor(N/K)
+ n_mod_k = N%K
+ count_less_than_k = K/2 if K % 2 == 1 else (K - 1)/2
+ sum = count_less_than_k*n_by_k
+ summation_limit = n_by_k - 1
+ sum += K*(summation_limit*(summation_limit + 1))/2
+ sum += (summation_limit+1)*(n_mod_k)
+ if n_mod_k > 0:
+ extra = n_mod_k - count_less_than_k
+ if K%2==0:
+ extra -= 1
+ sum += extra if extra > 0 else 0
+
+ print int(sum)
+
",0.0,sep-2020-editorial-help-mike,2013-09-16T13:48:37,"{""contest_participation"":3240,""challenge_submissions"":1167,""successful_submissions"":494}",2013-09-16T13:48:37,2016-12-03T12:59:31,tester,"###Python 2
+```python
+#!/usr/bin/py
+import math
+
+T = input()
+1 <= T <= 100
+
+for t in range(T):
+ N, K = map(int, raw_input().strip().split("" ""))
+ assert 1 <= N <= 10**9
+ assert 1 <= K <= 10**4
+ assert K <= N
+
+ n_by_k = math.floor(N/K)
+ n_mod_k = N%K
+ count_less_than_k = K/2 if K % 2 == 1 else (K - 1)/2
+ sum = count_less_than_k*n_by_k
+ summation_limit = n_by_k - 1
+ sum += K*(summation_limit*(summation_limit + 1))/2
+ sum += (summation_limit+1)*(n_mod_k)
+ if n_mod_k > 0:
+ extra = n_mod_k - count_less_than_k
+ if K%2==0:
+ extra -= 1
+ sum += extra if extra > 0 else 0
+
+ print int(sum)
+
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T17:46:49,Python
+7,800,chocolate-game,Chocolate Game,"Laurel and Hardy have N piles of chocolates with each pile containing some number of chocolates. The piles are arranged from left to right in a non decreasing order based on the number of chocolates in each pile. They play the following game.
+
+For every continuous subsequence of chocolate piles (at least 2 piles form a subsequence), you choose one of the piles and remove at least one chocolate from it. It should be noted that, on removal, the non-decreasing order of the chocolate piles must be maintained. The last person to make a valid move wins.
+
+Suppose, Laurel plays first always. In how many of the continuous subsequences of chocolate piles will he win, if a game is played?
+
+**Input Format**
+The first line contains an integer N denoting the number of piles. The next line contains the number of chocolates in each pile, arranged from left to right and separated by a single space between them.
+
+**Output Format**
+A single integer denoting the number of continuous subsequences of chocolate piles in which Laurel will win.
+
+**Constraints**
+2 <= n <= 100000
+1 <= d[i] <= 1,000,000,000
+
+**Sample Input**
+
+ 5
+ 1 1 2 2 3
+
+**Sample Output**
+
+ 5
+
+**Explanation**
+Of the 10 continuous-sub-sequence of chocolate piles,
+
+Laurel loses in [1,1], [1,1,2], [1,1,2,2], [1,2,2,3], [2,2] and
+wins in [1,1,2,2,3], [1,2], [1,2,2], [2,2,3] and [2,3] and hence 5.
+",code,Count continuous sub-sequences for winning Chocolate Game.,ai,2013-08-09T20:02:16,2022-08-31T08:15:06,"#
+# Complete the 'chocolateGame' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts INTEGER_ARRAY arr as parameter.
+#
+
+def chocolateGame(arr):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ arr_count = int(input().strip())
+
+ arr = list(map(int, input().rstrip().split()))
+
+ result = chocolateGame(arr)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","Laurel and Hardy have $n$ piles of chocolates with each pile containing some number of chocolates. The piles are arranged from left to right in a non decreasing order based on the number of chocolates in each pile. They play the following game.
+
+For every continuous subsequence of chocolate piles (at least 2 piles form a subsequence), Laurel and Hardy will play game on this subsequence of chocolate piles, Laurel plays first, and they play in turn. In one move, the player can choose one of the piles and remove at least one chocolate from it, but the non-decreasing order of the chocolate piles must be maintained. The last person to make a valid move wins.
+
+How many continuous subsequences of chocolate piles will Laurel win if both of them play optimally? The number of chocolates of each pile will be recovered after the game ends for each subsequences.
+",0.4878048780487805,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]","The first line contains an integer $n$ denoting the number of piles.
+The second line contains the number of chocolates in each pile, arranged from left to right and separated by a single space between them.
+","A single integer denoting the number of continuous subsequences of chocolate piles in which Laurel will win.
+"," 5
+ 1 1 2 2 3
+"," 5
+",Hard,2020 September Editorial: Chocolate Game,"This is a challenging problem. In case of any queries beyond the scope of this editorial, contact our problem setter, WanBo: wanbo_hackerrank@gmail.com
+
+Let us start by simplifying this problem:
+Given d[], can you win if you play first?
+
+d[0] <= d[1] <= ... <= d[n-1]
+
+
+Transform d[] to another array a[] using the following transformation:
+ a[i] = d[i+1] - d[i]
+
+So from the array d[] we get a new array a[]:
+ d[0], d[1], ... d[n-1]
+ d[1] - d[0], d[2] - d[1], ..., d[n-1] - d[n-2]
+
+a[i] = d[i + 1] - d[i]
+a[i - 1] = d[i] - d[i - 1]
+
+
+If we remove x from d[i]:
+ d[i] -= x ==> a[i] += x and a[i - 1] -= x
+==> we remove x from the a[i - 1] and add it to a[i]
+
+This is a classic staircase NIM game.
+a[] with N elements is a win state
+<==> 0 != xorsum{a[i] | 0 <= i < N and (N - i) % 2 == 1}
+
+Naive solution to the original problem:
+
+
+for(i = 0; i + 1
+
+We transform this to:
+==>
+
+for(i = 0; i < n; i++)
+ for(j = i + 1; j < n; j++) {
+ xor = 0
+ for(k = j; k >= i; k -= 2) xor ^= d[k]
+ if(xor != 0) res++
+ }
+
+==> The inner for(k = j; k >= i; k -= 2) can be easily optimized by maintain the xor prefix sum of odd position and even position separately. O(n^3) ==> O(n^2)
+
+==>
+We can find the number of losing states.
+How many y exist such that x xor y == 0 for a given x?
+
+<==> Find the number of elements equals to x.
+We can define a data structure to optimize this to O(n logn).
+This need enough analysis and careful coding, but it is not the hardest part of this challenge.
+
+
+C++ Solution
+
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+#define LL long long
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr ""#b"": ""void PV(T a, T b) {while(a != b)cout inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+templateinline bool chmax(T &a, T b) {return a v(d + i, d + j + 1);
+ for(int k = (int) v.size() - 1; k > 0; k--) v[k] -= v[k - 1];
+ reverse(ALL(v));
+ int xr = 0;
+ for(int k = 0; k 0) res++;
+ }
+ P(i);
+ }
+ return res;
+}
+
+map M;
+
+LL solve() {
+ LL res = 0;
+ {
+ M.clear();
+ M[0] = 1;
+ int xr = 0;
+ for(int i = n - 1; i >= 0; i -= 2) {
+ int t = d[i];
+ if(i > 0) t = d[i] - d[i - 1];
+ res += M[xr ^ d[i]];
+ if(i > 0) res += M[xr ^ t];
+ xr ^= t;
+ M[xr]++;
+ }
+ }
+ {
+ M.clear();
+ M[0] = 1;
+ int xr = 0;
+ for(int i = n - 2; i >= 0; i -= 2) {
+ int t = d[i];
+ if(i > 0) t = d[i] - d[i - 1];
+ res += M[xr ^ d[i]];
+ if(i > 0) res += M[xr ^ t];
+ xr ^= t;
+ M[xr]++;
+ }
+ }
+ res = (LL) n * (n - 1) / 2 - res;
+ return res;
+}
+
+int main() {
+ ios_base::sync_with_stdio(0);
+ cin >> N;
+ assert(1 > d[i];
+ assert(1 = d[i - 1]);
+ n = N;
+ //LL res1 = brute();
+ LL res2 = solve();
+ cout ",0.0,chocolate-game,2013-09-24T09:33:08,"{""contest_participation"":3240,""challenge_submissions"":230,""successful_submissions"":51}",2013-09-24T09:33:08,2016-07-23T16:18:17,setter,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+#define LL long long
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""< ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define mp make_pair
+#define pb push_back
+templatevoid PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n"");}
+templateinline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+templateinline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+const int inf = 0x3f3f3f3f;
+const int mod = int(1e9) + 7;
+
+int N, n;
+int d[100010];
+int s[100010];
+int s1[100010];
+int s2[100010];
+
+LL brute() {
+ LL res = 0;
+ for(int i = 0; i < n; i++) {
+ for(int j = i + 1; j < n; j++) {
+ vector v(d + i, d + j + 1);
+ for(int k = (int) v.size() - 1; k > 0; k--) v[k] -= v[k - 1];
+ reverse(ALL(v));
+ int xr = 0;
+ for(int k = 0; k < v.size(); k += 2) xr ^= v[k];
+ if(xr > 0) res++;
+ }
+ P(i);
+ }
+ return res;
+}
+
+map M;
+
+LL solve() {
+ LL res = 0;
+ {
+ M.clear();
+ M[0] = 1;
+ int xr = 0;
+ for(int i = n - 1; i >= 0; i -= 2) {
+ int t = d[i];
+ if(i > 0) t = d[i] - d[i - 1];
+ res += M[xr ^ d[i]];
+ if(i > 0) res += M[xr ^ t];
+ xr ^= t;
+ M[xr]++;
+ }
+ }
+ {
+ M.clear();
+ M[0] = 1;
+ int xr = 0;
+ for(int i = n - 2; i >= 0; i -= 2) {
+ int t = d[i];
+ if(i > 0) t = d[i] - d[i - 1];
+ res += M[xr ^ d[i]];
+ if(i > 0) res += M[xr ^ t];
+ xr ^= t;
+ M[xr]++;
+ }
+ }
+ res = (LL) n * (n - 1) / 2 - res;
+ return res;
+}
+
+int main() {
+ ios_base::sync_with_stdio(0);
+ cin >> N;
+ assert(1 <= N && N <= 100000);
+ for(int i = 0; i < N; i++) {
+ cin >> d[i];
+ assert(1 <= d[i] && d[i] <= 1000000000);
+ }
+ for(int i = 1; i < N; i++) assert(d[i] >= d[i - 1]);
+ n = N;
+ //LL res1 = brute();
+ LL res2 = solve();
+ cout << res2 << endl;
+ //P2(res1, res2);
+ //assert(res1 == res2);
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T16:18:18,C++
+8,836,sherlock-puzzle,Sherlock Puzzle,"Sherlock Holmes is bored to death as there aren't any interesting cases to solve. Dr Watson finding it impossible to be around Sherlock goes out to get some fresh air. Just as he lays his feet out of the door, he is thrown right back into his house by the explosion in front of his apartment. The metropolitan police arrive at the scene a few minutes later. They search the place thoroughly for any evidence that could throw some light on the event that unfolded. Unable to get any clues, they call Sherlock for help. After repeated persuasion by Mycroft Holmes and Dr Watson, Sherlock agrees to look at the crime scene.
+
+Sherlock walks into the apartment, the walls are all black and dripping wet as the fire was recently extinguished. With his skills, he observes, deduces and eliminates the impossible. What's left after it is a simple puzzle left by an evil computer genius and the future Arch Nemesis of Sherlock, Jim Moriarty.
+
+Given a binary string (**S**) which contains '0's and '1's and an integer **K**,
+find the length (**L**) of the longest contiguous subsequence of (S * K) such that twice the number of zeroes is <= thrice the number of ones (2 * #0s <= 3 * #1s) in that sequence.
+
+S * K is defined as follows:
+S * 1 = S
+S * K = S + S * (K - 1)
+
+**Input Format**
+The first (and only) line contains an integer K and the binary string S separated by a single space.
+
+**Constraints**
+1 <= |S| <= 1,000,000
+1 <= K <= 1,000,000
+
+**Output Format**
+A single integer L - the answer to the test case
+
+**Sample Input**
+
+ 2 00010
+
+**Sample Output**
+
+ 2
+
+**Explanation**
+
+ S * K = 0001000010
+
+""1"" and ""10"" meet the requirement that 2 * #0 <= 3 * #1
+The longest one is ""10"", length = 2.
+",code,"Help Sherlock get close to his Arch Nemesis, Jim Moriarty.",ai,2013-08-24T15:49:01,2022-09-02T09:54:36,,,,"Sherlock Holmes is bored to death as there aren't any interesting cases to solve. Dr Watson finding it impossible to be around Sherlock goes out to get some fresh air. Just as he lays his feet out of the door, he is thrown right back into his house by the explosion in front of his apartment. The metropolitan police arrive at the scene a few minutes later. They search the place thoroughly for any evidence that could throw some light on the event that unfolded. Unable to get any clues, they call Sherlock for help. After repeated persuasion by Mycroft Holmes and Dr Watson, Sherlock agrees to look at the crime scene.
+
+Sherlock walks into the apartment, the walls are all black and dripping wet as the fire was recently extinguished. With his skills, he observes, deduces and eliminates the impossible. What's left after it is a simple puzzle left by an evil computer genius and the future Arch Nemesis of Sherlock, Jim Moriarty.
+
+Given a binary string (**S**) which contains '0's and '1's and an integer **K**,
+find the length (**L**) of the longest contiguous subsequence of (S * K) such that twice the number of zeroes is <= thrice the number of ones (2 * #0s <= 3 * #1s) in that sequence.
+
+S * K is defined as follows:
+S * 1 = S
+S * K = S + S * (K - 1)
+
+**Input Format**
+The first (and only) line contains an integer K and the binary string S separated by a single space.
+
+**Constraints**
+1 <= |S| <= 1,000,000
+1 <= K <= 1,000,000
+
+**Output Format**
+A single integer L - the answer to the test case
+
+**Sample Input**
+
+ 2 00010
+
+**Sample Output**
+
+ 2
+
+**Explanation**
+
+ S * K = 0001000010
+
+""1"" and ""10"" meet the requirement that 2 * #0 <= 3 * #1
+The longest one is ""10"", length = 2.
+",0.5675675675675675,"[""bash"",""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""pascal"",""perl"",""php"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""pypy3""]",,,,,Hard,2020 September Editorial: Sherlock Puzzle,"For any more queries, beyond the scope of this editorial, feel free to contact our problem setter WanBo: wanbo_hackerrank@gmail.com
+
+What is the longest contiguous sub-sequence of (S * K) with (2 * number of zeroes <= 3 * number of ones)?
+Let replace '0' by -2 and '1' by 3:
+
+Then we need to find the longest sub-string such that the sum[i, j] >= 0.
+
+1) If sum(S) >= 0, answer = len(S) * K
+
+2) If S == 1, how can we find the answer?
+ p[i] = S[0] + S[1] + ... + S[i]
+ sum[i, j] = p[j + 1] - p[i]
+==> For every i, we just need to find the largest j that p[j] >= p[i].
+
+How do we accelerate the search?
+ n can be as large as 10^6 so we need to find the j for every i at least O(log n). But p[i] is not ordered, and because of this we can not use binary search directly.
+
+If rmax[k] = max{p[i] | k <= i < n}
+==> rmax[0] >= rmax[1] >= ... >= rmax[n - 1]
+
+
+Then for every i, we just need to find the largest k that rmax[k] >= p[i]. We can solve it by binary search. We can solve this sub-problem O(nlogn).
+
+Now, can we optimize O(nlogn) to O(n)?
+Observe that when you find a best interval (i0,j0) and want to find a better (i1,j1) with i1 > i0, there must be p[i1] < p[i0] and j1 > j0 (An exercise to the reader - Why?). Therefore, you increment the value of i until you find smaller value of p[i], and then increase j until rmax[j + 1] < p[i]. We will increase i, j at most 2 * n times, so that we can solve it linearly.
+
+3) If S > 1, how do we solve this problem?
+If the longest subsequence is a substring of S, then we can solve it as S == 1. Else we need to maximize the length of suffix(S) + S * i + prefix(S)
+suffix(S)_1 + S * i + prefix(S)_1 >= suffix(S)_2 + S * j + prefix(S)_2
+S + S * i + S > S * j ==> i >= j - 1.
+Obviously, i >= j - 1, so the best i will be the (largest_i) or (largest_i - 1).
+
+How do we calculate the largest_i?
+
+T = sum(suffix(S) + prefix(S))
+largest_i = -T / sum(S)
+
+
+We can set the i to largest_i and largest_i - 1, and choose the best answer.
+
+If we set i = x:
+ T + S * x >= 0 ==> T >= -S * x.
+
+What we need to solve is:
+What's the longest suffix(S) + prefix(S) that sum of this should be >= -S * x
+
+==> sub-problem:
+S[i, ..., n - 1] + S[0, ..., j] >= threshold
+What the maximal n - i + (j + 1)?
+
+For suffix(S):
+If rsum[i] = sum[i, n - 1]
+If i0 < i1 and rsum[i0] >= rsum[i1], then i1 can not be the best choice.
+We can maintain a monotonous sequence of suffix that:
+(i0, rsum[i0]) (i1, rsum[i1]) ...
+i0 < i1 < ...
+sum[i0] < sum[i1] < ...
+
+For prefix(S):
+If lsum[i] = sum[0, i]
+If i0 < i1 and lsum[i0] <= lsum[i1], then i0 can not be the best choice.
+We can maintain a monotonous sequence of suffix that:
+(i0, lsum[i0]) (i1, lsum[i1]) ...
+i0 < i1 < ...
+sum[i0] > sum[i1] > ...
+
+==>
+Given A[] and B[], A is increasing, B is decreasing, for every A[i], how to find the largest j that B[j] >= T - A[i].
+This can be solve in O(n) like the method described in the case when K == 1. (exercise)
+
+C++ Solution from the Problem Setter, WanBo
+
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+typedef long long LL;
+typedef vector VI;
+typedef pair PII;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr ""#b"": "" void PV(T a, T b) {while(a != b)cout inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template inline bool chmax(T &a, T b) {return a L, R;
+ for(int i = n - 1; i >= 0; i--) {
+ while(!L.empty() && sL[i] >= L.back().x) L.pop_back();
+ L.pb(mp(sL[i], n - i));
+ }
+
+ for(int i = 0; i = R.back().x) R.pop_back();
+ R.pb(mp(sR[i], i + 1));
+ }
+
+ int res = 0;
+ for(int i = 0; i = least) chmax(res, L[i].y);
+ for(int i = 0; i = least) chmax(res, R[i].y);
+ int l = 0, r = (int) R.size() - 1;
+ while(l = 0) {
+ while(r >= 0 && L[l].x + R[r].x = 0) chmax(res, L[l].y + R[r].y);
+ l++;
+
+ }
+ return res;
+}
+
+
+int p[N];
+int rmax[N];
+
+LL solve() {
+ for(int i = 0; i = 0; i--) rmax[i] = max(rmax[i + 1], p[i]);
+ int mx = 0;
+ int l = 0;
+ int r = 0;
+ for(int i = 0; i = p[l]) continue;
+ int rr = -1;
+ while(r = 0) {
+ rr = r - i;
+ r++;
+ }
+ r--;
+ int len = rr;
+ if(mx pt(S.length() + 1, 0);
+ LL res = 0;
+ for(int i = 0; i = 0 && chmax(res, (LL)(j - i + 1))) {
+ pi = i, pj = j;
+ }
+ }
+ return res;
+}
+
+int main() {
+ cin >> K >> s;
+ n = s.length();
+ for(int i = 0; i = 0) {
+ res = (LL) n * K;
+ } else {
+ int tot = 0;
+ {
+ int mx = 0;
+ for(int i = n - 1; i >= 0; i--) {
+ sL[i] = sL[i + 1] + d[i];
+ chmax(mx, sL[i]);
+ }
+ tot += mx;
+ }
+ {
+ int mx = 0;
+ for(int i = 0; i 0) sR[i] = sR[i - 1] + d[i];
+ else sR[i] = d[i];
+ chmax(mx, sR[i]);
+ }
+ tot += mx;
+ }
+
+ if(K >= 2) {
+ LL T = min(K - 2, tot / abs(score));
+ res += n * T;
+ // P(res);
+ res += crossMid(-score * T);
+ chmax(res, solve());
+ } else {
+ res = solve();
+ }
+ }
+ cout ",0.0,sep2020-sherlock-puzzle,2013-09-24T09:42:06,"{""contest_participation"":3240,""challenge_submissions"":292,""successful_submissions"":72}",2013-09-24T09:42:06,2016-07-23T17:59:56,setter,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+typedef long long LL;
+typedef vector VI;
+typedef pair PII;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""< ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define FOR(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
+#define uni(v) sort(ALL(v)), v.resize(unique(ALL(v)) - v.begin())
+#define mp make_pair
+#define pb push_back
+#define x first
+#define y second
+struct _ {_() {ios_base::sync_with_stdio(0);}} _;
+template void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n""); cout.flush();}
+template inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template inline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+const int inf = 0x3f3f3f3f;
+const int mod = int(1e9) + 7;
+const int N = 1111111;
+
+string s;
+int K;
+int n;
+int c0, c1;
+int score;
+int d[N];
+int sL[N];
+int sR[N];
+
+
+int crossMid(int least) {
+ vector L, R;
+ for(int i = n - 1; i >= 0; i--) {
+ while(!L.empty() && sL[i] >= L.back().x) L.pop_back();
+ L.pb(mp(sL[i], n - i));
+ }
+
+ for(int i = 0; i < n; i++) {
+ while(!R.empty() && sR[i] >= R.back().x) R.pop_back();
+ R.pb(mp(sR[i], i + 1));
+ }
+
+ int res = 0;
+ for(int i = 0; i < L.size(); i++) if(L[i].x >= least) chmax(res, L[i].y);
+ for(int i = 0; i < R.size(); i++) if(R[i].x >= least) chmax(res, R[i].y);
+ int l = 0, r = (int) R.size() - 1;
+ while(l < L.size() && r >= 0) {
+ while(r >= 0 && L[l].x + R[r].x < least) r--;
+ if(r >= 0) chmax(res, L[l].y + R[r].y);
+ l++;
+
+ }
+ return res;
+}
+
+
+int p[N];
+int rmax[N];
+
+LL solve() {
+ for(int i = 0; i < n; i++) p[i + 1] = sR[i];
+ rmax[n] = p[n];
+ for(int i = n - 1; i >= 0; i--) rmax[i] = max(rmax[i + 1], p[i]);
+ int mx = 0;
+ int l = 0;
+ int r = 0;
+ for(int i = 0; i < n; i++) {
+ if(i != 0 && p[i] >= p[l]) continue;
+ int rr = -1;
+ while(r <= n && rmax[r] - p[i] >= 0) {
+ rr = r - i;
+ r++;
+ }
+ r--;
+ int len = rr;
+ if(mx <= len) {
+ mx = len;
+ l = i;
+ }
+ }
+ return mx;
+}
+
+LL brute() {
+ string S;
+ for(int i = 0; i < K; i++) S += s;
+ vector pt(S.length() + 1, 0);
+ LL res = 0;
+ for(int i = 0; i < S.length(); i++) pt[i + 1] = pt[i] + d[i % n];
+ int pi = -1, pj = -1;
+ for(int i = 0; i < S.length(); i++)
+ for(int j = i; j < S.length(); j++) {
+ LL sc = pt[j + 1] - pt[i];
+ if(sc >= 0 && chmax(res, (LL)(j - i + 1))) {
+ pi = i, pj = j;
+ }
+ }
+ return res;
+}
+
+int main() {
+ cin >> K >> s;
+ n = s.length();
+ for(int i = 0; i < n; i++) {
+ if(s[i] == '0') {
+ c0++;
+ d[i] = -2;
+ } else {
+ c1++;
+ d[i] = 3;
+ }
+ score += d[i];
+ }
+
+ //P(score);
+ LL res = 0;
+ if(score >= 0) {
+ res = (LL) n * K;
+ } else {
+ int tot = 0;
+ {
+ int mx = 0;
+ for(int i = n - 1; i >= 0; i--) {
+ sL[i] = sL[i + 1] + d[i];
+ chmax(mx, sL[i]);
+ }
+ tot += mx;
+ }
+ {
+ int mx = 0;
+ for(int i = 0; i < n; i++) {
+ if(i > 0) sR[i] = sR[i - 1] + d[i];
+ else sR[i] = d[i];
+ chmax(mx, sR[i]);
+ }
+ tot += mx;
+ }
+
+ if(K >= 2) {
+ LL T = min(K - 2, tot / abs(score));
+ res += n * T;
+ // P(res);
+ res += crossMid(-score * T);
+ chmax(res, solve());
+ } else {
+ res = solve();
+ }
+ }
+ cout << res << endl;
+ //P(brute());
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T17:59:56,C++
+9,1049,angry-children-2,Angry Children 2,"Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has **N** packets of candies and would like to distribute one packet to each of the **K** children in the village (each packet may contain different number of candies). To avoid a fight between the children, he would like to pick **K** out of **N** packets such that the unfairness is minimized.
+
+Suppose the **K** packets have (x1 , x2 , x3 ,....xk ) candies in them, where xi denotes the number of candies in the ith packet, then we define *unfairness* as
+
+
+
+where \|a\| denotes the absolute value of a.
+
+**Input Format**
+The first line contains an integer N.
+The second line contains an integer K.
+N lines follow each integer containing the candy in the ith packet.
+
+**Output Format**
+A single integer which will be minimum unfairness.
+
+**Constraints**
+2<=N<=105
+2<=K<=N
+0<= number of candies in each packet <=109
+
+**Sample Input #00**
+
+ 7
+ 3
+ 10
+ 100
+ 300
+ 200
+ 1000
+ 20
+ 30
+
+**Sample Output #00**
+
+ 40
+
+**Explanation #00**
+
+Bill Gates will choose packets having 10, 20 and 30 candies.So unfairness will be \|10-20\| + \|20-30\| + \|10-30\| = 40. We can verify that it will be minimum in this way.
+
+**Sample Input #01**
+
+ 10
+ 4
+ 1
+ 2
+ 3
+ 4
+ 10
+ 20
+ 30
+ 40
+ 100
+ 200
+
+**Sample Output #01**
+
+ 10
+
+**Explanation #01**
+
+Bill Gates will choose 4 packets having 1,2,3 and 4 candies. So, unfairness will be \|1-2\| + \|1-3\| + \|1-4\| + \|2-3\| + \|2-4\| + \|3-4\| = 10
+",code,Select K elements from N elements such that the sum absolute value of differences of adjacent elements is minimized,ai,2013-10-08T12:22:10,2022-08-31T08:14:42,"#
+# Complete the 'angryChildren' function below.
+#
+# The function is expected to return a LONG_INTEGER.
+# The function accepts following parameters:
+# 1. INTEGER k
+# 2. INTEGER_ARRAY packets
+#
+
+def angryChildren(k, packets):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ n = int(input().strip())
+
+ k = int(input().strip())
+
+ packets = []
+
+ for _ in range(n):
+ packets_item = int(input().strip())
+ packets.append(packets_item)
+
+ result = angryChildren(k, packets)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has brought a box of packets of candies and would like to distribute one packet to each of the children. Each of the packets contains a number of candies. He wants to minimize the cumulative difference in the number of candies in the packets he hands out. This is called the *unfairness sum*. Determine the minimum unfairness sum achievable.
+
+For example, he brings $n = 7$ packets where the number of candies is $packets = [3,3,4,5,7,9,10]$. There are $k = 3$ children. The minimum difference between all packets can be had with $3, 3, 4$ from indices $0, 1$ and $2$. We must get the difference in the following pairs: $\{(0,1),(0,2),(1,2)\}$. We calculate the *unfairness sum* as:
+```
+packets candies
+0 3 indices difference result
+1 3 (0,1),(0,2) |3-3| + |3-4| 1
+2 4 (1,2) |3-4| 1
+
+Total = 2
+```
+
+**Function Description**
+
+Complete the *angryChildren* function in the editor below. It should return an integer that represents the minimum unfairness sum achievable.
+
+angryChildren has the following parameter(s):
+
+- *k*: an integer that represents the number of children
+- *packets*: an array of integers that represent the number of candies in each packet ",0.5328947368421053,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]","The first line contains an integer $n$.
+The second line contains an integer $k$.
+Each of the next $n$ lines contains an integer $packets[i]$.
+","A single integer representing the minimum achievable unfairness sum.
+
+**Sample Input 0**
+
+ 7
+ 3
+ 10
+ 100
+ 300
+ 200
+ 1000
+ 20
+ 30
+
+**Sample Output 0**
+
+ 40
+
+**Explanation 0**
+
+Bill Gates will choose packets having 10, 20 and 30 candies. The unfairness sum is $|10-20| + |20-30| + |10-30| = 40$.
+
+**Sample Input 1**
+
+ 10
+ 4
+ 1
+ 2
+ 3
+ 4
+ 10
+ 20
+ 30
+ 40
+ 100
+ 200
+
+**Sample Output 1**
+
+ 10
+
+**Explanation 1**
+
+Bill Gates will choose 4 packets having 1,2,3 and 4 candies. The unfairness sum i $|1-2| + |1-3| + |1-4| + |2-3| + |2-4| + |3-4| = 10$.
+", , ,Hard,Angry Children 2 : Oct 2020 Editorial,"Angry Children 2
+
+Choose K out of N elements of an array, following the given constraints. Read the complete problem statement here
+
+Difficulty Level
+
+Medium
+
+Required Knowledge
+
+Sorting, Easy Dynammic Progamming
+
+Time Complexity
+
+O(NlogN)
+
+Approach
+
+In this problem, we are given a list of N numbers out of which K numbers are to be chosen such that the anger coefficient is minimized.
+
+Let us define D as the anger-coefficient of chosen K numbers.
+
+First, we claim that k such numbers can only be obtained if we sort the list and chose k contiguous numbers. This can easily be proved. Suppose we choose numbers X1 , X2 , X3 ,....Xr , Xr+1 ,....,XK (all are in increasing order but not continuous in the sorted list) i.e. there exists a number p which lies between Xr and Xr+1 .Now, if we include p and drop X1 , our anger coefficient will decrease by an amount =
+
+( |X1 - X2 | + |X1 - X3 | + .... + |X1 - XK | ) - ( |p - X2 | + |p - X3 | + .... + |p - XK | )
+
+which is certainly positive. This shows that the solution will consist of k continues elements of the sorted list. Now there exists (N-K+1) such sets of elements. The problem can be redefined as to find the minimum of the D obtained from all these sets.
+
+First, we sort the list in increasing order: X1 , X2 , X3 ,....XK ,XK+1 ,....,XN . The next step is to find the value of D for the first K elements i.e. from X1 to XK . suppose we have calculated D for first i elements. when we include Xi+1 , the value of D increases by ( |Xi+1 - X1 | + |Xi+1 - X2 | +....+ |Xi+1 - Xi | ), which in turn is equal to ( i*XK - (X1 + X2 + ....+Xi ) ). We just need to store the sum of current elements and repeat the step for i = 1 to k-1.
+
+Now that we have the solution for X1 to XK , we would want to calculate the same for X2 to XK+1 . This can be done in O(1) time.
+
+New anger coefficient = old anger coefficient + ( |XK+1 - X2 | + |XK+1 - X3 | + .... + |XK+1 - XK | ) - ( |X1 - X2 | + |X1 - X3 | + .... + |X1 - XK | ). This can be written in the following form:
+
+New anger coefficient = old anger coefficient + K.(XK - X1 ) - K.(X1 + X2 +....+XK ) + ( X1 - XK )
+
+At every point we just need to update the sum of the K elements, calculate the new anger co-efficient and update the minimum value of the same.
+
+Setter's Code :
+
+n = input()
+k = input()
+assert 1 <= n <= 10**5
+assert 1 <= k <= n
+
+lis = []
+for i in range(n):
+ lis.append(input())
+
+lis.sort()
+sum_lis = []
+for i in lis:
+ assert 0 <= i <= 10**9
+
+val = 1-k
+answer = 0
+
+sum_lis.append(lis[0])
+
+for i in range(1,n):
+ sum_lis.append(sum_lis[i-1]+lis[i])
+
+for i in range(k):
+ answer += val*lis[i]
+ val += 2
+
+final_answer = answer
+for i in range(k,n):
+ new_answer = answer + (k-1)*lis[i] + (k-1)*lis[i-k] - 2*(sum_lis[i-1]-sum_lis[i-k])
+ final_answer = min(new_answer, final_answer)
+ answer = new_answer
+
+print final_answer
+
+
+Tester's Code :
+
+#include<stdio.h>
+#include<stdlib.h>
+#include<algorithm>
+#include<assert.h>
+using namespace std;
+#define Max_N 100001
+typedef long long int ll;
+long long int sum[Max_N];
+int N,K,input[Max_N];
+ll min(ll a,ll b)
+{
+ if(a>b) return b;
+ else return a;
+}
+int main()
+{
+ int val;
+ scanf(""%d%d"",&N,&K);
+ assert(1<=N && N<=100000);
+ assert(1<=K && K<=N);
+ for(int i=1;i<=N;i++)
+ {
+ scanf(""%d"",&input[i]);
+ assert(0<=input[i] && input[i]<=1000000000);
+ }
+ input[0]=0;
+ sort(input+1,input+N+1);
+ sum[0]=0;
+ for(int i=1;i<=N;i++) sum[i]=input[i]+sum[i-1];
+
+ val=1-K;
+ ll answer=0,compare,previous;
+ for(int i=1;i<=K;i++){
+ answer+=(ll)val*input[i];
+ val+=2;
+ }
+ //printf(""%lld is answeer\n"",answer);
+ previous=answer;
+ for(int i=K+1;i<=N;i++){
+ compare=(ll)(K-1)*input[i];
+ compare=previous + (ll)(K-1)*input[i] + (ll)(K-1)*input[i-K]-(ll)2*(sum[i-1]-sum[i-K]);
+ answer=min(answer,compare);
+ previous=compare;
+ }
+ printf(""%lld\n"",answer);
+ return 0;
+}
+
",0.0,oct-2020-angry-children-ii,2013-10-29T06:01:32,"{""contest_participation"":7868,""challenge_submissions"":2266,""successful_submissions"":1120}",2013-10-29T06:01:32,2018-05-14T17:07:47,setter,"###Python 2
+```python
+n = input()
+k = input()
+assert 1 <= n <= 10**5
+assert 1 <= k <= n
+
+lis = []
+for i in range(n):
+ lis.append(input())
+
+lis.sort()
+sum_lis = []
+for i in lis:
+ assert 0 <= i <= 10**9
+
+val = 1-k
+answer = 0
+
+sum_lis.append(lis[0])
+
+for i in range(1,n):
+ sum_lis.append(sum_lis[i-1]+lis[i])
+
+for i in range(k):
+ answer += val*lis[i]
+ val += 2
+
+final_answer = answer
+for i in range(k,n):
+ new_answer = answer + (k-1)*lis[i] + (k-1)*lis[i-k] - 2*(sum_lis[i-1]-sum_lis[i-k])
+ final_answer = min(new_answer, final_answer)
+ answer = new_answer
+
+print final_answer
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T14:51:01,Python
+10,1049,angry-children-2,Angry Children 2,"Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has **N** packets of candies and would like to distribute one packet to each of the **K** children in the village (each packet may contain different number of candies). To avoid a fight between the children, he would like to pick **K** out of **N** packets such that the unfairness is minimized.
+
+Suppose the **K** packets have (x1 , x2 , x3 ,....xk ) candies in them, where xi denotes the number of candies in the ith packet, then we define *unfairness* as
+
+
+
+where \|a\| denotes the absolute value of a.
+
+**Input Format**
+The first line contains an integer N.
+The second line contains an integer K.
+N lines follow each integer containing the candy in the ith packet.
+
+**Output Format**
+A single integer which will be minimum unfairness.
+
+**Constraints**
+2<=N<=105
+2<=K<=N
+0<= number of candies in each packet <=109
+
+**Sample Input #00**
+
+ 7
+ 3
+ 10
+ 100
+ 300
+ 200
+ 1000
+ 20
+ 30
+
+**Sample Output #00**
+
+ 40
+
+**Explanation #00**
+
+Bill Gates will choose packets having 10, 20 and 30 candies.So unfairness will be \|10-20\| + \|20-30\| + \|10-30\| = 40. We can verify that it will be minimum in this way.
+
+**Sample Input #01**
+
+ 10
+ 4
+ 1
+ 2
+ 3
+ 4
+ 10
+ 20
+ 30
+ 40
+ 100
+ 200
+
+**Sample Output #01**
+
+ 10
+
+**Explanation #01**
+
+Bill Gates will choose 4 packets having 1,2,3 and 4 candies. So, unfairness will be \|1-2\| + \|1-3\| + \|1-4\| + \|2-3\| + \|2-4\| + \|3-4\| = 10
+",code,Select K elements from N elements such that the sum absolute value of differences of adjacent elements is minimized,ai,2013-10-08T12:22:10,2022-08-31T08:14:42,"#
+# Complete the 'angryChildren' function below.
+#
+# The function is expected to return a LONG_INTEGER.
+# The function accepts following parameters:
+# 1. INTEGER k
+# 2. INTEGER_ARRAY packets
+#
+
+def angryChildren(k, packets):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ n = int(input().strip())
+
+ k = int(input().strip())
+
+ packets = []
+
+ for _ in range(n):
+ packets_item = int(input().strip())
+ packets.append(packets_item)
+
+ result = angryChildren(k, packets)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","Bill Gates is on one of his philanthropic journeys to a village in Utopia. He has brought a box of packets of candies and would like to distribute one packet to each of the children. Each of the packets contains a number of candies. He wants to minimize the cumulative difference in the number of candies in the packets he hands out. This is called the *unfairness sum*. Determine the minimum unfairness sum achievable.
+
+For example, he brings $n = 7$ packets where the number of candies is $packets = [3,3,4,5,7,9,10]$. There are $k = 3$ children. The minimum difference between all packets can be had with $3, 3, 4$ from indices $0, 1$ and $2$. We must get the difference in the following pairs: $\{(0,1),(0,2),(1,2)\}$. We calculate the *unfairness sum* as:
+```
+packets candies
+0 3 indices difference result
+1 3 (0,1),(0,2) |3-3| + |3-4| 1
+2 4 (1,2) |3-4| 1
+
+Total = 2
+```
+
+**Function Description**
+
+Complete the *angryChildren* function in the editor below. It should return an integer that represents the minimum unfairness sum achievable.
+
+angryChildren has the following parameter(s):
+
+- *k*: an integer that represents the number of children
+- *packets*: an array of integers that represent the number of candies in each packet ",0.5328947368421053,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]","The first line contains an integer $n$.
+The second line contains an integer $k$.
+Each of the next $n$ lines contains an integer $packets[i]$.
+","A single integer representing the minimum achievable unfairness sum.
+
+**Sample Input 0**
+
+ 7
+ 3
+ 10
+ 100
+ 300
+ 200
+ 1000
+ 20
+ 30
+
+**Sample Output 0**
+
+ 40
+
+**Explanation 0**
+
+Bill Gates will choose packets having 10, 20 and 30 candies. The unfairness sum is $|10-20| + |20-30| + |10-30| = 40$.
+
+**Sample Input 1**
+
+ 10
+ 4
+ 1
+ 2
+ 3
+ 4
+ 10
+ 20
+ 30
+ 40
+ 100
+ 200
+
+**Sample Output 1**
+
+ 10
+
+**Explanation 1**
+
+Bill Gates will choose 4 packets having 1,2,3 and 4 candies. The unfairness sum i $|1-2| + |1-3| + |1-4| + |2-3| + |2-4| + |3-4| = 10$.
+", , ,Hard,Angry Children 2 : Oct 2020 Editorial,"Angry Children 2
+
+Choose K out of N elements of an array, following the given constraints. Read the complete problem statement here
+
+Difficulty Level
+
+Medium
+
+Required Knowledge
+
+Sorting, Easy Dynammic Progamming
+
+Time Complexity
+
+O(NlogN)
+
+Approach
+
+In this problem, we are given a list of N numbers out of which K numbers are to be chosen such that the anger coefficient is minimized.
+
+Let us define D as the anger-coefficient of chosen K numbers.
+
+First, we claim that k such numbers can only be obtained if we sort the list and chose k contiguous numbers. This can easily be proved. Suppose we choose numbers X1 , X2 , X3 ,....Xr , Xr+1 ,....,XK (all are in increasing order but not continuous in the sorted list) i.e. there exists a number p which lies between Xr and Xr+1 .Now, if we include p and drop X1 , our anger coefficient will decrease by an amount =
+
+( |X1 - X2 | + |X1 - X3 | + .... + |X1 - XK | ) - ( |p - X2 | + |p - X3 | + .... + |p - XK | )
+
+which is certainly positive. This shows that the solution will consist of k continues elements of the sorted list. Now there exists (N-K+1) such sets of elements. The problem can be redefined as to find the minimum of the D obtained from all these sets.
+
+First, we sort the list in increasing order: X1 , X2 , X3 ,....XK ,XK+1 ,....,XN . The next step is to find the value of D for the first K elements i.e. from X1 to XK . suppose we have calculated D for first i elements. when we include Xi+1 , the value of D increases by ( |Xi+1 - X1 | + |Xi+1 - X2 | +....+ |Xi+1 - Xi | ), which in turn is equal to ( i*XK - (X1 + X2 + ....+Xi ) ). We just need to store the sum of current elements and repeat the step for i = 1 to k-1.
+
+Now that we have the solution for X1 to XK , we would want to calculate the same for X2 to XK+1 . This can be done in O(1) time.
+
+New anger coefficient = old anger coefficient + ( |XK+1 - X2 | + |XK+1 - X3 | + .... + |XK+1 - XK | ) - ( |X1 - X2 | + |X1 - X3 | + .... + |X1 - XK | ). This can be written in the following form:
+
+New anger coefficient = old anger coefficient + K.(XK - X1 ) - K.(X1 + X2 +....+XK ) + ( X1 - XK )
+
+At every point we just need to update the sum of the K elements, calculate the new anger co-efficient and update the minimum value of the same.
+
+Setter's Code :
+
+n = input()
+k = input()
+assert 1 <= n <= 10**5
+assert 1 <= k <= n
+
+lis = []
+for i in range(n):
+ lis.append(input())
+
+lis.sort()
+sum_lis = []
+for i in lis:
+ assert 0 <= i <= 10**9
+
+val = 1-k
+answer = 0
+
+sum_lis.append(lis[0])
+
+for i in range(1,n):
+ sum_lis.append(sum_lis[i-1]+lis[i])
+
+for i in range(k):
+ answer += val*lis[i]
+ val += 2
+
+final_answer = answer
+for i in range(k,n):
+ new_answer = answer + (k-1)*lis[i] + (k-1)*lis[i-k] - 2*(sum_lis[i-1]-sum_lis[i-k])
+ final_answer = min(new_answer, final_answer)
+ answer = new_answer
+
+print final_answer
+
+
+Tester's Code :
+
+#include<stdio.h>
+#include<stdlib.h>
+#include<algorithm>
+#include<assert.h>
+using namespace std;
+#define Max_N 100001
+typedef long long int ll;
+long long int sum[Max_N];
+int N,K,input[Max_N];
+ll min(ll a,ll b)
+{
+ if(a>b) return b;
+ else return a;
+}
+int main()
+{
+ int val;
+ scanf(""%d%d"",&N,&K);
+ assert(1<=N && N<=100000);
+ assert(1<=K && K<=N);
+ for(int i=1;i<=N;i++)
+ {
+ scanf(""%d"",&input[i]);
+ assert(0<=input[i] && input[i]<=1000000000);
+ }
+ input[0]=0;
+ sort(input+1,input+N+1);
+ sum[0]=0;
+ for(int i=1;i<=N;i++) sum[i]=input[i]+sum[i-1];
+
+ val=1-K;
+ ll answer=0,compare,previous;
+ for(int i=1;i<=K;i++){
+ answer+=(ll)val*input[i];
+ val+=2;
+ }
+ //printf(""%lld is answeer\n"",answer);
+ previous=answer;
+ for(int i=K+1;i<=N;i++){
+ compare=(ll)(K-1)*input[i];
+ compare=previous + (ll)(K-1)*input[i] + (ll)(K-1)*input[i-K]-(ll)2*(sum[i-1]-sum[i-K]);
+ answer=min(answer,compare);
+ previous=compare;
+ }
+ printf(""%lld\n"",answer);
+ return 0;
+}
+
",0.0,oct-2020-angry-children-ii,2013-10-29T06:01:32,"{""contest_participation"":7868,""challenge_submissions"":2266,""successful_submissions"":1120}",2013-10-29T06:01:32,2018-05-14T17:07:47,tester,"###C++
+```cpp
+#include
+#include
+#include
+#include
+using namespace std;
+#define Max_N 100001
+typedef long long int ll;
+long long int sum[Max_N];
+int N,K,input[Max_N];
+ll min(ll a,ll b)
+{
+ if(a>b) return b;
+ else return a;
+}
+int main()
+{
+ int val;
+ scanf(""%d%d"",&N,&K);
+ assert(1<=N && N<=100000);
+ assert(1<=K && K<=N);
+ for(int i=1;i<=N;i++)
+ {
+ scanf(""%d"",&input[i]);
+ assert(0<=input[i] && input[i]<=1000000000);
+ }
+ input[0]=0;
+ sort(input+1,input+N+1);
+ sum[0]=0;
+ for(int i=1;i<=N;i++) sum[i]=input[i]+sum[i-1];
+
+ val=1-K;
+ ll answer=0,compare,previous;
+ for(int i=1;i<=K;i++){
+ answer+=(ll)val*input[i];
+ val+=2;
+ }
+ //printf(""%lld is answeer\n"",answer);
+ previous=answer;
+ for(int i=K+1;i<=N;i++){
+ compare=(ll)(K-1)*input[i];
+ compare=previous + (ll)(K-1)*input[i] + (ll)(K-1)*input[i-K]-(ll)2*(sum[i-1]-sum[i-K]);
+ answer=min(answer,compare);
+ previous=compare;
+ }
+ printf(""%lld\n"",answer);
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T14:51:25,C++
+11,1084,period,Period,"You are given 2 integers **a** and **b**. Let a number be defined as . As we know  will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define
+
+ (where x an integer) and the operation  on AC number as:
+
+
+
+This problem is to find the smallest positive integer **n**, such that:
+
+
+
+We call the integer **n** as period. You are given **a**, **b** and **m**. Can you figure out the period?
+
+**Input Format**
+The first line of the input contains a single integer T denoting the number of test-cases.
+T lines follow, each containing 3 integers - a, b and m separated by a single space.
+
+**Output Format**
+Output the Period if it exists, otherwise output ""-1"" (quotes only for reference)
+
+**Constraints**
+1 ≤ T ≤ 300
+5 ≤ m ≤ 107
+0 ≤ a, b < m
+
+
+**Sample Input #00**
+
+ 4
+ 0 0 13
+ 1 0 7
+ 3 0 10007
+ 1 1 19
+
+**Sample Output #00**
+
+ -1
+ 1
+ 5003
+ 18
+
+**Explanation #00**
+
+For the 1st test-case, no amount of operation ⊗ on a = 0, b = 0 gives 1 on the RHS. Hence the answer is -1.
+When a = 1, b = 0, we have 1 for n = 1.
+On repeated operations, the third and the fourth testcases sum to 1 for n = 5003 and n = 18 respectively.
+",code,Can you find the period?,ai,2013-10-16T05:50:59,2022-09-02T09:54:45,,,,"You are given 2 integers **a** and **b**. Let a number be defined as
+. As we know  will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define
+
+ (where x an integer) and the operation  on AC number as:
+
+
+
+This problem is to find the smallest positive integer **n**, such that:
+
+
+
+We call the integer **n** as period. You are given **a**, **b** and **m**. Can you figure out the period?
+
+**Input Format**
+The first line of the input contains a single integer T denoting the number of test-cases.
+T lines follow, each containing 3 integers - a, b and m separated by a single space.
+
+**Output Format**
+Output the Period if it exists, otherwise output ""-1"" (quotes only for reference)
+
+**Constraints**
+1 ≤ T ≤ 300
+5 ≤ m ≤ 107
+0 ≤ a, b < m
+
+
+**Sample Input #00**
+
+ 4
+ 0 0 13
+ 1 0 7
+ 3 0 10007
+ 1 1 19
+
+**Sample Output #00**
+
+ -1
+ 1
+ 5003
+ 18
+
+**Explanation #00**
+
+For the 1st test-case, no amount of operation ⊗ on a = 0, b = 0 gives 1 on the RHS. Hence the answer is -1.
+When a = 1, b = 0, we have 1 for n = 1.
+On repeated operations, the third and the fourth testcases sum to 1 for n = 5003 and n = 18 respectively.
+",0.5645161290322581,"[""bash"",""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""pascal"",""perl"",""php"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""pypy3""]", , , , ,Hard,Period : Oct 2020 Editorial,"Problem Period
+
+Difficulty : Medium-Hard
+
+Required Knowledge : Group Theory, Euler's Criterion, Lagrange's theorem
+
+Problem Setter : AekDy Coin
+
+Problem Tester : Cao Peng
+
+Approach
+
+For one given P, the AC number that satisfies 0 ≤ a,b < p
+and a2 ≅ 5b2 (mod P) have th property:
+
+Suppose,
+
+∀n ∈ Z+ ,
+(a + b√5)n = c + d√5
+
+Then we have c2 = 5d2 (mod P)
+Quite obvious by mathematical induction.
+So if a2 ≅5b2 (mod P), we could not find the Period since the expected result AC number is with c=1 and d = 0.
+
+So for the remaindering AC number, we have a2 ≠5b2 (mod P)
+If 5 is one quadratic residue modulo P, then we can find (P-1)2 such unique AC number satisfy. a2 ≠5b2 (mod P)
+
+Proof:
+
+If 5 is one quadratic residue modulo P , then for the primitive root g , we have
+
+g2k ≅5(mod P) the AC number such that a2 ≅5b2 (mod P) must satisfy:
+
+g2I(a) ≅g2k g2I(b) (mod P), which means
+
+2I(a)≅2(k+I(b))(mod P - 1), there are totally 2(P-1) AC number that satisfy that condition. (which means they also satisfy
+
+a2 ≅5b2 (mod P), but don't forget 0 + 0√5, so there are
+
+P2 - 2(P-1) - 1 = (P-1)2 AC numbers such that a2 ≠5b2 (mod P)
+
+If 5 is not one quadratic residue modulo P, then we can find P2 - 1 = (P-1)(P+1) such unique AC number satisfies,
+
+a2 ≠5b2 (mod P), because only one AC number o + 0√5 satisfies,
+
+a2 ≅5b2 (mod P)
+
+We can use Euler's Criterion to judge whether 5 is one quadratic residue modulo P in O(logP) time.
+The identity element in this group is 1.
+However there are other 2 properties that guarantee it is a group. I will ignore the proof here.
+
+Finally, base one [Lagrange's Theorem)(http://en.wikipedia.org/wiki/Lagrange%27s_theorem_(group_theory) ) we have
+Period C, where C is the number of AC number satisfies
+a2 ≠5b2 (mod P). Simple brute force will work.
+
+Setter's Code
+
+#include<iostream>
+#include<queue>
+#include<cstdio>
+#include<cmath>
+#include<string>
+#include<vector>
+#include<algorithm>
+#include<stack>
+#include<cstring>
+#include<map>
+using namespace std;
+
+typedef long long LL;
+typedef pair<int,int> PII;
+#define pb push_back
+#define mp make_pair
+
+bool isPrime(int n) {
+ if(n==1)return 0;
+ for(int i =2; i * i <= n; ++ i) if( n % i == 0 ) return 0;
+ return 1;
+}
+
+inline LL MOD(LL a, LL b) {a%=b; return a<0?a+b:a;}
+
+LL powmod(LL a, LL b, LL c){
+ LL ret = 1%c; a%=c;
+ while(b){
+ if(b&1)ret=ret*a%c;
+ a=a*a%c;
+ b>>=1;
+ }
+ return ret;
+}
+// P is one prime number
+LL inv( LL a, LL p) {return powmod( a, p - 2, p ) ; }
+
+LL P;
+class Element {
+public:
+ LL a, b;
+ // a + b Sqrt(5)
+ Element(){}
+ Element(LL _a, LL _b) :a(_a),b(_b){}
+ Element operator+(const Element e) {
+ return Element(MOD(a + e.a , P),MOD(b + e.b , P));
+ }
+ Element operator*(const Element e) {
+ return Element(MOD(a*e.a + b*e.b * 5, P),MOD(a*e.b+b*e.a, P));
+ }
+ Element operator^(LL k){
+ if(k==0) return Element(1,0);
+ --k;
+ Element ret = *this, a = *this;
+ while(k){
+ if(k&1) ret= ret * a ;
+ a = a * a;
+ k >>= 1;
+ }
+ return ret;
+ }
+ Element inverse(){
+ if(!a&&!b) return *this;
+ if(b == 0) {
+ return Element(inv(a, P) , 0 );
+ }
+ if(a == 0) {
+ return Element(0, inv(5*b%P, P));
+ }
+ LL iv = inv( MOD(-b,P) , P );
+ LL x, y;
+ y = inv( iv * (a*a%P) % P + b*5 , P );
+ x = (iv * a % P * y) % P;
+ return Element( x, y) ;
+ }
+ bool isZ(){
+ return !a && !b;
+ }
+ bool isE(){
+ return a == 1 && b == 0;
+ }
+ bool operator<(const Element e) const {
+ if(a == e.a) return b < e.b;
+ return a < e.a;
+ }
+ void rand_gen(){
+ do{a = rand()%P; b= rand()%P;}while(0);
+ }
+ void out(){
+ cout << a <<"" "" << b << endl;
+ }
+};
+
+// a + b Sqrt(5)
+LL circle( Element a ) {
+ Element b =a;
+ LL c = 1;
+ while( ! a.isE( )) {
+ a = a * b;
+ ++ c;
+ //a.out();
+ if(a.a == b.a && a.b == b.b) {
+ return - 1;
+ }
+ }
+ return c;
+}
+
+bool isRes(LL a, LL P ){
+ return powmod(a, (P-1)/2, P) == 1;
+}
+
+LL my_solution(Element e , LL P) {
+ LL a = e.a, b = e.b;
+ if(MOD(a*a-5*b*b,P)==0) return -1;
+ LL n = P*P,ans;
+ if(isRes(5,P)) {
+ n = n - 2*P+1;
+ }else -- n;
+ ans = n;
+ for(LL i = 1; i*i <= n; ++ i) if(n%i == 0) {
+ if( (Element(a,b) ^(i)).isE() )
+ ans = min(ans, i );
+ if( (Element(a,b) ^(n/i)).isE() )
+ ans = min(ans, n/i );
+ }
+ return ans;
+}
+
+void dp(){
+ while( true ) {
+ P = rand()%1000 + 6;
+ while(!isPrime(P)) ++ P;
+ Element e; e.rand_gen();
+ LL my_ans = my_solution(e, P);
+ LL bf = circle(e) ;
+ static int cas = 0; ++ cas;
+ if(my_ans == bf) {
+ cout <<""correct @"" << cas <<"" ans = "" << my_ans<< endl;
+ }else {
+ cout <<""error""<<endl;
+ cout << P << endl;
+ e.out();
+ return;
+ }
+ }
+}
+
+Element rand_one_bad(LL P) {
+ for (LL a = 1; a < P; ++a)
+ for (LL b = 1; b < P; ++b) {
+ if (MOD(a * a - 5 * b * b, P) == 0) {
+ return Element(a, b);
+ }
+ }
+ return Element(0,0);
+}
+
+void gen(int x ){
+ char in[] = ""input00.in"";
+ in[6]='0'+x;
+ freopen(in,""w"", stdout);
+
+ int T = (x+1)*10;
+ int LIMIT[] = {100, 10000, 1e6,1e6};
+ cout << T << endl;
+ while(T --) {
+ P = rand()% (int)LIMIT[x/3] + 13;
+ while(!isPrime(P)) ++ P;
+ Element e; e.rand_gen();
+ if( P < 1e4 && isRes(5,P) && rand()%2 == 0) {
+ e = rand_one_bad(P);
+ }
+ cout << e.a <<"" "" << e.b <<"" "" << P << endl;
+ }
+}
+
+
+void run(int x ){
+ char in[] = ""input00.in"";
+ char out[] = ""output01.out"";
+ in[6]='0'+x;
+ out[7]='0'+x;
+
+ freopen(in,""r"",stdin);
+ freopen(out,""w"", stdout);
+ int T ;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ cout << my_solution( Element(a,b), P) << endl;
+ }
+}
+
+void _cmp_with_bf(int x ){
+ char in[] = ""input00.in"";
+ char out[] = ""output01.out"";
+ in[6]='0'+x;
+ out[7]='0'+x;
+
+ freopen(in,""r"",stdin);
+
+ int T ,cas = 0;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ LL my = my_solution( Element(a,b), P) ;
+ LL bf = circle( Element(a,b) ) ;
+ if(my != bf) {
+ cout <<""SB""<<endl;
+ cout << a <<"" "" << b <<"" "" << P << endl;
+ cout <<my <<"" "" << bf << endl;
+ exit(0);
+ }
+ cout <<""correct @"" << x <<"" case "" << cas ++ << endl;
+ }
+}
+int main() {
+ srand( time( NULL )) ;
+ // for(int i = 0; i < 10;++i) gen(i);
+ // for(int i = 0; i < 10; ++ i) run(i);
+// for(int i=0;i<10;++i) _cmp_with_bf(i);
+ int T ;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ cout << my_solution( Element(a,b), P) << endl;
+ }
+ return 0;
+}
+
+
+Tester's Code
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+typedef long long ll;
+
+int mul(ll x,ll y,int p) {
+ return x * y % p;
+}
+
+int powermod(ll x,ll y,int p) { //x ^ y mod p
+ if (x == 0) {
+ return 0;
+ }
+ if (y == 0) {
+ return 1;
+ }
+ if (y & 1) {
+ return mul(powermod(x, y ^ 1, p), x, p);
+ }
+ x = powermod(x, y >> 1, p);
+ return mul(x, x, p);
+}
+
+pair<int,int> help(int a,int b,ll x,int p) { // (a + b * sqrt(5)) ^ n mod p
+ if (x == 0) {
+ return make_pair(1, 0);
+ }
+ pair<int,int> A, B;
+ if (x & 1) {
+ A = help(a, b, x - 1, p);
+ B = make_pair(a, b);
+ }
+ else {
+ A = B = help(a, b, x >> 1, p);
+ }
+ a = mul(A.first, B.first, p) + mul(5, mul(A.second,B.second, p), p);
+ if (a >= p) {
+ a -= p;
+ }
+ b = mul(A.first, B.second, p) + mul(A.second , B.first, p);
+ if (b >= p) {
+ b -= p;
+ }
+ return make_pair(a, b);
+}
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+int z;
+ for (scanf(""%d"",&z);z;--z) {
+ int a,b,p;
+ ll x;
+ scanf(""%d%d%d"",&a,&b,&p);
+ if (mul(a,a,p) == mul(mul(b,b,p),5,p)) {
+ puts(""-1"");
+ continue;
+ }
+ else if (powermod(5, p >> 1, p) == 1) {
+ x = p - 1;
+ x *= (p - 1);
+
+
+ }
+ else {
+ x = p;
+ x *= x;
+ --x;
+ }
+ ll answer = -1;
+ pair<int,int> temp;
+ for (ll i = 1; i * i <= x; ++i) {
+ if (x % i) {
+ continue;
+ }
+ if ((answer < 0) || (i < answer)) {
+ temp = help(a,b,i,p);
+ if ((temp.first == 1) && (temp.second == 0)) {
+ answer = i;
+ }
+ }
+ if ((answer < 0) || (x / i < answer)) {
+ temp = help(a,b,x / i,p);
+ if ((temp.first == 1) && (temp.second == 0)) {
+ answer = x / i;
+ }
+
+ }
+ }
+ printf(""%lld\n"",answer);
+
+ }
+ return 0;
+}
+
",0.0,oct-2020-editorial-period,2013-10-29T06:13:09,"{""contest_participation"":7868,""challenge_submissions"":564,""successful_submissions"":106}",2013-10-29T06:13:09,2016-07-23T18:18:41,setter,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+
+typedef long long LL;
+typedef pair PII;
+#define pb push_back
+#define mp make_pair
+
+bool isPrime(int n) {
+ if(n==1)return 0;
+ for(int i =2; i * i <= n; ++ i) if( n % i == 0 ) return 0;
+ return 1;
+}
+
+inline LL MOD(LL a, LL b) {a%=b; return a<0?a+b:a;}
+
+LL powmod(LL a, LL b, LL c){
+ LL ret = 1%c; a%=c;
+ while(b){
+ if(b&1)ret=ret*a%c;
+ a=a*a%c;
+ b>>=1;
+ }
+ return ret;
+}
+// P is one prime number
+LL inv( LL a, LL p) {return powmod( a, p - 2, p ) ; }
+
+LL P;
+class Element {
+public:
+ LL a, b;
+ // a + b Sqrt(5)
+ Element(){}
+ Element(LL _a, LL _b) :a(_a),b(_b){}
+ Element operator+(const Element e) {
+ return Element(MOD(a + e.a , P),MOD(b + e.b , P));
+ }
+ Element operator*(const Element e) {
+ return Element(MOD(a*e.a + b*e.b * 5, P),MOD(a*e.b+b*e.a, P));
+ }
+ Element operator^(LL k){
+ if(k==0) return Element(1,0);
+ --k;
+ Element ret = *this, a = *this;
+ while(k){
+ if(k&1) ret= ret * a ;
+ a = a * a;
+ k >>= 1;
+ }
+ return ret;
+ }
+ Element inverse(){
+ if(!a&&!b) return *this;
+ if(b == 0) {
+ return Element(inv(a, P) , 0 );
+ }
+ if(a == 0) {
+ return Element(0, inv(5*b%P, P));
+ }
+ LL iv = inv( MOD(-b,P) , P );
+ LL x, y;
+ y = inv( iv * (a*a%P) % P + b*5 , P );
+ x = (iv * a % P * y) % P;
+ return Element( x, y) ;
+ }
+ bool isZ(){
+ return !a && !b;
+ }
+ bool isE(){
+ return a == 1 && b == 0;
+ }
+ bool operator<(const Element e) const {
+ if(a == e.a) return b < e.b;
+ return a < e.a;
+ }
+ void rand_gen(){
+ do{a = rand()%P; b= rand()%P;}while(0);
+ }
+ void out(){
+ cout << a <<"" "" << b << endl;
+ }
+};
+
+// a + b Sqrt(5)
+LL circle( Element a ) {
+ Element b =a;
+ LL c = 1;
+ while( ! a.isE( )) {
+ a = a * b;
+ ++ c;
+ //a.out();
+ if(a.a == b.a && a.b == b.b) {
+ return - 1;
+ }
+ }
+ return c;
+}
+
+bool isRes(LL a, LL P ){
+ return powmod(a, (P-1)/2, P) == 1;
+}
+
+LL my_solution(Element e , LL P) {
+ LL a = e.a, b = e.b;
+ if(MOD(a*a-5*b*b,P)==0) return -1;
+ LL n = P*P,ans;
+ if(isRes(5,P)) {
+ n = n - 2*P+1;
+ }else -- n;
+ ans = n;
+ for(LL i = 1; i*i <= n; ++ i) if(n%i == 0) {
+ if( (Element(a,b) ^(i)).isE() )
+ ans = min(ans, i );
+ if( (Element(a,b) ^(n/i)).isE() )
+ ans = min(ans, n/i );
+ }
+ return ans;
+}
+
+void dp(){
+ while( true ) {
+ P = rand()%1000 + 6;
+ while(!isPrime(P)) ++ P;
+ Element e; e.rand_gen();
+ LL my_ans = my_solution(e, P);
+ LL bf = circle(e) ;
+ static int cas = 0; ++ cas;
+ if(my_ans == bf) {
+ cout <<""correct @"" << cas <<"" ans = "" << my_ans<< endl;
+ }else {
+ cout <<""error""<> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ cout << my_solution( Element(a,b), P) << endl;
+ }
+}
+
+void _cmp_with_bf(int x ){
+ char in[] = ""input00.in"";
+ char out[] = ""output01.out"";
+ in[6]='0'+x;
+ out[7]='0'+x;
+
+ freopen(in,""r"",stdin);
+
+ int T ,cas = 0;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ LL my = my_solution( Element(a,b), P) ;
+ LL bf = circle( Element(a,b) ) ;
+ if(my != bf) {
+ cout <<""SB""<> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ cout << my_solution( Element(a,b), P) << endl;
+ }
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T18:18:32,C++
+12,1084,period,Period,"You are given 2 integers **a** and **b**. Let a number be defined as . As we know  will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define
+
+ (where x an integer) and the operation  on AC number as:
+
+
+
+This problem is to find the smallest positive integer **n**, such that:
+
+
+
+We call the integer **n** as period. You are given **a**, **b** and **m**. Can you figure out the period?
+
+**Input Format**
+The first line of the input contains a single integer T denoting the number of test-cases.
+T lines follow, each containing 3 integers - a, b and m separated by a single space.
+
+**Output Format**
+Output the Period if it exists, otherwise output ""-1"" (quotes only for reference)
+
+**Constraints**
+1 ≤ T ≤ 300
+5 ≤ m ≤ 107
+0 ≤ a, b < m
+
+
+**Sample Input #00**
+
+ 4
+ 0 0 13
+ 1 0 7
+ 3 0 10007
+ 1 1 19
+
+**Sample Output #00**
+
+ -1
+ 1
+ 5003
+ 18
+
+**Explanation #00**
+
+For the 1st test-case, no amount of operation ⊗ on a = 0, b = 0 gives 1 on the RHS. Hence the answer is -1.
+When a = 1, b = 0, we have 1 for n = 1.
+On repeated operations, the third and the fourth testcases sum to 1 for n = 5003 and n = 18 respectively.
+",code,Can you find the period?,ai,2013-10-16T05:50:59,2022-09-02T09:54:45,,,,"You are given 2 integers **a** and **b**. Let a number be defined as
+. As we know  will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define
+
+ (where x an integer) and the operation  on AC number as:
+
+
+
+This problem is to find the smallest positive integer **n**, such that:
+
+
+
+We call the integer **n** as period. You are given **a**, **b** and **m**. Can you figure out the period?
+
+**Input Format**
+The first line of the input contains a single integer T denoting the number of test-cases.
+T lines follow, each containing 3 integers - a, b and m separated by a single space.
+
+**Output Format**
+Output the Period if it exists, otherwise output ""-1"" (quotes only for reference)
+
+**Constraints**
+1 ≤ T ≤ 300
+5 ≤ m ≤ 107
+0 ≤ a, b < m
+
+
+**Sample Input #00**
+
+ 4
+ 0 0 13
+ 1 0 7
+ 3 0 10007
+ 1 1 19
+
+**Sample Output #00**
+
+ -1
+ 1
+ 5003
+ 18
+
+**Explanation #00**
+
+For the 1st test-case, no amount of operation ⊗ on a = 0, b = 0 gives 1 on the RHS. Hence the answer is -1.
+When a = 1, b = 0, we have 1 for n = 1.
+On repeated operations, the third and the fourth testcases sum to 1 for n = 5003 and n = 18 respectively.
+",0.5645161290322581,"[""bash"",""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""pascal"",""perl"",""php"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""pypy3""]", , , , ,Hard,Period : Oct 2020 Editorial,"Problem Period
+
+Difficulty : Medium-Hard
+
+Required Knowledge : Group Theory, Euler's Criterion, Lagrange's theorem
+
+Problem Setter : AekDy Coin
+
+Problem Tester : Cao Peng
+
+Approach
+
+For one given P, the AC number that satisfies 0 ≤ a,b < p
+and a2 ≅ 5b2 (mod P) have th property:
+
+Suppose,
+
+∀n ∈ Z+ ,
+(a + b√5)n = c + d√5
+
+Then we have c2 = 5d2 (mod P)
+Quite obvious by mathematical induction.
+So if a2 ≅5b2 (mod P), we could not find the Period since the expected result AC number is with c=1 and d = 0.
+
+So for the remaindering AC number, we have a2 ≠5b2 (mod P)
+If 5 is one quadratic residue modulo P, then we can find (P-1)2 such unique AC number satisfy. a2 ≠5b2 (mod P)
+
+Proof:
+
+If 5 is one quadratic residue modulo P , then for the primitive root g , we have
+
+g2k ≅5(mod P) the AC number such that a2 ≅5b2 (mod P) must satisfy:
+
+g2I(a) ≅g2k g2I(b) (mod P), which means
+
+2I(a)≅2(k+I(b))(mod P - 1), there are totally 2(P-1) AC number that satisfy that condition. (which means they also satisfy
+
+a2 ≅5b2 (mod P), but don't forget 0 + 0√5, so there are
+
+P2 - 2(P-1) - 1 = (P-1)2 AC numbers such that a2 ≠5b2 (mod P)
+
+If 5 is not one quadratic residue modulo P, then we can find P2 - 1 = (P-1)(P+1) such unique AC number satisfies,
+
+a2 ≠5b2 (mod P), because only one AC number o + 0√5 satisfies,
+
+a2 ≅5b2 (mod P)
+
+We can use Euler's Criterion to judge whether 5 is one quadratic residue modulo P in O(logP) time.
+The identity element in this group is 1.
+However there are other 2 properties that guarantee it is a group. I will ignore the proof here.
+
+Finally, base one [Lagrange's Theorem)(http://en.wikipedia.org/wiki/Lagrange%27s_theorem_(group_theory) ) we have
+Period C, where C is the number of AC number satisfies
+a2 ≠5b2 (mod P). Simple brute force will work.
+
+Setter's Code
+
+#include<iostream>
+#include<queue>
+#include<cstdio>
+#include<cmath>
+#include<string>
+#include<vector>
+#include<algorithm>
+#include<stack>
+#include<cstring>
+#include<map>
+using namespace std;
+
+typedef long long LL;
+typedef pair<int,int> PII;
+#define pb push_back
+#define mp make_pair
+
+bool isPrime(int n) {
+ if(n==1)return 0;
+ for(int i =2; i * i <= n; ++ i) if( n % i == 0 ) return 0;
+ return 1;
+}
+
+inline LL MOD(LL a, LL b) {a%=b; return a<0?a+b:a;}
+
+LL powmod(LL a, LL b, LL c){
+ LL ret = 1%c; a%=c;
+ while(b){
+ if(b&1)ret=ret*a%c;
+ a=a*a%c;
+ b>>=1;
+ }
+ return ret;
+}
+// P is one prime number
+LL inv( LL a, LL p) {return powmod( a, p - 2, p ) ; }
+
+LL P;
+class Element {
+public:
+ LL a, b;
+ // a + b Sqrt(5)
+ Element(){}
+ Element(LL _a, LL _b) :a(_a),b(_b){}
+ Element operator+(const Element e) {
+ return Element(MOD(a + e.a , P),MOD(b + e.b , P));
+ }
+ Element operator*(const Element e) {
+ return Element(MOD(a*e.a + b*e.b * 5, P),MOD(a*e.b+b*e.a, P));
+ }
+ Element operator^(LL k){
+ if(k==0) return Element(1,0);
+ --k;
+ Element ret = *this, a = *this;
+ while(k){
+ if(k&1) ret= ret * a ;
+ a = a * a;
+ k >>= 1;
+ }
+ return ret;
+ }
+ Element inverse(){
+ if(!a&&!b) return *this;
+ if(b == 0) {
+ return Element(inv(a, P) , 0 );
+ }
+ if(a == 0) {
+ return Element(0, inv(5*b%P, P));
+ }
+ LL iv = inv( MOD(-b,P) , P );
+ LL x, y;
+ y = inv( iv * (a*a%P) % P + b*5 , P );
+ x = (iv * a % P * y) % P;
+ return Element( x, y) ;
+ }
+ bool isZ(){
+ return !a && !b;
+ }
+ bool isE(){
+ return a == 1 && b == 0;
+ }
+ bool operator<(const Element e) const {
+ if(a == e.a) return b < e.b;
+ return a < e.a;
+ }
+ void rand_gen(){
+ do{a = rand()%P; b= rand()%P;}while(0);
+ }
+ void out(){
+ cout << a <<"" "" << b << endl;
+ }
+};
+
+// a + b Sqrt(5)
+LL circle( Element a ) {
+ Element b =a;
+ LL c = 1;
+ while( ! a.isE( )) {
+ a = a * b;
+ ++ c;
+ //a.out();
+ if(a.a == b.a && a.b == b.b) {
+ return - 1;
+ }
+ }
+ return c;
+}
+
+bool isRes(LL a, LL P ){
+ return powmod(a, (P-1)/2, P) == 1;
+}
+
+LL my_solution(Element e , LL P) {
+ LL a = e.a, b = e.b;
+ if(MOD(a*a-5*b*b,P)==0) return -1;
+ LL n = P*P,ans;
+ if(isRes(5,P)) {
+ n = n - 2*P+1;
+ }else -- n;
+ ans = n;
+ for(LL i = 1; i*i <= n; ++ i) if(n%i == 0) {
+ if( (Element(a,b) ^(i)).isE() )
+ ans = min(ans, i );
+ if( (Element(a,b) ^(n/i)).isE() )
+ ans = min(ans, n/i );
+ }
+ return ans;
+}
+
+void dp(){
+ while( true ) {
+ P = rand()%1000 + 6;
+ while(!isPrime(P)) ++ P;
+ Element e; e.rand_gen();
+ LL my_ans = my_solution(e, P);
+ LL bf = circle(e) ;
+ static int cas = 0; ++ cas;
+ if(my_ans == bf) {
+ cout <<""correct @"" << cas <<"" ans = "" << my_ans<< endl;
+ }else {
+ cout <<""error""<<endl;
+ cout << P << endl;
+ e.out();
+ return;
+ }
+ }
+}
+
+Element rand_one_bad(LL P) {
+ for (LL a = 1; a < P; ++a)
+ for (LL b = 1; b < P; ++b) {
+ if (MOD(a * a - 5 * b * b, P) == 0) {
+ return Element(a, b);
+ }
+ }
+ return Element(0,0);
+}
+
+void gen(int x ){
+ char in[] = ""input00.in"";
+ in[6]='0'+x;
+ freopen(in,""w"", stdout);
+
+ int T = (x+1)*10;
+ int LIMIT[] = {100, 10000, 1e6,1e6};
+ cout << T << endl;
+ while(T --) {
+ P = rand()% (int)LIMIT[x/3] + 13;
+ while(!isPrime(P)) ++ P;
+ Element e; e.rand_gen();
+ if( P < 1e4 && isRes(5,P) && rand()%2 == 0) {
+ e = rand_one_bad(P);
+ }
+ cout << e.a <<"" "" << e.b <<"" "" << P << endl;
+ }
+}
+
+
+void run(int x ){
+ char in[] = ""input00.in"";
+ char out[] = ""output01.out"";
+ in[6]='0'+x;
+ out[7]='0'+x;
+
+ freopen(in,""r"",stdin);
+ freopen(out,""w"", stdout);
+ int T ;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ cout << my_solution( Element(a,b), P) << endl;
+ }
+}
+
+void _cmp_with_bf(int x ){
+ char in[] = ""input00.in"";
+ char out[] = ""output01.out"";
+ in[6]='0'+x;
+ out[7]='0'+x;
+
+ freopen(in,""r"",stdin);
+
+ int T ,cas = 0;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ LL my = my_solution( Element(a,b), P) ;
+ LL bf = circle( Element(a,b) ) ;
+ if(my != bf) {
+ cout <<""SB""<<endl;
+ cout << a <<"" "" << b <<"" "" << P << endl;
+ cout <<my <<"" "" << bf << endl;
+ exit(0);
+ }
+ cout <<""correct @"" << x <<"" case "" << cas ++ << endl;
+ }
+}
+int main() {
+ srand( time( NULL )) ;
+ // for(int i = 0; i < 10;++i) gen(i);
+ // for(int i = 0; i < 10; ++ i) run(i);
+// for(int i=0;i<10;++i) _cmp_with_bf(i);
+ int T ;
+ cin >> T;
+ while(T --) {
+ LL a, b; cin >> a >> b >> P;
+ if(!isPrime(P) || P <= 5 || a >= P || b >= P || a < 0 || b < 0) {
+ cerr <<""SB"" << endl;
+ exit(0);
+ }
+ cout << my_solution( Element(a,b), P) << endl;
+ }
+ return 0;
+}
+
+
+Tester's Code
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+typedef long long ll;
+
+int mul(ll x,ll y,int p) {
+ return x * y % p;
+}
+
+int powermod(ll x,ll y,int p) { //x ^ y mod p
+ if (x == 0) {
+ return 0;
+ }
+ if (y == 0) {
+ return 1;
+ }
+ if (y & 1) {
+ return mul(powermod(x, y ^ 1, p), x, p);
+ }
+ x = powermod(x, y >> 1, p);
+ return mul(x, x, p);
+}
+
+pair<int,int> help(int a,int b,ll x,int p) { // (a + b * sqrt(5)) ^ n mod p
+ if (x == 0) {
+ return make_pair(1, 0);
+ }
+ pair<int,int> A, B;
+ if (x & 1) {
+ A = help(a, b, x - 1, p);
+ B = make_pair(a, b);
+ }
+ else {
+ A = B = help(a, b, x >> 1, p);
+ }
+ a = mul(A.first, B.first, p) + mul(5, mul(A.second,B.second, p), p);
+ if (a >= p) {
+ a -= p;
+ }
+ b = mul(A.first, B.second, p) + mul(A.second , B.first, p);
+ if (b >= p) {
+ b -= p;
+ }
+ return make_pair(a, b);
+}
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+int z;
+ for (scanf(""%d"",&z);z;--z) {
+ int a,b,p;
+ ll x;
+ scanf(""%d%d%d"",&a,&b,&p);
+ if (mul(a,a,p) == mul(mul(b,b,p),5,p)) {
+ puts(""-1"");
+ continue;
+ }
+ else if (powermod(5, p >> 1, p) == 1) {
+ x = p - 1;
+ x *= (p - 1);
+
+
+ }
+ else {
+ x = p;
+ x *= x;
+ --x;
+ }
+ ll answer = -1;
+ pair<int,int> temp;
+ for (ll i = 1; i * i <= x; ++i) {
+ if (x % i) {
+ continue;
+ }
+ if ((answer < 0) || (i < answer)) {
+ temp = help(a,b,i,p);
+ if ((temp.first == 1) && (temp.second == 0)) {
+ answer = i;
+ }
+ }
+ if ((answer < 0) || (x / i < answer)) {
+ temp = help(a,b,x / i,p);
+ if ((temp.first == 1) && (temp.second == 0)) {
+ answer = x / i;
+ }
+
+ }
+ }
+ printf(""%lld\n"",answer);
+
+ }
+ return 0;
+}
+
",0.0,oct-2020-editorial-period,2013-10-29T06:13:09,"{""contest_participation"":7868,""challenge_submissions"":564,""successful_submissions"":106}",2013-10-29T06:13:09,2016-07-23T18:18:41,tester,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+
+typedef long long ll;
+
+int mul(ll x,ll y,int p) {
+ return x * y % p;
+}
+
+int powermod(ll x,ll y,int p) { //x ^ y mod p
+ if (x == 0) {
+ return 0;
+ }
+ if (y == 0) {
+ return 1;
+ }
+ if (y & 1) {
+ return mul(powermod(x, y ^ 1, p), x, p);
+ }
+ x = powermod(x, y >> 1, p);
+ return mul(x, x, p);
+}
+
+pair help(int a,int b,ll x,int p) { // (a + b * sqrt(5)) ^ n mod p
+ if (x == 0) {
+ return make_pair(1, 0);
+ }
+ pair A, B;
+ if (x & 1) {
+ A = help(a, b, x - 1, p);
+ B = make_pair(a, b);
+ }
+ else {
+ A = B = help(a, b, x >> 1, p);
+ }
+ a = mul(A.first, B.first, p) + mul(5, mul(A.second,B.second, p), p);
+ if (a >= p) {
+ a -= p;
+ }
+ b = mul(A.first, B.second, p) + mul(A.second , B.first, p);
+ if (b >= p) {
+ b -= p;
+ }
+ return make_pair(a, b);
+}
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+int z;
+ for (scanf(""%d"",&z);z;--z) {
+ int a,b,p;
+ ll x;
+ scanf(""%d%d%d"",&a,&b,&p);
+ if (mul(a,a,p) == mul(mul(b,b,p),5,p)) {
+ puts(""-1"");
+ continue;
+ }
+ else if (powermod(5, p >> 1, p) == 1) {
+ x = p - 1;
+ x *= (p - 1);
+
+
+ }
+ else {
+ x = p;
+ x *= x;
+ --x;
+ }
+ ll answer = -1;
+ pair temp;
+ for (ll i = 1; i * i <= x; ++i) {
+ if (x % i) {
+ continue;
+ }
+ if ((answer < 0) || (i < answer)) {
+ temp = help(a,b,i,p);
+ if ((temp.first == 1) && (temp.second == 0)) {
+ answer = i;
+ }
+ }
+ if ((answer < 0) || (x / i < answer)) {
+ temp = help(a,b,x / i,p);
+ if ((temp.first == 1) && (temp.second == 0)) {
+ answer = x / i;
+ }
+
+ }
+ }
+ printf(""%lld\n"",answer);
+
+ }
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T18:18:41,C++
+13,1090,missile-defend,HackerX,"**Update:** A slight modification in the problem statement (see below)
+
+Evil Nation A is angry and plans to launch **N** guided-missiles at the peaceful Nation B in an attempt to wipe out all of Nation B's people. Nation A's missile _i_ will arrive in nation B at time ti . Missile _i_ communicates with its headquarters by unique radio signals with a frequency equal to fi . Can you help the peaceful Nation B survive by building a defensive system that will stop the missiles dead in the sky?
+
+**Defensive system:**
+
+The only way to defend Nation B from the attacking missile is by counter attacking them with a _hackerX_ missile. You have a lot of _hackerX_ missiles and each one of them has its own radio frequency. An individual _hackerX_ missile can destroy Evil Nation A’s attacking missile if the radio frequency of both of the missiles match. Each _hackerX_ missile can be used an indefinite number of times. Its invincible and doesn't get destroyed in the collision.
+
+The good news is you can adjust the frequency of the _hackerX_ missile to match the evil missiles' frequency. When changing the _hackerX_ missile's initial frequency fA to the new defending frequency fB, you will need \|fB - fA\| units of time to do.
+
+Each _hackerX_ missile can only destroy one of Nation A's missile at a time. So if two evil missiles with same frequency arrive at the same time, you need at least two _hackerX_ missiles with the same frequency as the evil missiles to avoid damage.
+
+If two evil missles with same frequency arrive at the same time, we can destroy them both with one _hackerX_ missile. You can set the frequency of a _hackerX_ missile to any value when its fired.
+
+What is the minimum number of _hackerX_ missiles you must launch to keep Nation B safe?
+
+
+**Input Format:**
+The first line contains a single integer **N** denoting the number of missiles.
+This is followed by **N** lines each containing two integers ti and fi denoting the time & frequency of the ith missile.
+
+**Output Format:**
+A single integer denoting the minimum number of _hackerX_ missiles you need to defend the nation.
+
+**Constraints:**
+1 <= N <= 100000
+0 <= ti <= 100000
+0 <= fi <= 100000
+t1 <= t2 <= ... <= tN
+
+**Sample Input #00**
+
+ 4
+ 1 1
+ 2 2
+ 3 1
+ 5 1
+
+**Sample Output #00**
+
+ 1
+
+**Explanation #00**
+
+A _HackerX_ missile is launched at t = 1 with a frequency f = 1, and destroys the first missile. It re-tunes its frequency to f = 2 in 1 unit of time, and destroys the missile that is going to hit Nation B at t = 2. It re-tunes its frequency back to 1 in 1 unit of time and destroys the missile that is going to hit the nation at t = 3. It is relaunched at t = 5 with f = 1 and destroys the missile that is going to hit nation B at t = 5. Hence, you need only 1 _HackerX_ to protect nation B.
+
+**Sample Input #01**
+
+ 4
+ 1 1
+ 2 3
+ 3 1
+ 5 1
+
+**Sample Output #01**
+
+ 2
+
+**Explanation #01**
+
+Destroy 1 missile at t = 1, f = 1. now at t = 2, there is a missile with frequency 3. The launched missile takes 2 units of time to destroy this, hence we need a new hackerX missile to destroy this one. The first hackerX missile can destroy the 3rd missile which has the same frequency as itself. The same hackerX missile destroys the missile that is hitting its city at t = 5. Thus, we need atleast 2 hackerX missiles. ",code,Find the minimum number of hackerX missiles you must launch to keep Nation B safe.,ai,2013-10-16T17:50:34,2022-08-31T08:14:32,"#
+# Complete the 'missileDefend' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts 2D_INTEGER_ARRAY missiles as parameter.
+#
+
+def missileDefend(missiles):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ n = int(input().strip())
+
+ missiles = []
+
+ for _ in range(n):
+ missiles.append(list(map(int, input().rstrip().split())))
+
+ result = missileDefend(missiles)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","**Update:** A slight modification in the problem statement (see below)
+
+Evil Nation A is angry and plans to launch **N** guided-missiles at the peaceful Nation B in an attempt to wipe out all of Nation B's people. Nation A's missile _i_ will arrive in nation B at time ti . Missile _i_ communicates with its headquarters by unique radio signals with a frequency equal to fi . Can you help the peaceful Nation B survive by building a defensive system that will stop the missiles dead in the sky?
+
+**Defensive system:**
+
+The only way to defend Nation B from the attacking missile is by counter attacking them with a _hackerX_ missile. You have a lot of _hackerX_ missiles and each one of them has its own radio frequency. An individual _hackerX_ missile can destroy Evil Nation A’s attacking missile if the radio frequency of both of the missiles match. Each _hackerX_ missile can be used an indefinite number of times. Its invincible and doesn't get destroyed in the collision.
+
+The good news is you can adjust the frequency of the _hackerX_ missile to match the evil missiles' frequency. When changing the _hackerX_ missile's initial frequency fA to the new defending frequency fB, you will need \|fB - fA\| units of time to do.
+
+Each _hackerX_ missile can only destroy one of Nation A's missile at a time. So if two evil missiles with same frequency arrive at the same time, you need at least two _hackerX_ missiles with the same frequency as the evil missiles to avoid damage.
+
+If two evil missles with same frequency arrive at the same time, we can destroy them both with one _hackerX_ missile. You can set the frequency of a _hackerX_ missile to any value when its fired.
+
+What is the minimum number of _hackerX_ missiles you must launch to keep Nation B safe?
+
+
+**Input Format:**
+The first line contains a single integer **N** denoting the number of missiles.
+This is followed by **N** lines each containing two integers ti and fi denoting the time & frequency of the ith missile.
+
+**Output Format:**
+A single integer denoting the minimum number of _hackerX_ missiles you need to defend the nation.
+
+**Constraints:**
+1 <= N <= 100000
+0 <= ti <= 100000
+0 <= fi <= 100000
+t1 <= t2 <= ... <= tN
+
+**Sample Input #00**
+
+ 4
+ 1 1
+ 2 2
+ 3 1
+ 5 1
+
+**Sample Output #00**
+
+ 1
+
+**Explanation #00**
+
+A _HackerX_ missile is launched at t = 1 with a frequency f = 1, and destroys the first missile. It re-tunes its frequency to f = 2 in 1 unit of time, and destroys the missile that is going to hit Nation B at t = 2. It re-tunes its frequency back to 1 in 1 unit of time and destroys the missile that is going to hit the nation at t = 3. It is relaunched at t = 5 with f = 1 and destroys the missile that is going to hit nation B at t = 5. Hence, you need only 1 _HackerX_ to protect nation B.
+
+**Sample Input #01**
+
+ 4
+ 1 1
+ 2 3
+ 3 1
+ 5 1
+
+**Sample Output #01**
+
+ 2
+
+**Explanation #01**
+
+Destroy 1 missile at t = 1, f = 1. now at t = 2, there is a missile with frequency 3. The launched missile takes 2 units of time to destroy this, hence we need a new hackerX missile to destroy this one. The first hackerX missile can destroy the 3rd missile which has the same frequency as itself. The same hackerX missile destroys the missile that is hitting its city at t = 5. Thus, we need atleast 2 hackerX missiles. ",0.5384615384615384,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]",,,,,Hard,hackerX : Oct 20/20 Editorial,"Problem : hackerX
+
+Difficulty : Medium-Hard
+
+Required Knowledge : Minimum Path cover, Dilworth's theorem
+
+Problem Setter : Wanbo
+
+Problem Tester : Cao Peng , Khongor
+
+Approach
+
+What's the requirement if one hackerX missiles can defend both (ti, fi) and (tj, fj) when ti <= tj?
+
+tj - ti >= \|fi - fj\| (because you just need \|fi - fj\| units time to change the frequency from fi to fj,
+so you can defend tj after defend ti by this hackerX missiles if you need.
+So if we regard every coming missiles (ti, fi) as an vertex i, and if tj - ti >= \|fi - fj\| then we add an edge from i to j,
+this edge indicates that one hackerX can defend the jth missile after defending the ith missile.
+
+So the solution for this challenge seems obvious, we just need to find the ""Minimum Path Cover""(Can be changed to MaxFlow problem) of this graph.
+
+But n can be as large as 100000, and there are at most O(n2 ) edges, even generating the graph will get TLE, we need to optimize our solution.
+
+We haven't taken advantage of the particularity of this graph in the previous analysis, we just look this as a more general problem.
+
+tj - ti >= \|fi - fj\|
+<==>
+If fi < fj, tj - ti >= fj - fi ==> ti - fi <= tj - fj ==> Ai <= Aj (Ai = ti - fi)
+If fi >= fj, tj - ti >= fi - fj ==> ti + fi <= tj + fj ==> Bi <= Bj (Bi = ti + fi)
+
+Can we remove some constraints?
+
+
+ti <= tj
+If fi < fj, Ai <= Aj ==> Ai + 2 * fi <= Aj + 2 * fj ==> Bi <= Bj
+If fi >= fj, Bi <= Bj ==> Bi - 2 * fi <= Bj - 2 * fj ==> Ai <= Aj
+
+
+We can combine 2) with 3) to ""Ai <= Aj && Bi <= Bj""
+Ai + Bi <= Aj + Bj ==> ti <= tj ==> ti <= tj can be removed.
+
+==>
+
+edge(i->j) <==> Ai <= Aj && Bi <= Bj
+
+We need to find the minimum path cover in the graph which edge(i->j) <==> Ai <= Aj && Bi <= Bj.
+
+According to Dilworth's theorem , the minimum path cover in this graph is equal to the longest anti-chain.
+So we just need to choose a maximum vertexes subset from the graph, where any of two do not have an edge.
+1. Sort the (Ai, Bi) by the first key value Ai, if Ai == Aj, then smaller Bi comes first.
+2. The longest decreasing subsequence of Bi will be the answer.(This is a very classic question that can be solved by O(nlgn).
+
+Problem Setter Code :
+
+#include <map>
+#include <set>
+#include <list>
+#include <queue>
+#include <deque>
+#include <stack>
+#include <bitset>
+#include <vector>
+#include <ctime>
+#include <cmath>
+#include <cstdio>
+#include <string>
+#include <cstring>
+#include <cassert>
+#include <numeric>
+#include <iomanip>
+#include <sstream>
+#include <fstream>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+typedef long long LL;
+typedef pair<int, int> PII;
+typedef pair<LL, LL> PLL;
+typedef vector<int> VI;
+typedef vector<LL> VL;
+typedef vector<PII> VPII;
+typedef vector<PLL> VPLL;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""<<(x)<<""]\n""
+#define PP(x,i) cerr<<""[""#x<<i<<"" = ""<<x[i]<<""]\n""
+#define P2(x,y) cerr<<""[""#x"" = ""<<(x)<<"", ""#y"" = ""<<(y)<<""]\n""
+#define TM(a,b) cerr<<""[""#a"" -> ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define FOR(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
+#define rep(i, n) for(int i = 0; i < n; i++)
+#define UN(v) sort(ALL(v)), v.resize(unique(ALL(v))-v.begin())
+#define mp make_pair
+#define pb push_back
+#define x first
+#define y second
+struct _ {_() {ios_base::sync_with_stdio(0);}} _;
+template<class T> void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n"");}
+template<class T> inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template<class T> inline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+template<class T> string tostring(T x, int len = 0) {stringstream ss; ss << x; string r = ss.str(); if(r.length() < len) r = string(len - r.length(), '0') + r; return r;}
+template<class T> void convert(string x, T& r) {stringstream ss(x); ss >> r;}
+template<class A, class B> ostream& operator<<(ostream &o, pair<A, B> t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;}
+const int inf = 0x3f3f3f3f;
+const int mod = int(1e9) + 7;
+const int N = 111111;
+
+int t[N], f[N];
+int d[N];
+int n;
+
+
+int LIS(VI v) {
+ fill(d, d + n, 1);
+ for(int i = 0; i < n; i++)
+ for(int j = 0; j < i; j++)
+ if(v[i] > v[j]) chmax(d[i], d[j] + 1);
+ int res = 0;
+ for(int i = 0; i < n; i++) chmax(res, d[i]);
+ return res;
+}
+
+int LIS1(VI v) {
+ MM(d, 0x3f);
+ d[1] = v[0];
+ for(int i = 1; i < v.size(); i++) {
+ int t = upper_bound(d + 1, d + N, v[i]) - d;
+ if(t != 1 && d[t - 1] >= v[i]) continue;
+ d[t] = v[i];
+ }
+ int res = 0;
+ for(int i = 1; i < N; i++) if(d[i] != inf) res = i;
+ return res;
+}
+
+int main() {
+ cin >> n;
+ for(int i = 0; i < n; i++) cin >> t[i] >> f[i];
+ for(int i = 1; i < n; i++) assert(t[i] >= t[i - 1]);
+ VI v;
+ VPII vp;
+ for(int i = 0; i < n; i++) vp.pb(mp(t[i] - f[i], t[i] + f[i]));
+ sort(ALL(vp));
+ for(int i = 0; i < n; i++) v.pb(vp[i].second);
+ reverse(ALL(v));
+ //PV(ALL(v));
+ cout << LIS1(v) << endl;
+ //P2(LIS1(v), LIS(v));
+ //assert(LIS1(v) == LIS(v));
+ return 0;
+}
+
+
+Problem Tester Code :
+
+#include <cstdio>
+#include <algorithm>
+#include <set>
+
+using namespace std;
+
+pair<int,int> a[100005];
+set<int> have;
+
+int main() {
+int n;
+ scanf(""%d"",&n);
+ for (int i = 0; i < n; ++i) {
+ int x,y;
+ scanf(""%d%d"",&x,&y);
+ a[i] = make_pair(x + y,x - y);
+ }
+ sort(a, a + n);
+ for (int i = 0; i < n; ++i) {
+ //printf(""%d %d\n"",a[i].first,a[i].second);
+
+ set<int>::iterator t = have.lower_bound(a[i].second);
+
+ if ((t != have.end()) && (*t == a[i].second)) {
+ continue;
+ }
+ if (t != have.begin()) {
+ have.erase(--t);
+
+ }
+ have.insert(a[i].second);
+ }
+ printf(""%d\n"",have.size());
+ return 0;
+}
+
+
+
+
+
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+#include <utility>
+using namespace std;
+
+#define Pair pair<int, int>
+
+#define MAX 100000
+
+Pair v[MAX];
+int a[MAX];
+int dp[MAX + 1];
+
+int main() {
+ int n;
+ scanf(""%d"", &n);
+ for (int i = 0; i < n; i++) {
+ int x, y;
+ scanf(""%d%d"", &x, &y);
+ v[i] = make_pair(x - y, x + y);
+ }
+ sort(v, v + n);
+ for (int i = 0; i < n; i++)
+ a[i] = v[n - i - 1].second;
+ int r = 1;
+ dp[1] = a[0];
+ for (int i = 1; i < n; i++) {
+ int low = 1, high = r;
+ if (a[i] <= dp[1]) {
+ dp[1] = a[i];
+ continue;
+ }
+ while (low < high) {
+ int mid = (low + high + 1) / 2;
+ if (dp[mid] >= a[i])
+ high = mid - 1;
+ else
+ low = mid;
+ }
+ if (low == r) r++;
+ dp[low + 1] = a[i];
+ }
+ cout << r << endl;
+ return 0;
+}
+
",0.0,oct-2020-editorial-hackerx,2013-10-30T05:56:08,"{""contest_participation"":7868,""challenge_submissions"":955,""successful_submissions"":110}",2013-10-30T05:56:08,2016-07-23T14:05:03,setter,"###C++
+```cpp
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+typedef long long LL;
+typedef pair PII;
+typedef pair PLL;
+typedef vector VI;
+typedef vector VL;
+typedef vector VPII;
+typedef vector VPLL;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""<<(x)<<""]\n""
+#define PP(x,i) cerr<<""[""#x< ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define FOR(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
+#define rep(i, n) for(int i = 0; i < n; i++)
+#define UN(v) sort(ALL(v)), v.resize(unique(ALL(v))-v.begin())
+#define mp make_pair
+#define pb push_back
+#define x first
+#define y second
+struct _ {_() {ios_base::sync_with_stdio(0);}} _;
+template void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n"");}
+template inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template inline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+template string tostring(T x, int len = 0) {stringstream ss; ss << x; string r = ss.str(); if(r.length() < len) r = string(len - r.length(), '0') + r; return r;}
+template void convert(string x, T& r) {stringstream ss(x); ss >> r;}
+template ostream& operator<<(ostream &o, pair t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;}
+const int inf = 0x3f3f3f3f;
+const int mod = int(1e9) + 7;
+const int N = 111111;
+
+int t[N], f[N];
+int d[N];
+int n;
+
+
+int LIS(VI v) {
+ fill(d, d + n, 1);
+ for(int i = 0; i < n; i++)
+ for(int j = 0; j < i; j++)
+ if(v[i] > v[j]) chmax(d[i], d[j] + 1);
+ int res = 0;
+ for(int i = 0; i < n; i++) chmax(res, d[i]);
+ return res;
+}
+
+int LIS1(VI v) {
+ MM(d, 0x3f);
+ d[1] = v[0];
+ for(int i = 1; i < v.size(); i++) {
+ int t = upper_bound(d + 1, d + N, v[i]) - d;
+ if(t != 1 && d[t - 1] >= v[i]) continue;
+ d[t] = v[i];
+ }
+ int res = 0;
+ for(int i = 1; i < N; i++) if(d[i] != inf) res = i;
+ return res;
+}
+
+int main() {
+ cin >> n;
+ for(int i = 0; i < n; i++) cin >> t[i] >> f[i];
+ for(int i = 1; i < n; i++) assert(t[i] >= t[i - 1]);
+ VI v;
+ VPII vp;
+ for(int i = 0; i < n; i++) vp.pb(mp(t[i] - f[i], t[i] + f[i]));
+ sort(ALL(vp));
+ for(int i = 0; i < n; i++) v.pb(vp[i].second);
+ reverse(ALL(v));
+ //PV(ALL(v));
+ cout << LIS1(v) << endl;
+ //P2(LIS1(v), LIS(v));
+ //assert(LIS1(v) == LIS(v));
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T14:04:43,C++
+14,1090,missile-defend,HackerX,"**Update:** A slight modification in the problem statement (see below)
+
+Evil Nation A is angry and plans to launch **N** guided-missiles at the peaceful Nation B in an attempt to wipe out all of Nation B's people. Nation A's missile _i_ will arrive in nation B at time ti . Missile _i_ communicates with its headquarters by unique radio signals with a frequency equal to fi . Can you help the peaceful Nation B survive by building a defensive system that will stop the missiles dead in the sky?
+
+**Defensive system:**
+
+The only way to defend Nation B from the attacking missile is by counter attacking them with a _hackerX_ missile. You have a lot of _hackerX_ missiles and each one of them has its own radio frequency. An individual _hackerX_ missile can destroy Evil Nation A’s attacking missile if the radio frequency of both of the missiles match. Each _hackerX_ missile can be used an indefinite number of times. Its invincible and doesn't get destroyed in the collision.
+
+The good news is you can adjust the frequency of the _hackerX_ missile to match the evil missiles' frequency. When changing the _hackerX_ missile's initial frequency fA to the new defending frequency fB, you will need \|fB - fA\| units of time to do.
+
+Each _hackerX_ missile can only destroy one of Nation A's missile at a time. So if two evil missiles with same frequency arrive at the same time, you need at least two _hackerX_ missiles with the same frequency as the evil missiles to avoid damage.
+
+If two evil missles with same frequency arrive at the same time, we can destroy them both with one _hackerX_ missile. You can set the frequency of a _hackerX_ missile to any value when its fired.
+
+What is the minimum number of _hackerX_ missiles you must launch to keep Nation B safe?
+
+
+**Input Format:**
+The first line contains a single integer **N** denoting the number of missiles.
+This is followed by **N** lines each containing two integers ti and fi denoting the time & frequency of the ith missile.
+
+**Output Format:**
+A single integer denoting the minimum number of _hackerX_ missiles you need to defend the nation.
+
+**Constraints:**
+1 <= N <= 100000
+0 <= ti <= 100000
+0 <= fi <= 100000
+t1 <= t2 <= ... <= tN
+
+**Sample Input #00**
+
+ 4
+ 1 1
+ 2 2
+ 3 1
+ 5 1
+
+**Sample Output #00**
+
+ 1
+
+**Explanation #00**
+
+A _HackerX_ missile is launched at t = 1 with a frequency f = 1, and destroys the first missile. It re-tunes its frequency to f = 2 in 1 unit of time, and destroys the missile that is going to hit Nation B at t = 2. It re-tunes its frequency back to 1 in 1 unit of time and destroys the missile that is going to hit the nation at t = 3. It is relaunched at t = 5 with f = 1 and destroys the missile that is going to hit nation B at t = 5. Hence, you need only 1 _HackerX_ to protect nation B.
+
+**Sample Input #01**
+
+ 4
+ 1 1
+ 2 3
+ 3 1
+ 5 1
+
+**Sample Output #01**
+
+ 2
+
+**Explanation #01**
+
+Destroy 1 missile at t = 1, f = 1. now at t = 2, there is a missile with frequency 3. The launched missile takes 2 units of time to destroy this, hence we need a new hackerX missile to destroy this one. The first hackerX missile can destroy the 3rd missile which has the same frequency as itself. The same hackerX missile destroys the missile that is hitting its city at t = 5. Thus, we need atleast 2 hackerX missiles. ",code,Find the minimum number of hackerX missiles you must launch to keep Nation B safe.,ai,2013-10-16T17:50:34,2022-08-31T08:14:32,"#
+# Complete the 'missileDefend' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts 2D_INTEGER_ARRAY missiles as parameter.
+#
+
+def missileDefend(missiles):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ n = int(input().strip())
+
+ missiles = []
+
+ for _ in range(n):
+ missiles.append(list(map(int, input().rstrip().split())))
+
+ result = missileDefend(missiles)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","**Update:** A slight modification in the problem statement (see below)
+
+Evil Nation A is angry and plans to launch **N** guided-missiles at the peaceful Nation B in an attempt to wipe out all of Nation B's people. Nation A's missile _i_ will arrive in nation B at time ti . Missile _i_ communicates with its headquarters by unique radio signals with a frequency equal to fi . Can you help the peaceful Nation B survive by building a defensive system that will stop the missiles dead in the sky?
+
+**Defensive system:**
+
+The only way to defend Nation B from the attacking missile is by counter attacking them with a _hackerX_ missile. You have a lot of _hackerX_ missiles and each one of them has its own radio frequency. An individual _hackerX_ missile can destroy Evil Nation A’s attacking missile if the radio frequency of both of the missiles match. Each _hackerX_ missile can be used an indefinite number of times. Its invincible and doesn't get destroyed in the collision.
+
+The good news is you can adjust the frequency of the _hackerX_ missile to match the evil missiles' frequency. When changing the _hackerX_ missile's initial frequency fA to the new defending frequency fB, you will need \|fB - fA\| units of time to do.
+
+Each _hackerX_ missile can only destroy one of Nation A's missile at a time. So if two evil missiles with same frequency arrive at the same time, you need at least two _hackerX_ missiles with the same frequency as the evil missiles to avoid damage.
+
+If two evil missles with same frequency arrive at the same time, we can destroy them both with one _hackerX_ missile. You can set the frequency of a _hackerX_ missile to any value when its fired.
+
+What is the minimum number of _hackerX_ missiles you must launch to keep Nation B safe?
+
+
+**Input Format:**
+The first line contains a single integer **N** denoting the number of missiles.
+This is followed by **N** lines each containing two integers ti and fi denoting the time & frequency of the ith missile.
+
+**Output Format:**
+A single integer denoting the minimum number of _hackerX_ missiles you need to defend the nation.
+
+**Constraints:**
+1 <= N <= 100000
+0 <= ti <= 100000
+0 <= fi <= 100000
+t1 <= t2 <= ... <= tN
+
+**Sample Input #00**
+
+ 4
+ 1 1
+ 2 2
+ 3 1
+ 5 1
+
+**Sample Output #00**
+
+ 1
+
+**Explanation #00**
+
+A _HackerX_ missile is launched at t = 1 with a frequency f = 1, and destroys the first missile. It re-tunes its frequency to f = 2 in 1 unit of time, and destroys the missile that is going to hit Nation B at t = 2. It re-tunes its frequency back to 1 in 1 unit of time and destroys the missile that is going to hit the nation at t = 3. It is relaunched at t = 5 with f = 1 and destroys the missile that is going to hit nation B at t = 5. Hence, you need only 1 _HackerX_ to protect nation B.
+
+**Sample Input #01**
+
+ 4
+ 1 1
+ 2 3
+ 3 1
+ 5 1
+
+**Sample Output #01**
+
+ 2
+
+**Explanation #01**
+
+Destroy 1 missile at t = 1, f = 1. now at t = 2, there is a missile with frequency 3. The launched missile takes 2 units of time to destroy this, hence we need a new hackerX missile to destroy this one. The first hackerX missile can destroy the 3rd missile which has the same frequency as itself. The same hackerX missile destroys the missile that is hitting its city at t = 5. Thus, we need atleast 2 hackerX missiles. ",0.5384615384615384,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]",,,,,Hard,hackerX : Oct 20/20 Editorial,"Problem : hackerX
+
+Difficulty : Medium-Hard
+
+Required Knowledge : Minimum Path cover, Dilworth's theorem
+
+Problem Setter : Wanbo
+
+Problem Tester : Cao Peng , Khongor
+
+Approach
+
+What's the requirement if one hackerX missiles can defend both (ti, fi) and (tj, fj) when ti <= tj?
+
+tj - ti >= \|fi - fj\| (because you just need \|fi - fj\| units time to change the frequency from fi to fj,
+so you can defend tj after defend ti by this hackerX missiles if you need.
+So if we regard every coming missiles (ti, fi) as an vertex i, and if tj - ti >= \|fi - fj\| then we add an edge from i to j,
+this edge indicates that one hackerX can defend the jth missile after defending the ith missile.
+
+So the solution for this challenge seems obvious, we just need to find the ""Minimum Path Cover""(Can be changed to MaxFlow problem) of this graph.
+
+But n can be as large as 100000, and there are at most O(n2 ) edges, even generating the graph will get TLE, we need to optimize our solution.
+
+We haven't taken advantage of the particularity of this graph in the previous analysis, we just look this as a more general problem.
+
+tj - ti >= \|fi - fj\|
+<==>
+If fi < fj, tj - ti >= fj - fi ==> ti - fi <= tj - fj ==> Ai <= Aj (Ai = ti - fi)
+If fi >= fj, tj - ti >= fi - fj ==> ti + fi <= tj + fj ==> Bi <= Bj (Bi = ti + fi)
+
+Can we remove some constraints?
+
+
+ti <= tj
+If fi < fj, Ai <= Aj ==> Ai + 2 * fi <= Aj + 2 * fj ==> Bi <= Bj
+If fi >= fj, Bi <= Bj ==> Bi - 2 * fi <= Bj - 2 * fj ==> Ai <= Aj
+
+
+We can combine 2) with 3) to ""Ai <= Aj && Bi <= Bj""
+Ai + Bi <= Aj + Bj ==> ti <= tj ==> ti <= tj can be removed.
+
+==>
+
+edge(i->j) <==> Ai <= Aj && Bi <= Bj
+
+We need to find the minimum path cover in the graph which edge(i->j) <==> Ai <= Aj && Bi <= Bj.
+
+According to Dilworth's theorem , the minimum path cover in this graph is equal to the longest anti-chain.
+So we just need to choose a maximum vertexes subset from the graph, where any of two do not have an edge.
+1. Sort the (Ai, Bi) by the first key value Ai, if Ai == Aj, then smaller Bi comes first.
+2. The longest decreasing subsequence of Bi will be the answer.(This is a very classic question that can be solved by O(nlgn).
+
+Problem Setter Code :
+
+#include <map>
+#include <set>
+#include <list>
+#include <queue>
+#include <deque>
+#include <stack>
+#include <bitset>
+#include <vector>
+#include <ctime>
+#include <cmath>
+#include <cstdio>
+#include <string>
+#include <cstring>
+#include <cassert>
+#include <numeric>
+#include <iomanip>
+#include <sstream>
+#include <fstream>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+typedef long long LL;
+typedef pair<int, int> PII;
+typedef pair<LL, LL> PLL;
+typedef vector<int> VI;
+typedef vector<LL> VL;
+typedef vector<PII> VPII;
+typedef vector<PLL> VPLL;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""<<(x)<<""]\n""
+#define PP(x,i) cerr<<""[""#x<<i<<"" = ""<<x[i]<<""]\n""
+#define P2(x,y) cerr<<""[""#x"" = ""<<(x)<<"", ""#y"" = ""<<(y)<<""]\n""
+#define TM(a,b) cerr<<""[""#a"" -> ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define FOR(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
+#define rep(i, n) for(int i = 0; i < n; i++)
+#define UN(v) sort(ALL(v)), v.resize(unique(ALL(v))-v.begin())
+#define mp make_pair
+#define pb push_back
+#define x first
+#define y second
+struct _ {_() {ios_base::sync_with_stdio(0);}} _;
+template<class T> void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n"");}
+template<class T> inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template<class T> inline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+template<class T> string tostring(T x, int len = 0) {stringstream ss; ss << x; string r = ss.str(); if(r.length() < len) r = string(len - r.length(), '0') + r; return r;}
+template<class T> void convert(string x, T& r) {stringstream ss(x); ss >> r;}
+template<class A, class B> ostream& operator<<(ostream &o, pair<A, B> t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;}
+const int inf = 0x3f3f3f3f;
+const int mod = int(1e9) + 7;
+const int N = 111111;
+
+int t[N], f[N];
+int d[N];
+int n;
+
+
+int LIS(VI v) {
+ fill(d, d + n, 1);
+ for(int i = 0; i < n; i++)
+ for(int j = 0; j < i; j++)
+ if(v[i] > v[j]) chmax(d[i], d[j] + 1);
+ int res = 0;
+ for(int i = 0; i < n; i++) chmax(res, d[i]);
+ return res;
+}
+
+int LIS1(VI v) {
+ MM(d, 0x3f);
+ d[1] = v[0];
+ for(int i = 1; i < v.size(); i++) {
+ int t = upper_bound(d + 1, d + N, v[i]) - d;
+ if(t != 1 && d[t - 1] >= v[i]) continue;
+ d[t] = v[i];
+ }
+ int res = 0;
+ for(int i = 1; i < N; i++) if(d[i] != inf) res = i;
+ return res;
+}
+
+int main() {
+ cin >> n;
+ for(int i = 0; i < n; i++) cin >> t[i] >> f[i];
+ for(int i = 1; i < n; i++) assert(t[i] >= t[i - 1]);
+ VI v;
+ VPII vp;
+ for(int i = 0; i < n; i++) vp.pb(mp(t[i] - f[i], t[i] + f[i]));
+ sort(ALL(vp));
+ for(int i = 0; i < n; i++) v.pb(vp[i].second);
+ reverse(ALL(v));
+ //PV(ALL(v));
+ cout << LIS1(v) << endl;
+ //P2(LIS1(v), LIS(v));
+ //assert(LIS1(v) == LIS(v));
+ return 0;
+}
+
+
+Problem Tester Code :
+
+#include <cstdio>
+#include <algorithm>
+#include <set>
+
+using namespace std;
+
+pair<int,int> a[100005];
+set<int> have;
+
+int main() {
+int n;
+ scanf(""%d"",&n);
+ for (int i = 0; i < n; ++i) {
+ int x,y;
+ scanf(""%d%d"",&x,&y);
+ a[i] = make_pair(x + y,x - y);
+ }
+ sort(a, a + n);
+ for (int i = 0; i < n; ++i) {
+ //printf(""%d %d\n"",a[i].first,a[i].second);
+
+ set<int>::iterator t = have.lower_bound(a[i].second);
+
+ if ((t != have.end()) && (*t == a[i].second)) {
+ continue;
+ }
+ if (t != have.begin()) {
+ have.erase(--t);
+
+ }
+ have.insert(a[i].second);
+ }
+ printf(""%d\n"",have.size());
+ return 0;
+}
+
+
+
+
+
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+#include <utility>
+using namespace std;
+
+#define Pair pair<int, int>
+
+#define MAX 100000
+
+Pair v[MAX];
+int a[MAX];
+int dp[MAX + 1];
+
+int main() {
+ int n;
+ scanf(""%d"", &n);
+ for (int i = 0; i < n; i++) {
+ int x, y;
+ scanf(""%d%d"", &x, &y);
+ v[i] = make_pair(x - y, x + y);
+ }
+ sort(v, v + n);
+ for (int i = 0; i < n; i++)
+ a[i] = v[n - i - 1].second;
+ int r = 1;
+ dp[1] = a[0];
+ for (int i = 1; i < n; i++) {
+ int low = 1, high = r;
+ if (a[i] <= dp[1]) {
+ dp[1] = a[i];
+ continue;
+ }
+ while (low < high) {
+ int mid = (low + high + 1) / 2;
+ if (dp[mid] >= a[i])
+ high = mid - 1;
+ else
+ low = mid;
+ }
+ if (low == r) r++;
+ dp[low + 1] = a[i];
+ }
+ cout << r << endl;
+ return 0;
+}
+
",0.0,oct-2020-editorial-hackerx,2013-10-30T05:56:08,"{""contest_participation"":7868,""challenge_submissions"":955,""successful_submissions"":110}",2013-10-30T05:56:08,2016-07-23T14:05:03,tester,"###C++
+```cpp
+
+#include
+#include
+#include
+
+using namespace std;
+
+pair a[100005];
+set have;
+
+int main() {
+int n;
+ scanf(""%d"",&n);
+ for (int i = 0; i < n; ++i) {
+ int x,y;
+ scanf(""%d%d"",&x,&y);
+ a[i] = make_pair(x + y,x - y);
+ }
+ sort(a, a + n);
+ for (int i = 0; i < n; ++i) {
+ //printf(""%d %d\n"",a[i].first,a[i].second);
+
+ set::iterator t = have.lower_bound(a[i].second);
+
+ if ((t != have.end()) && (*t == a[i].second)) {
+ continue;
+ }
+ if (t != have.begin()) {
+ have.erase(--t);
+
+ }
+ have.insert(a[i].second);
+ }
+ printf(""%d\n"",have.size());
+ return 0;
+}
+
+
+
+
+
+
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+
+#define Pair pair
+
+#define MAX 100000
+
+Pair v[MAX];
+int a[MAX];
+int dp[MAX + 1];
+
+int main() {
+ int n;
+ scanf(""%d"", &n);
+ for (int i = 0; i < n; i++) {
+ int x, y;
+ scanf(""%d%d"", &x, &y);
+ v[i] = make_pair(x - y, x + y);
+ }
+ sort(v, v + n);
+ for (int i = 0; i < n; i++)
+ a[i] = v[n - i - 1].second;
+ int r = 1;
+ dp[1] = a[0];
+ for (int i = 1; i < n; i++) {
+ int low = 1, high = r;
+ if (a[i] <= dp[1]) {
+ dp[1] = a[i];
+ continue;
+ }
+ while (low < high) {
+ int mid = (low + high + 1) / 2;
+ if (dp[mid] >= a[i])
+ high = mid - 1;
+ else
+ low = mid;
+ }
+ if (low == r) r++;
+ dp[low + 1] = a[i];
+ }
+ cout << r << endl;
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:13,2016-07-23T14:05:04,C++
+15,1042,flip,Find The Operations,"You are given a square grid of size N, with rows numbered from 0 to N - 1 starting from the top and columns numbered from 0 to N - 1 starting from the left.
+
+A cell (u, v) refers to the cell that is on the uth row and the vth column. Each cell contains an integer - 0 or 1. You can pick any cell and flip the number in all the cells (including the picked cell) within the Manhattan distance D from the picked cell. A flip here means changing the number from 0 to 1 and vice-versa. The manhattan distance from the cell (u, v) to the cell (x, y) is equal to $|u - x| + |v - y|$ where $|i|$ is the absolute value of i.
+
+Your mission is to change all values in the grid to zero without using more than N×N flips.
+
+**Input Format**
+The first line of the input contains two integers N and D separated by a single space.
+Each line in the next N lines contains N integers separated by a single space which are either 0 or 1. the ith number on the jth line is the number on the cell (i - 1, j - 1) of the grid.
+
+**Constraints**
+1 ≤ N ≤ 20
+ 0 ≤ D ≤ 40
+
+**Output Format**
+If there is no solution, your output should contain exactly a single string ""Impossible"" (without quotes). If a solution exists, print out the string ""Possible"" (without quotes) in the first line of your output. In the second line, print out an integer M which represent the number of operations that you need. Each line in the next M lines should contain a pair of integers separated by a single space representing the cell that you picked for the corresponding operation. Note that if there is more than one solution you can pick any one of them.
+
+**Sample Input:#00**
+
+ 3 1
+ 0 1 0
+ 1 1 1
+ 0 1 0
+
+**Sample Output:#00**
+
+ Possible
+ 1
+ 1 1
+
+**Sample Input:#01**
+
+ 3 2
+ 1 0 1
+ 1 1 0
+ 0 0 0
+
+**Sample Output:#01**
+
+ Impossible
+
+**Explanation**
+
+In the first testcase, we can perform the first operation in the center cell, this will flip all the elements to 0 within 1 manhattan distance.
+In the second testcase, we cannot make it an all 0 matrix under 9 moves. Hence, Impossible.
+",code,Let's try to modify a 0-1 grid.,ai,2013-10-07T10:39:47,2022-09-02T09:54:42,,,,"You are given a square grid of size N, with rows numbered from 0 to N - 1 starting from the top and columns numbered from 0 to N - 1 starting from the left.
+
+A cell (u, v) refers to the cell that is on the uth row and the vth column. Each cell contains an integer - 0 or 1. You can pick any cell and flip the number in all the cells (including the picked cell) within the Manhattan distance D from the picked cell. A flip here means changing the number from 0 to 1 and vice-versa. The manhattan distance from the cell (u, v) to the cell (x, y) is equal to $|u - x| + |v - y|$ where $|i|$ is the absolute value of i.
+
+Your mission is to change all values in the grid to zero without using more than N×N flips.
+
+**Input Format**
+The first line of the input contains two integers N and D separated by a single space.
+Each line in the next N lines contains N integers separated by a single space which are either 0 or 1. the ith number on the jth line is the number on the cell (i - 1, j - 1) of the grid.
+
+**Constraints**
+1 ≤ N ≤ 20
+ 0 ≤ D ≤ 40
+
+**Output Format**
+If there is no solution, your output should contain exactly a single string ""Impossible"" (without quotes). If a solution exists, print out the string ""Possible"" (without quotes) in the first line of your output. In the second line, print out an integer M which represent the number of operations that you need. Each line in the next M lines should contain a pair of integers separated by a single space representing the cell that you picked for the corresponding operation. Note that if there is more than one solution you can pick any one of them.
+
+**Sample Input:#00**
+
+ 3 1
+ 0 1 0
+ 1 1 1
+ 0 1 0
+
+**Sample Output:#00**
+
+ Possible
+ 1
+ 1 1
+
+**Sample Input:#01**
+
+ 3 2
+ 1 0 1
+ 1 1 0
+ 0 0 0
+
+**Sample Output:#01**
+
+ Impossible
+
+**Explanation**
+
+In the first testcase, we can perform the first operation in the center cell, this will flip all the elements to 0 within 1 manhattan distance.
+In the second testcase, we cannot make it an all 0 matrix under 9 moves. Hence, Impossible.
+",0.5,"[""bash"",""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""pascal"",""perl"",""php"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""pypy3""]",,,,,Hard,Find The Operations : Nov 20/20 Editorial,"Find The Operations
+Let's try to modify a 0-1 grid. Problem statement here .
+
+Difficulty Level
+
+Medium-Hard
+
+Required Knowledge
+
+Gaussian Elimination, Linear Algebra
+
+Time Complexity
+
+O(N^2) for each test case
+
+Problem Setter
+Tran Dang Tuan Anh
+
+Problem Tester
+Peng Cao
+
+Approach
+Given N and D
+and initial matrix given is M[N][N].
+Construct Matrices A[NXN][NXN] and B[NXN]. Such as
+For all A [i][j] i be the index for each value in M, and A[i][j] = 1 if j lies in the given ""D"" Manhattan distance from i.
+
+Hence we get the A[][] matrix that contains the information of all the j values that will be flipped, for corresponding i.
+
+And we fill B[i] with initial values of all i in M[N][N]
+
+Now we know that each element will be flipped only once. It can have a value 0 or 1 initially. So we try to solve by Gaussian Elimination equation Ax=B but instead of subtraction we take ^(XOR) as we don't have to deal with -ve values.
+
+If B[i] ==1 and corresponding all the j's in A[i][j] are 0. It is Impossible to solve.
+Also when B[i]== 1 and diagonal A[i][i] =0 we can not flip the value hence Impossible to solve.
+For all other cases it is Possible and in the end we are left with a diagonal matrix and the result matrix B. Corresponding to the state where all Elements are 0.
+
+After that we simply count the elements in B[NXN] array and for each index in B (index/N, index%N) is the required index.
+
+Setter's Code :
+
+#include <cstdio>
+#include <iostream>
+#include <algorithm>
+#include <vector>
+#include <queue>
+#include <stack>
+#include <set>
+#include <map>
+#include <cstring>
+#include <cstdlib>
+#include <cmath>
+#include <string>
+#include <memory.h>
+#include <sstream>
+#include <complex>
+#include <cassert>
+
+#define REP(i,n) for(int i = 0, _n = (n); i < _n; i++)
+#define REPD(i,n) for(int i = (n) - 1; i >= 0; i--)
+#define FOR(i,a,b) for (int i = (a), _b = (b); i <= _b; i++)
+#define FORD(i,a,b) for (int i = (a), _b = (b); i >= _b; i--)
+#define FORN(i,a,b) for(int i=a;i<b;i++)
+#define FOREACH(it,c) for (__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)
+#define RESET(c,x) memset (c, x, sizeof (c))
+
+#define PI acos(-1)
+#define sqr(x) ((x) * (x))
+#define PB push_back
+#define MP make_pair
+#define F first
+#define S second
+#define Aint(c) (c).begin(), (c).end()
+#define SIZE(c) (c).size()
+
+#define DEBUG(x) { cerr << #x << "" = "" << x << endl; }
+#define PR(a,n) {cerr<<#a<<"" = ""; FOR(_,1,n) cerr << a[_] << ' '; cerr <<endl;}
+#define PR0(a,n) {cerr<<#a<<"" = "";REP(_,n) cerr << a[_] << ' '; cerr << endl;}
+#define LL long long
+
+#define maxn 24
+
+using namespace std;
+
+int Gauss(int n, int a[][maxn * maxn], int b[]) {
+ for (int i = 0; i < n; i++) {
+ int row = -1;
+ for (int j = i; j < n; j++)
+ if (a[j][i]) {
+ row = j;
+ break;
+ }
+
+ if (row == -1) continue;
+
+ if (!a[i][i])
+ for (int j = 0; j <= n; j++)
+ a[i][j] ^= a[row][j];
+
+ for (int k = i; k < n; k++)
+ if (k != i && a[k][i] == 1) {
+ for (int j = 0; j <= n; j++)
+ a[k][j] ^= a[i][j];
+ }
+ }
+
+ for (int i = 0; i < n; i++)
+ if (a[i][n]) {
+ int ok = 0;
+ for (int j = 0; j < n; j++)
+ if (a[i][j]) {
+ ok = 1;
+ break;
+ }
+ if (!ok) return 0;
+ }
+
+ for (int i = n - 1; i >= 0; i--) {
+ if (a[i][i] == 0 && a[i][n] == 1) return 0;
+ if (a[i][i] == 0) b[i] = 0;
+ else b[i] = a[i][n];
+
+ if (b[i])
+ for (int j = i - 1; j >= 0; j--)
+ if (a[j][i] == 1) a[j][n] ^= 1;
+ }
+
+ return 1;
+}
+
+int n, d, g[maxn][maxn], a[maxn * maxn][maxn * maxn], root[maxn * maxn];
+
+int main() {
+ cin >> n >> d;
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++)
+ cin >> g[i][j];
+
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++) {
+ int row = i * n + j;
+
+ a[row][n * n] = g[i][j];
+
+ for (int x = 0; x < n; x++)
+ for (int y = 0; y < n; y++)
+ if (abs(x - i) + abs(y - j) <= d) {
+ // cerr << x * n + y << endl;
+ a[row][x * n + y] = 1;
+ }
+ }
+
+ int res = Gauss(n * n, a, root);
+
+ if (!res) cout << ""Impossible"" << endl;
+ else {
+ cout << ""Possible"" << endl;
+ int cnt = 0;
+ for (int i = 0; i < n * n; i++)
+ cnt += root[i];
+
+ cout << cnt << endl;
+
+ for (int i = 0; i < n * n; i++)
+ if (root[i]) cout << i / n << "" "" << i % n << endl;
+ }
+
+ return 0;
+}
+
+
+Tester's Code
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+const int N = 402;
+int a[N][N],b[N];
+vector<int> result;
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+ int n, d,i,j,k;
+ scanf(""%d%d"",&n,&d);
+ for (i = 0; i < n; ++i) {
+ for (j = 0; j < n; ++j) {
+ scanf(""%d"",b + i * n + j);
+ for (int x = max(i - d, 0); (x < n) && (x <= i + d); ++x) {
+ int dd = x - i;
+ if (dd < 0) {
+ dd = -dd;
+ }
+ dd = d - dd;
+ for (int y = max(j - dd, 0); (y < n) && (y <= j + dd); ++y) {
+ a[i * n + j][x * n + y] = 1;
+ }
+ }
+
+ }
+ }
+ int m = n * n;
+
+ for (i = 0; i < m; ++i) {
+
+ for (j = i; j < m; ++j) {
+ if (a[j][i]) {
+ break;
+ }
+ }
+ if (j < m) {
+ if (j != i) {
+ // exchange row j and row i
+ for (k = 0; k < m; ++k) {
+ int t = a[j][k];
+ a[j][k] = a[i][k];
+ a[i][k] = t;
+ }
+ k = b[i];
+ b[i] = b[j];
+ b[j] = k;
+ }
+ for (j = i + 1; j < m; ++j) {
+ if (a[j][i]) {
+ for (int k = i; k < m; ++k) {
+ a[j][k] ^= a[i][k];
+ }
+ b[j] ^= b[i];
+ }
+ }
+
+ }
+ }
+
+ for (i = m - 1; i >= 0; --i) {
+ for (j = i + 1; j < m; ++j) {
+ b[i] ^= (a[i][j] & b[j]);
+ }
+ if ((a[i][i] == 0) && (b[i] != 0)) {
+ break;
+ }
+ if (b[i]) {
+ result.push_back(i);
+ }
+ }
+ if (i < 0) {
+ puts(""Possible"");
+ printf(""%d\n"",result.size());
+ for (int i = 0; i < result.size(); ++i) {
+ printf(""%d %d\n"",result[i] / n, result[i] % n);
+ }
+
+ }
+ else {
+ puts(""Impossible"");
+ }
+
+ return 0;
+}
+
",0.0,nov-2020-editorial-find-the-operations,2013-11-27T06:59:25,"{""contest_participation"":3343,""challenge_submissions"":160,""successful_submissions"":76}",2013-11-27T06:59:25,2016-12-08T11:34:28,setter,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define REP(i,n) for(int i = 0, _n = (n); i < _n; i++)
+#define REPD(i,n) for(int i = (n) - 1; i >= 0; i--)
+#define FOR(i,a,b) for (int i = (a), _b = (b); i <= _b; i++)
+#define FORD(i,a,b) for (int i = (a), _b = (b); i >= _b; i--)
+#define FORN(i,a,b) for(int i=a;i= 0; i--) {
+ if (a[i][i] == 0 && a[i][n] == 1) return 0;
+ if (a[i][i] == 0) b[i] = 0;
+ else b[i] = a[i][n];
+
+ if (b[i])
+ for (int j = i - 1; j >= 0; j--)
+ if (a[j][i] == 1) a[j][n] ^= 1;
+ }
+
+ return 1;
+}
+
+int n, d, g[maxn][maxn], a[maxn * maxn][maxn * maxn], root[maxn * maxn];
+
+int main() {
+ cin >> n >> d;
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++)
+ cin >> g[i][j];
+
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++) {
+ int row = i * n + j;
+
+ a[row][n * n] = g[i][j];
+
+ for (int x = 0; x < n; x++)
+ for (int y = 0; y < n; y++)
+ if (abs(x - i) + abs(y - j) <= d) {
+ // cerr << x * n + y << endl;
+ a[row][x * n + y] = 1;
+ }
+ }
+
+ int res = Gauss(n * n, a, root);
+
+ if (!res) cout << ""Impossible"" << endl;
+ else {
+ cout << ""Possible"" << endl;
+ int cnt = 0;
+ for (int i = 0; i < n * n; i++)
+ cnt += root[i];
+
+ cout << cnt << endl;
+
+ for (int i = 0; i < n * n; i++)
+ if (root[i]) cout << i / n << "" "" << i % n << endl;
+ }
+
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:14,2016-07-23T18:03:16,C++
+16,1042,flip,Find The Operations,"You are given a square grid of size N, with rows numbered from 0 to N - 1 starting from the top and columns numbered from 0 to N - 1 starting from the left.
+
+A cell (u, v) refers to the cell that is on the uth row and the vth column. Each cell contains an integer - 0 or 1. You can pick any cell and flip the number in all the cells (including the picked cell) within the Manhattan distance D from the picked cell. A flip here means changing the number from 0 to 1 and vice-versa. The manhattan distance from the cell (u, v) to the cell (x, y) is equal to $|u - x| + |v - y|$ where $|i|$ is the absolute value of i.
+
+Your mission is to change all values in the grid to zero without using more than N×N flips.
+
+**Input Format**
+The first line of the input contains two integers N and D separated by a single space.
+Each line in the next N lines contains N integers separated by a single space which are either 0 or 1. the ith number on the jth line is the number on the cell (i - 1, j - 1) of the grid.
+
+**Constraints**
+1 ≤ N ≤ 20
+ 0 ≤ D ≤ 40
+
+**Output Format**
+If there is no solution, your output should contain exactly a single string ""Impossible"" (without quotes). If a solution exists, print out the string ""Possible"" (without quotes) in the first line of your output. In the second line, print out an integer M which represent the number of operations that you need. Each line in the next M lines should contain a pair of integers separated by a single space representing the cell that you picked for the corresponding operation. Note that if there is more than one solution you can pick any one of them.
+
+**Sample Input:#00**
+
+ 3 1
+ 0 1 0
+ 1 1 1
+ 0 1 0
+
+**Sample Output:#00**
+
+ Possible
+ 1
+ 1 1
+
+**Sample Input:#01**
+
+ 3 2
+ 1 0 1
+ 1 1 0
+ 0 0 0
+
+**Sample Output:#01**
+
+ Impossible
+
+**Explanation**
+
+In the first testcase, we can perform the first operation in the center cell, this will flip all the elements to 0 within 1 manhattan distance.
+In the second testcase, we cannot make it an all 0 matrix under 9 moves. Hence, Impossible.
+",code,Let's try to modify a 0-1 grid.,ai,2013-10-07T10:39:47,2022-09-02T09:54:42,,,,"You are given a square grid of size N, with rows numbered from 0 to N - 1 starting from the top and columns numbered from 0 to N - 1 starting from the left.
+
+A cell (u, v) refers to the cell that is on the uth row and the vth column. Each cell contains an integer - 0 or 1. You can pick any cell and flip the number in all the cells (including the picked cell) within the Manhattan distance D from the picked cell. A flip here means changing the number from 0 to 1 and vice-versa. The manhattan distance from the cell (u, v) to the cell (x, y) is equal to $|u - x| + |v - y|$ where $|i|$ is the absolute value of i.
+
+Your mission is to change all values in the grid to zero without using more than N×N flips.
+
+**Input Format**
+The first line of the input contains two integers N and D separated by a single space.
+Each line in the next N lines contains N integers separated by a single space which are either 0 or 1. the ith number on the jth line is the number on the cell (i - 1, j - 1) of the grid.
+
+**Constraints**
+1 ≤ N ≤ 20
+ 0 ≤ D ≤ 40
+
+**Output Format**
+If there is no solution, your output should contain exactly a single string ""Impossible"" (without quotes). If a solution exists, print out the string ""Possible"" (without quotes) in the first line of your output. In the second line, print out an integer M which represent the number of operations that you need. Each line in the next M lines should contain a pair of integers separated by a single space representing the cell that you picked for the corresponding operation. Note that if there is more than one solution you can pick any one of them.
+
+**Sample Input:#00**
+
+ 3 1
+ 0 1 0
+ 1 1 1
+ 0 1 0
+
+**Sample Output:#00**
+
+ Possible
+ 1
+ 1 1
+
+**Sample Input:#01**
+
+ 3 2
+ 1 0 1
+ 1 1 0
+ 0 0 0
+
+**Sample Output:#01**
+
+ Impossible
+
+**Explanation**
+
+In the first testcase, we can perform the first operation in the center cell, this will flip all the elements to 0 within 1 manhattan distance.
+In the second testcase, we cannot make it an all 0 matrix under 9 moves. Hence, Impossible.
+",0.5,"[""bash"",""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""pascal"",""perl"",""php"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""pypy3""]",,,,,Hard,Find The Operations : Nov 20/20 Editorial," Find The Operations
+Let's try to modify a 0-1 grid. Problem statement here .
+
+Difficulty Level
+
+Medium-Hard
+
+Required Knowledge
+
+Gaussian Elimination, Linear Algebra
+
+Time Complexity
+
+O(N^2) for each test case
+
+Problem Setter
+Tran Dang Tuan Anh
+
+Problem Tester
+Peng Cao
+
+Approach
+Given N and D
+and initial matrix given is M[N][N].
+Construct Matrices A[NXN][NXN] and B[NXN]. Such as
+For all A [i][j] i be the index for each value in M, and A[i][j] = 1 if j lies in the given ""D"" Manhattan distance from i.
+
+Hence we get the A[][] matrix that contains the information of all the j values that will be flipped, for corresponding i.
+
+And we fill B[i] with initial values of all i in M[N][N]
+
+Now we know that each element will be flipped only once. It can have a value 0 or 1 initially. So we try to solve by Gaussian Elimination equation Ax=B but instead of subtraction we take ^(XOR) as we don't have to deal with -ve values.
+
+If B[i] ==1 and corresponding all the j's in A[i][j] are 0. It is Impossible to solve.
+Also when B[i]== 1 and diagonal A[i][i] =0 we can not flip the value hence Impossible to solve.
+For all other cases it is Possible and in the end we are left with a diagonal matrix and the result matrix B. Corresponding to the state where all Elements are 0.
+
+After that we simply count the elements in B[NXN] array and for each index in B (index/N, index%N) is the required index.
+
+Setter's Code :
+
+#include <cstdio>
+#include <iostream>
+#include <algorithm>
+#include <vector>
+#include <queue>
+#include <stack>
+#include <set>
+#include <map>
+#include <cstring>
+#include <cstdlib>
+#include <cmath>
+#include <string>
+#include <memory.h>
+#include <sstream>
+#include <complex>
+#include <cassert>
+
+#define REP(i,n) for(int i = 0, _n = (n); i < _n; i++)
+#define REPD(i,n) for(int i = (n) - 1; i >= 0; i--)
+#define FOR(i,a,b) for (int i = (a), _b = (b); i <= _b; i++)
+#define FORD(i,a,b) for (int i = (a), _b = (b); i >= _b; i--)
+#define FORN(i,a,b) for(int i=a;i<b;i++)
+#define FOREACH(it,c) for (__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)
+#define RESET(c,x) memset (c, x, sizeof (c))
+
+#define PI acos(-1)
+#define sqr(x) ((x) * (x))
+#define PB push_back
+#define MP make_pair
+#define F first
+#define S second
+#define Aint(c) (c).begin(), (c).end()
+#define SIZE(c) (c).size()
+
+#define DEBUG(x) { cerr << #x << "" = "" << x << endl; }
+#define PR(a,n) {cerr<<#a<<"" = ""; FOR(_,1,n) cerr << a[_] << ' '; cerr <<endl;}
+#define PR0(a,n) {cerr<<#a<<"" = "";REP(_,n) cerr << a[_] << ' '; cerr << endl;}
+#define LL long long
+
+#define maxn 24
+
+using namespace std;
+
+int Gauss(int n, int a[][maxn * maxn], int b[]) {
+ for (int i = 0; i < n; i++) {
+ int row = -1;
+ for (int j = i; j < n; j++)
+ if (a[j][i]) {
+ row = j;
+ break;
+ }
+
+ if (row == -1) continue;
+
+ if (!a[i][i])
+ for (int j = 0; j <= n; j++)
+ a[i][j] ^= a[row][j];
+
+ for (int k = i; k < n; k++)
+ if (k != i && a[k][i] == 1) {
+ for (int j = 0; j <= n; j++)
+ a[k][j] ^= a[i][j];
+ }
+ }
+
+ for (int i = 0; i < n; i++)
+ if (a[i][n]) {
+ int ok = 0;
+ for (int j = 0; j < n; j++)
+ if (a[i][j]) {
+ ok = 1;
+ break;
+ }
+ if (!ok) return 0;
+ }
+
+ for (int i = n - 1; i >= 0; i--) {
+ if (a[i][i] == 0 && a[i][n] == 1) return 0;
+ if (a[i][i] == 0) b[i] = 0;
+ else b[i] = a[i][n];
+
+ if (b[i])
+ for (int j = i - 1; j >= 0; j--)
+ if (a[j][i] == 1) a[j][n] ^= 1;
+ }
+
+ return 1;
+}
+
+int n, d, g[maxn][maxn], a[maxn * maxn][maxn * maxn], root[maxn * maxn];
+
+int main() {
+ cin >> n >> d;
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++)
+ cin >> g[i][j];
+
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++) {
+ int row = i * n + j;
+
+ a[row][n * n] = g[i][j];
+
+ for (int x = 0; x < n; x++)
+ for (int y = 0; y < n; y++)
+ if (abs(x - i) + abs(y - j) <= d) {
+ // cerr << x * n + y << endl;
+ a[row][x * n + y] = 1;
+ }
+ }
+
+ int res = Gauss(n * n, a, root);
+
+ if (!res) cout << ""Impossible"" << endl;
+ else {
+ cout << ""Possible"" << endl;
+ int cnt = 0;
+ for (int i = 0; i < n * n; i++)
+ cnt += root[i];
+
+ cout << cnt << endl;
+
+ for (int i = 0; i < n * n; i++)
+ if (root[i]) cout << i / n << "" "" << i % n << endl;
+ }
+
+ return 0;
+}
+
+
+Tester's Code
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+const int N = 402;
+int a[N][N],b[N];
+vector<int> result;
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+ int n, d,i,j,k;
+ scanf(""%d%d"",&n,&d);
+ for (i = 0; i < n; ++i) {
+ for (j = 0; j < n; ++j) {
+ scanf(""%d"",b + i * n + j);
+ for (int x = max(i - d, 0); (x < n) && (x <= i + d); ++x) {
+ int dd = x - i;
+ if (dd < 0) {
+ dd = -dd;
+ }
+ dd = d - dd;
+ for (int y = max(j - dd, 0); (y < n) && (y <= j + dd); ++y) {
+ a[i * n + j][x * n + y] = 1;
+ }
+ }
+
+ }
+ }
+ int m = n * n;
+
+ for (i = 0; i < m; ++i) {
+
+ for (j = i; j < m; ++j) {
+ if (a[j][i]) {
+ break;
+ }
+ }
+ if (j < m) {
+ if (j != i) {
+ // exchange row j and row i
+ for (k = 0; k < m; ++k) {
+ int t = a[j][k];
+ a[j][k] = a[i][k];
+ a[i][k] = t;
+ }
+ k = b[i];
+ b[i] = b[j];
+ b[j] = k;
+ }
+ for (j = i + 1; j < m; ++j) {
+ if (a[j][i]) {
+ for (int k = i; k < m; ++k) {
+ a[j][k] ^= a[i][k];
+ }
+ b[j] ^= b[i];
+ }
+ }
+
+ }
+ }
+
+ for (i = m - 1; i >= 0; --i) {
+ for (j = i + 1; j < m; ++j) {
+ b[i] ^= (a[i][j] & b[j]);
+ }
+ if ((a[i][i] == 0) && (b[i] != 0)) {
+ break;
+ }
+ if (b[i]) {
+ result.push_back(i);
+ }
+ }
+ if (i < 0) {
+ puts(""Possible"");
+ printf(""%d\n"",result.size());
+ for (int i = 0; i < result.size(); ++i) {
+ printf(""%d %d\n"",result[i] / n, result[i] % n);
+ }
+
+ }
+ else {
+ puts(""Impossible"");
+ }
+
+ return 0;
+}
+
",0.0,nov-2020-editorial-find-the-operations,2013-11-27T06:59:25,"{""contest_participation"":3343,""challenge_submissions"":160,""successful_submissions"":76}",2013-11-27T06:59:25,2016-12-08T11:34:28,tester,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+
+const int N = 402;
+int a[N][N],b[N];
+vector result;
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+ int n, d,i,j,k;
+ scanf(""%d%d"",&n,&d);
+ for (i = 0; i < n; ++i) {
+ for (j = 0; j < n; ++j) {
+ scanf(""%d"",b + i * n + j);
+ for (int x = max(i - d, 0); (x < n) && (x <= i + d); ++x) {
+ int dd = x - i;
+ if (dd < 0) {
+ dd = -dd;
+ }
+ dd = d - dd;
+ for (int y = max(j - dd, 0); (y < n) && (y <= j + dd); ++y) {
+ a[i * n + j][x * n + y] = 1;
+ }
+ }
+
+ }
+ }
+ int m = n * n;
+
+ for (i = 0; i < m; ++i) {
+
+ for (j = i; j < m; ++j) {
+ if (a[j][i]) {
+ break;
+ }
+ }
+ if (j < m) {
+ if (j != i) {
+ // exchange row j and row i
+ for (k = 0; k < m; ++k) {
+ int t = a[j][k];
+ a[j][k] = a[i][k];
+ a[i][k] = t;
+ }
+ k = b[i];
+ b[i] = b[j];
+ b[j] = k;
+ }
+ for (j = i + 1; j < m; ++j) {
+ if (a[j][i]) {
+ for (int k = i; k < m; ++k) {
+ a[j][k] ^= a[i][k];
+ }
+ b[j] ^= b[i];
+ }
+ }
+
+ }
+ }
+
+ for (i = m - 1; i >= 0; --i) {
+ for (j = i + 1; j < m; ++j) {
+ b[i] ^= (a[i][j] & b[j]);
+ }
+ if ((a[i][i] == 0) && (b[i] != 0)) {
+ break;
+ }
+ if (b[i]) {
+ result.push_back(i);
+ }
+ }
+ if (i < 0) {
+ puts(""Possible"");
+ printf(""%d\n"",result.size());
+ for (int i = 0; i < result.size(); ++i) {
+ printf(""%d %d\n"",result[i] / n, result[i] % n);
+ }
+
+ }
+ else {
+ puts(""Impossible"");
+ }
+
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:14,2016-07-23T18:04:21,C++
+17,779,oil-well,Oil Well,"Mr. Road Runner bought a piece of land in the middle of a desert for a nominal amount. It turns out that the piece of land is now worth millions of dollars as it has an oil reserve under it. Mr. Road Runner contacts the ACME corp to set up the oil wells on his land. Setting up oil wells is a costly affair and the charges of setting up oil wells are as follows.
+
+The rectangular plot bought by Mr. Road Runner is divided into *r* * *c* blocks. Only some blocks are suitable for setting up the oil well and these blocks have been marked. ACME charges nothing for building the first oil well. For every subsequent oil well built, the cost would be the maximum **ACME distance** between the new oil well and the existing oil wells.
+
+If *(x,y)* is the position of the block where a new oil well is setup and *(x1, y1)* is the position of the block of an existing oil well, the *ACME distance* is given by
+
+ max(|x-x1|, |y-y1|)
+
+the maximum *ACME distance* is the maximum among all the *ACME distance* between existing oil wells and new wells.
+
+If the distance of any two adjacent blocks (horizontal or vertical) is considered 1 unit, what is the minimum cost *(E)* in units it takes to set up oil wells across all the marked blocks?
+
+**Input format**
+The first line of the input contains two space separated integers *r* *c*.
+*r* lines follow each containing *c* space separated integers.
+1 indicates that the block is suitable for setting up an oil well, whereas 0 isn't.
+
+ r c
+ M11 M12 ... M1c
+ M21 M22 ... M2c
+ ...
+ Mr1 Mr2 ... Mrc
+
+**Output format**
+Print the minimum value E as the answer.
+
+**Constraints**
+
+ 1 <= r, c <= 50
+
+**Sample Input #00:**
+
+ 3 4
+ 1 0 0 0
+ 1 0 0 0
+ 0 0 1 0
+
+**Sample Output #00:**
+
+ 3
+
+
+**Explanation:**
+(1, 1) (2, 1) (3, 3) are the places where are to be setup.
+There are 3! = 6 ways to do it.
+
+(1, 1) (2, 1) (3, 3) ==> cost = 0 + 1 + 2 = 3
+(1, 1) (3, 3) (2, 1) ==> cost = 0 + 2 + 2 = 4
+(2, 1) (1, 1) (3, 3) ==> cost = 0 + 1 + 2 = 3
+(2, 1) (3, 3) (1, 1) ==> cost = 0 + 2 + 2 = 4
+(3, 3) (1, 1) (2, 1) ==> cost = 0 + 2 + 2 = 4
+(3, 3) (2, 1) (1, 1) ==> cost = 0 + 2 + 2 = 4
+
+So E = 3",code,Given RxC matrix with 0/1. Rearrange the cells having 1 so that the manhattan disctance sum of adjacent cells in this list is minimal. Fidn the sum,ai,2013-07-25T18:13:47,2022-08-31T08:14:52,"#
+# Complete the 'oilWell' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts 2D_INTEGER_ARRAY blocks as parameter.
+#
+
+def oilWell(blocks):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ first_multiple_input = input().rstrip().split()
+
+ r = int(first_multiple_input[0])
+
+ c = int(first_multiple_input[1])
+
+ blocks = []
+
+ for _ in range(r):
+ blocks.append(list(map(int, input().rstrip().split())))
+
+ result = oilWell(blocks)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","Mr. Road Runner bought a piece of land in the middle of a desert for a nominal amount. It turns out that the piece of land is now worth millions of dollars as it has an oil reserve under it. Mr. Road Runner contacts the ACME corp to set up the oil wells on his land. Setting up oil wells is a costly affair and the charges of setting up oil wells are as follows.
+
+The rectangular plot bought by Mr. Road Runner is divided into *r* * *c* blocks. Only some blocks are suitable for setting up the oil well and these blocks have been marked. ACME charges nothing for building the first oil well. For every subsequent oil well built, the cost would be the maximum **ACME distance** between the new oil well and the existing oil wells.
+
+If *(x,y)* is the position of the block where a new oil well is setup and *(x1, y1)* is the position of the block of an existing oil well, the *ACME distance* is given by
+
+ max(|x-x1|, |y-y1|)
+
+the maximum *ACME distance* is the maximum among all the *ACME distance* between existing oil wells and new wells.
+
+If the distance of any two adjacent blocks (horizontal or vertical) is considered 1 unit, what is the minimum cost *(E)* in units it takes to set up oil wells across all the marked blocks?
+",0.547945205,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]","The first line of the input contains two space separated integers *r* *c*.
+*r* lines follow each containing *c* space separated integers.
+1 indicates that the block is suitable for setting up an oil well, whereas 0 isn't.
+
+ r c
+ M11 M12 ... M1c
+ M21 M22 ... M2c
+ ...
+ Mr1 Mr2 ... Mrc
+","Print the minimum value E as the answer.
+"," 3 4
+ 1 0 0 0
+ 1 0 0 0
+ 0 0 1 0
+"," 3
+",Hard,November 2020 Editorial: Oil Well,"A General Idea
+
+The solution is based on this:
+After setting up k points, only the minimal rectangle covering all the existing points is of importance to us. Start with K = 0, 1, 2 .. etc. and progress.
+
+Why is this the case?
+
+1) For the points inside the rectangle which have not yet been set up, the cost for setting up those is fixed: the sum of the maximum distance between each of them to the edge of the rectangle.
+
+2) For the points outside the rectangle, the maximum distance will only be dependent on the points in this rectangle, because the oil wells inside that rectangle cannot be a a greater distance.
+
+So let us start with this easy Dynamic Programming function, by using the above mentioned rule inductively:
+
+Let F(lx, ly, rx, ry) be the cost of setting up all the oil wells inside rectangle with top-left corner at coordinates (lx, ly) and bottom-right corner at coordinates (rx, ry).
+
+F(lx, ly, rx, ry) = min(F(lx', ly', rx', ry') + cost_of_points_not_set_up)
+
+n <= 50
+The upper bound on the number of points is O(n ^ 2).
+
+There are n ^ 4 states, and we need to enumurate (lx', ly', rx', ry') which will be done O(n ^ 4) times, and we need to calculate the cost which can be done in O(n ^ 2) time, so the total complexity is O(n ^ 10).
+
+How do we optimize this?>
+
+As we can see, if there are at least one point strictly between (lx, ly, rx, ry) and (lx', ly', rx', ry'), the cost will not be optimal. So, we add the inner points first before expanding the rectangle.
+
+Here is the rule we will enforce:
+While adding a new point, the new rectangle can not contain any point which is strictly inside it.
+
+So the choice of (lx', ly', rx', ry') will be restricted. And we can calculate the cost of the new points in O(n). So the complexity can be optimized to O(n ^ 4) * O(n) = O(n ^ 5).
+
+Solution:
+
+#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+const int inf = 1000000000;
+const int N = 52;
+int dp[N][N][N][N], a[N][N];
+
+int ab(int x) {
+ return (x > 0)?x:(-x);
+}
+
+int dis(int x1,int y1,int x2,int y2) {
+ return max(ab(x1 - x2), ab(y1 - y2));
+}
+
+int cal(int x,int y,int x1,int y1,int x2, int y2) {
+ return max(dis(x,y,x1,y1), dis(x,y,x2,y2));
+}
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+ int m, n;
+ scanf(""%d%d"",&m,&n);
+ for (int i = 0; i < m; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"",&a[i][j]);
+ }
+ }
+ for (int i = m - 1; i >= 0; --i) {
+ for (int j = n - 1; j >= 0; --j) {
+ for (int k = i; k < m; ++k) {
+ for (int h = (k == i)?(j + 1):j; h < n; ++h) {
+ dp[i][j][k][h] = inf;
+
+ if (i < k) {
+ int may = dp[i + 1][j][k][h];
+ for (int y = j; y <= h; ++y) {
+ if (a[i][y]) {
+ may += cal(i, y, i + 1, j, k, h);
+ }
+
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+ may = dp[i][j][k - 1][h];
+ for (int y = j; y <= h; ++y) {
+ if (a[k][y]) {
+ may += cal(k, y, i ,j, k - 1, h);
+
+ }
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+ }
+ if (j < h) {
+ int may = dp[i][j + 1][k][h];
+ for (int x = i; x <= k; ++x) {
+ if (a[x][j]) {
+ may += cal(x, j, i, j + 1, k, h);
+ }
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+ may = dp[i][j][k][h - 1];
+ for (int x = i; x <= k; ++x) {
+ if (a[x][h]) {
+ may += cal(x, h, i, j, k, h - 1);
+ }
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+
+ }
+
+ }
+ }
+ }
+ }
+ printf(""%d\n"",dp[0][0][m - 1][n - 1]);
+ return 0;
+}
+
",0.0,nov2020-oil-well,2013-11-27T09:48:45,"{""contest_participation"":3343,""challenge_submissions"":405,""successful_submissions"":60}",2013-11-27T09:48:45,2016-07-23T15:04:07,setter,"###C++
+```cpp
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+
+const int inf = 1000000000;
+const int N = 52;
+int dp[N][N][N][N], a[N][N];
+
+int ab(int x) {
+ return (x > 0)?x:(-x);
+}
+
+int dis(int x1,int y1,int x2,int y2) {
+ return max(ab(x1 - x2), ab(y1 - y2));
+}
+
+int cal(int x,int y,int x1,int y1,int x2, int y2) {
+ return max(dis(x,y,x1,y1), dis(x,y,x2,y2));
+}
+
+
+int main() {
+ /* Enter your code here. Read input from STDIN. Print output to STDOUT */
+ int m, n;
+ scanf(""%d%d"",&m,&n);
+ for (int i = 0; i < m; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"",&a[i][j]);
+ }
+ }
+ for (int i = m - 1; i >= 0; --i) {
+ for (int j = n - 1; j >= 0; --j) {
+ for (int k = i; k < m; ++k) {
+ for (int h = (k == i)?(j + 1):j; h < n; ++h) {
+ dp[i][j][k][h] = inf;
+
+ if (i < k) {
+ int may = dp[i + 1][j][k][h];
+ for (int y = j; y <= h; ++y) {
+ if (a[i][y]) {
+ may += cal(i, y, i + 1, j, k, h);
+ }
+
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+ may = dp[i][j][k - 1][h];
+ for (int y = j; y <= h; ++y) {
+ if (a[k][y]) {
+ may += cal(k, y, i ,j, k - 1, h);
+
+ }
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+ }
+ if (j < h) {
+ int may = dp[i][j + 1][k][h];
+ for (int x = i; x <= k; ++x) {
+ if (a[x][j]) {
+ may += cal(x, j, i, j + 1, k, h);
+ }
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+ may = dp[i][j][k][h - 1];
+ for (int x = i; x <= k; ++x) {
+ if (a[x][h]) {
+ may += cal(x, h, i, j, k, h - 1);
+ }
+ }
+ dp[i][j][k][h] = min(dp[i][j][k][h], may);
+
+ }
+
+ }
+ }
+ }
+ }
+ printf(""%d\n"",dp[0][0][m - 1][n - 1]);
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:14,2016-07-23T15:04:07,C++
+18,625,random,Random,"Given an array 'D' with n elements: d[0], d[1], ..., d[n-1], you can perform the following two steps on the array.
+
+1. Randomly choose two indexes (l, r) with l < r, swap (d[l], d[r])
+2. Randomly choose two indexes (l, r) with l < r, reverse (d[l...r]) (both inclusive)
+
+After you perform the first operation **a** times and the second operation **b** times, you randomly choose two indices _l_ & _r_ with _l_ < _r_ and calculate the S = sum(d[l...r]) (both inclusive).
+
+Now, you are to find the expected value of S.
+
+**Input Format**
+The first line of the input contains 3 space separated integers - n, a and b.
+The next line contains n space separated integers which are the elements of the array *d*.
+
+ n a b
+ d[0] d[1] ... d[n-1]
+
+**Output Format**
+Print the expected value of S.
+
+ E(S)
+
+**Constraints**
+
+2 <= n <= 1000
+1 <= a <= 109
+1 <= b <= 10
+
+The answer will be considered correct, if the absolute or relative error doesn't exceed 10-4 .
+
+**Sample Input #00:**
+
+ 3 1 1
+ 1 2 3
+
+**Sample Output #00:**
+
+ 4.666667
+
+**Explanation #00:**
+
+At step 1):
+You have three choices:
+1. swap(1, 2), 2 1 3
+2. swap(1, 3), 3 2 1
+3. swap(2, 3), 1 3 2
+
+At step 2):
+For every result you have three choices for reversing:
+1. [2 1 3] -> [1 2 3] [3 1 2] [2 3 1]
+2. [3 2 1] -> [2 3 1] [1 2 3] [3 1 2]
+3. [1 3 2] -> [3 1 2] [2 3 1] [1 2 3]
+
+So you have 9 possible arrays with each having a 1/9 probability.
+
+For the last step:
+Each of the 9 arrays will have 3 possible sums with equal probability. For [1 2 3], you can get 1+2, 2+3 and 1+2+3.
+Since there will be 27 outcome for this input, one can calculate the expected value by finding sum of all 27 S and dividing it by 27. ",code,Expected value of a random sub array?,ai,2013-04-26T18:31:55,2022-09-02T09:55:42,,,,"Given an array 'D' with n elements: d[0], d[1], ..., d[n-1], you can perform the following two steps on the array.
+
+1. Randomly choose two indexes (l, r) with l < r, swap (d[l], d[r])
+2. Randomly choose two indexes (l, r) with l < r, reverse (d[l...r]) (both inclusive)
+
+After you perform the first operation **a** times and the second operation **b** times, you randomly choose two indices _l_ & _r_ with _l_ < _r_ and calculate the S = sum(d[l...r]) (both inclusive).
+
+Now, you are to find the expected value of S.
+
+**Input Format**
+The first line of the input contains 3 space separated integers - n, a and b.
+The next line contains n space separated integers which are the elements of the array *d*.
+
+ n a b
+ d[0] d[1] ... d[n-1]
+
+**Output Format**
+Print the expected value of S.
+
+ E(S)
+
+**Constraints**
+
+2 <= n <= 1000
+1 <= a <= 109
+1 <= b <= 10
+
+The answer will be considered correct, if the absolute or relative error doesn't exceed 10-4 .
+
+**Sample Input #00:**
+
+ 3 1 1
+ 1 2 3
+
+**Sample Output #00:**
+
+ 4.666667
+
+**Explanation #00:**
+
+At step 1):
+You have three choices:
+1. swap(0, 1), 2 1 3
+2. swap(0, 2), 3 2 1
+3. swap(1, 2), 1 3 2
+
+At step 2):
+For every result you have three choices for reversing:
+1. [2 1 3] -> [1 2 3] [3 1 2] [2 3 1]
+2. [3 2 1] -> [2 3 1] [1 2 3] [3 1 2]
+3. [1 3 2] -> [3 1 2] [2 3 1] [1 2 3]
+
+So you have 9 possible arrays with each having a 1/9 probability.
+
+For the last step:
+Each of the 9 arrays will have 3 possible sums with equal probability. For [1 2 3], you can get 1+2, 2+3 and 1+2+3.
+Since there will be 27 outcome for this input, one can calculate the expected value by finding sum of all 27 S and dividing it by 27. ",0.4226190476190476,"[""bash"",""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""pascal"",""perl"",""php"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""pypy3""]", , , , ,Hard,November 2020 Editorial - Random,"Here are the two atomic steps which need to be performed a number of times:
+
+1) Randomly choose two indexes (l, r) with l < r and then swap (d[l], d[r]).
+2) Randomly choose two indexes (l, r) with l < r and then reverse (d[l…r]) (both inclusive)
+
+We can calculate these two steps separately, because of the linearity of the expectation, we can calculate the expected array after the first step (repeated a times): (A[0], A[1], ..., A[n - 1]) and use this array as the input of the second step (repeated b times), then we can calculate the final answer based on the output at the end of the second step.
+
+Solution for Step (1), i.e. swapping elements:
+
+How does one compute the expected value of the element in the i-th position after Step (1)?
+Let P(i, j, k) be the possibility that d[i] goes to the j-th position after executing Step (1) k times.
+
+A[i] = P(i, i, n1) * d[i] + sum(P(j, i, n1) * d[j] (i != j))
+
+// because all the operations are randomly chosen.
+P(i, i, k) = P(0, 0, k)
+P(j, i, k) = P(0, 1, k)
+
+==> A[i] = P(0, 0, n1) * d[i] + P(0, 1, n1) * (sum - d[i])
+
+P(0, 1, n1) = P(0, 2, n1) = ... = P(0, n - 1, n1)
+
+and
+
+P(0, 0, n1) + P(0, 1, n1) + ... + P(0, n - 1, n1) = P(0, 0, n1) + (n - 1) * P(0, 1, n1) = 1
+
+==> P(0, 1, n1) = (1 - P(0, 0, n1)) / (n - 1).
+
+So we only need to calculate P(0, 0, n1).
+
+P(0, 0, k) = P(0, 0, k - 1) * P(unchanged) + P(0, 1, k - 1) * P(swap(0, 1)) + P(0, 2, k - 1) * P(swap(0, 2)) + ... + P(0, n - 1, k - 1) * P(swap(0, n - 1))
+
+Because P(0, 1, k) = P(0, 2, k) = ... = P(0, n - 1, k), P(swap(0, 1)) = P(swap(0, 2)) = ... = P(swap(0, n - 1))
+
+//P(swap(0, 1)) = 1 / C(n, 2)
+//P(unchanged) + (n - 1) * P(swap(0, 1)) = 1 ==> P(unchanged) = (n - 2) / n.
+
+==>
+
+P(0, 0, k) = P(0, 0, k - 1) * P(unchanged) + P(0, 1, k - 1) * P(swap(0, 1)) * (n - 1)
+ = P(0, 0, k - 1) * P(unchanged) + (1 - P(0, 0, k - 1)) * P(swap(0, 1))
+ = a * P(0, 0, k - 1) + b
+
+F[k] = a * F[k - 1] + b
+
+==> F[k] + r = a * (F[k] + r) //geometric progression
+==> F[n1] + r = a ^ n1 * (1 + r)
+==> F[n1] = a ^ n1 * (1 + r) - r
+
+Solution for Step (2), i.e. reversing elements:
+Because n2 is relatively small, so we can calculate the expected output array after each operation.
+A0 A1 ... An-1
+The first problem to solve is: after executing one random reverse, what is the expected output?
+Similar to the first step, we only need to calculate the P(i, j): the possibility that Ai goes to the jth position.
+
+P(i, j) = number_of_reverse_intervals_swap_(i, j) / C(n, 2)
+number_of_reverse_intervals_swap_(i, j) = min(i + 1, n - j).
+
+Solution:
+
+#include <map>
+#include <set>
+#include <list>
+#include <cmath>
+#include <ctime>
+#include <stack>
+#include <queue>
+#include <vector>
+#include <cstdio>
+#include <string>
+#include <bitset>
+#include <climits>
+#include <cstdlib>
+#include <cstring>
+#include <utility>
+#include <sstream>
+#include <iostream>
+#include <algorithm>
+#define sqr(x) ((x)*(x))
+#define ABS(x) ((x<0)?(-(x)):(x))
+#define eps (1e-13)
+#define mp make_pair
+#define pb push_back
+#define Pair pair<int,int>
+#define xx first
+#define yy second
+#define equal(a,b) (ABS((a)-(b))<eps)
+using namespace std;
+
+template<class T> string tostring(T x) { ostringstream out; out<<x; return out.str();}
+long long toint(string s) { istringstream in(s); long long x; in>>x; return x; }
+
+int dx[8]={0, 0, 1,-1, 1, 1,-1,-1};
+int dy[8]={1,-1, 0, 0,-1, 1,-1, 1};
+int kx[8]={1, 1,-1,-1, 2, 2,-2,-2};
+int ky[8]={2,-2, 2,-2, 1,-1, 1,-1};
+
+/////////////////////////////////////////////////////////////////////////////////////////////////////
+
+int d[1000], n;
+double p1, p2;
+
+#define MAX 2
+
+typedef struct matrix
+{
+ int row,col;
+ double m[MAX][MAX];
+ matrix(int r,int c,int k)
+ {
+ row=r;
+ col=c;
+ for (int i=0;i<r;i++)
+ for (int j=0;j<c;j++)
+ m[i][j]=k;
+ }
+ matrix(){}
+} matrix;
+matrix operator *(matrix a,matrix b)
+{
+ matrix c;
+ double t;
+ c.row=a.row; c.col=b.col;
+ for (int i=0;i<c.row;i++)
+ for (int j=0;j<c.col;j++)
+ {
+ t=0;
+ for (int k=0;k<a.col;k++)
+ t=(t+a.m[i][k]*b.m[k][j]);
+ c.m[i][j]=t;
+ }
+ return c;
+}
+matrix pow(matrix a,int k)
+{
+ matrix c;
+ if (k==1) return a;
+ c = pow(a, k / 2);
+ c = c * c;
+ if (k % 2 == 0) return c;
+ else return c * a;
+}
+
+int ways(int cnt) {
+ return cnt * (cnt - 1) / 2;
+}
+
+void calc(int cnt) {
+ int tot = ways(n);
+ matrix m(2, 2, 0);
+ m.m[0][0] = (tot - n + 1.0) / tot; m.m[0][1] = (n - 1.0) / tot;
+ m.m[1][0] = 1.0 / tot; m.m[1][1] = (tot - 1.0) / tot;
+
+ m = pow(m, cnt);
+ p1 = m.m[0][0];
+ p2 = m.m[0][1];
+}
+
+double f[1000][1000]; // probability of j'th number being at i'th place after all operations
+double g[1000][1000];
+
+
+double sum1[1000][1001], sum2[1000][1001], sum3[1000][1001];
+void calc2(int cnt) {
+ memset(f, 0, sizeof(f));
+ for (int i = 0; i < n; i++)
+ for (int j = 0; j < n; j++)
+ if (i == j) f[i][j] = p1;
+ else f[i][j] = p2 / (n - 1);
+
+ for (int iter = 0; iter < cnt; iter++) {
+ for (int c = 0; c < n; c++) {
+ sum1[c][0] = sum2[c][0] = sum3[c][0] = 0.0;
+ for (int i = 0; i < n; i++) {
+ sum1[c][i + 1] = sum1[c][i] + f[i][c];
+ sum2[c][i + 1] = sum2[c][i] + f[i][c] * (n - i) / (double) ways(n);
+ sum3[c][i + 1] = sum3[c][i] + f[i][c] * (i + 1) / (double) ways(n);
+ }
+ }
+ for (int i = 0; i < n; i++) {
+ for (int k = 0; k < n; k++) {
+ // same
+ g[i][k] += f[i][k] * (min(n - 1 - i, i) + ways(i) + ways(n - 1 - i)) / (double) ways(n);
+ if (n - i - 1 > i) g[i][k] += (sum1[k][n - i] - sum1[k][i + 1]) * (i + 1) / (double) ways(n); // i + 1 .. n - i - 1
+ if (n - i - 1 < i) g[i][k] += (sum1[k][i] - sum1[k][n - i - 1]) * (n - i) / (double) ways(n); // n - i - 1 .. i - 1
+
+ if (i != n - 1) g[i][k] += (sum2[k][n] - sum2[k][max(n - i - 1, i) + 1]); // max(n - i - 1, i)+1 .. n - 1
+ if (i != 0) g[i][k] += (sum3[k][min(n - i - 1, i)]); // 0 .. min(n - i - 1, i) - 1
+ }
+ }
+ memcpy(f, g, sizeof(g));
+ memset(g, 0, sizeof(g));
+ }
+}
+
+int main() {
+// freopen(""random.in"", ""r"", stdin);
+ int n1, n2;
+ scanf(""%d%d%d"", &n, &n1, &n2);
+ for (int i = 0; i < n; i++)
+ scanf(""%d"", &d[i]);
+ calc(n1);
+ calc2(n2);
+ double res = 0.0;
+ for (int i = 0; i < n; i++) { // place
+ double p = ((i + 1) * (n - i) - 1.0) / (n * (n - 1) / 2.0);
+ for (int j = 0; j < n; j++) // number
+ res += d[j] * f[i][j] * p;
+ }
+ printf(""%.9lf\n"", res);
+ return 0;
+}
+
",0.0,nov2020-random,2013-11-27T11:19:54,"{""contest_participation"":3343,""challenge_submissions"":129,""successful_submissions"":52}",2013-11-27T11:19:54,2016-07-23T19:18:26,setter,"###C++
+```cpp
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#define sqr(x) ((x)*(x))
+#define ABS(x) ((x<0)?(-(x)):(x))
+#define eps (1e-13)
+#define mp make_pair
+#define pb push_back
+#define Pair pair
+#define xx first
+#define yy second
+#define equal(a,b) (ABS((a)-(b)) string tostring(T x) { ostringstream out; out<>x; return x; }
+
+int dx[8]={0, 0, 1,-1, 1, 1,-1,-1};
+int dy[8]={1,-1, 0, 0,-1, 1,-1, 1};
+int kx[8]={1, 1,-1,-1, 2, 2,-2,-2};
+int ky[8]={2,-2, 2,-2, 1,-1, 1,-1};
+
+/////////////////////////////////////////////////////////////////////////////////////////////////////
+
+int d[1000], n;
+double p1, p2;
+
+#define MAX 2
+
+typedef struct matrix
+{
+ int row,col;
+ double m[MAX][MAX];
+ matrix(int r,int c,int k)
+ {
+ row=r;
+ col=c;
+ for (int i=0;i i) g[i][k] += (sum1[k][n - i] - sum1[k][i + 1]) * (i + 1) / (double) ways(n); // i + 1 .. n - i - 1
+ if (n - i - 1 < i) g[i][k] += (sum1[k][i] - sum1[k][n - i - 1]) * (n - i) / (double) ways(n); // n - i - 1 .. i - 1
+
+ if (i != n - 1) g[i][k] += (sum2[k][n] - sum2[k][max(n - i - 1, i) + 1]); // max(n - i - 1, i)+1 .. n - 1
+ if (i != 0) g[i][k] += (sum3[k][min(n - i - 1, i)]); // 0 .. min(n - i - 1, i) - 1
+ }
+ }
+ memcpy(f, g, sizeof(g));
+ memset(g, 0, sizeof(g));
+ }
+}
+
+int main() {
+// freopen(""random.in"", ""r"", stdin);
+ int n1, n2;
+ scanf(""%d%d%d"", &n, &n1, &n2);
+ for (int i = 0; i < n; i++)
+ scanf(""%d"", &d[i]);
+ calc(n1);
+ calc2(n2);
+ double res = 0.0;
+ for (int i = 0; i < n; i++) { // place
+ double p = ((i + 1) * (n - i) - 1.0) / (n * (n - 1) / 2.0);
+ for (int j = 0; j < n; j++) // number
+ res += d[j] * f[i][j] * p;
+ }
+ printf(""%.9lf\n"", res);
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:14,2016-07-23T19:18:26,C++
+19,1574,hacker-country,Hacker Country,"There are *N* cities in the Hacker Country. There is a unique directed road connecting each pair of different cities directly. However, each road has its own cost which you must pay for passing it each time. You are planning to visit the country. Here are the conditions to be satisfied:
+
++ You can start at any city you'd like to
++ You can pass through as many roads as you can
++ You must pass at least 2 different cities
++ At the end of the trip, you should come back to the city where you started
++ The average cost per road should be minimum
+
+As a top programmer, could you calculate the minimum average cost?
+
+**Input format**
+The first line of the input is an integer *N*.
+Each of the next *N* lines contains *N* integers separated by a single space. The jth integer of the ith row denotes the amount you must pay to go from the ith city to the jth city.
+There are no roads that connect a city to itself.
+
+**Constraints**
+1 < N <= 500
+0 < cost of any road <= 200.
+ith integer of the ith row will always be 0 implying there is no self connecting road.
+
+**Output format**
+Output the minimum cost as a rational number p/q. The greatest common divisor of p and q should be 1.
+
+**Sample input**
+
+ 2
+ 0 1
+ 2 0
+
+**Sample Output**
+
+ 3/2
+
+**Explanation**
+
+You travel across both the cities with an average cost of (2+1)/2 = 3/2
+
+**Timelimits**
+Timelimits for this challenge is given [here](https://www.hackerrank.com/environment)",code,What is the minimum cost of a road trip in Hacker Country? ,ai,2013-12-20T08:10:24,2022-08-31T08:14:32,"#
+# Complete the 'hackerCountry' function below.
+#
+# The function is expected to return a STRING.
+# The function accepts 2D_INTEGER_ARRAY tolls as parameter.
+#
+
+def hackerCountry(tolls):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ n = int(input().strip())
+
+ tolls = []
+
+ for _ in range(n):
+ tolls.append(list(map(int, input().rstrip().split())))
+
+ result = hackerCountry(tolls)
+
+ fptr.write(result + '\n')
+
+ fptr.close()
+","There are *N* cities in *Hacker Country*. Each pair of cities are directly connected by a unique directed road, and each road has its own toll that must be paid every time it is used. You're planning a road trip in *Hacker Country*, and its itinerary must satisfy the following conditions:
+
++ You can start in any city.
++ You must use $2$ or more different roads (meaning you will visit $2$ or more cities).
++ At the end of your trip, you should be back in your city of origin.
++ The average cost (sum of tolls paid per road traveled) should be minimum.
+
+Can you calculate the *minimum average cost* of a trip in *Hacker Country*?
+
+**Time Limits**
+Time limits for this challenge are provided [here](https://www.hackerrank.com/environment).",0.5333333333333333,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]","The first line is an integer, $N$ (number of cities).
+The $N$ subsequent lines of $N$ space-separated integers each describe the respective tolls or traveling from city $i$ to city $j$; in other words, the $j^{th}$ integer of the $i^{th}$ line denotes the toll for traveling from city $i$ to city $j$.
+
+**Note:** As there are no roads connecting a city to itself, the $i^{th}$ integer of line $i$ will always be $0$.
+
+**Constraints**
+$1 \lt N \leq 500$
+$0 \lt toll \ cost \leq 200$
+$roads \ traveled \geq 2$",Print the *minimum cost* as a rational number $p \ / \ q$ (tolls paid over roads traveled). The *greatest common divisor* of $p$ and $q$ should be $1$. ," 2
+ 0 1
+ 2 0", 3/2,Hard,Hacker Country : Codesprint 5 Editorial,"Hacker Country
+
+Difficulty Level : Easy-Hard
+Required Knowledge : Directed Cycles, minimum mean length
+Problem Setter : Cao Peng
+Problem Tester : Dmytro Soboliev
+
+Approach
+
+The approach for this problem is explained here
+
+Setter's Code
+
+#include <cstdio>
+#include <cstring>
+#include <cassert>
+#include <algorithm>
+
+
+using namespace std;
+
+const int N = 505;
+
+int d[N][N],a[N][N];
+
+int cmp(const pair<int,int> &a,const pair<int,int> &b) { // a - b
+ return a.first * b.second - a.second * b.first;
+}
+
+int gcd(int a,int b){
+ return b?gcd(b,a%b):a;
+}
+
+
+
+int main() {
+int n;
+ scanf(""%d"",&n);
+ assert((n > 1) && (n <= 500));
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"",&a[i][j]);
+ if (i == j) {
+ assert(a[i][j] == 0);
+ }
+ else {
+ assert((a[i][j] > 0) && (a[i][j] <= 200));
+ }
+ }
+ }
+
+ // d[i + 1][j] = min(d[i][k] + a[k][j])
+
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ bool mark = false;
+ for (int k = 0; k < n; ++k) {
+ if (k != j) {
+ if (mark) {
+ d[i + 1][j] = min(d[i + 1][j] , d[i][k] + a[k][j]);
+ }
+ else {
+ mark = true;
+ d[i + 1][j] = d[i][k] + a[k][j];
+ }
+ }
+ }
+ }
+
+ }
+
+ pair<int,int> answer;
+ // answer = min max (d[n][i] - d[k][i]) / (n - k)
+ for (int i = 0; i < n; ++i) {
+ pair<int,int> now = make_pair(d[n][i] - d[0][i], n);
+ for (int k = 1; k < n; ++k) {
+ pair<int,int> temp = make_pair(d[n][i] - d[k][i], n - k);
+ if (cmp(temp, now) > 0) {
+ now = temp;
+ }
+ }
+ if ((i == 0) || (cmp(now, answer) < 0)) {
+ answer = now;
+ }
+ }
+ int g = gcd(answer.first, answer.second);
+ printf(""%d/%d\n"",answer.first / g, answer.second / g);
+ return 0;
+}
+
+
+Tester's Code
+
+#include <iostream>
+#include <cstdio>
+
+using namespace std;
+
+const int maxN = 600;
+const int inf = 1000000000;
+int g[maxN][maxN], d[maxN][maxN];
+int n;
+
+long long gcd(long long a, long long b) {
+ if (a == 0 || b == 0) {
+ return a + b;
+ }
+ if (a > b) {
+ return gcd(a % b, b);
+ } else {
+ return gcd(b % a, a);
+ }
+}
+
+int main() {
+ scanf(""%d"", &n);
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"", &g[i][j]);
+ }
+ }
+
+ for (int i = 1; i <= n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ int best = inf;
+ for (int k = 0; k < n; ++k) {
+ if (j != k) {
+ best = min(best, d[i - 1][k] + g[k][j]);
+ }
+ }
+ d[i][j] = best;
+ }
+ }
+
+ long long p = inf, q = 1;
+ for (int i = 0; i < n; ++i) {
+ long long a = 0, b = 1;
+ for (int j = 0; j < n; ++j) {
+ long long c = d[n][i] - d[j][i];
+ long long d = n - j;
+
+ if (c * b > a * d) {
+ a = c;
+ b = d;
+ }
+ }
+
+ if (a * q < b * p) {
+ p = a;
+ q = b;
+ }
+ }
+
+ long long d = gcd(p, q);
+ p /= d;
+ q /= d;
+
+ cout << p << ""/"" << q << endl;
+
+ return 0;
+}
+
",0.0,codesprint5-hacker-country,2014-01-21T11:07:30,"{""contest_participation"":12558,""challenge_submissions"":482,""successful_submissions"":103}",2014-01-21T11:07:30,2016-07-23T14:03:54,setter,"###C++
+```cpp
+#include
+#include
+#include
+#include
+
+
+using namespace std;
+
+const int N = 505;
+
+int d[N][N],a[N][N];
+
+int cmp(const pair &a,const pair &b) { // a - b
+ return a.first * b.second - a.second * b.first;
+}
+
+int gcd(int a,int b){
+ return b?gcd(b,a%b):a;
+}
+
+
+
+int main() {
+int n;
+ scanf(""%d"",&n);
+ assert((n > 1) && (n <= 500));
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"",&a[i][j]);
+ if (i == j) {
+ assert(a[i][j] == 0);
+ }
+ else {
+ assert((a[i][j] > 0) && (a[i][j] <= 200));
+ }
+ }
+ }
+
+ // d[i + 1][j] = min(d[i][k] + a[k][j])
+
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ bool mark = false;
+ for (int k = 0; k < n; ++k) {
+ if (k != j) {
+ if (mark) {
+ d[i + 1][j] = min(d[i + 1][j] , d[i][k] + a[k][j]);
+ }
+ else {
+ mark = true;
+ d[i + 1][j] = d[i][k] + a[k][j];
+ }
+ }
+ }
+ }
+
+ }
+
+ pair answer;
+ // answer = min max (d[n][i] - d[k][i]) / (n - k)
+ for (int i = 0; i < n; ++i) {
+ pair now = make_pair(d[n][i] - d[0][i], n);
+ for (int k = 1; k < n; ++k) {
+ pair temp = make_pair(d[n][i] - d[k][i], n - k);
+ if (cmp(temp, now) > 0) {
+ now = temp;
+ }
+ }
+ if ((i == 0) || (cmp(now, answer) < 0)) {
+ answer = now;
+ }
+ }
+ int g = gcd(answer.first, answer.second);
+ printf(""%d/%d\n"",answer.first / g, answer.second / g);
+ return 0;
+}
+
+```
+",not-set,2016-04-24T02:02:15,2016-07-23T14:03:41,C++
+20,1574,hacker-country,Hacker Country,"There are *N* cities in the Hacker Country. There is a unique directed road connecting each pair of different cities directly. However, each road has its own cost which you must pay for passing it each time. You are planning to visit the country. Here are the conditions to be satisfied:
+
++ You can start at any city you'd like to
++ You can pass through as many roads as you can
++ You must pass at least 2 different cities
++ At the end of the trip, you should come back to the city where you started
++ The average cost per road should be minimum
+
+As a top programmer, could you calculate the minimum average cost?
+
+**Input format**
+The first line of the input is an integer *N*.
+Each of the next *N* lines contains *N* integers separated by a single space. The jth integer of the ith row denotes the amount you must pay to go from the ith city to the jth city.
+There are no roads that connect a city to itself.
+
+**Constraints**
+1 < N <= 500
+0 < cost of any road <= 200.
+ith integer of the ith row will always be 0 implying there is no self connecting road.
+
+**Output format**
+Output the minimum cost as a rational number p/q. The greatest common divisor of p and q should be 1.
+
+**Sample input**
+
+ 2
+ 0 1
+ 2 0
+
+**Sample Output**
+
+ 3/2
+
+**Explanation**
+
+You travel across both the cities with an average cost of (2+1)/2 = 3/2
+
+**Timelimits**
+Timelimits for this challenge is given [here](https://www.hackerrank.com/environment)",code,What is the minimum cost of a road trip in Hacker Country? ,ai,2013-12-20T08:10:24,2022-08-31T08:14:32,"#
+# Complete the 'hackerCountry' function below.
+#
+# The function is expected to return a STRING.
+# The function accepts 2D_INTEGER_ARRAY tolls as parameter.
+#
+
+def hackerCountry(tolls):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ n = int(input().strip())
+
+ tolls = []
+
+ for _ in range(n):
+ tolls.append(list(map(int, input().rstrip().split())))
+
+ result = hackerCountry(tolls)
+
+ fptr.write(result + '\n')
+
+ fptr.close()
+","There are *N* cities in *Hacker Country*. Each pair of cities are directly connected by a unique directed road, and each road has its own toll that must be paid every time it is used. You're planning a road trip in *Hacker Country*, and its itinerary must satisfy the following conditions:
+
++ You can start in any city.
++ You must use $2$ or more different roads (meaning you will visit $2$ or more cities).
++ At the end of your trip, you should be back in your city of origin.
++ The average cost (sum of tolls paid per road traveled) should be minimum.
+
+Can you calculate the *minimum average cost* of a trip in *Hacker Country*?
+
+**Time Limits**
+Time limits for this challenge are provided [here](https://www.hackerrank.com/environment).",0.5333333333333333,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""r"",""ruby"",""rust"",""scala"",""swift"",""typescript""]","The first line is an integer, $N$ (number of cities).
+The $N$ subsequent lines of $N$ space-separated integers each describe the respective tolls or traveling from city $i$ to city $j$; in other words, the $j^{th}$ integer of the $i^{th}$ line denotes the toll for traveling from city $i$ to city $j$.
+
+**Note:** As there are no roads connecting a city to itself, the $i^{th}$ integer of line $i$ will always be $0$.
+
+**Constraints**
+$1 \lt N \leq 500$
+$0 \lt toll \ cost \leq 200$
+$roads \ traveled \geq 2$",Print the *minimum cost* as a rational number $p \ / \ q$ (tolls paid over roads traveled). The *greatest common divisor* of $p$ and $q$ should be $1$. ," 2
+ 0 1
+ 2 0", 3/2,Hard,Hacker Country : Codesprint 5 Editorial,"Hacker Country
+
+Difficulty Level : Easy-Hard
+Required Knowledge : Directed Cycles, minimum mean length
+Problem Setter : Cao Peng
+Problem Tester : Dmytro Soboliev
+
+Approach
+
+The approach for this problem is explained here
+
+Setter's Code
+
+#include <cstdio>
+#include <cstring>
+#include <cassert>
+#include <algorithm>
+
+
+using namespace std;
+
+const int N = 505;
+
+int d[N][N],a[N][N];
+
+int cmp(const pair<int,int> &a,const pair<int,int> &b) { // a - b
+ return a.first * b.second - a.second * b.first;
+}
+
+int gcd(int a,int b){
+ return b?gcd(b,a%b):a;
+}
+
+
+
+int main() {
+int n;
+ scanf(""%d"",&n);
+ assert((n > 1) && (n <= 500));
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"",&a[i][j]);
+ if (i == j) {
+ assert(a[i][j] == 0);
+ }
+ else {
+ assert((a[i][j] > 0) && (a[i][j] <= 200));
+ }
+ }
+ }
+
+ // d[i + 1][j] = min(d[i][k] + a[k][j])
+
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ bool mark = false;
+ for (int k = 0; k < n; ++k) {
+ if (k != j) {
+ if (mark) {
+ d[i + 1][j] = min(d[i + 1][j] , d[i][k] + a[k][j]);
+ }
+ else {
+ mark = true;
+ d[i + 1][j] = d[i][k] + a[k][j];
+ }
+ }
+ }
+ }
+
+ }
+
+ pair<int,int> answer;
+ // answer = min max (d[n][i] - d[k][i]) / (n - k)
+ for (int i = 0; i < n; ++i) {
+ pair<int,int> now = make_pair(d[n][i] - d[0][i], n);
+ for (int k = 1; k < n; ++k) {
+ pair<int,int> temp = make_pair(d[n][i] - d[k][i], n - k);
+ if (cmp(temp, now) > 0) {
+ now = temp;
+ }
+ }
+ if ((i == 0) || (cmp(now, answer) < 0)) {
+ answer = now;
+ }
+ }
+ int g = gcd(answer.first, answer.second);
+ printf(""%d/%d\n"",answer.first / g, answer.second / g);
+ return 0;
+}
+
+
+Tester's Code
+
+#include <iostream>
+#include <cstdio>
+
+using namespace std;
+
+const int maxN = 600;
+const int inf = 1000000000;
+int g[maxN][maxN], d[maxN][maxN];
+int n;
+
+long long gcd(long long a, long long b) {
+ if (a == 0 || b == 0) {
+ return a + b;
+ }
+ if (a > b) {
+ return gcd(a % b, b);
+ } else {
+ return gcd(b % a, a);
+ }
+}
+
+int main() {
+ scanf(""%d"", &n);
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"", &g[i][j]);
+ }
+ }
+
+ for (int i = 1; i <= n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ int best = inf;
+ for (int k = 0; k < n; ++k) {
+ if (j != k) {
+ best = min(best, d[i - 1][k] + g[k][j]);
+ }
+ }
+ d[i][j] = best;
+ }
+ }
+
+ long long p = inf, q = 1;
+ for (int i = 0; i < n; ++i) {
+ long long a = 0, b = 1;
+ for (int j = 0; j < n; ++j) {
+ long long c = d[n][i] - d[j][i];
+ long long d = n - j;
+
+ if (c * b > a * d) {
+ a = c;
+ b = d;
+ }
+ }
+
+ if (a * q < b * p) {
+ p = a;
+ q = b;
+ }
+ }
+
+ long long d = gcd(p, q);
+ p /= d;
+ q /= d;
+
+ cout << p << ""/"" << q << endl;
+
+ return 0;
+}
+
",0.0,codesprint5-hacker-country,2014-01-21T11:07:30,"{""contest_participation"":12558,""challenge_submissions"":482,""successful_submissions"":103}",2014-01-21T11:07:30,2016-07-23T14:03:54,tester,"###C++
+```cpp
+#include
+#include
+
+using namespace std;
+
+const int maxN = 600;
+const int inf = 1000000000;
+int g[maxN][maxN], d[maxN][maxN];
+int n;
+
+long long gcd(long long a, long long b) {
+ if (a == 0 || b == 0) {
+ return a + b;
+ }
+ if (a > b) {
+ return gcd(a % b, b);
+ } else {
+ return gcd(b % a, a);
+ }
+}
+
+int main() {
+ scanf(""%d"", &n);
+ for (int i = 0; i < n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ scanf(""%d"", &g[i][j]);
+ }
+ }
+
+ for (int i = 1; i <= n; ++i) {
+ for (int j = 0; j < n; ++j) {
+ int best = inf;
+ for (int k = 0; k < n; ++k) {
+ if (j != k) {
+ best = min(best, d[i - 1][k] + g[k][j]);
+ }
+ }
+ d[i][j] = best;
+ }
+ }
+
+ long long p = inf, q = 1;
+ for (int i = 0; i < n; ++i) {
+ long long a = 0, b = 1;
+ for (int j = 0; j < n; ++j) {
+ long long c = d[n][i] - d[j][i];
+ long long d = n - j;
+
+ if (c * b > a * d) {
+ a = c;
+ b = d;
+ }
+ }
+
+ if (a * q < b * p) {
+ p = a;
+ q = b;
+ }
+ }
+
+ long long d = gcd(p, q);
+ p /= d;
+ q /= d;
+
+ cout << p << ""/"" << q << endl;
+
+ return 0;
+}
+```
+",not-set,2016-04-24T02:02:15,2016-07-23T14:03:54,C++
+21,1667,matrix-tracing,Matrix Tracing,"A word from the English dictionary is taken and arranged as a matrix. e.g. ""MATHEMATICS""
+
+MATHE
+ATHEM
+THEMA
+HEMAT
+EMATI
+MATIC
+ATICS
+
+There are many ways to trace this matrix in a way that helps you construct this word. You start tracing the matrix from the top-left position and at each iteration, you either move RIGHT or DOWN, and ultimately reach the bottom-right of the matrix. It is assured that any such tracing generates the same word. How many such tracings can be possible for a given
+word of length m+n-1 written as a matrix of size m * n?
+
+**Input Format**
+The first line of input contains an integer T. T test cases follow.
+Each test case contains 2 space separated integers m & n (in a new line) indicating that the matrix has m rows and each row has n characters.
+
+**Constraints**
+1 <= T <= 103
+1 ≤ m,n ≤ 106
+
+**Output Format**
+Print the number of ways (S) the word can be traced as explained in the problem statement.
+If the number is larger than 109 +7,
+print `S mod (10^9 + 7)` for each testcase (in a new line).
+
+**Sample Input**
+
+ 1
+ 2 3
+
+**Sample Output**
+
+ 3
+
+**Explanation**
+Let's consider a word AWAY written as the matrix
+
+ AWA
+ WAY
+
+Here, the word AWAY can be traced in 3 different ways, traversing either RIGHT or DOWN.
+
+ AWA
+ Y
+
+ AW
+ AY
+
+ A
+ WAY
+
+Hence the answer is 3.
+
+**Timelimit**
+Time limit for this challenge is given [here](https://www.hackerrank.com/environment)",code,How many ways can you trace a given matrix? - 30 Points,ai,2014-01-14T08:25:46,2022-09-02T09:54:13,"#
+# Complete the 'solve' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts following parameters:
+# 1. INTEGER n
+# 2. INTEGER m
+#
+
+def solve(n, m):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ t = int(input().strip())
+
+ for t_itr in range(t):
+ first_multiple_input = input().rstrip().split()
+
+ n = int(first_multiple_input[0])
+
+ m = int(first_multiple_input[1])
+
+ result = solve(n, m)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","A word from the English dictionary is taken and arranged as a matrix. e.g. ""MATHEMATICS""
+
+ MATHE
+ ATHEM
+ THEMA
+ HEMAT
+ EMATI
+ MATIC
+ ATICS
+
+There are many ways to trace this matrix in a way that helps you construct this word. You start tracing the matrix from the top-left position and at each iteration, you either move RIGHT or DOWN, and ultimately reach the bottom-right of the matrix. It is assured that any such tracing generates the same word. How many such tracings can be possible for a given
+word of length m+n-1 written as a matrix of size m * n?
+
+**Input Format**
+The first line of input contains an integer T. T test cases follow.
+Each test case contains 2 space separated integers m & n (in a new line) indicating that the matrix has m rows and each row has n characters.
+
+**Constraints**
+1 <= T <= 103
+1 ≤ m,n ≤ 106
+
+**Output Format**
+Print the number of ways (S) the word can be traced as explained in the problem statement.
+If the number is larger than 109 +7,
+print `S mod (10^9 + 7)` for each testcase (in a new line).
+
+**Sample Input**
+
+ 1
+ 2 3
+
+**Sample Output**
+
+ 3
+
+**Explanation**
+Let's consider a word AWAY written as the matrix
+
+ AWA
+ WAY
+
+Here, the word AWAY can be traced in 3 different ways, traversing either RIGHT or DOWN.
+
+ AWA
+ Y
+
+ AW
+ AY
+
+ A
+ WAY
+
+Hence the answer is 3.
+
+**Timelimit**
+Time limit for this challenge is given [here](https://www.hackerrank.com/environment)",0.5637583892617449,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""ruby"",""rust"",""scala"",""swift"",""typescript"",""r""]", , , , ,Hard,Matrix Tracing : Codesprint 5 Editorial ,"Matrix Tracing
+
+Difficulty Level : Easy-Medium
+Required Knowledge : Combinatorics, Counting, Inverse modulo operation
+Problem Setter : Dheeraj
+Problem Tester : Abhiranjan
+
+Approach
+
+Firstly we note that we are given a grid, and only possible ways to reach from top left to bottom right is a DOWN move and RIGHT move.
+It can be observed that that from each point there are always a DOWN and LEFT move (if it doesn't go off board). So given m,n in total we have m-1 RIGHT moves and n-1 LEFT moves. And imagine we auto-move RIGHT and just have to choose when to move DOWN.
+
+So from m+n-2 total moves we choose m-1 down moves. Hence total ways comes out to be m+n-2 Cm-1 .
+
+Another way to look at is m+n-2 total moves where m-1 are of one type and n-1 are of another type
+
+Hence total number of move is: (m+n-2)!/(m-1)!(n-1)!
+
+As we have to print ans mod 109 +7, answer should go as
+
+moves = (m+n-2)! / (m-1)! (n-1)! % (10^9+7)
+ = (m+n-2)! * (m-1)!^(-1) * (n-1)!^(-1) % (10^9+7)
+
+
+For this we need to separately calculate Numerator and Denominator using modular and inverse modular operation.
+
+Factorial
+To calculate the factorial we use the following property
+
+(a*b) mod m = ((a mod m)*(b mod m)) mod m
+
+
+to calculate factorial as
+
+fact(0) = 1
+fact(n) = fact(n-1)*n % (10^9+7)
+
+
+Inverse
+Fermat's Little theorem says that
+
+a^(p-1) == 1 mod p
+
+where p is prime
+ gcd(a, p) != 1
+
+
+Multiplying both sides by a^(-1)
, we get
+
+a^(p-1) * a^(-1) == a^(-1) mod p
+a^(p-2) == a^(-1) mod p
+a^(-1) == a^(p-2) mod p
+
+
+Larger Powers
+For calculating larger powers we use the following property
+
+ 1 , m == 0
+a^m = (b*b) % p , even m
+ (b*b*a) % p , odd m
+
+where
+ b = a^floor(m/2)
+
+
+In this way we can calculate a^m
in log(m)
steps.
+
+Final Solution
+
+So, we can rewrite our above equation as
+
+ moves = (m+n-2)! * (m-1)!^(-1) * (n-1)!^(-1) % (10^9+7)
+ = (m+n-2)! * (m-1)!^(p-2) * (n-1)!^(p-2) % (10^9+7)
+
+
+Setter's Solution
+
+#!/usr/bin/py
+mod = 10**9 + 7
+
+def getfactmod(b):
+ val = 1
+ for i in range(1,b):
+ val =((val%mod)*((i+1)%mod))%mod
+ return val
+
+def getpowermod(a,b):
+ if b==0:
+ return 1
+ if b == 1:
+ return a
+ temp = getpowermod(a,b/2)
+ if b%2==0:
+ return ((temp%mod)**2)%mod
+ else:
+ return (a*((temp%mod)**2))%mod
+
+def inversemod(a):
+ return getpowermod(a,mod-2)
+
+if __name__ == '__main__':
+ t = input()
+ assert 1 <= t <= 10**3
+ for _ in range(t):
+ a,b = map(int, raw_input().strip().split(' '))
+ assert 1 <= a <= 10**6
+ assert 1 <= b <= 10**6
+ denominator = 1
+ numerator = 1
+ for i in range(1, a+b-1):
+ numerator = ((numerator%mod)*(i%mod))%mod
+ for i in range(1, a):
+ denominator = ((denominator%mod)*(i%mod))%mod
+ for i in range(1, b):
+ denominator = ((denominator%mod)*(i%mod))%mod
+ answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod
+ print answer
+
+
+Tester's Solution
+
+#include <bits/stdc++.h>
+using namespace std;
+
+const int sz = 2e6;
+const long long mod = 1e9+7;
+
+long long fact[sz];
+
+long long _pow(int a, int b) {
+ if(b == 0)
+ return 1ll;
+ long long ret = _pow(a, b/2);
+ ret = (ret*ret) % mod;
+ ret = (ret+mod)% mod;
+ if(b%2 == 1)
+ ret = (ret*a) % mod;
+ ret = (ret+mod)% mod;
+ assert(ret >= 0);
+ assert(ret < mod);
+ return ret;
+}
+
+long long inv(int a) {
+ a%= mod;
+ a = (a+mod)%mod;
+ return _pow(a, mod-2);
+}
+
+int main()
+{
+ fact[0] = 1;
+ for(int i = (int)1; i <= (int)sz-1; ++i) {
+ fact[i] = (fact[i-1]*i) % mod;
+ }
+ int test;
+ scanf(""%d"", &test);
+ assert(test >= 1);
+ assert(test <= 1e3);
+ while(test--) {
+ int n, m;
+ cin >> n >> m;
+ assert(1 <= n); assert(n <= 1e6);
+ assert(1 <= m); assert(m <= 1e6);
+ n--; m--;
+ long long ans = fact[n+m];
+ ans = (ans*inv(fact[n])) % mod;
+ ans = (ans + mod) % mod;
+ ans = (ans*inv(fact[m])) % mod;
+ ans = (ans + mod) % mod;
+ assert(ans >= 0);
+ assert( ans < mod);
+ cout << ans << ""\n"";
+ }
+
+ return 0;
+}
+
",0.0,codesprint5-matrix-tracing,2014-01-23T06:50:58,"{""contest_participation"":12558,""challenge_submissions"":2521,""successful_submissions"":1331}",2014-01-23T06:50:58,2016-07-23T16:33:25,setter,"###Python 2
+```python
+#!/usr/bin/py
+mod = 10**9 + 7
+
+def getfactmod(b):
+ val = 1
+ for i in range(1,b):
+ val =((val%mod)*((i+1)%mod))%mod
+ return val
+
+def getpowermod(a,b):
+ if b==0:
+ return 1
+ if b == 1:
+ return a
+ temp = getpowermod(a,b/2)
+ if b%2==0:
+ return ((temp%mod)**2)%mod
+ else:
+ return (a*((temp%mod)**2))%mod
+
+def inversemod(a):
+ return getpowermod(a,mod-2)
+
+if __name__ == '__main__':
+ t = input()
+ assert 1 <= t <= 10**3
+ for _ in range(t):
+ a,b = map(int, raw_input().strip().split(' '))
+ assert 1 <= a <= 10**6
+ assert 1 <= b <= 10**6
+ denominator = 1
+ numerator = 1
+ for i in range(1, a+b-1):
+ numerator = ((numerator%mod)*(i%mod))%mod
+ for i in range(1, a):
+ denominator = ((denominator%mod)*(i%mod))%mod
+ for i in range(1, b):
+ denominator = ((denominator%mod)*(i%mod))%mod
+ answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod
+ print answer
+
+```
+",not-set,2016-04-24T02:02:15,2016-07-23T16:33:12,Python
+22,1667,matrix-tracing,Matrix Tracing,"A word from the English dictionary is taken and arranged as a matrix. e.g. ""MATHEMATICS""
+
+MATHE
+ATHEM
+THEMA
+HEMAT
+EMATI
+MATIC
+ATICS
+
+There are many ways to trace this matrix in a way that helps you construct this word. You start tracing the matrix from the top-left position and at each iteration, you either move RIGHT or DOWN, and ultimately reach the bottom-right of the matrix. It is assured that any such tracing generates the same word. How many such tracings can be possible for a given
+word of length m+n-1 written as a matrix of size m * n?
+
+**Input Format**
+The first line of input contains an integer T. T test cases follow.
+Each test case contains 2 space separated integers m & n (in a new line) indicating that the matrix has m rows and each row has n characters.
+
+**Constraints**
+1 <= T <= 103
+1 ≤ m,n ≤ 106
+
+**Output Format**
+Print the number of ways (S) the word can be traced as explained in the problem statement.
+If the number is larger than 109 +7,
+print `S mod (10^9 + 7)` for each testcase (in a new line).
+
+**Sample Input**
+
+ 1
+ 2 3
+
+**Sample Output**
+
+ 3
+
+**Explanation**
+Let's consider a word AWAY written as the matrix
+
+ AWA
+ WAY
+
+Here, the word AWAY can be traced in 3 different ways, traversing either RIGHT or DOWN.
+
+ AWA
+ Y
+
+ AW
+ AY
+
+ A
+ WAY
+
+Hence the answer is 3.
+
+**Timelimit**
+Time limit for this challenge is given [here](https://www.hackerrank.com/environment)",code,How many ways can you trace a given matrix? - 30 Points,ai,2014-01-14T08:25:46,2022-09-02T09:54:13,"#
+# Complete the 'solve' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts following parameters:
+# 1. INTEGER n
+# 2. INTEGER m
+#
+
+def solve(n, m):
+ # Write your code here
+
+","#!/bin/python3
+
+import math
+import os
+import random
+import re
+import sys
+
+","if __name__ == '__main__':
+ fptr = open(os.environ['OUTPUT_PATH'], 'w')
+
+ t = int(input().strip())
+
+ for t_itr in range(t):
+ first_multiple_input = input().rstrip().split()
+
+ n = int(first_multiple_input[0])
+
+ m = int(first_multiple_input[1])
+
+ result = solve(n, m)
+
+ fptr.write(str(result) + '\n')
+
+ fptr.close()
+","A word from the English dictionary is taken and arranged as a matrix. e.g. ""MATHEMATICS""
+
+ MATHE
+ ATHEM
+ THEMA
+ HEMAT
+ EMATI
+ MATIC
+ ATICS
+
+There are many ways to trace this matrix in a way that helps you construct this word. You start tracing the matrix from the top-left position and at each iteration, you either move RIGHT or DOWN, and ultimately reach the bottom-right of the matrix. It is assured that any such tracing generates the same word. How many such tracings can be possible for a given
+word of length m+n-1 written as a matrix of size m * n?
+
+**Input Format**
+The first line of input contains an integer T. T test cases follow.
+Each test case contains 2 space separated integers m & n (in a new line) indicating that the matrix has m rows and each row has n characters.
+
+**Constraints**
+1 <= T <= 103
+1 ≤ m,n ≤ 106
+
+**Output Format**
+Print the number of ways (S) the word can be traced as explained in the problem statement.
+If the number is larger than 109 +7,
+print `S mod (10^9 + 7)` for each testcase (in a new line).
+
+**Sample Input**
+
+ 1
+ 2 3
+
+**Sample Output**
+
+ 3
+
+**Explanation**
+Let's consider a word AWAY written as the matrix
+
+ AWA
+ WAY
+
+Here, the word AWAY can be traced in 3 different ways, traversing either RIGHT or DOWN.
+
+ AWA
+ Y
+
+ AW
+ AY
+
+ A
+ WAY
+
+Hence the answer is 3.
+
+**Timelimit**
+Time limit for this challenge is given [here](https://www.hackerrank.com/environment)",0.5637583892617449,"[""c"",""clojure"",""cpp"",""cpp14"",""cpp20"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""ruby"",""rust"",""scala"",""swift"",""typescript"",""r""]", , , , ,Hard,Matrix Tracing : Codesprint 5 Editorial ,"Matrix Tracing
+
+Difficulty Level : Easy-Medium
+Required Knowledge : Combinatorics, Counting, Inverse modulo operation
+Problem Setter : Dheeraj
+Problem Tester : Abhiranjan
+
+Approach
+
+Firstly we note that we are given a grid, and only possible ways to reach from top left to bottom right is a DOWN move and RIGHT move.
+It can be observed that that from each point there are always a DOWN and LEFT move (if it doesn't go off board). So given m,n in total we have m-1 RIGHT moves and n-1 LEFT moves. And imagine we auto-move RIGHT and just have to choose when to move DOWN.
+
+So from m+n-2 total moves we choose m-1 down moves. Hence total ways comes out to be m+n-2 Cm-1 .
+
+Another way to look at is m+n-2 total moves where m-1 are of one type and n-1 are of another type
+
+Hence total number of move is: (m+n-2)!/(m-1)!(n-1)!
+
+As we have to print ans mod 109 +7, answer should go as
+
+moves = (m+n-2)! / (m-1)! (n-1)! % (10^9+7)
+ = (m+n-2)! * (m-1)!^(-1) * (n-1)!^(-1) % (10^9+7)
+
+
+For this we need to separately calculate Numerator and Denominator using modular and inverse modular operation.
+
+Factorial
+To calculate the factorial we use the following property
+
+(a*b) mod m = ((a mod m)*(b mod m)) mod m
+
+
+to calculate factorial as
+
+fact(0) = 1
+fact(n) = fact(n-1)*n % (10^9+7)
+
+
+Inverse
+Fermat's Little theorem says that
+
+a^(p-1) == 1 mod p
+
+where p is prime
+ gcd(a, p) != 1
+
+
+Multiplying both sides by a^(-1)
, we get
+
+a^(p-1) * a^(-1) == a^(-1) mod p
+a^(p-2) == a^(-1) mod p
+a^(-1) == a^(p-2) mod p
+
+
+Larger Powers
+For calculating larger powers we use the following property
+
+ 1 , m == 0
+a^m = (b*b) % p , even m
+ (b*b*a) % p , odd m
+
+where
+ b = a^floor(m/2)
+
+
+In this way we can calculate a^m
in log(m)
steps.
+
+Final Solution
+
+So, we can rewrite our above equation as
+
+ moves = (m+n-2)! * (m-1)!^(-1) * (n-1)!^(-1) % (10^9+7)
+ = (m+n-2)! * (m-1)!^(p-2) * (n-1)!^(p-2) % (10^9+7)
+
+
+Setter's Solution
+
+#!/usr/bin/py
+mod = 10**9 + 7
+
+def getfactmod(b):
+ val = 1
+ for i in range(1,b):
+ val =((val%mod)*((i+1)%mod))%mod
+ return val
+
+def getpowermod(a,b):
+ if b==0:
+ return 1
+ if b == 1:
+ return a
+ temp = getpowermod(a,b/2)
+ if b%2==0:
+ return ((temp%mod)**2)%mod
+ else:
+ return (a*((temp%mod)**2))%mod
+
+def inversemod(a):
+ return getpowermod(a,mod-2)
+
+if __name__ == '__main__':
+ t = input()
+ assert 1 <= t <= 10**3
+ for _ in range(t):
+ a,b = map(int, raw_input().strip().split(' '))
+ assert 1 <= a <= 10**6
+ assert 1 <= b <= 10**6
+ denominator = 1
+ numerator = 1
+ for i in range(1, a+b-1):
+ numerator = ((numerator%mod)*(i%mod))%mod
+ for i in range(1, a):
+ denominator = ((denominator%mod)*(i%mod))%mod
+ for i in range(1, b):
+ denominator = ((denominator%mod)*(i%mod))%mod
+ answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod
+ print answer
+
+
+Tester's Solution
+
+#include <bits/stdc++.h>
+using namespace std;
+
+const int sz = 2e6;
+const long long mod = 1e9+7;
+
+long long fact[sz];
+
+long long _pow(int a, int b) {
+ if(b == 0)
+ return 1ll;
+ long long ret = _pow(a, b/2);
+ ret = (ret*ret) % mod;
+ ret = (ret+mod)% mod;
+ if(b%2 == 1)
+ ret = (ret*a) % mod;
+ ret = (ret+mod)% mod;
+ assert(ret >= 0);
+ assert(ret < mod);
+ return ret;
+}
+
+long long inv(int a) {
+ a%= mod;
+ a = (a+mod)%mod;
+ return _pow(a, mod-2);
+}
+
+int main()
+{
+ fact[0] = 1;
+ for(int i = (int)1; i <= (int)sz-1; ++i) {
+ fact[i] = (fact[i-1]*i) % mod;
+ }
+ int test;
+ scanf(""%d"", &test);
+ assert(test >= 1);
+ assert(test <= 1e3);
+ while(test--) {
+ int n, m;
+ cin >> n >> m;
+ assert(1 <= n); assert(n <= 1e6);
+ assert(1 <= m); assert(m <= 1e6);
+ n--; m--;
+ long long ans = fact[n+m];
+ ans = (ans*inv(fact[n])) % mod;
+ ans = (ans + mod) % mod;
+ ans = (ans*inv(fact[m])) % mod;
+ ans = (ans + mod) % mod;
+ assert(ans >= 0);
+ assert( ans < mod);
+ cout << ans << ""\n"";
+ }
+
+ return 0;
+}
+
",0.0,codesprint5-matrix-tracing,2014-01-23T06:50:58,"{""contest_participation"":12558,""challenge_submissions"":2521,""successful_submissions"":1331}",2014-01-23T06:50:58,2016-07-23T16:33:25,tester,"###C++
+```cpp
+#include
+using namespace std;
+
+const int sz = 2e6;
+const long long mod = 1e9+7;
+
+long long fact[sz];
+
+long long _pow(int a, int b) {
+ if(b == 0)
+ return 1ll;
+ long long ret = _pow(a, b/2);
+ ret = (ret*ret) % mod;
+ ret = (ret+mod)% mod;
+ if(b%2 == 1)
+ ret = (ret*a) % mod;
+ ret = (ret+mod)% mod;
+ assert(ret >= 0);
+ assert(ret < mod);
+ return ret;
+}
+
+long long inv(int a) {
+ a%= mod;
+ a = (a+mod)%mod;
+ return _pow(a, mod-2);
+}
+
+int main()
+{
+ fact[0] = 1;
+ for(int i = (int)1; i <= (int)sz-1; ++i) {
+ fact[i] = (fact[i-1]*i) % mod;
+ }
+ int test;
+ scanf(""%d"", &test);
+ assert(test >= 1);
+ assert(test <= 1e3);
+ while(test--) {
+ int n, m;
+ cin >> n >> m;
+ assert(1 <= n); assert(n <= 1e6);
+ assert(1 <= m); assert(m <= 1e6);
+ n--; m--;
+ long long ans = fact[n+m];
+ ans = (ans*inv(fact[n])) % mod;
+ ans = (ans + mod) % mod;
+ ans = (ans*inv(fact[m])) % mod;
+ ans = (ans + mod) % mod;
+ assert(ans >= 0);
+ assert( ans < mod);
+ cout << ans << ""\n"";
+ }
+
+ return 0;
+}
+
+```
+",not-set,2016-04-24T02:02:15,2016-07-23T16:33:25,C++
+23,959,recalling-early-days-gp-with-trees,Recalling Early Days GP with Trees,"[Chinese Version](https://hr-testcases.s3.amazonaws.com/959/959-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/959/959_rus.md)
+
+You are given a [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with N nodes and each has a value associated with it. You are given Q queries, each of which is either an update or a retrieval operation.
+
+The **update query** is of the format
+
+ i j X
+
+This means you'd have to add a [GP](http://en.wikipedia.org/wiki/Geometric_progression) series to the nodes which lie in the path from node `i` to node `j` (both inclusive) with first term of the GP as `X` on node `i` and the common ratio as `R` (given in the input)
+
+The **retrieval** query is of the format
+
+i j
+
+You need to return the sum of the node values (S) lying in the path from node i to node j modulo 100711433.
+
+**Input Format**
+The first line contains two integers (N and R respectively) separated by a space.
+In the next N-1 lines, the ith line describes the ith edge: a line with two integers a b separated by a single space denotes an edge between a, b.
+The next line contains 2 space separated integers (U and Q respectively) representing the number of Update and Query operations to follow.
+U lines follow. Each of the next U lines contains 3 space separated integers (i,j, and X respectively).
+Each of the next Q lines contains 2 space separated integers, i and j respectively.
+
+**Output Format**
+It contains exactly Q lines and each line containing the answer of the ith query.
+
+**Constraints**
+
+2 <= N <= 100000
+2 <= R <= 109
+1 <= U <= 100000
+1 <= Q <= 100000
+1 <= X <= 10
+1 <= a, b, i, j <= N
+
+**Sample Input**
+
+ 6 2
+ 1 2
+ 1 4
+ 2 6
+ 4 5
+ 4 3
+ 2 2
+ 1 6 3
+ 5 3 5
+ 6 4
+ 5 1
+
+**Sample Output**
+
+ 31
+ 18
+
+**Explanation**
+
+The node values after the first updation becomes :
+
+ 3 6 0 0 0 12
+
+The node values after second updation becomes :
+
+ 3 6 20 10 5 12
+
+Answer to Query #1: 12 + 6 + 3 + 10 = 31
+Answer to Query #2: 5 + 10 +3 = 18 ",code,Answer the queries performed on trees.,ai,2013-09-25T18:56:57,2022-08-31T08:33:17,,,,"[Chinese Version](https://hr-testcases.s3.amazonaws.com/959/959-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/959/959_rus.md)
+
+You are given a [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with N nodes and each has a value associated with it. You are given Q queries, each of which is either an update or a retrieval operation.
+
+The **update query** is of the format
+
+ i j X
+
+This means you'd have to add a [GP](http://en.wikipedia.org/wiki/Geometric_progression) series to the nodes which lie in the path from node `i` to node `j` (both inclusive) with first term of the GP as `X` on node `i` and the common ratio as `R` (given in the input)
+
+The **retrieval** query is of the format
+
+i j
+
+You need to return the sum of the node values (S) lying in the path from node i to node j modulo 100711433.
+
+**Input Format**
+The first line contains two integers (N and R respectively) separated by a space.
+In the next N-1 lines, the ith line describes the ith edge: a line with two integers a b separated by a single space denotes an edge between a, b.
+The next line contains 2 space separated integers (U and Q respectively) representing the number of Update and Query operations to follow.
+U lines follow. Each of the next U lines contains 3 space separated integers (i,j, and X respectively).
+Each of the next Q lines contains 2 space separated integers, i and j respectively.
+
+**Output Format**
+It contains exactly Q lines and each line containing the answer of the ith query.
+
+**Constraints**
+
+2 <= N <= 100000
+2 <= R <= 109
+1 <= U <= 100000
+1 <= Q <= 100000
+1 <= X <= 10
+1 <= a, b, i, j <= N
+
+**Sample Input**
+
+ 6 2
+ 1 2
+ 1 4
+ 2 6
+ 4 5
+ 4 3
+ 2 2
+ 1 6 3
+ 5 3 5
+ 6 4
+ 5 1
+
+**Sample Output**
+
+ 31
+ 18
+
+**Explanation**
+
+The node values after the first updation becomes :
+
+ 3 6 0 0 0 12
+
+The node values after second updation becomes :
+
+ 3 6 20 10 5 12
+
+Answer to Query #1: 12 + 6 + 3 + 10 = 31
+Answer to Query #2: 5 + 10 +3 = 18 ",0.4090909090909091,"[""ada"",""bash"",""c"",""clojure"",""coffeescript"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fortran"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""octave"",""pascal"",""perl"",""php"",""pypy3"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""whitespace""]",,,,,Hard,Recalling Early Days with GP Trees : 101 Hack January Editorial,"Recalling Early Days with GP Trees
+
+Difficulty Level : Medium-Hard
+Problem Setter : Devendra Agarwal
+Problem Tester : Wanbo
+
+Approach
+
+Observations
+
+
+The Number 100711433 is a prime number , so that we can find its inverse (except when R is not a multiple of 100711433)
+You need to first tackle all the Updates and then all the Queries.
+
+
+Choose any node as root of the tree.
+
+Make 2 arrays Dist_DFSL[] and Dist_DFSR[] for the Tree.
+
+Update Method
+
+i j St
+
+Let anc be the ancestor node of node i and node j.
+
+Add value St in Dist_DFSL[i]
+
+Add -St*power(R,d1+1) in Dist_DFSL[Parent[anc]] where d1 denotes the total number of edges between node i and node anc and power(a,b) denotes a^b mod 100711433
+
+Add -St*power(R,d1) in Dist_DFSR[anc] where d1 denotes the total number of edges between node i and node anc and power(a,b) denotes a^b mod 100711433
+
+Add St*power(R,d1+d2) in Dist_DFSR[j] where d2 represent the total edges in path from ancestor to j.
+
+d1 and d2 can be calculated by precalculating the depth of each node from root.
+
+d1=depth[i]-depth[anc]
+
+d2=depth[j]-depth[anc]
+
+After all Update Queries, we need the final values at each node and to do so ,we run a DFS on the Tree and do the following:
+
+Dist_DFSL[parent]=(Dist_DFSL[parent]+Dist_DFSL[child]*R)%mod
+
+Dist_DFSR[parent]=(Dist_DFSR[parent]+Dist_DFSR[child]*R_inverse)%mod
+
+Note :: R_Inverse * R = 1 mod (100711433)
+
+Now value at each Node is :
+
+Sum[Node]=Dist_DFSL[Node]+ Dist_DFSR[NOde]
+
+Now, Run a BFS(or DFS) on the graph and store the sum to each Node from the root in Sum[] array.
+
+Answering the Query
+
+i j
+
+Answer= Sum[i] + Sum[j] - Sum[anc] - Sum[Parent[anc]]
+
+NOTE :Precaution in Calculating R_inv and solving the problem when R is multiple of 100711433
+
+Time Complexity: O( (U+Q) log N) //computing lca part otherwise everything in O(1) time.
+
+Setter's Solution
+
+//Author : Devendra Agarwal
+#include<stdio.h>
+#include<algorithm>
+#include<iostream>
+#include<vector>
+#include<string.h>
+using namespace std;
+
+#define MaxN 100001 //Maximum Nodes
+
+typedef long long int ll;
+
+int N,R,level[MaxN],Parent[MaxN],Dist_DFSL[MaxN],Dist_DFSR[MaxN],Root[MaxN][17],Store_Power_R[MaxN],store[MaxN],mod=100711433,R_inv,Sum[MaxN],Queue[MaxN];
+
+vector<int> Graph[MaxN]; //to store graph
+
+
+/* To calculate the inverse of a number in multiplicative modulo b*/
+int inverse(int a,int b) //b>a
+{
+ int Remainder,p0=0,p1=1,pcurr=1,q,m=b;
+ while(a!=0)
+ {
+ Remainder=b%a;
+ q=b/a;
+ if(Remainder!=0)
+ {
+ pcurr=p0-((ll)p1*(ll)q)%m;
+ if(pcurr<0)
+ pcurr+=m;
+ p0=p1;
+ p1=pcurr;
+ }
+ b=a;
+ a=Remainder;
+ }
+ return pcurr;
+}
+
+/*Storing the Parent and height using DFS*/
+void DFS(int root)
+{
+ for(vector<int> ::iterator it=Graph[root].begin();it!=Graph[root].end();it++){
+ if((*it)!=Parent[root]){ //not visiting more than once
+ level[(*it)]=level[root]+1;
+ Parent[(*it)]=root;
+ DFS((*it));
+ }
+ }
+ return;
+}
+/*Calculating Data necessary for calculating ancestor and some pre-processing for quicker implementation*/
+void process()
+{
+ memset(Root,-1,sizeof(Root));
+ for(int i=1;i<=N;i++) Root[i][0]=Parent[i];
+ for(int i=1;(1<<i) <= N; i++)
+ for(int j=1;j<=N;j++)
+ if(Root[j][i-1]!=-1)
+ Root[j][i]=Root[Root[j][i-1]][i-1];
+
+ store[0]=0;
+ store[1]=0;
+ int cmp=2;
+ for(int i=2;i<=N;i++){
+ if(cmp>i) store[i]=store[i-1];
+ else{
+ store[i]=store[i-1]+1;
+ cmp<<=1;
+ }
+ }
+ Store_Power_R[0]=1;
+ for(int i=1;i<=N;i++)
+ Store_Power_R[i]=((ll)Store_Power_R[i-1]*(ll)R)%mod;
+}
+/*Returns the lca of two nodes, same implementation as was used in topcoder tutorials*/
+int lca(int p,int q) //Fnds the LCA of 2 nodes
+{
+ int temp;
+
+ if(level[p]>level[q]){
+ temp=p;p=q;q=temp;
+ }
+
+ //level[q]>=level[p]
+ int steps=store[level[q]];
+ for(int i=steps;i>=0;i--)
+ if(level[q]-(1<<i) >= level[p])
+ q=Root[q][i];
+
+ if(p==q) return p;
+ for(int i=steps;i>=0;i--)
+ if(Root[p][i]!=Root[q][i])
+ p=Root[p][i],q=Root[q][i];
+ return Parent[p];
+}
+/*This Find the Dist_DFSL and Dist_DFSR after all update queries*/
+void DFS_new(int root)
+{
+ for(vector<int> ::iterator it=Graph[root].begin();it!=Graph[root].end();it++){
+ if((*it)!=Parent[root]){ //not visiting more than once
+ DFS_new((*it));
+ Dist_DFSL[root]=(Dist_DFSL[root]+((ll)Dist_DFSL[*it]*(ll)R)%mod)%mod; //Updating root from children
+ Dist_DFSR[root]=(Dist_DFSR[root]+((ll)Dist_DFSR[*it]*(ll)R_inv)%mod)%mod; //Updating root from children
+ }
+ }
+}
+/*This find the Sum[] array*/
+void BFS(int root)
+{
+ Queue[0]=root;
+ int st=0,end=1,node;
+ while(st<end){
+ node=Queue[st];
+ st++;
+ for(vector<int>::iterator it=Graph[node].begin();it!=Graph[node].end();it++){
+ if((*it)!=Parent[node]){
+ Sum[(*it)]=(Sum[(*it)]+Sum[node])%mod;
+ Queue[end]=(*it);
+ end++;
+ }
+ }
+ }
+}
+int main()
+{
+ int x,y,U,Q,anc,ans,St;
+ scanf(""%d%d"",&N,&R);
+ if(R%mod!=0) //Checking the tricky case
+ R_inv=inverse(R,mod);
+ else
+ R_inv=0;
+
+ for(int i=1;i<N;i++){
+ scanf(""%d%d"",&x,&y);
+ Graph[x].push_back(y);
+ Graph[y].push_back(x);
+ }
+
+ level[1]=0;
+ Parent[1]=0;
+ DFS(1);
+ process();
+
+ memset(Dist_DFSL,0,sizeof(Dist_DFSL));
+ memset(Dist_DFSR,0,sizeof(Dist_DFSR));
+ memset(Sum,0,sizeof(Sum));
+
+ scanf(""%d%d"",&U,&Q);
+ while(U--){
+ scanf(""%d%d%d"",&x,&y,&St);
+ anc=lca(x,y);
+ Dist_DFSL[x]=(Dist_DFSL[x]+St)%mod;
+ Dist_DFSL[Parent[anc]]=(Dist_DFSL[Parent[anc]]-((ll)St*(ll)Store_Power_R[level[x]-level[anc]+1])%mod)%mod;
+ Dist_DFSR[y]=(Dist_DFSR[y]+((ll)St*(ll)Store_Power_R[level[y]+level[x]-2*level[anc]])%mod)%mod;
+ Dist_DFSR[anc]=(Dist_DFSR[anc]-((ll)St*(ll)Store_Power_R[level[x]-level[anc]])%mod)%mod;
+ }
+
+ Dist_DFSL[0]=Dist_DFSR[0]=0;
+
+ DFS_new(1);
+
+ if(R%mod!=0) //Check for the tricky test case
+ for(int i=1;i<=N;i++) Sum[i]=(Dist_DFSL[i]+Dist_DFSR[i])%mod;
+ else
+ for(int i=1;i<=N;i++) Sum[i]=Dist_DFSL[i];
+
+ BFS(1);
+
+ while(Q--){
+ scanf(""%d%d"",&x,&y);
+ anc=lca(x,y);
+ ans=(Sum[x]+Sum[y]-Sum[anc]-Sum[Parent[anc]])%mod;
+ printf(""%d\n"",(ans+ mod)%mod);
+ }
+
+ return 0;
+}
+
+
+Tester's Solution
+
+#include <map>
+#include <set>
+#include <list>
+#include <queue>
+#include <deque>
+#include <stack>
+#include <bitset>
+#include <vector>
+#include <ctime>
+#include <cmath>
+#include <cstdio>
+#include <string>
+#include <cstring>
+#include <cassert>
+#include <numeric>
+#include <iomanip>
+#include <sstream>
+#include <fstream>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+typedef long long LL;
+typedef pair<int, int> PII;
+typedef pair<LL, LL> PLL;
+typedef vector<int> VI;
+typedef vector<LL> VL;
+typedef vector<PII> VPII;
+typedef vector<PLL> VPLL;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""<<(x)<<""]\n""
+#define PP(x,i) cerr<<""[""#x<<i<<"" = ""<<x[i]<<""]\n""
+#define P2(x,y) cerr<<""[""#x"" = ""<<(x)<<"", ""#y"" = ""<<(y)<<""]\n""
+#define TM(a,b) cerr<<""[""#a"" -> ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define FOR(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
+#define rep(i, n) for(int i = 0; i < n; i++)
+#define UN(v) sort(ALL(v)), v.resize(unique(ALL(v))-v.begin())
+#define mp make_pair
+#define pb push_back
+#define x first
+#define y second
+struct _ {_() {ios_base::sync_with_stdio(0);}} _;
+template<class T> void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n"");}
+template<class T> inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template<class T> inline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+template<class T> string tostring(T x, int len = 0) {stringstream ss; ss << x; string r = ss.str(); if(r.length() < len) r = string(len - r.length(), '0') + r; return r;}
+template<class T> void convert(string x, T& r) {stringstream ss(x); ss >> r;}
+template<class A, class B> ostream& operator<<(ostream &o, pair<A, B> t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;}
+const int inf = 0x3f3f3f3f;
+const int mod = 100711433;
+const int N = 111111;
+
+const int V = 111111;
+vector<int> g[V];
+vector<int> chain[V];
+int father[V], heavy[V];
+int depth[V], size[V];
+int chainID[V], top[V];
+int tL[V], tR[V];
+int w[V];
+
+void DFS(int u) {
+ size[u] = 1;
+ for(int i = 0; i < g[u].size(); i++) {
+ int v = g[u][i];
+ if(v == father[u]) continue;
+ father[v] = u;
+ depth[v] = depth[u] + 1;
+ DFS(v);
+ size[u] += size[v];
+ if(heavy[u] == -1 || size[v] > size[heavy[u]]) heavy[u] = v;
+ }
+}
+
+void HLD_DFS(int n) {
+ MM(heavy, -1);
+ MM(father, -1);
+ MM(depth, 0);
+ DFS(0);
+ int id = 0;
+ for(int i = 0; i < n; i++) {
+ if(father[i] == -1 || heavy[father[i]] != i) {
+ for(int k = i; k != -1; k = heavy[k]) {
+ chainID[k] = id;
+ chain[id].push_back(k);
+ top[k] = i;
+ }
+ id++;
+ }
+ }
+
+ for(int i = 0; i < id; i++) {
+ tL[i] = i > 0 ? tR[i - 1] + 1 : 1;
+ tR[i] = tL[i] + chain[i].size() - 1;
+ for(int j = 0; j < chain[i].size(); j++) {
+ w[chain[i][j]] = tL[i] + j;
+ }
+ }
+}
+
+int LCA(int u, int v) {
+ while(chainID[u] != chainID[v]) {
+ if(depth[top[u]] > depth[top[v]]) swap(u, v);
+ v = father[top[v]];
+ }
+ return depth[u] < depth[v] ? u : v;
+}
+
+
+LL exp(LL x, LL n, LL m = ~0ULL >> 1) {
+ x %= m;
+ LL r = 1 % m;
+ while(n) {
+ if(n & 1) r = r * x % m;
+ x = x * x % m, n >>= 1;
+ }
+ return r;
+}
+
+LL inv(int x) {
+ return exp(x, mod - 2, mod);
+}
+
+int n, R;
+int iR;
+LL q[N];
+LL iq[N];
+
+void ADD(int u, int v, int s, int r) {
+ /*
+ if(depth[u] > depth[v]) {
+ int ns;
+ while(chain[u] != chain[v]) {
+ int len = top[u] - u + 1;
+ ns = s * q[top[u] - u + 1] % mod;
+ add(w[top[u]], w[u], ns * R % mod, iR);
+ u = top[u] + 1;
+ }
+ add(w[v], w[u], ns * R % mod , iR);
+ } else {
+ int ns;
+ swap(u, v);
+ VPII vp;
+ while(chain[u] != chain[v]) {
+ int len = top[u] - u + 1;
+ ns = s * q[top[u] - u + 1] % mod;
+ vp.pb(mp(top[u], w[u]));
+ u = top[u] + 1;
+ }
+ add(w[v], w[u], ns * R % mod , iR);
+ }
+ */
+}
+
+LL d[N];
+
+int main() {
+ cin >> n >> R;
+ for(int i = 0; i < n - 1; i++) {
+ int u, v;
+ cin >> u >> v;
+ u--, v--;
+ g[u].pb(v);
+ g[v].pb(u);
+ }
+
+ HLD_DFS(n);
+
+ int U, Q;
+ cin >> U >> Q;
+
+ iR = inv(R);
+ iq[0] = q[0] = 1;
+ for(int i = 1; i < N; i++) q[i] = q[i - 1] * R % mod;
+ for(int i = 1; i < N; i++) iq[i] = iq[i - 1] * iR % mod;
+
+ while(U--) {
+ int u, v, s;
+ cin >> u >> v >> s;
+ u--, v--;
+ int x = LCA(u, v);
+ int t = depth[u] - depth[x];
+ vector<int> left, right;
+ while(u != x) {
+ left.pb(u);
+ u = father[u];
+ }
+ left.pb(x);
+ while(v != x) {
+ right.pb(v);
+ v = father[v];
+ }
+ reverse(ALL(right));
+ for(int i = 0; i < right.size(); i++) left.pb(right[i]);
+
+ for(int i = 0; i < left.size(); i++) {
+ d[left[i]] += s;
+ s = (LL) s * R % mod;
+ }
+ /* ADD(u, x, s, R);
+ ADD(x, v, s * q[t] % mod, R);
+ ADD(x, x, -s * q[t] % mod, 1);*/
+ }
+
+ while(Q--) {
+ int u, v;
+ cin >> u >> v;
+ u--, v--;
+ int x = LCA(u, v);
+// LL r = SUM(u) + SUM(v) - 2 * SUM(father[x]);
+// r = (r % mod + mod) % mod;
+ LL r = 0;
+ while(u != x) {
+ r += d[u];
+ u = father[u];
+ }
+ r += d[x];
+ while(v != x) {
+ r += d[v];
+ v = father[v];
+ }
+ r = (r % mod + mod) % mod;
+ cout << r << endl;
+ }
+ return 0;
+}
+
",0.0,101-hack-jan-recalling-early-days-with-gp-trees,2014-02-03T12:29:31,"{""contest_participation"":1791,""challenge_submissions"":71,""successful_submissions"":23}",2014-02-03T12:29:31,2016-05-13T00:03:45,setter," //Author : Devendra Agarwal
+ #include
+ #include
+ #include
+ #include
+ #include
+ using namespace std;
+
+ #define MaxN 100001 //Maximum Nodes
+
+ typedef long long int ll;
+
+ int N,R,level[MaxN],Parent[MaxN],Dist_DFSL[MaxN],Dist_DFSR[MaxN],Root[MaxN][17],Store_Power_R[MaxN],store[MaxN],mod=100711433,R_inv,Sum[MaxN],Queue[MaxN];
+
+ vector Graph[MaxN]; //to store graph
+
+
+ /* To calculate the inverse of a number in multiplicative modulo b*/
+ int inverse(int a,int b) //b>a
+ {
+ int Remainder,p0=0,p1=1,pcurr=1,q,m=b;
+ while(a!=0)
+ {
+ Remainder=b%a;
+ q=b/a;
+ if(Remainder!=0)
+ {
+ pcurr=p0-((ll)p1*(ll)q)%m;
+ if(pcurr<0)
+ pcurr+=m;
+ p0=p1;
+ p1=pcurr;
+ }
+ b=a;
+ a=Remainder;
+ }
+ return pcurr;
+ }
+
+ /*Storing the Parent and height using DFS*/
+ void DFS(int root)
+ {
+ for(vector ::iterator it=Graph[root].begin();it!=Graph[root].end();it++){
+ if((*it)!=Parent[root]){ //not visiting more than once
+ level[(*it)]=level[root]+1;
+ Parent[(*it)]=root;
+ DFS((*it));
+ }
+ }
+ return;
+ }
+ /*Calculating Data necessary for calculating ancestor and some pre-processing for quicker implementation*/
+ void process()
+ {
+ memset(Root,-1,sizeof(Root));
+ for(int i=1;i<=N;i++) Root[i][0]=Parent[i];
+ for(int i=1;(1<i) store[i]=store[i-1];
+ else{
+ store[i]=store[i-1]+1;
+ cmp<<=1;
+ }
+ }
+ Store_Power_R[0]=1;
+ for(int i=1;i<=N;i++)
+ Store_Power_R[i]=((ll)Store_Power_R[i-1]*(ll)R)%mod;
+ }
+ /*Returns the lca of two nodes, same implementation as was used in topcoder tutorials*/
+ int lca(int p,int q) //Fnds the LCA of 2 nodes
+ {
+ int temp;
+
+ if(level[p]>level[q]){
+ temp=p;p=q;q=temp;
+ }
+
+ //level[q]>=level[p]
+ int steps=store[level[q]];
+ for(int i=steps;i>=0;i--)
+ if(level[q]-(1<= level[p])
+ q=Root[q][i];
+
+ if(p==q) return p;
+ for(int i=steps;i>=0;i--)
+ if(Root[p][i]!=Root[q][i])
+ p=Root[p][i],q=Root[q][i];
+ return Parent[p];
+ }
+ /*This Find the Dist_DFSL and Dist_DFSR after all update queries*/
+ void DFS_new(int root)
+ {
+ for(vector ::iterator it=Graph[root].begin();it!=Graph[root].end();it++){
+ if((*it)!=Parent[root]){ //not visiting more than once
+ DFS_new((*it));
+ Dist_DFSL[root]=(Dist_DFSL[root]+((ll)Dist_DFSL[*it]*(ll)R)%mod)%mod; //Updating root from children
+ Dist_DFSR[root]=(Dist_DFSR[root]+((ll)Dist_DFSR[*it]*(ll)R_inv)%mod)%mod; //Updating root from children
+ }
+ }
+ }
+ /*This find the Sum[] array*/
+ void BFS(int root)
+ {
+ Queue[0]=root;
+ int st=0,end=1,node;
+ while(st::iterator it=Graph[node].begin();it!=Graph[node].end();it++){
+ if((*it)!=Parent[node]){
+ Sum[(*it)]=(Sum[(*it)]+Sum[node])%mod;
+ Queue[end]=(*it);
+ end++;
+ }
+ }
+ }
+ }
+ int main()
+ {
+ int x,y,U,Q,anc,ans,St;
+ scanf(""%d%d"",&N,&R);
+ if(R%mod!=0) //Checking the tricky case
+ R_inv=inverse(R,mod);
+ else
+ R_inv=0;
+
+ for(int i=1;i
+[Russian Version](https://hr-testcases.s3.amazonaws.com/959/959_rus.md)
+
+You are given a [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with N nodes and each has a value associated with it. You are given Q queries, each of which is either an update or a retrieval operation.
+
+The **update query** is of the format
+
+ i j X
+
+This means you'd have to add a [GP](http://en.wikipedia.org/wiki/Geometric_progression) series to the nodes which lie in the path from node `i` to node `j` (both inclusive) with first term of the GP as `X` on node `i` and the common ratio as `R` (given in the input)
+
+The **retrieval** query is of the format
+
+i j
+
+You need to return the sum of the node values (S) lying in the path from node i to node j modulo 100711433.
+
+**Input Format**
+The first line contains two integers (N and R respectively) separated by a space.
+In the next N-1 lines, the ith line describes the ith edge: a line with two integers a b separated by a single space denotes an edge between a, b.
+The next line contains 2 space separated integers (U and Q respectively) representing the number of Update and Query operations to follow.
+U lines follow. Each of the next U lines contains 3 space separated integers (i,j, and X respectively).
+Each of the next Q lines contains 2 space separated integers, i and j respectively.
+
+**Output Format**
+It contains exactly Q lines and each line containing the answer of the ith query.
+
+**Constraints**
+
+2 <= N <= 100000
+2 <= R <= 109
+1 <= U <= 100000
+1 <= Q <= 100000
+1 <= X <= 10
+1 <= a, b, i, j <= N
+
+**Sample Input**
+
+ 6 2
+ 1 2
+ 1 4
+ 2 6
+ 4 5
+ 4 3
+ 2 2
+ 1 6 3
+ 5 3 5
+ 6 4
+ 5 1
+
+**Sample Output**
+
+ 31
+ 18
+
+**Explanation**
+
+The node values after the first updation becomes :
+
+ 3 6 0 0 0 12
+
+The node values after second updation becomes :
+
+ 3 6 20 10 5 12
+
+Answer to Query #1: 12 + 6 + 3 + 10 = 31
+Answer to Query #2: 5 + 10 +3 = 18 ",code,Answer the queries performed on trees.,ai,2013-09-25T18:56:57,2022-08-31T08:33:17,,,,"[Chinese Version](https://hr-testcases.s3.amazonaws.com/959/959-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/959/959_rus.md)
+
+You are given a [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with N nodes and each has a value associated with it. You are given Q queries, each of which is either an update or a retrieval operation.
+
+The **update query** is of the format
+
+ i j X
+
+This means you'd have to add a [GP](http://en.wikipedia.org/wiki/Geometric_progression) series to the nodes which lie in the path from node `i` to node `j` (both inclusive) with first term of the GP as `X` on node `i` and the common ratio as `R` (given in the input)
+
+The **retrieval** query is of the format
+
+i j
+
+You need to return the sum of the node values (S) lying in the path from node i to node j modulo 100711433.
+
+**Input Format**
+The first line contains two integers (N and R respectively) separated by a space.
+In the next N-1 lines, the ith line describes the ith edge: a line with two integers a b separated by a single space denotes an edge between a, b.
+The next line contains 2 space separated integers (U and Q respectively) representing the number of Update and Query operations to follow.
+U lines follow. Each of the next U lines contains 3 space separated integers (i,j, and X respectively).
+Each of the next Q lines contains 2 space separated integers, i and j respectively.
+
+**Output Format**
+It contains exactly Q lines and each line containing the answer of the ith query.
+
+**Constraints**
+
+2 <= N <= 100000
+2 <= R <= 109
+1 <= U <= 100000
+1 <= Q <= 100000
+1 <= X <= 10
+1 <= a, b, i, j <= N
+
+**Sample Input**
+
+ 6 2
+ 1 2
+ 1 4
+ 2 6
+ 4 5
+ 4 3
+ 2 2
+ 1 6 3
+ 5 3 5
+ 6 4
+ 5 1
+
+**Sample Output**
+
+ 31
+ 18
+
+**Explanation**
+
+The node values after the first updation becomes :
+
+ 3 6 0 0 0 12
+
+The node values after second updation becomes :
+
+ 3 6 20 10 5 12
+
+Answer to Query #1: 12 + 6 + 3 + 10 = 31
+Answer to Query #2: 5 + 10 +3 = 18 ",0.4090909090909091,"[""ada"",""bash"",""c"",""clojure"",""coffeescript"",""cpp"",""cpp14"",""cpp20"",""csharp"",""d"",""elixir"",""erlang"",""fortran"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""java15"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""octave"",""pascal"",""perl"",""php"",""pypy3"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""typescript"",""visualbasic"",""whitespace""]",,,,,Hard,Recalling Early Days with GP Trees : 101 Hack January Editorial,"Recalling Early Days with GP Trees
+
+Difficulty Level : Medium-Hard
+Problem Setter : Devendra Agarwal
+Problem Tester : Wanbo
+
+Approach
+
+Observations
+
+
+The Number 100711433 is a prime number , so that we can find its inverse (except when R is not a multiple of 100711433)
+You need to first tackle all the Updates and then all the Queries.
+
+
+Choose any node as root of the tree.
+
+Make 2 arrays Dist_DFSL[] and Dist_DFSR[] for the Tree.
+
+Update Method
+
+i j St
+
+Let anc be the ancestor node of node i and node j.
+
+Add value St in Dist_DFSL[i]
+
+Add -St*power(R,d1+1) in Dist_DFSL[Parent[anc]] where d1 denotes the total number of edges between node i and node anc and power(a,b) denotes a^b mod 100711433
+
+Add -St*power(R,d1) in Dist_DFSR[anc] where d1 denotes the total number of edges between node i and node anc and power(a,b) denotes a^b mod 100711433
+
+Add St*power(R,d1+d2) in Dist_DFSR[j] where d2 represent the total edges in path from ancestor to j.
+
+d1 and d2 can be calculated by precalculating the depth of each node from root.
+
+d1=depth[i]-depth[anc]
+
+d2=depth[j]-depth[anc]
+
+After all Update Queries, we need the final values at each node and to do so ,we run a DFS on the Tree and do the following:
+
+Dist_DFSL[parent]=(Dist_DFSL[parent]+Dist_DFSL[child]*R)%mod
+
+Dist_DFSR[parent]=(Dist_DFSR[parent]+Dist_DFSR[child]*R_inverse)%mod
+
+Note :: R_Inverse * R = 1 mod (100711433)
+
+Now value at each Node is :
+
+Sum[Node]=Dist_DFSL[Node]+ Dist_DFSR[NOde]
+
+Now, Run a BFS(or DFS) on the graph and store the sum to each Node from the root in Sum[] array.
+
+Answering the Query
+
+i j
+
+Answer= Sum[i] + Sum[j] - Sum[anc] - Sum[Parent[anc]]
+
+NOTE :Precaution in Calculating R_inv and solving the problem when R is multiple of 100711433
+
+Time Complexity: O( (U+Q) log N) //computing lca part otherwise everything in O(1) time.
+
+Setter's Solution
+
+//Author : Devendra Agarwal
+#include<stdio.h>
+#include<algorithm>
+#include<iostream>
+#include<vector>
+#include<string.h>
+using namespace std;
+
+#define MaxN 100001 //Maximum Nodes
+
+typedef long long int ll;
+
+int N,R,level[MaxN],Parent[MaxN],Dist_DFSL[MaxN],Dist_DFSR[MaxN],Root[MaxN][17],Store_Power_R[MaxN],store[MaxN],mod=100711433,R_inv,Sum[MaxN],Queue[MaxN];
+
+vector<int> Graph[MaxN]; //to store graph
+
+
+/* To calculate the inverse of a number in multiplicative modulo b*/
+int inverse(int a,int b) //b>a
+{
+ int Remainder,p0=0,p1=1,pcurr=1,q,m=b;
+ while(a!=0)
+ {
+ Remainder=b%a;
+ q=b/a;
+ if(Remainder!=0)
+ {
+ pcurr=p0-((ll)p1*(ll)q)%m;
+ if(pcurr<0)
+ pcurr+=m;
+ p0=p1;
+ p1=pcurr;
+ }
+ b=a;
+ a=Remainder;
+ }
+ return pcurr;
+}
+
+/*Storing the Parent and height using DFS*/
+void DFS(int root)
+{
+ for(vector<int> ::iterator it=Graph[root].begin();it!=Graph[root].end();it++){
+ if((*it)!=Parent[root]){ //not visiting more than once
+ level[(*it)]=level[root]+1;
+ Parent[(*it)]=root;
+ DFS((*it));
+ }
+ }
+ return;
+}
+/*Calculating Data necessary for calculating ancestor and some pre-processing for quicker implementation*/
+void process()
+{
+ memset(Root,-1,sizeof(Root));
+ for(int i=1;i<=N;i++) Root[i][0]=Parent[i];
+ for(int i=1;(1<<i) <= N; i++)
+ for(int j=1;j<=N;j++)
+ if(Root[j][i-1]!=-1)
+ Root[j][i]=Root[Root[j][i-1]][i-1];
+
+ store[0]=0;
+ store[1]=0;
+ int cmp=2;
+ for(int i=2;i<=N;i++){
+ if(cmp>i) store[i]=store[i-1];
+ else{
+ store[i]=store[i-1]+1;
+ cmp<<=1;
+ }
+ }
+ Store_Power_R[0]=1;
+ for(int i=1;i<=N;i++)
+ Store_Power_R[i]=((ll)Store_Power_R[i-1]*(ll)R)%mod;
+}
+/*Returns the lca of two nodes, same implementation as was used in topcoder tutorials*/
+int lca(int p,int q) //Fnds the LCA of 2 nodes
+{
+ int temp;
+
+ if(level[p]>level[q]){
+ temp=p;p=q;q=temp;
+ }
+
+ //level[q]>=level[p]
+ int steps=store[level[q]];
+ for(int i=steps;i>=0;i--)
+ if(level[q]-(1<<i) >= level[p])
+ q=Root[q][i];
+
+ if(p==q) return p;
+ for(int i=steps;i>=0;i--)
+ if(Root[p][i]!=Root[q][i])
+ p=Root[p][i],q=Root[q][i];
+ return Parent[p];
+}
+/*This Find the Dist_DFSL and Dist_DFSR after all update queries*/
+void DFS_new(int root)
+{
+ for(vector<int> ::iterator it=Graph[root].begin();it!=Graph[root].end();it++){
+ if((*it)!=Parent[root]){ //not visiting more than once
+ DFS_new((*it));
+ Dist_DFSL[root]=(Dist_DFSL[root]+((ll)Dist_DFSL[*it]*(ll)R)%mod)%mod; //Updating root from children
+ Dist_DFSR[root]=(Dist_DFSR[root]+((ll)Dist_DFSR[*it]*(ll)R_inv)%mod)%mod; //Updating root from children
+ }
+ }
+}
+/*This find the Sum[] array*/
+void BFS(int root)
+{
+ Queue[0]=root;
+ int st=0,end=1,node;
+ while(st<end){
+ node=Queue[st];
+ st++;
+ for(vector<int>::iterator it=Graph[node].begin();it!=Graph[node].end();it++){
+ if((*it)!=Parent[node]){
+ Sum[(*it)]=(Sum[(*it)]+Sum[node])%mod;
+ Queue[end]=(*it);
+ end++;
+ }
+ }
+ }
+}
+int main()
+{
+ int x,y,U,Q,anc,ans,St;
+ scanf(""%d%d"",&N,&R);
+ if(R%mod!=0) //Checking the tricky case
+ R_inv=inverse(R,mod);
+ else
+ R_inv=0;
+
+ for(int i=1;i<N;i++){
+ scanf(""%d%d"",&x,&y);
+ Graph[x].push_back(y);
+ Graph[y].push_back(x);
+ }
+
+ level[1]=0;
+ Parent[1]=0;
+ DFS(1);
+ process();
+
+ memset(Dist_DFSL,0,sizeof(Dist_DFSL));
+ memset(Dist_DFSR,0,sizeof(Dist_DFSR));
+ memset(Sum,0,sizeof(Sum));
+
+ scanf(""%d%d"",&U,&Q);
+ while(U--){
+ scanf(""%d%d%d"",&x,&y,&St);
+ anc=lca(x,y);
+ Dist_DFSL[x]=(Dist_DFSL[x]+St)%mod;
+ Dist_DFSL[Parent[anc]]=(Dist_DFSL[Parent[anc]]-((ll)St*(ll)Store_Power_R[level[x]-level[anc]+1])%mod)%mod;
+ Dist_DFSR[y]=(Dist_DFSR[y]+((ll)St*(ll)Store_Power_R[level[y]+level[x]-2*level[anc]])%mod)%mod;
+ Dist_DFSR[anc]=(Dist_DFSR[anc]-((ll)St*(ll)Store_Power_R[level[x]-level[anc]])%mod)%mod;
+ }
+
+ Dist_DFSL[0]=Dist_DFSR[0]=0;
+
+ DFS_new(1);
+
+ if(R%mod!=0) //Check for the tricky test case
+ for(int i=1;i<=N;i++) Sum[i]=(Dist_DFSL[i]+Dist_DFSR[i])%mod;
+ else
+ for(int i=1;i<=N;i++) Sum[i]=Dist_DFSL[i];
+
+ BFS(1);
+
+ while(Q--){
+ scanf(""%d%d"",&x,&y);
+ anc=lca(x,y);
+ ans=(Sum[x]+Sum[y]-Sum[anc]-Sum[Parent[anc]])%mod;
+ printf(""%d\n"",(ans+ mod)%mod);
+ }
+
+ return 0;
+}
+
+
+Tester's Solution
+
+#include <map>
+#include <set>
+#include <list>
+#include <queue>
+#include <deque>
+#include <stack>
+#include <bitset>
+#include <vector>
+#include <ctime>
+#include <cmath>
+#include <cstdio>
+#include <string>
+#include <cstring>
+#include <cassert>
+#include <numeric>
+#include <iomanip>
+#include <sstream>
+#include <fstream>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+typedef long long LL;
+typedef pair<int, int> PII;
+typedef pair<LL, LL> PLL;
+typedef vector<int> VI;
+typedef vector<LL> VL;
+typedef vector<PII> VPII;
+typedef vector<PLL> VPLL;
+#define MM(a,x) memset(a,x,sizeof(a));
+#define ALL(x) (x).begin(), (x).end()
+#define P(x) cerr<<""[""#x<<"" = ""<<(x)<<""]\n""
+#define PP(x,i) cerr<<""[""#x<<i<<"" = ""<<x[i]<<""]\n""
+#define P2(x,y) cerr<<""[""#x"" = ""<<(x)<<"", ""#y"" = ""<<(y)<<""]\n""
+#define TM(a,b) cerr<<""[""#a"" -> ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n"";
+#define FOR(it,v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++)
+#define rep(i, n) for(int i = 0; i < n; i++)
+#define UN(v) sort(ALL(v)), v.resize(unique(ALL(v))-v.begin())
+#define mp make_pair
+#define pb push_back
+#define x first
+#define y second
+struct _ {_() {ios_base::sync_with_stdio(0);}} _;
+template<class T> void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "" "" : ""\n"");}
+template<class T> inline bool chmin(T &a, T b) {return a > b ? a = b, 1 : 0;}
+template<class T> inline bool chmax(T &a, T b) {return a < b ? a = b, 1 : 0;}
+template<class T> string tostring(T x, int len = 0) {stringstream ss; ss << x; string r = ss.str(); if(r.length() < len) r = string(len - r.length(), '0') + r; return r;}
+template<class T> void convert(string x, T& r) {stringstream ss(x); ss >> r;}
+template<class A, class B> ostream& operator<<(ostream &o, pair<A, B> t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;}
+const int inf = 0x3f3f3f3f;
+const int mod = 100711433;
+const int N = 111111;
+
+const int V = 111111;
+vector<int> g[V];
+vector<int> chain[V];
+int father[V], heavy[V];
+int depth[V], size[V];
+int chainID[V], top[V];
+int tL[V], tR[V];
+int w[V];
+
+void DFS(int u) {
+ size[u] = 1;
+ for(int i = 0; i < g[u].size(); i++) {
+ int v = g[u][i];
+ if(v == father[u]) continue;
+ father[v] = u;
+ depth[v] = depth[u] + 1;
+ DFS(v);
+ size[u] += size[v];
+ if(heavy[u] == -1 || size[v] > size[heavy[u]]) heavy[u] = v;
+ }
+}
+
+void HLD_DFS(int n) {
+ MM(heavy, -1);
+ MM(father, -1);
+ MM(depth, 0);
+ DFS(0);
+ int id = 0;
+ for(int i = 0; i < n; i++) {
+ if(father[i] == -1 || heavy[father[i]] != i) {
+ for(int k = i; k != -1; k = heavy[k]) {
+ chainID[k] = id;
+ chain[id].push_back(k);
+ top[k] = i;
+ }
+ id++;
+ }
+ }
+
+ for(int i = 0; i < id; i++) {
+ tL[i] = i > 0 ? tR[i - 1] + 1 : 1;
+ tR[i] = tL[i] + chain[i].size() - 1;
+ for(int j = 0; j < chain[i].size(); j++) {
+ w[chain[i][j]] = tL[i] + j;
+ }
+ }
+}
+
+int LCA(int u, int v) {
+ while(chainID[u] != chainID[v]) {
+ if(depth[top[u]] > depth[top[v]]) swap(u, v);
+ v = father[top[v]];
+ }
+ return depth[u] < depth[v] ? u : v;
+}
+
+
+LL exp(LL x, LL n, LL m = ~0ULL >> 1) {
+ x %= m;
+ LL r = 1 % m;
+ while(n) {
+ if(n & 1) r = r * x % m;
+ x = x * x % m, n >>= 1;
+ }
+ return r;
+}
+
+LL inv(int x) {
+ return exp(x, mod - 2, mod);
+}
+
+int n, R;
+int iR;
+LL q[N];
+LL iq[N];
+
+void ADD(int u, int v, int s, int r) {
+ /*
+ if(depth[u] > depth[v]) {
+ int ns;
+ while(chain[u] != chain[v]) {
+ int len = top[u] - u + 1;
+ ns = s * q[top[u] - u + 1] % mod;
+ add(w[top[u]], w[u], ns * R % mod, iR);
+ u = top[u] + 1;
+ }
+ add(w[v], w[u], ns * R % mod , iR);
+ } else {
+ int ns;
+ swap(u, v);
+ VPII vp;
+ while(chain[u] != chain[v]) {
+ int len = top[u] - u + 1;
+ ns = s * q[top[u] - u + 1] % mod;
+ vp.pb(mp(top[u], w[u]));
+ u = top[u] + 1;
+ }
+ add(w[v], w[u], ns * R % mod , iR);
+ }
+ */
+}
+
+LL d[N];
+
+int main() {
+ cin >> n >> R;
+ for(int i = 0; i < n - 1; i++) {
+ int u, v;
+ cin >> u >> v;
+ u--, v--;
+ g[u].pb(v);
+ g[v].pb(u);
+ }
+
+ HLD_DFS(n);
+
+ int U, Q;
+ cin >> U >> Q;
+
+ iR = inv(R);
+ iq[0] = q[0] = 1;
+ for(int i = 1; i < N; i++) q[i] = q[i - 1] * R % mod;
+ for(int i = 1; i < N; i++) iq[i] = iq[i - 1] * iR % mod;
+
+ while(U--) {
+ int u, v, s;
+ cin >> u >> v >> s;
+ u--, v--;
+ int x = LCA(u, v);
+ int t = depth[u] - depth[x];
+ vector<int> left, right;
+ while(u != x) {
+ left.pb(u);
+ u = father[u];
+ }
+ left.pb(x);
+ while(v != x) {
+ right.pb(v);
+ v = father[v];
+ }
+ reverse(ALL(right));
+ for(int i = 0; i < right.size(); i++) left.pb(right[i]);
+
+ for(int i = 0; i < left.size(); i++) {
+ d[left[i]] += s;
+ s = (LL) s * R % mod;
+ }
+ /* ADD(u, x, s, R);
+ ADD(x, v, s * q[t] % mod, R);
+ ADD(x, x, -s * q[t] % mod, 1);*/
+ }
+
+ while(Q--) {
+ int u, v;
+ cin >> u >> v;
+ u--, v--;
+ int x = LCA(u, v);
+// LL r = SUM(u) + SUM(v) - 2 * SUM(father[x]);
+// r = (r % mod + mod) % mod;
+ LL r = 0;
+ while(u != x) {
+ r += d[u];
+ u = father[u];
+ }
+ r += d[x];
+ while(v != x) {
+ r += d[v];
+ v = father[v];
+ }
+ r = (r % mod + mod) % mod;
+ cout << r << endl;
+ }
+ return 0;
+}
+
",0.0,101-hack-jan-recalling-early-days-with-gp-trees,2014-02-03T12:29:31,"{""contest_participation"":1791,""challenge_submissions"":71,""successful_submissions"":23}",2014-02-03T12:29:31,2016-05-13T00:03:45,tester,"
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include
+ #include