diff --git "a/public_challenges_sample_v1.csv" "b/public_challenges_sample_v1.csv" new file mode 100644--- /dev/null +++ "b/public_challenges_sample_v1.csv" @@ -0,0 +1,62394 @@ +,challenge_id,challenge_slug,challenge_name,challenge_body,challenge_kind,challenge_preview,challenge_category,challenge_created_at,challenge_updated_at,python3_template,python3_template_head,python3_template_tail,problem_statement,difficulty,allowed_languages,input_format,output_format,sample_input,sample_output,difficulty_tag,editorial_title,editorial_content,editorial_draft,editorial_slug,editorial_published_at,editorial_statistics,editorial_created_at,editorial_updated_at,editorial_solution_kind,editorial_solution_code,editorial_solution_language,editorial_solution_created_at,editorial_solution_updated_at,language +0,337,randomsumexpected,Random Sum - Expected Sum,"Given an a list D of N integers, and an integer T, two numbers L and R are randomly chosen such that 0 ≤ L ≤ R < N. + +What is the expected sum of the subarray {d[L]...d[R]} given that (sum{d[L],...d[R]} <= T)? + +**Input Format:** + +The first line will contain two numbers: N and T. N lines follow, each containing one number from list D. + +**Output Format:** + +Output one number P, the expected sum of D[L]...D[R] upto 9 decimal places. + +**Constraints:** + +1 <= N < 100000 + +0 <= D[i] < 10^7 + +0 < T <= 10^9 + +**Sample Input:** +
+5 10
+4 
+5 
+3 
+7
+1
+
+ +**Sample Output:** +
6.111111111
+ +**Explaination** + +[4],[5],[3],[7],[1],[4,5],[5,3],[3,7],[7,1] subarrays satisfy the property. + +4 + 5 + 3 + 7 + 1 + 9 + 8 + 10 + 8 = 55 + +55/9 = 6.11111111 + +",code,What is the expected sum of a randomly chosen range of numbers?,ai,2013-01-29T20:58:30,2016-09-09T09:28:39,,,,"Given an a list D of N integers, and an integer T, two numbers L and R are randomly chosen such that 0 ≤ L ≤ R < N. + +What is the expected sum of the subarray {d[L]...d[R]} given that (sum{d[L],...d[R]} <= T)? + +**Input Format:** + +The first line will contain two numbers: N and T. N lines follow, each containing one number from list D. + +**Output Format:** + +Output one number P, the expected sum of D[L]...D[R] upto 9 decimal places. + +**Constraints:** + +1 <= N < 100000 + +0 <= D[i] < 10^7 + +0 < T <= 10^9 + +**Sample Input:** +
+5 10
+4 
+5 
+3 
+7
+1
+
+ +**Sample Output:** +
6.111111111
+ +**Explaination** + +[4],[5],[3],[7],[1],[4,5],[5,3],[3,7],[7,1] subarrays satisfy the property. + +4 + 5 + 3 + 7 + 1 + 9 + 8 + 10 + 8 = 55 + +55/9 = 6.11111111 + +",0.495260664,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,"Random Sum - Expected Sum Solution by Siddharth Bora","

Random Sum - Expected Sum

+ +

Idea: Two-Pointer

+ +

Short Explanation: +You are expected to have the read the solution to Random Sum problem as the two-pointer idea is carried forward from that. +The problem asks us to give the expected sum of the arrays that have been found in the previous problem. This can be done maintaing a cumulative sum and a cumulative of cumulative sum and keeping a total sum that is updated as we calculate the count moving the two pointers as in the previous problem.

+ +

Long Explanation: +We pre-calculate two arrays. Firstly a cumulative sum and then a cumulative of cumulative sum. The first of these gives the sum of number from the starting to a particular index. The second gives us the sum of all the sequences that start at index 0 and end at indices from 0 to i basically the ith value will be ele0 + (ele0 + ele 1) +...+ (ele0+..+elei) where elex is the xth element in the array. +Now since we need the sum of all the sequences that sum to <= T, we augment the previous question (Random Sum) solution to find the total sum too. Basically whenever we have an l,r we can calculate the sum of all sequences starting at l and ending at indices between l and r(left end inclusive) by +cumcumsum[r-1]-((l>0)?cumcumsum[l-1]:0)-(r-l)*((l>0)?cumsum[l-1]:0); +where cumcumsum is the cumulative of cumulative sum array and cumsum is the cumulative sum array. Here we are subtracting all cumulative sums less than l and also subtracting the portion of cumcumsum[r-1] which extends to the left of l namely the third term. This gives us the cumulative sum and finally we simply have to divide this by the previous answer to get the expected value.

+ +

Language : C++

+ +
using namespace std;
+#include <cmath>
+#include <cstdio>
+#include <list>
+#include <map>
+#include <set>
+#include <queue>
+#include <deque>
+#include <stack>
+#include <bitset>
+#include <string>
+#include <vector>
+#include <iostream>
+#include <sstream>
+#include <algorithm>
+#define all(c) (c).begin(),(c).end()
+#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
+typedef long long ll; 
+typedef pair<int,int> pii; 
+#define FOR(i,n) for (int i = 0; i < n; i++)
+#define SZ(x) ((int)x.size())
+#define PB push_back
+#define MP make_pair
+#define sf(x) scanf(""%d"",&x)
+#define pf(x) printf(""%d\n"",x)
+#define split(str) {vs.clear();istringstream ss(str);while(ss>>(str))vs.push_back(str);}
+#define PI 3.141592653589793
+int main()
+{
+  ll count=0;
+  ll count2=0;
+  int n,t;
+  sf(n);sf(t);
+  ll sum=0;
+  int l=0;
+  int r=-1;
+  vector<int> v;
+  while(n--)
+  {
+    int a;
+    sf(a);
+    v.PB(a);
+  }
+  vector<ll> cumsum;
+  FOR(i,v.size())
+    cumsum.PB(v[i]);
+  for(int i=1;i<v.size();i++)
+    cumsum[i]+=cumsum[i-1];
+
+  vector<ll> cumcumsum;
+  FOR(i,v.size())
+    cumcumsum.PB(cumsum[i]);
+  for(int i=1;i<v.size();i++)
+    cumcumsum[i]+=cumcumsum[i-1];
+ // FOR(i,v.size())
+   // cout<<cumcumsum[i]<<endl;
+  while(l<v.size())
+  {
+    //cout<<r<<"" ""<<(r<v.size())<<"" ""<<(sum<=t)<<endl;
+    while(r<(int)v.size() && sum<=t)
+    {
+      //cout<<""hello""<<endl;
+      //count2+=cumsum[r];
+      r++;
+      if(r<v.size())
+      {
+    sum+=v[r];
+      }
+    }
+    if(r-l>0)
+    {  count+=r-l;
+    //cout<<r<<"" ""<<l<<endl;
+    count2+=cumcumsum[r-1]-((l>0)?cumcumsum[l-1]:0)-(r-l)*((l>0)?cumsum[l-1]:0);
+    }
+    sum-=v[l];
+    l++;
+  }
+  //cout<<count2<<endl;
+  //cout<<count<<endl;
+  double ans=count2*1.0/count;
+  printf(""%.9lf\n"",ans);
+}
+
",0.0,randexpsum,2013-03-04T16:26:12,"{""contest_participation"":6014,""challenge_submissions"":421,""successful_submissions"":210}",2013-03-04T16:26:12,2016-05-13T00:04:48,tester," using namespace std; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #define all(c) (c).begin(),(c).end() + #define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) + typedef long long ll; + typedef pair pii; + #define FOR(i,n) for (int i = 0; i < n; i++) + #define SZ(x) ((int)x.size()) + #define PB push_back + #define MP make_pair + #define sf(x) scanf(""%d"",&x) + #define pf(x) printf(""%d\n"",x) + #define split(str) {vs.clear();istringstream ss(str);while(ss>>(str))vs.push_back(str);} + #define PI 3.141592653589793 + int main() + { + ll count=0; + ll count2=0; + int n,t; + sf(n);sf(t); + ll sum=0; + int l=0; + int r=-1; + vector v; + while(n--) + { + int a; + sf(a); + v.PB(a); + } + vector cumsum; + FOR(i,v.size()) + cumsum.PB(v[i]); + for(int i=1;i cumcumsum; + FOR(i,v.size()) + cumcumsum.PB(cumsum[i]); + for(int i=1;i0) + { count+=r-l; + //cout<0)?cumcumsum[l-1]:0)-(r-l)*((l>0)?cumsum[l-1]:0); + } + sum-=v[l]; + l++; + } + //cout<.MathJax_SVG_Display {text-align: center; margin: 1em 0em; position: relative; display: block!important; text-indent: 0; max-width: none; max-height: none; min-width: 0; min-height: 0; width: 100%} +.MathJax_SVG .MJX-monospace {font-family: monospace} +.MathJax_SVG .MJX-sans-serif {font-family: sans-serif} +.MathJax_SVG {display: inline; font-style: normal; font-weight: normal; line-height: normal; font-size: 100%; font-size-adjust: none; text-indent: 0; text-align: left; text-transform: none; letter-spacing: normal; word-spacing: normal; word-wrap: normal; white-space: nowrap; float: none; direction: ltr; max-width: none; max-height: none; min-width: 0; min-height: 0; border: 0; padding: 0; margin: 0} +.MathJax_SVG * {transition: none; -webkit-transition: none; -moz-transition: none; -ms-transition: none; -o-transition: none} +.mjx-svg-href {fill: blue; stroke: blue} +

N Puzzle

+ +

N Puzzle is a sliding blocks game that takes place on a k * k grid with k * k - 1 tiles +each numbered from 1 to N. Your task is to reposition the tiles in their proper order

+ +

Difficulty Level

+ +

Medium ( Implementation heavy )

+ +

Problem Setter

+ +

Dheeraj M R

+ +

Required Knowledge

+ +

A* algorithm

+ +

Approach

+ +

N-Puzzle is a classic 1 player game that teaches the basics of heuristics in arriving at +solutions in Artificial Intelligence.

+ +

Let us consider for the sake of simplicity, N = 8

+ +

The final configuration of an 8 - puzzle will look like

+ +
0 1 2
+3 4 5
+6 7 8
+
+ +

A* algorithm talks about a cost function +and a heuristic.

+ +

cost = heuristic_cost + #of steps taken to reach the current state.

+ +

the tiles are numbered. For a given unsolved 8 - puzzle configuration say

+ +
0 3 8
+4 1 7
+2 6 5
+
+ +

We use 2 heuristics for every state and at every iteration

+ +

1 such heuristic is

+ +

h1 => The number of misplaced tiles.

+ +

In the above example, the number of misplaced tiles are 8

+ +

2nd heuristic we use is

+ +

h2 => The manahattan distance between a tile's original position to its current position.

+ +

In the above example, the manhattan distance for all tiles are as follows

+ +

ab => where a is the manhattan distance of tile b.

+ +

h2 = 23 + 28 + 14 + 11 + 27 + 42 + 16 + 15

+ +

h2 = 14

+ +

Given 2 heuristics, it is always advised to use the maximum as the maximum never underestimates the cost to reach the +required end state ( initial configuration of 8 Puzzle )

+ +

If it took 10 moves to reach the current state as shown above, then the cost function of a given state of N - puzzle

+ +

is given as

+ +
cost = max( h1, h2 ) + 10
+
+cost = max( 14, 8 ) + 10 = 24
+
+ +

We can then implement a priority queue and record each of possible moves from a given initial state of the board +and then pop the state with the lowest cost function. This procedure is guaranteed to give us a solution.

+ +

Problem Setter's code: C++

+ +

here

",0.0,may-2020-editorial-npuzzle,2013-06-10T13:14:35,"{""contest_participation"":3663,""challenge_submissions"":135,""successful_submissions"":0}",2013-06-10T13:14:35,2016-05-13T00:04:45,setter," #include + #include + #include + #include + #include + #include + + #define INRANGE(i, a, b) (i >= a && i < b) + + using namespace std; + + + class SlidingBlock + { + public: + vector < int > disc; + int n; + int cost; + int empty_slot; + vector< string > record_move; + SlidingBlock(); + SlidingBlock( int ); + SlidingBlock( vector < int >, vector < string > ); + vector < string > getMove(); + void makeMove( const string move = string() ); + bool solved(); + vector < SlidingBlock > branches(); + void setCost(); + void print(); + void readBlock(); + bool operator< ( const SlidingBlock& ) const; + bool operator> ( const SlidingBlock& ) const; + }; + + SlidingBlock::SlidingBlock() + { + SlidingBlock( 3 ); + } + + SlidingBlock::SlidingBlock( int size ) + { + n = size; + } + + void SlidingBlock::readBlock() + { + int temp; + for( int i = 0; i < n; i++ ) + { + for( int j = 0; j < n; j++ ) + { + cin >> temp; + disc.push_back( temp ); + } + } + int pos = std::abs( std::distance( find( disc.begin(), disc.end(), 0 ), disc.begin()) ); + empty_slot = pos; + setCost(); + + } + + SlidingBlock::SlidingBlock( vector < int > node, vector < string > moves ) + { + disc.clear(); + n = ( int )sqrt( node.size() ); + for( int i = 0; i < ( int )node.size(); ++i ) + { + disc.push_back( node[ i ] ); + if( node[ i ] == 0 ) + empty_slot = i; + } + + for( int i = 0; i < moves.size(); i++ ) + record_move.push_back( moves[ i ] ); + setCost(); + } + + void SlidingBlock::setCost() + { + int h1 = 0 , h2 = 0; + //setting heuristic 1 => number of misplaced blocks + //setting heuristic 2 => distance of the node to its block + for( int i = 0; i < n; i++ ) + { + for( int j = 0; j < n; j++ ) + { + + int val = disc[ n * i + j ]; + if( val != n * i + j && val != 0 ) + { + h1 += 1; + int exp_pos_x = ( val ) / n; + int exp_pos_y = ( val ) % n; + h2 += abs( i - exp_pos_x ) + abs( j - exp_pos_y ); + } + } + } + cost = max( h1, h2) + this->record_move.size(); + } + + vector < string > SlidingBlock::getMove() + { + vector < string > movements; + if( empty_slot/n > 0 ) + movements.push_back( ""UP"" ); + if( empty_slot%n > 0 ) + movements.push_back( ""LEFT"" ); + if( empty_slot/n < n - 1 ) + movements.push_back( ""DOWN"" ); + if( empty_slot%n < n - 1 ) + movements.push_back( ""RIGHT"" ); + + return movements; + } + + void SlidingBlock::makeMove( string move ) + { + if( move.empty() ) + { + vector < string > moves = getMove(); + int rand_point_index = rand() % moves.size(); + makeMove( moves[ rand_point_index ] ); + } + else + { + record_move.push_back( move ); + int temp = empty_slot; + if( move.compare(""UP"") == 0 ) + empty_slot -= n; + if( move.compare(""DOWN"") == 0 ) + empty_slot += n; + if( move.compare(""LEFT"") == 0 ) + empty_slot -= 1; + if( move.compare(""RIGHT"") == 0 ) + empty_slot += 1; + swap( disc[ temp ], disc[ empty_slot ] ); + } + setCost(); + } + + bool SlidingBlock::solved() + { + bool answer = true; + for( int i = 0; i < n; i++ ) + { + for( int j = 0; j < n; j++ ) + { + answer &= disc[ n * i + j ] == ( n * i + j ); + } + } + return answer; + } + + vector < SlidingBlock > SlidingBlock::branches() + { + vector < string > moves = getMove(); + vector < SlidingBlock > valid_branches; + for( int i = 0; i < ( int )moves.size(); ++i ) + { + valid_branches.push_back( SlidingBlock( disc , record_move ) ); + valid_branches[ i ].makeMove( moves[ i ] ); + } + return valid_branches; + } + + void SlidingBlock::print() + { + for( int i = 0; i < n; i++ ) + { + for( int j = 0; j < n; j++ ) + { + cout << disc[ n*i + j ] << "" ""; + } + cout << endl; + } + } + + bool SlidingBlock::operator< ( const SlidingBlock& node ) const + { + for( int i = 0; i < ( int )node.disc.size(); i++ ) + { + if( node.disc[ i ] < this->disc[ i ] ) + { + return true; + } + else if( node.disc[ i ] > this->disc[ i ] ) + { + return false; + } + else + { + continue; + } + } + return false; + } + + bool SlidingBlock::operator> ( const SlidingBlock& node ) const + { + for( int i = 0; i < ( int )node.disc.size(); i++ ) + { + if( node.disc[ i ] > this->disc[ i ] ) + { + return true; + } + else if( node.disc[ i ] < this->disc[ i ] ) + { + return false; + } + else + { + continue; + } + } + return false; + } + + struct OrderByCost + { + bool operator() ( const SlidingBlock &a, const SlidingBlock &b ) const + { + return a.cost >= b.cost; + } + }; + + class Search + { + public: + SlidingBlock start; + priority_queue< SlidingBlock, vector < SlidingBlock >, OrderByCost > pq; + set< SlidingBlock > explored; + vector < SlidingBlock > expanded; + + Search( int n ) + { + start = SlidingBlock( n ); + start.readBlock(); + searchAndPrint(); + } + + void searchAndPrint() + { + pushNode( start ); + SlidingBlock node = SlidingBlock( start.disc, start.record_move ); + setExplored( node ); + while( !node.solved() ) + { + node = getNextNode(); + expanded.push_back( node ); + vector < SlidingBlock > valid_branches = node.branches(); + //Iterate over neighbors + for( int i = 0; i < ( int ) valid_branches.size(); i++ ) + { + if( !isExplored( valid_branches[ i ] ) ) + { + pushNode( valid_branches[ i ] ); + setExplored( node ); + } + } + } + cout << node.record_move.size() << endl; + + for( auto i = node.record_move.begin(); i != node.record_move.end(); ++i ) + cout << *i << endl; + + } + + void pushNode( SlidingBlock node ) + { + pq.push( node ); + } + + void setExplored( SlidingBlock node ) + { + explored.insert( node ); + } + + bool isExplored( SlidingBlock node ) + { + return explored.count( node ) > 0; + } + + SlidingBlock getNextNode() + { + SlidingBlock node = pq.top(); + pq.pop(); + return node; + } + }; + + int main() + { + set< SlidingBlock > explored; + int n; + cin >> n; + Search *game = new Search( n ); + }",not-set,2016-04-24T02:02:11,2016-04-24T02:02:11,C++ +2,746,game-of-throne-ii,Game Of Thrones - II,"This follows from [Game of Thrones - I](https://www.hackerrank.com/contests/july13/challenges/game-of-thrones). + +Now that the king knows how to find out whether a given word has an [anagram](https://en.wikipedia.org/wiki/Anagram) which is a [palindrome](http://en.wikipedia.org/wiki/Palindrome) or not, he encounters another challenge. He realizes that there can be more than one palindrome anagrams for a given word. Can you help him find out how many palindrome anagrams are possible for a given word ? + +The king has many words. For each given word, he needs to find out the number of palindrome anagrams of the string. As the number of anagrams can be large, the king needs the number of anagrams % (109+ 7). + +**Input format :**
+A single line which contains the input string
+ +**Output format :** +A single line which contains the number of anagram strings which are palindrome % (109 + 7). + +**Constraints :** +1<=length of string <= 10^5 +Each character of the string is a lowercase alphabet. +Each test case has at least 1 anagram which is a palindrome. + +**Sample Input 01 :** + + aaabbbb + +**Sample Output 01 :** + + 3 + +**Explanation :** +Three palindrome permutations of the given string are abbabba , bbaaabb and bababab. + +**Sample Input 02 :** + + cdcdcdcdeeeef + +**Sample Output 02 :** + + 90 +",code,Can you help the king find the number of ways his door can be unlocked?,ai,2013-07-02T17:07:43,2022-09-02T09:54:54,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts STRING s as parameter. +# + +def solve(s): + # 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') + + s = input() + + result = solve(s) + + fptr.write(str(result) + '\n') + + fptr.close() +","This follows from [Game of Thrones - I](https://www.hackerrank.com/contests/july13/challenges/game-of-thrones). + +Now that the king knows how to find out whether a given word has an [anagram](https://en.wikipedia.org/wiki/Anagram) which is a [palindrome](http://en.wikipedia.org/wiki/Palindrome) or not, he encounters another challenge. He realizes that there can be more than one palindrome anagrams for a given word. Can you help him find out how many palindrome anagrams are possible for a given word ? + +The king has many words. For each given word, he needs to find out the number of palindrome anagrams of the string. As the number of anagrams can be large, the king needs the number of anagrams % (109+ 7). + +**Input format :**
+A single line which contains the input string
+ +**Output format :** +A single line which contains the number of anagram strings which are palindrome % (109 + 7). + +**Constraints :** +1<=length of string <= 10^5 +Each character of the string is a lowercase alphabet. +Each test case has at least 1 anagram which is a palindrome. + +**Sample Input 01 :** + + aaabbbb + +**Sample Output 01 :** + + 3 + +**Explanation :** +Three palindrome permutations of the given string are abbabba , bbaaabb and bababab. + +**Sample Input 02 :** + + cdcdcdcdeeeef + +**Sample Output 02 :** + + 90 +",0.5016778523489933,"[""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,20/20 Hack July Editorial: Game of Thrones - 2,"

Game Of Thrones - II

+ +

Problem: Given a string such that at least one of anagram of string is palindrome. Tell how many anagram of given string will be palindrome.

+ +

Difficulty level: Easy
+Required Knowledge: Permutations, Modular Inverse
+Time Complexity: O(N)

+ +

Approach: Given a string tell how many anagram of given string will be palindrome. So we can consider a sub-string which we can get by taking half of number of each character. length of this sub-string will L/2 where L is length of original string. we can get permutation of given string then we can concatenate the reverse of given half. so get anagram of given string which will be palindrome.So, we can use following formula to get number of permutation of given first half.

+ +

So , as answer can be very huge . But as in question we are asked for number of permutations which are palindrome % 10^9+7 and we know 10^9 + 7 is a prime number . So, we can get it using modular inverse techniques.

+ +

Problem Setter's code:

+ +
#!/usr/bin/py
+from collections import Counter
+
+mod = 10**9 + 7
+
+def hasPalindrome(word):
+    x = Counter(word)
+    count = 0
+    for i in x:
+        if x[i]%2!=0:
+            count += 1
+
+    if count > 1:
+        return False
+    else:
+        return True
+
+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__':
+    word = raw_input()
+    assert 1 <= len(word) <= 10**5
+    assert hasPalindrome(word) == True
+    counter = Counter(word)
+    denominator = 1
+    numerator = 0
+    for i in counter:
+        numerator += counter[i]/2
+        denominator = ((denominator%mod)*(getfactmod(counter[i]/2)%mod))%mod
+
+    numerator = getfactmod(numerator)
+    answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod
+    print answer
+
+ +

Tester's code:

+ +
#include <cstdio>
+#include <cstring>
+#include <bits/stdc++.h>
+
+using namespace std;
+int t;
+const long long mod = 1000000007;
+
+long long pow(long long osn){
+    long long res = 1, tmp = osn;
+    int m = int(mod - 2);
+    while(m){
+        if(m % 2){
+            res = (res * tmp) % mod;
+            --m;
+        }
+        m >>= 1;
+        tmp = (tmp * tmp) % mod;
+    }
+    return res;
+}
+
+long long fact(int num){
+    long long res(1), curp(num);
+    while(curp)res = (res * curp--) % mod;
+    return res;
+}
+
+int obr(){
+    int num[256];
+    memset(num, 0, sizeof(num));
+    char s[1001];
+    cin>>s;
+    int n = strlen(s);
+    for(int i = 0; i < n; ++i)++num[s[i]];
+    for(int i=0 ; i<256 ; i++)
+        num[i] = num[i]/2;
+    n = n/2;
+    long long res = fact(n);
+    for(int i = 'a'; i <= 'z'; ++i)
+        if(num[i])res = (res * pow(fact(num[i]))) % mod;
+    for(int i = 'A'; i <= 'Z'; ++i)
+        if(num[i])res = (res * pow(fact(num[i]))) % mod;
+    int topr = int(res);
+    printf(""%d\n"", topr);
+    return 0;
+}
+
+int main(){
+    t = 1;
+    for(int i = 0; i < t; ++i)
+        obr();
+    return 0;
+}
+
",0.0,july-2020-editorial-game-of-thrones-ii,2013-07-22T04:35:37,"{""contest_participation"":4325,""challenge_submissions"":1181,""successful_submissions"":695}",2013-07-22T04:35:37,2016-12-02T19:33:05,setter,"###Python 2 +```python +#!/usr/bin/py +from collections import Counter + +mod = 10**9 + 7 + +def hasPalindrome(word): + x = Counter(word) + count = 0 + for i in x: + if x[i]%2!=0: + count += 1 + + if count > 1: + return False + else: + return True + +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__': + word = raw_input() + assert 1 <= len(word) <= 10**5 + assert hasPalindrome(word) == True + counter = Counter(word) + denominator = 1 + numerator = 0 + for i in counter: + numerator += counter[i]/2 + denominator = ((denominator%mod)*(getfactmod(counter[i]/2)%mod))%mod + + numerator = getfactmod(numerator) + answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod + print answer +``` +",not-set,2016-04-24T02:02:12,2016-07-23T18:36:16,Python +3,746,game-of-throne-ii,Game Of Thrones - II,"This follows from [Game of Thrones - I](https://www.hackerrank.com/contests/july13/challenges/game-of-thrones). + +Now that the king knows how to find out whether a given word has an [anagram](https://en.wikipedia.org/wiki/Anagram) which is a [palindrome](http://en.wikipedia.org/wiki/Palindrome) or not, he encounters another challenge. He realizes that there can be more than one palindrome anagrams for a given word. Can you help him find out how many palindrome anagrams are possible for a given word ? + +The king has many words. For each given word, he needs to find out the number of palindrome anagrams of the string. As the number of anagrams can be large, the king needs the number of anagrams % (109+ 7). + +**Input format :**
+A single line which contains the input string
+ +**Output format :** +A single line which contains the number of anagram strings which are palindrome % (109 + 7). + +**Constraints :** +1<=length of string <= 10^5 +Each character of the string is a lowercase alphabet. +Each test case has at least 1 anagram which is a palindrome. + +**Sample Input 01 :** + + aaabbbb + +**Sample Output 01 :** + + 3 + +**Explanation :** +Three palindrome permutations of the given string are abbabba , bbaaabb and bababab. + +**Sample Input 02 :** + + cdcdcdcdeeeef + +**Sample Output 02 :** + + 90 +",code,Can you help the king find the number of ways his door can be unlocked?,ai,2013-07-02T17:07:43,2022-09-02T09:54:54,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts STRING s as parameter. +# + +def solve(s): + # 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') + + s = input() + + result = solve(s) + + fptr.write(str(result) + '\n') + + fptr.close() +","This follows from [Game of Thrones - I](https://www.hackerrank.com/contests/july13/challenges/game-of-thrones). + +Now that the king knows how to find out whether a given word has an [anagram](https://en.wikipedia.org/wiki/Anagram) which is a [palindrome](http://en.wikipedia.org/wiki/Palindrome) or not, he encounters another challenge. He realizes that there can be more than one palindrome anagrams for a given word. Can you help him find out how many palindrome anagrams are possible for a given word ? + +The king has many words. For each given word, he needs to find out the number of palindrome anagrams of the string. As the number of anagrams can be large, the king needs the number of anagrams % (109+ 7). + +**Input format :**
+A single line which contains the input string
+ +**Output format :** +A single line which contains the number of anagram strings which are palindrome % (109 + 7). + +**Constraints :** +1<=length of string <= 10^5 +Each character of the string is a lowercase alphabet. +Each test case has at least 1 anagram which is a palindrome. + +**Sample Input 01 :** + + aaabbbb + +**Sample Output 01 :** + + 3 + +**Explanation :** +Three palindrome permutations of the given string are abbabba , bbaaabb and bababab. + +**Sample Input 02 :** + + cdcdcdcdeeeef + +**Sample Output 02 :** + + 90 +",0.5016778523489933,"[""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,20/20 Hack July Editorial: Game of Thrones - 2,"

Game Of Thrones - II

+ +

Problem: Given a string such that at least one of anagram of string is palindrome. Tell how many anagram of given string will be palindrome.

+ +

Difficulty level: Easy
+Required Knowledge: Permutations, Modular Inverse
+Time Complexity: O(N)

+ +

Approach: Given a string tell how many anagram of given string will be palindrome. So we can consider a sub-string which we can get by taking half of number of each character. length of this sub-string will L/2 where L is length of original string. we can get permutation of given string then we can concatenate the reverse of given half. so get anagram of given string which will be palindrome.So, we can use following formula to get number of permutation of given first half.

+ +

So , as answer can be very huge . But as in question we are asked for number of permutations which are palindrome % 10^9+7 and we know 10^9 + 7 is a prime number . So, we can get it using modular inverse techniques.

+ +

Problem Setter's code:

+ +
#!/usr/bin/py
+from collections import Counter
+
+mod = 10**9 + 7
+
+def hasPalindrome(word):
+    x = Counter(word)
+    count = 0
+    for i in x:
+        if x[i]%2!=0:
+            count += 1
+
+    if count > 1:
+        return False
+    else:
+        return True
+
+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__':
+    word = raw_input()
+    assert 1 <= len(word) <= 10**5
+    assert hasPalindrome(word) == True
+    counter = Counter(word)
+    denominator = 1
+    numerator = 0
+    for i in counter:
+        numerator += counter[i]/2
+        denominator = ((denominator%mod)*(getfactmod(counter[i]/2)%mod))%mod
+
+    numerator = getfactmod(numerator)
+    answer = ((numerator%mod)*(inversemod(denominator)%mod))%mod
+    print answer
+
+ +

Tester's code:

+ +
#include <cstdio>
+#include <cstring>
+#include <bits/stdc++.h>
+
+using namespace std;
+int t;
+const long long mod = 1000000007;
+
+long long pow(long long osn){
+    long long res = 1, tmp = osn;
+    int m = int(mod - 2);
+    while(m){
+        if(m % 2){
+            res = (res * tmp) % mod;
+            --m;
+        }
+        m >>= 1;
+        tmp = (tmp * tmp) % mod;
+    }
+    return res;
+}
+
+long long fact(int num){
+    long long res(1), curp(num);
+    while(curp)res = (res * curp--) % mod;
+    return res;
+}
+
+int obr(){
+    int num[256];
+    memset(num, 0, sizeof(num));
+    char s[1001];
+    cin>>s;
+    int n = strlen(s);
+    for(int i = 0; i < n; ++i)++num[s[i]];
+    for(int i=0 ; i<256 ; i++)
+        num[i] = num[i]/2;
+    n = n/2;
+    long long res = fact(n);
+    for(int i = 'a'; i <= 'z'; ++i)
+        if(num[i])res = (res * pow(fact(num[i]))) % mod;
+    for(int i = 'A'; i <= 'Z'; ++i)
+        if(num[i])res = (res * pow(fact(num[i]))) % mod;
+    int topr = int(res);
+    printf(""%d\n"", topr);
+    return 0;
+}
+
+int main(){
+    t = 1;
+    for(int i = 0; i < t; ++i)
+        obr();
+    return 0;
+}
+
",0.0,july-2020-editorial-game-of-thrones-ii,2013-07-22T04:35:37,"{""contest_participation"":4325,""challenge_submissions"":1181,""successful_submissions"":695}",2013-07-22T04:35:37,2016-12-02T19:33:05,tester,"###C++ +```cpp +#include +#include +#include + +using namespace std; +int t; +const long long mod = 1000000007; + +long long pow(long long osn){ + long long res = 1, tmp = osn; + int m = int(mod - 2); + while(m){ + if(m % 2){ + res = (res * tmp) % mod; + --m; + } + m >>= 1; + tmp = (tmp * tmp) % mod; + } + return res; +} + +long long fact(int num){ + long long res(1), curp(num); + while(curp)res = (res * curp--) % mod; + return res; +} + +int obr(){ + int num[256]; + memset(num, 0, sizeof(num)); + char s[1001]; + cin>>s; + int n = strlen(s); + for(int i = 0; i < n; ++i)++num[s[i]]; + for(int i=0 ; i<256 ; i++) + num[i] = num[i]/2; + n = n/2; + long long res = fact(n); + for(int i = 'a'; i <= 'z'; ++i) + if(num[i])res = (res * pow(fact(num[i]))) % mod; + for(int i = 'A'; i <= 'Z'; ++i) + if(num[i])res = (res * pow(fact(num[i]))) % mod; + int topr = int(res); + printf(""%d\n"", topr); + return 0; +} + +int main(){ + t = 1; + for(int i = 0; i < t; ++i) + obr(); + return 0; +} +``` +",not-set,2016-04-24T02:02:12,2016-07-23T18:36:38,C++ +4,791,kth-ancestor,Kth Ancestor,"A tree of P nodes is an un-directed connected graph having P-1 edges. Let us denote R as the root node. If A is a node such that it is at a distance of L from R, and B is a node such that it is at at distance of L+1 from +R and A is connected to B, then we call A as the parent of B. + +Similarly, if A is at a distance of L from R and B is at a distance of L+K from R and there is a path of length K from A to B, then we call A as the Kth parent of B. + +Susan likes to play with graphs and Tree data structure is one of her favorites. She has designed a problem and wants to know if anyone can solve it. Sometimes she adds or removes a leaf node. Your task is to figure out the K-th parent of a node at any instant. + +**Input Format** +The first line contain an integer T denoting the number of test-cases. T test cases follow. First line of each test case contains an integer P, the number of nodes in the tree. +P lines follows each containing two integers X and Y separated by a single space denoting Y as the parent of X. if Y is 0, then X is the root node of the tree. (0 is for namesake and is not in the tree). +The next line contains an integer Q, the number of queries. +Q lines follow each containing a query. + + ++ 0 Y X : X is added as a new leaf node whose parent is Y ++ 1 X : This tells that leaf node X is removed from the tree ++ 2 X K : In this query output the Kth parent of X + +**Note** + +Each node index is any number between 1 and 105 i.e., a tree with a single node can have its root indexed as 105 + +**Output Format** +For each query of type 2, output the Kth parent of X. If Kth parent doesn't exist, output 0 and if the node doesn't exist, output 0. + +**Constraints** +1<=T<=3 +1<=P<=105 +1<=Q<=105 +1<=X<=105 +0<=Y<=105 +1<=K<=105 + +**Sample Input** + + 2 + 7 + 2 0 + 5 2 + 3 5 + 7 5 + 9 8 + 8 2 + 6 8 + 10 + 0 5 15 + 2 15 2 + 1 3 + 0 15 20 + 0 20 13 + 2 13 4 + 2 13 3 + 2 6 10 + 2 11 1 + 2 9 1 + 1 + 10000 0 + 3 + 0 10000 4 + 1 4 + 2 4 1 + +**Sample Output** + + 2 + 2 + 5 + 0 + 0 + 8 + 0 + +**Explanation** + +There are 2 test cases. The first test case has 7 nodes with 2 as its root. There are 10 queries + ++ 0 5 15 -> 15 is added as a leaf node to 5. ++ 2 15 2 -> 2nd parent of 15 is 15->5->2 is 2. ++ 1 3 -> leaf node 3 is removed from the tree. ++ 0 15 20 -> 20 is added as a leaf node to 15. ++ 0 20 13 -> 13 is added as a leaf node to 20. ++ 2 13 4 -> 4th parent of 13 is 2. ++ 2 13 3 -> 3rd parent of 13 is 5. ++ 2 6 10 -> there is no 10th parent of 6 and hence 0. ++ 2 11 1 -> 11 is not a node in the tree, hence 0. ++ 2 9 1 -> 9's parent is 8. + +the second testcase has a tree with only 1 node (100000). + ++ 0 10000 4 -> 4 is added as a leaf node to 10000. ++ 1 4 -> 4 is removed. ++ 2 4 1 -> as 4 is already removed, answer is 0. ",code,Figure out the K-th parent of a node at any instant.,ai,2013-08-01T18:06:31,2022-08-31T08:14:29,,,,"A tree of $P$ nodes is an un-directed connected graph having $P-1$ edges. Let us denote $R$ as the root node. If $A$ is a node such that it is at a distance of $L$ from $R$, and $B$ is a node such that it is at at distance of $L+1$ from +$R$ and $A$ is connected to $B$, then we call $A$ as the parent of $B$. + +Similarly, if $A$ is at a distance of $L$ from $R$ and $B$ is at a distance of $L+K$ from $R$ and there is a path of length $K$ from $A$ to $B$, then we call $A$ as the $K$th parent of $B$. + +Susan likes to play with graphs and Tree data structure is one of her favorites. She has designed a problem and wants to know if anyone can solve it. Sometimes she adds or removes a leaf node. Your task is to figure out the $K$th parent of a node at any instant. +",0.4352941176470588,"[""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""]","The first line contain an integer $T$ denoting the number of test cases. $T$ test cases follow. First line of each test case contains an integer $P$, the number of nodes in the tree. +$P$ lines follows each containing two integers $X$ and $Y$ separated by a single space denoting $Y$ as the parent of $X$. If $Y$ is $0$, then X is the root node of the tree. ($0$ is for namesake and is not in the tree). +The next line contains an integer $Q$, the number of queries. +$Q$ lines follow each containing a query. + + ++ $0$ $Y$ $X$ : $X$ is added as a new leaf node whose parent is $Y$ . $X$ is not in the tree while $Y$ is in. ++ $1$ $X$ : This tells that leaf node $X$ is removed from the tree. $X$ is a leaf in the tree. ++ $2$ $X$ $K$ : In this query output the $K$th parent of $X$ . $X$ is a node in the tree. + +**Note** + ++ Each node index is any number between 1 and 105 i.e., a tree with a single node can have its root indexed as 105 +","For each query of type $2$, output the $K$th parent of $X$. If $K$th parent doesn't exist, output $0$ and if the node doesn't exist, output $0$. +"," 2 + 7 + 2 0 + 5 2 + 3 5 + 7 5 + 9 8 + 8 2 + 6 8 + 10 + 0 5 15 + 2 15 2 + 1 3 + 0 15 20 + 0 20 13 + 2 13 4 + 2 13 3 + 2 6 10 + 2 11 1 + 2 9 1 + 1 + 10000 0 + 3 + 0 10000 4 + 1 4 + 2 4 1 +"," 2 + 2 + 5 + 0 + 0 + 8 + 0 +",Hard,Kth Parent : August 2020 Editorial,"

Problem Statement

+ +

Susan needs to find the kth parent of a node in the tree.

+ +

Difficulty level Medium

+ +

Required Knowledge Trees, Binary Logic

+ +

Time Complexity O(NlogN)

+ +

Approach

+ +

The naive approach for this problem is very obvious. Just store the parent of each node and find the kth parent by finding parent of each parent. But as the number of queries are large, this approach in the worst case (example: tree having only two leaf nodes) exceeds time limit.

+ +

The pick of the problem is that, instead of storing the parent of every node, we store all 2ith parent of a node i.e. 20th , 21st, 22th ... parent for each node.

+ +

Now for finding kth parent of a node A,

+ +

Let,
+k = (bl-1bl-2....b0) in binary representation be a l-bit number k.

+ +

So k = b0 + b1 * 21 + ... + bl-2 * 2l-2 + bl-1 * 2l-1

+ +

Let s bits of these l bits are 1, p1,p2,...ps be indices at which bit value is 1.
+k = 2p1 + 2p2 + ... + 2ps

+ +

Using above distribution of k, we can find kth node by following procedure.
+A1 = 2p1th parent of A
+A2 = 2p2th parent of A1, implies 2p1th + 2p2th parent of A
+A3 = 2p3th parent of A2 which will also be 2p1th + 2p2th + 2p3th parent of A.

+ +

Similarly
+As = 2psth parent of As-1 and also 2p1th+2p2th .... 2psth parent of A i.e. kth parent of A.

+ +

So it takes only s summations for finding kth parent. Since s is the number of bits in k. +So this process takes O(s) = O(log k) time;

+ +

Now the problem is how to find 2i parents of each node?

+ +

Let parent[i][j] be 2jth parent of node i. +Initially we know parent[i][0] i.e. first parent of all the nodes.

+ +

For j>0

+ +
parent[i][j] =  2^jth parent of i   
+             =  (2^j-1th + 2^j-1th) parent of i   
+             =  2^j-1th parent of (2^j-1th parent of i)    
+             =  2^j-1th parent of parent[i][j-1]   
+             =  parent[parent[i][j-1][j-1]  
+
+ +

The pseudo code is as follows

+ +
for i from 1 to n
+    parent[i][0] = parent of i
+
+for i from 1 to n
+    for j from 1 to m
+        parent[i][j] = parent[parent[i][j-1]][j-1]
+
+ +

In above code, m is the maximum value j can attain. In worst case, the highest value of parent a node can have is n-1.

+ +

2^m<=n-1 +m = O(log n)

+ +

Hence above process takes O(n log n) time as well as O(n log n) space.

+ +

Problem Setter's code

+ +
//shashwat001
+
+#include <cstdio>
+#include <cstring>
+#include <cstdlib>
+#include <cmath>
+#include <iostream>
+#include <string>
+#include <vector>
+#include <set>
+#include <queue>
+#include <stack>
+#include <map>
+#include <utility>
+#include <algorithm>
+#include <cassert>
+
+using namespace std;
+
+#define INF 2147483647
+#define LINF 9223372036854775807
+#define mp make_pair
+#define pb push_back
+
+typedef long long int lli;
+typedef pair<int,int> pi;
+
+int p[100000][40]={{0}};
+int a[100005],isnode[100005];
+int main ()
+{
+
+    int q,ch,x,y,t;
+    scanf(""%d"",&t);
+    assert(t>=1 && t<=3);
+    while(t--)
+    {
+        memset(p,0,sizeof(p));
+        memset(isnode,0,sizeof(isnode));
+        int i,n,j;
+        scanf(""%d"",&n);
+        assert(n>=1 && n<=100000);
+        for(i = 0;i < n;i++)
+        {
+            scanf(""%d %d"",&x,&y);
+            assert(x>=1 && x<=100000);
+            assert(y>=0 && y<=100000);
+            a[i] = x;
+            if(y!=0)
+                assert(isnode[y]==1);
+            assert(isnode[x]==0);
+            isnode[x] = 1;
+            p[x][0] = y;
+        }
+        int lgn = (int)(log(n)/log(2))+1;
+        for(j = 1;j<=lgn;j++)
+        {
+            for(i = 0;i < n;i++)
+            {
+                p[a[i]][j] = p[p[a[i]][j-1]][j-1];
+            }
+        }
+
+        scanf(""%d"",&q);
+        assert(q>0 && q<=100000);
+        for(i = 0;i < q;i++)
+        {
+            scanf(""%d"",&ch);
+            assert(ch>=0 && ch<=2);
+            if(ch == 0) //Add an edge
+            {
+                scanf(""%d %d"",&x,&y);
+
+                assert(y>=1 && y<=100000);
+                assert(x>=1 && x<=100000);
+
+                assert(isnode[x]==1);
+                assert(isnode[y]==0);
+                isnode[y] = 1;
+                p[y][0] = x;
+                j = 0;
+                while(p[y][j]!=0)
+                {
+                    p[y][j+1] = p[p[y][j]][j];
+                    j++;
+                }
+                while(j<=lgn)
+                {
+                    p[y][j] = 0;
+                    j++;
+                }
+            }
+            else if(ch == 1) //Remove an edge
+            {
+                scanf(""%d"",&x);
+                assert(x>=1 && x<=100000);
+                assert(isnode[x]==1);
+                isnode[x] = 0;
+                for(j = 0;j <= lgn;j++)
+                {
+                    p[x][j] = 0;
+                }
+            }
+            else
+            {
+                scanf(""%d %d"",&x,&y);
+                assert(x>=1 && x<=100000);
+                assert(y>=1 && y<=100000);
+                j = 0;
+                while(y>0)
+                {
+                    if(y&1)
+                        x = p[x][j];
+                    y = y>>1;
+                    j++;
+                }
+                printf(""%d\n"",x);
+            }
+        }
+    }
+    return 0;
+}
+
",0.0,aug-2020-editorial-kth-parent,2013-08-13T08:25:00,"{""contest_participation"":3656,""challenge_submissions"":458,""successful_submissions"":180}",2013-08-13T08:25:00,2016-12-02T15:06:47,setter,"###C++ +```cpp +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define INF 2147483647 +#define LINF 9223372036854775807 +#define mp make_pair +#define pb push_back + +typedef long long int lli; +typedef pair pi; + +int p[100000][40]={{0}}; +int a[100005],isnode[100005]; +int main () +{ + + int q,ch,x,y,t; + scanf(""%d"",&t); + assert(t>=1 && t<=3); + while(t--) + { + memset(p,0,sizeof(p)); + memset(isnode,0,sizeof(isnode)); + int i,n,j; + scanf(""%d"",&n); + assert(n>=1 && n<=100000); + for(i = 0;i < n;i++) + { + scanf(""%d %d"",&x,&y); + assert(x>=1 && x<=100000); + assert(y>=0 && y<=100000); + a[i] = x; + if(y!=0) + assert(isnode[y]==1); + assert(isnode[x]==0); + isnode[x] = 1; + p[x][0] = y; + } + int lgn = (int)(log(n)/log(2))+1; + for(j = 1;j<=lgn;j++) + { + for(i = 0;i < n;i++) + { + p[a[i]][j] = p[p[a[i]][j-1]][j-1]; + } + } + + scanf(""%d"",&q); + assert(q>0 && q<=100000); + for(i = 0;i < q;i++) + { + scanf(""%d"",&ch); + assert(ch>=0 && ch<=2); + if(ch == 0) //Add an edge + { + scanf(""%d %d"",&x,&y); + + assert(y>=1 && y<=100000); + assert(x>=1 && x<=100000); + + assert(isnode[x]==1); + assert(isnode[y]==0); + isnode[y] = 1; + p[y][0] = x; + j = 0; + while(p[y][j]!=0) + { + p[y][j+1] = p[p[y][j]][j]; + j++; + } + while(j<=lgn) + { + p[y][j] = 0; + j++; + } + } + else if(ch == 1) //Remove an edge + { + scanf(""%d"",&x); + assert(x>=1 && x<=100000); + assert(isnode[x]==1); + isnode[x] = 0; + for(j = 0;j <= lgn;j++) + { + p[x][j] = 0; + } + } + else + { + scanf(""%d %d"",&x,&y); + assert(x>=1 && x<=100000); + assert(y>=1 && y<=100000); + j = 0; + while(y>0) + { + if(y&1) + x = p[x][j]; + y = y>>1; + j++; + } + printf(""%d\n"",x); + } + } + } + return 0; +} + +``` +",not-set,2016-04-24T02:02:12,2016-07-23T13:56:04,C++ +5,803,help-mike,Help Mike,"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) +",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,setter,"###C++ +```cpp + +#include + +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 + +![image1](https://hr-filepicker.s3.amazonaws.com/angry-children-2-eq-1.png) + +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 + +![image1](https://hr-filepicker.s3.amazonaws.com/angry-children-2-eq-1.png) + +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 ![Image1](https://hr-filepicker.s3.amazonaws.com/period1.png). As we know ![Image1](https://hr-filepicker.s3.amazonaws.com/period1.png) will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define + +![Image2](https://hr-filepicker.s3.amazonaws.com/period2.png) (where x an integer)

and the operation ![Image3](https://hr-filepicker.s3.amazonaws.com/perioda.png) on AC number as: + +![Image4](https://hr-filepicker.s3.amazonaws.com/period4.png) + +This problem is to find the smallest positive integer **n**, such that: + +![Image5](https://hr-filepicker.s3.amazonaws.com/period5.png) + +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 +![image1](https://s3.amazonaws.com/hr-assets/0/1526567764-7f13ff1150-period1.png). As we know ![image1](https://s3.amazonaws.com/hr-assets/0/1526567764-7f13ff1150-period1.png) will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define + +![Image2](https://s3.amazonaws.com/hr-assets/0/1526567811-db0dd614fb-period2.png) (where x an integer)

and the operation ![Image3](https://s3.amazonaws.com/hr-assets/0/1526567834-0366f2bad1-perioda.png) on AC number as: + +![Image4](https://s3.amazonaws.com/hr-assets/0/1526567862-8b1090f7e1-period4.png) + +This problem is to find the smallest positive integer **n**, such that: + +![Image5](https://s3.amazonaws.com/hr-assets/0/1526567879-29dc56cbe4-period5.png) + +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)≅g2kg2I(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 ![Image1](https://hr-filepicker.s3.amazonaws.com/period1.png). As we know ![Image1](https://hr-filepicker.s3.amazonaws.com/period1.png) will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define + +![Image2](https://hr-filepicker.s3.amazonaws.com/period2.png) (where x an integer)

and the operation ![Image3](https://hr-filepicker.s3.amazonaws.com/perioda.png) on AC number as: + +![Image4](https://hr-filepicker.s3.amazonaws.com/period4.png) + +This problem is to find the smallest positive integer **n**, such that: + +![Image5](https://hr-filepicker.s3.amazonaws.com/period5.png) + +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 +![image1](https://s3.amazonaws.com/hr-assets/0/1526567764-7f13ff1150-period1.png). As we know ![image1](https://s3.amazonaws.com/hr-assets/0/1526567764-7f13ff1150-period1.png) will be an irrational number when b is non-zero. In this problem, we call it the AC number. We define + +![Image2](https://s3.amazonaws.com/hr-assets/0/1526567811-db0dd614fb-period2.png) (where x an integer)

and the operation ![Image3](https://s3.amazonaws.com/hr-assets/0/1526567834-0366f2bad1-perioda.png) on AC number as: + +![Image4](https://s3.amazonaws.com/hr-assets/0/1526567862-8b1090f7e1-period4.png) + +This problem is to find the smallest positive integer **n**, such that: + +![Image5](https://s3.amazonaws.com/hr-assets/0/1526567879-29dc56cbe4-period5.png) + +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)≅g2kg2I(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?

+ +
    +
  1. ti <= tj
  2. +
  3. If fi < fj, Ai <= Aj ==> Ai + 2 * fi <= Aj + 2 * fj ==> Bi <= Bj
  4. +
  5. If fi >= fj, Bi <= Bj ==> Bi - 2 * fi <= Bj - 2 * fj ==> Ai <= Aj
  6. +
+ +

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?

+ +
    +
  1. ti <= tj
  2. +
  3. If fi < fj, Ai <= Aj ==> Ai + 2 * fi <= Aj + 2 * fj ==> Bi <= Bj
  4. +
  5. If fi >= fj, Bi <= Bj ==> Bi - 2 * fi <= Bj - 2 * fj ==> Ai <= Aj
  6. +
+ +

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-2Cm-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-2Cm-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

+ +
    +
  1. The Number 100711433 is a prime number , so that we can find its inverse (except when R is not a multiple of 100711433)

  2. +
  3. You need to first tackle all the Updates and then all the Queries.

  4. +
+ +

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

+ +
    +
  1. The Number 100711433 is a prime number , so that we can find its inverse (except when R is not a multiple of 100711433)

  2. +
  3. You need to first tackle all the Updates and then all the Queries.

  4. +
+ +

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 + #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 = 100711433; + const int N = 111111; + + const int V = 111111; + vector g[V]; + vector 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 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; + } + + + +",not-set,2016-04-24T02:02:15,2016-04-24T02:02:15,C++ +25,1058,cube-summation,Cube Summation,"[Chinese Version](https://hr-testcases.s3.amazonaws.com/1058/1058-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/1058/1058_rus.md)
+ +You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. + + UPDATE x y z W + +updates the value of block (x,y,z) to W. + + QUERY x1 y1 z1 x2 y2 z2 + +calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coordinate between y1 and y2 (inclusive) and z coordinate between z1 and z2 (inclusive). + +**Input Format** +The first line contains an integer T, the number of test-cases. T testcases follow. +For each test case, the first line will contain two integers N and M separated by a single space. +N defines the N * N * N matrix. +M defines the number of operations. +The next M lines will contain either + + 1. UPDATE x y z W + 2. QUERY x1 y1 z1 x2 y2 z2 + + +**Output Format** +Print the result for each QUERY. + +**Constrains** +1 <= T <= 50 +1 <= N <= 100 +1 <= M <= 1000 +1 <= x1 <= x2 <= N +1 <= y1 <= y2 <= N +1 <= z1 <= z2 <= N +1 <= x,y,z <= N +-109 <= W <= 109 + +**Sample Input** + + 2 + 4 5 + UPDATE 2 2 2 4 + QUERY 1 1 1 3 3 3 + UPDATE 1 1 1 23 + QUERY 2 2 2 4 4 4 + QUERY 1 1 1 3 3 3 + 2 4 + UPDATE 2 2 2 1 + QUERY 1 1 1 1 1 1 + QUERY 1 1 1 2 2 2 + QUERY 2 2 2 2 2 2 + +**Sample Output** + + 4 + 4 + 27 + 0 + 1 + 1 + +**Explanation** +First test case, we are given a cube of 4 * 4 * 4 and 5 queries. Initially all the cells (1,1,1) to (4,4,4) are 0. +`UPDATE 2 2 2 4` makes the cell (2,2,2) = 4 +`QUERY 1 1 1 3 3 3`. As (2,2,2) is updated to 4 and the rest are all 0. The answer to this query is 4. +`UPDATE 1 1 1 23`. updates the cell (1,1,1) to 23. +`QUERY 2 2 2 4 4 4`. Only the cell (1,1,1) and (2,2,2) are non-zero and (1,1,1) is not between (2,2,2) and (4,4,4). So, the answer is 4. +`QUERY 1 1 1 3 3 3`. 2 cells are non-zero and their sum is 23+4 = 27. +",code,Update and query a 3-d matrix,ai,2013-10-10T09:07:12,2022-08-31T08:33:13,"# +# Complete the 'cubeSum' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. INTEGER n +# 2. STRING_ARRAY operations +# + +def cubeSum(n, operations): + # 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() + + matSize = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + ops = [] + + for _ in range(m): + ops_item = input() + ops.append(ops_item) + + res = cubeSum(matSize, ops) + + fptr.write('\n'.join(map(str, res))) + fptr.write('\n') + + fptr.close() +","[Chinese Version](https://hr-testcases.s3.amazonaws.com/1058/1058-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/1058/1058_rus.md)
+ +Define a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinates (1,1,1) and the last block is defined by the coordinates (n,n,n). There are two types of queries. + + UPDATE x y z W + +Update the value of block (x,y,z) to W. + + QUERY x1 y1 z1 x2 y2 z2 + +Calculate the sum of the values of blocks whose x coordinate is between x1 and x2 (inclusive), y coordinate between y1 and y2 (inclusive) and z coordinate between z1 and z2 (inclusive). + +**Function Description** + +Complete the *cubeSum* function in the editor below. + +*cubeSum* has the following parameters: +- *int n: the dimensions of the 3-d matrix +- *string operations[m]:* the operations to perform + +**Returns** +- *int[]:* the results of each `QUERY` operation + +**Input Format** +The first line contains an integer $T$, the number of test-cases. $T$ testcases follow. + +For each test case, the first line contains two space-separated integers, $n$ and $m$. + $n$ defines the $n\times n\times n$ matrix. +$m$ defines the number of operations. +The next $m$ lines will contain an operation either of these forms: + + 1. UPDATE x y z W + 2. QUERY x1 y1 z1 x2 y2 z2 + + + +**Constraints** +$1 \le T \le 50$ +$1 \le n \le 100$ +$1 \le m \le 1000$ +$1 \le x1 \le x2 \le n$ +$1 \le y1 \le y2 \le n$ +$1 \le z1 \le z2 \le n$ +$1 \le x,y,z \le n$ +-109 \le W \le 109 + +**Sample Input** + + 2 + 4 5 + UPDATE 2 2 2 4 + QUERY 1 1 1 3 3 3 + UPDATE 1 1 1 23 + QUERY 2 2 2 4 4 4 + QUERY 1 1 1 3 3 3 + 2 4 + UPDATE 2 2 2 1 + QUERY 1 1 1 1 1 1 + QUERY 1 1 1 2 2 2 + QUERY 2 2 2 2 2 2 + +**Sample Output** + + 4 + 4 + 27 + 0 + 1 + 1 + +**Explanation** +In the first test case, there is a cube of 4 * 4 * 4 and there are 5 queries. Initially all the cells (1,1,1) to (4,4,4) are 0. +`UPDATE 2 2 2 4` makes the cell (2,2,2) = 4 +`QUERY 1 1 1 3 3 3`. As (2,2,2) is updated to 4 and the rest are all 0. The answer to this query is 4. +`UPDATE 1 1 1 23`. updates the cell (1,1,1) to 23. +`QUERY 2 2 2 4 4 4`. Only the cell (1,1,1) and (2,2,2) are non-zero and (1,1,1) is not between (2,2,2) and (4,4,4). So, the answer is 4. +`QUERY 1 1 1 3 3 3`. 2 cells are non-zero and their sum is 23+4 = 27. +",0.56,"[""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,Cube Summation : 101 Hack January Editorial,"

Cube Summation

+ +

Difficulty Level : Medium
+Problem Setter : Ashok Kumar
+Problem Testers : Shashank, Abhiranjan
+Required Knowledge : Binary Index Tree

+ +

Approach
+This problem is based on fenwick trees. +Consider this problem:

+ +

A High level explanation of fenwick tree.

+ +

Consider this problem:

+ +

Given an array(let say A) of size n initialized to zero. In this array only two operations can be performed

+ +
    +
  1. update x
  2. +
  3. summation i j
  4. +
+ +

using fenwick tree both of these operation be done in O(logn) time.

+ +

First we have to construct a new array(let say B). B[i] stores summation of values of A[x] to A[i](here x is some index less than i). Now to get +""summation x y"" we have to calculate A[0]+....+A[j] and A[0]+....+A[i].

+ +

To get A[0]+....+A[j] we will make use of array B.

+ +
sum = 0;
+while(j>0) {
+      sum += B[j];
+      j -= (j & -j);        // consider updated j as x in above explanation. 
+}
+
+ +

This while loops takes O(logn) time. Similarly we can perform update operation.

+ +

In original problem we have to find summation in 3-dimensions. So we can again use fenwick tree with three dimension. Now summation operation will look like this:

+ +
    long long y1,x1,sum=0;
+    while (z>0) {
+        x1=x;
+        while(x1>0) {
+            y1=y;
+            while(y1>0) {
+                sum += matrix[x1][y1][z];
+                y1-= (y1 & -y1);   
+            }
+            x1 -= (x1 & -x1);
+        }
+        z -= (z & -z);
+
+    }
+    return sum;
+
+ +

Problem Setter's solution

+ +
#include<iostream>
+#include<cstdio>
+#include<cstring>
+
+using namespace std;
+
+long long matrix[101][101][101];
+
+
+void update(long long n,long long x,long long y,long long z,long long  val) {
+    long long y1,x1;
+
+    while(z <= n) {
+        x1 = x;
+        while(x1 <= n) {
+            y1 = y;
+            while(y1 <= n) {
+                matrix[x1][y1][z] += val;
+                y1 += (y1 & -y1 );
+            }
+            x1 += (x1 & -x1);
+        }
+        z += (z & -z);
+    }
+
+}
+
+long long calculate_sum(long long  x,long long y,long long z) {
+    long long y1,x1,sum=0;
+    while (z>0) {
+        x1=x;
+        while(x1>0) {
+            y1=y;
+            while(y1>0) {
+                sum += matrix[x1][y1][z];
+                y1-= (y1 & -y1);   
+            }
+            x1 -= (x1 & -x1);
+        }
+        z -= (z & -z);
+
+    }
+    return sum;
+}
+
+void process(long long n,long long m) {
+
+    long long x,y,z,x0,y0,z0;
+    long long value1,value2,val;
+    char command[10];
+
+    memset(matrix,0,sizeof(matrix));
+
+    while(m--) {
+        scanf(""%s"",command);
+
+        if(!strcmp(command,""QUERY"")) {
+            scanf(""%lld %lld %lld %lld %lld %lld"",&x0,&y0,&z0,&x,&y,&z);
+
+            value1 = calculate_sum(x,y,z)- calculate_sum(x0-1,y,z) 
+                    - calculate_sum(x,y0-1,z) + calculate_sum(x0-1,y0-1,z);
+
+            value2 = calculate_sum(x,y,z0-1) - calculate_sum(x0-1,y,z0-1)
+                    - calculate_sum(x,y0-1,z0-1)  + calculate_sum(x0-1,y0-1,z0-1);
+
+            printf(""%lld\n"",value1 - value2);
+            //PrintMatrix(n);
+
+        }
+
+        if(!strcmp(command,""UPDATE"")) {
+
+            scanf(""%lld %lld %lld %lld"",&x,&y,&z,&val);
+            x0 = x;
+            y0 = y;
+            z0 = z ;
+
+            value1 = calculate_sum(x,y,z)- calculate_sum(x0-1,y,z) 
+                    - calculate_sum(x,y0-1,z) + calculate_sum(x0-1,y0-1,z);
+            value2 = calculate_sum(x,y,z0-1) - calculate_sum(x0-1,y,z0-1)
+                    - calculate_sum(x,y0-1,z0-1)  + calculate_sum(x0-1,y0-1,z0-1);
+
+            update(n,x,y,z,val -(value1 - value2 ));
+
+        }
+
+    }
+}
+int main() {
+    long long cases; scanf(""%lld"",&cases);
+    while(cases--) {
+
+        long long n,m; scanf(""%lld %lld"",&n,&m);
+        process(n,m);
+    }
+    return 0;
+}
+
+ +

Tester's Solution

+ +
#include <bits/stdc++.h>
+using namespace std;
+
+const int sz = 111;
+
+long long tree[sz][sz][sz];
+
+void update(int x, int y, int z, long long val) {
+    int xx = x;
+    while(xx < sz) {
+        int yy = y;
+        while(yy < sz) {
+            int zz = z;
+            while(zz < sz) {
+                tree[xx][yy][zz] += val;    
+                zz += zz & (-zz);
+            }
+            yy += yy & (-yy);
+        }
+        xx += xx&(-xx);
+    }
+}
+
+long long f(int x, int y, int z) {
+    long long ret = 0;
+    int xx = x;
+    while(xx > 0) {
+        int yy = y;
+        while(yy > 0) {
+            int zz = z;
+            while(zz > 0) {
+                ret += tree[xx][yy][zz];
+                zz -= zz & (-zz);
+            }
+            yy -= yy & (-yy);
+        }
+        xx -= xx & (-xx);
+    }
+    return ret;
+}
+
+long long solve(int x1, int y1, int z1, int x2, int y2, int z2){
+    long long j4 = f(x1-1, y1-1, z1-1);
+    long long j1 = f(x2, y1-1, z1-1) - j4;
+    long long j2 = f(x1-1, y2, z1-1) - j4;
+    long long j3 = f(x1-1, y1-1, z2) - j4;
+
+    return f(x2, y2, z2) - f(x2, y1-1, z2) - f(x1-1, y2, z2) - f(x2, y2, z1-1) + 2*j4 + j1 + j2 + j3;
+}
+
+int main()
+{
+    int test;
+    scanf(""%d"", &test);
+    assert(test>=1);
+    assert(test<=50);
+
+    while(test--) {
+        memset(tree, 0, sizeof(tree));
+        int N, M;
+        cin >> N >> M;
+        assert(N>=1);
+        assert(N<=100);
+        assert(M>=1);
+        assert(M<=1000);
+        string st;
+       int x1, y1, z1, x2, y2, z2;
+       long long val;
+        while(M--) {
+            cin >> st;
+            assert(st == ""QUERY"" || st == ""UPDATE"");
+            if(st[0] == 'Q') {
+                cin >> x1 >> y1 >> z1;
+                cin >> x2 >> y2 >> z2;
+
+                assert(1 <= x1);
+                assert(x1 <= x2);
+                assert(x2 <= N);
+
+                assert(1 <= y1);
+                assert(y1 <= y2);
+                assert(y2 <= N);
+
+                assert(1 <= z1);
+                assert(z1 <= z2);
+                assert(z2 <= N);
+
+                cout << solve(x1, y1, z1, x2, y2, z2) << ""\n"";
+            }
+            else if (st[0] == 'U') {
+                cin >> x1 >> y1 >> z1 >> val;
+
+                assert(1 <= x1); assert(x1 <= N);
+                assert(1 <= y1); assert(y1 <= N);
+                assert(1 <= z1); assert(z1 <= N);
+                assert(-1e9 <= val);
+                assert(val <= 1e9);
+
+                long long existingVal = solve(x1, y1, z1, x1, y1, z1);
+                update(x1, y1, z1, val-existingVal);
+            }
+        }
+    }
+
+    return 0;
+}
+
+ +

Now Time Complexity of update and summation operation will be O((logn)^3). Since we have to reduce each x,y,z coordinate.

",0.0,101-hack-jan-cube-summation,2014-02-05T18:23:32,"{""contest_participation"":1791,""challenge_submissions"":401,""successful_submissions"":276}",2014-02-05T18:23:32,2016-05-13T00:03:42,setter," + #include + #include + #include + + using namespace std; + + long long matrix[101][101][101]; + + + void update(long long n,long long x,long long y,long long z,long long val) { + long long y1,x1; + + while(z <= n) { + x1 = x; + while(x1 <= n) { + y1 = y; + while(y1 <= n) { + matrix[x1][y1][z] += val; + y1 += (y1 & -y1 ); + } + x1 += (x1 & -x1); + } + z += (z & -z); + } + + } + + long long calculate_sum(long long x,long long y,long long z) { + long long y1,x1,sum=0; + while (z>0) { + x1=x; + while(x1>0) { + y1=y; + while(y1>0) { + sum += matrix[x1][y1][z]; + y1-= (y1 & -y1); + } + x1 -= (x1 & -x1); + } + z -= (z & -z); + + } + return sum; + } + + void process(long long n,long long m) { + + long long x,y,z,x0,y0,z0; + long long value1,value2,val; + char command[10]; + + memset(matrix,0,sizeof(matrix)); + + while(m--) { + scanf(""%s"",command); + + if(!strcmp(command,""QUERY"")) { + scanf(""%lld %lld %lld %lld %lld %lld"",&x0,&y0,&z0,&x,&y,&z); + + value1 = calculate_sum(x,y,z)- calculate_sum(x0-1,y,z) + - calculate_sum(x,y0-1,z) + calculate_sum(x0-1,y0-1,z); + + value2 = calculate_sum(x,y,z0-1) - calculate_sum(x0-1,y,z0-1) + - calculate_sum(x,y0-1,z0-1) + calculate_sum(x0-1,y0-1,z0-1); + + printf(""%lld\n"",value1 - value2); + //PrintMatrix(n); + + } + + if(!strcmp(command,""UPDATE"")) { + + scanf(""%lld %lld %lld %lld"",&x,&y,&z,&val); + x0 = x; + y0 = y; + z0 = z ; + + value1 = calculate_sum(x,y,z)- calculate_sum(x0-1,y,z) + - calculate_sum(x,y0-1,z) + calculate_sum(x0-1,y0-1,z); + value2 = calculate_sum(x,y,z0-1) - calculate_sum(x0-1,y,z0-1) + - calculate_sum(x,y0-1,z0-1) + calculate_sum(x0-1,y0-1,z0-1); + + update(n,x,y,z,val -(value1 - value2 )); + + } + + } + } + int main() { + long long cases; scanf(""%lld"",&cases); + while(cases--) { + + long long n,m; scanf(""%lld %lld"",&n,&m); + process(n,m); + } + return 0; + } +",not-set,2016-04-24T02:02:15,2016-04-24T02:02:15,C++ +26,1058,cube-summation,Cube Summation,"[Chinese Version](https://hr-testcases.s3.amazonaws.com/1058/1058-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/1058/1058_rus.md)
+ +You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. + + UPDATE x y z W + +updates the value of block (x,y,z) to W. + + QUERY x1 y1 z1 x2 y2 z2 + +calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coordinate between y1 and y2 (inclusive) and z coordinate between z1 and z2 (inclusive). + +**Input Format** +The first line contains an integer T, the number of test-cases. T testcases follow. +For each test case, the first line will contain two integers N and M separated by a single space. +N defines the N * N * N matrix. +M defines the number of operations. +The next M lines will contain either + + 1. UPDATE x y z W + 2. QUERY x1 y1 z1 x2 y2 z2 + + +**Output Format** +Print the result for each QUERY. + +**Constrains** +1 <= T <= 50 +1 <= N <= 100 +1 <= M <= 1000 +1 <= x1 <= x2 <= N +1 <= y1 <= y2 <= N +1 <= z1 <= z2 <= N +1 <= x,y,z <= N +-109 <= W <= 109 + +**Sample Input** + + 2 + 4 5 + UPDATE 2 2 2 4 + QUERY 1 1 1 3 3 3 + UPDATE 1 1 1 23 + QUERY 2 2 2 4 4 4 + QUERY 1 1 1 3 3 3 + 2 4 + UPDATE 2 2 2 1 + QUERY 1 1 1 1 1 1 + QUERY 1 1 1 2 2 2 + QUERY 2 2 2 2 2 2 + +**Sample Output** + + 4 + 4 + 27 + 0 + 1 + 1 + +**Explanation** +First test case, we are given a cube of 4 * 4 * 4 and 5 queries. Initially all the cells (1,1,1) to (4,4,4) are 0. +`UPDATE 2 2 2 4` makes the cell (2,2,2) = 4 +`QUERY 1 1 1 3 3 3`. As (2,2,2) is updated to 4 and the rest are all 0. The answer to this query is 4. +`UPDATE 1 1 1 23`. updates the cell (1,1,1) to 23. +`QUERY 2 2 2 4 4 4`. Only the cell (1,1,1) and (2,2,2) are non-zero and (1,1,1) is not between (2,2,2) and (4,4,4). So, the answer is 4. +`QUERY 1 1 1 3 3 3`. 2 cells are non-zero and their sum is 23+4 = 27. +",code,Update and query a 3-d matrix,ai,2013-10-10T09:07:12,2022-08-31T08:33:13,"# +# Complete the 'cubeSum' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. INTEGER n +# 2. STRING_ARRAY operations +# + +def cubeSum(n, operations): + # 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() + + matSize = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + ops = [] + + for _ in range(m): + ops_item = input() + ops.append(ops_item) + + res = cubeSum(matSize, ops) + + fptr.write('\n'.join(map(str, res))) + fptr.write('\n') + + fptr.close() +","[Chinese Version](https://hr-testcases.s3.amazonaws.com/1058/1058-chinese.md)
+[Russian Version](https://hr-testcases.s3.amazonaws.com/1058/1058_rus.md)
+ +Define a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinates (1,1,1) and the last block is defined by the coordinates (n,n,n). There are two types of queries. + + UPDATE x y z W + +Update the value of block (x,y,z) to W. + + QUERY x1 y1 z1 x2 y2 z2 + +Calculate the sum of the values of blocks whose x coordinate is between x1 and x2 (inclusive), y coordinate between y1 and y2 (inclusive) and z coordinate between z1 and z2 (inclusive). + +**Function Description** + +Complete the *cubeSum* function in the editor below. + +*cubeSum* has the following parameters: +- *int n: the dimensions of the 3-d matrix +- *string operations[m]:* the operations to perform + +**Returns** +- *int[]:* the results of each `QUERY` operation + +**Input Format** +The first line contains an integer $T$, the number of test-cases. $T$ testcases follow. + +For each test case, the first line contains two space-separated integers, $n$ and $m$. + $n$ defines the $n\times n\times n$ matrix. +$m$ defines the number of operations. +The next $m$ lines will contain an operation either of these forms: + + 1. UPDATE x y z W + 2. QUERY x1 y1 z1 x2 y2 z2 + + + +**Constraints** +$1 \le T \le 50$ +$1 \le n \le 100$ +$1 \le m \le 1000$ +$1 \le x1 \le x2 \le n$ +$1 \le y1 \le y2 \le n$ +$1 \le z1 \le z2 \le n$ +$1 \le x,y,z \le n$ +-109 \le W \le 109 + +**Sample Input** + + 2 + 4 5 + UPDATE 2 2 2 4 + QUERY 1 1 1 3 3 3 + UPDATE 1 1 1 23 + QUERY 2 2 2 4 4 4 + QUERY 1 1 1 3 3 3 + 2 4 + UPDATE 2 2 2 1 + QUERY 1 1 1 1 1 1 + QUERY 1 1 1 2 2 2 + QUERY 2 2 2 2 2 2 + +**Sample Output** + + 4 + 4 + 27 + 0 + 1 + 1 + +**Explanation** +In the first test case, there is a cube of 4 * 4 * 4 and there are 5 queries. Initially all the cells (1,1,1) to (4,4,4) are 0. +`UPDATE 2 2 2 4` makes the cell (2,2,2) = 4 +`QUERY 1 1 1 3 3 3`. As (2,2,2) is updated to 4 and the rest are all 0. The answer to this query is 4. +`UPDATE 1 1 1 23`. updates the cell (1,1,1) to 23. +`QUERY 2 2 2 4 4 4`. Only the cell (1,1,1) and (2,2,2) are non-zero and (1,1,1) is not between (2,2,2) and (4,4,4). So, the answer is 4. +`QUERY 1 1 1 3 3 3`. 2 cells are non-zero and their sum is 23+4 = 27. +",0.56,"[""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,Cube Summation : 101 Hack January Editorial,"

Cube Summation

+ +

Difficulty Level : Medium
+Problem Setter : Ashok Kumar
+Problem Testers : Shashank, Abhiranjan
+Required Knowledge : Binary Index Tree

+ +

Approach
+This problem is based on fenwick trees. +Consider this problem:

+ +

A High level explanation of fenwick tree.

+ +

Consider this problem:

+ +

Given an array(let say A) of size n initialized to zero. In this array only two operations can be performed

+ +
    +
  1. update x
  2. +
  3. summation i j
  4. +
+ +

using fenwick tree both of these operation be done in O(logn) time.

+ +

First we have to construct a new array(let say B). B[i] stores summation of values of A[x] to A[i](here x is some index less than i). Now to get +""summation x y"" we have to calculate A[0]+....+A[j] and A[0]+....+A[i].

+ +

To get A[0]+....+A[j] we will make use of array B.

+ +
sum = 0;
+while(j>0) {
+      sum += B[j];
+      j -= (j & -j);        // consider updated j as x in above explanation. 
+}
+
+ +

This while loops takes O(logn) time. Similarly we can perform update operation.

+ +

In original problem we have to find summation in 3-dimensions. So we can again use fenwick tree with three dimension. Now summation operation will look like this:

+ +
    long long y1,x1,sum=0;
+    while (z>0) {
+        x1=x;
+        while(x1>0) {
+            y1=y;
+            while(y1>0) {
+                sum += matrix[x1][y1][z];
+                y1-= (y1 & -y1);   
+            }
+            x1 -= (x1 & -x1);
+        }
+        z -= (z & -z);
+
+    }
+    return sum;
+
+ +

Problem Setter's solution

+ +
#include<iostream>
+#include<cstdio>
+#include<cstring>
+
+using namespace std;
+
+long long matrix[101][101][101];
+
+
+void update(long long n,long long x,long long y,long long z,long long  val) {
+    long long y1,x1;
+
+    while(z <= n) {
+        x1 = x;
+        while(x1 <= n) {
+            y1 = y;
+            while(y1 <= n) {
+                matrix[x1][y1][z] += val;
+                y1 += (y1 & -y1 );
+            }
+            x1 += (x1 & -x1);
+        }
+        z += (z & -z);
+    }
+
+}
+
+long long calculate_sum(long long  x,long long y,long long z) {
+    long long y1,x1,sum=0;
+    while (z>0) {
+        x1=x;
+        while(x1>0) {
+            y1=y;
+            while(y1>0) {
+                sum += matrix[x1][y1][z];
+                y1-= (y1 & -y1);   
+            }
+            x1 -= (x1 & -x1);
+        }
+        z -= (z & -z);
+
+    }
+    return sum;
+}
+
+void process(long long n,long long m) {
+
+    long long x,y,z,x0,y0,z0;
+    long long value1,value2,val;
+    char command[10];
+
+    memset(matrix,0,sizeof(matrix));
+
+    while(m--) {
+        scanf(""%s"",command);
+
+        if(!strcmp(command,""QUERY"")) {
+            scanf(""%lld %lld %lld %lld %lld %lld"",&x0,&y0,&z0,&x,&y,&z);
+
+            value1 = calculate_sum(x,y,z)- calculate_sum(x0-1,y,z) 
+                    - calculate_sum(x,y0-1,z) + calculate_sum(x0-1,y0-1,z);
+
+            value2 = calculate_sum(x,y,z0-1) - calculate_sum(x0-1,y,z0-1)
+                    - calculate_sum(x,y0-1,z0-1)  + calculate_sum(x0-1,y0-1,z0-1);
+
+            printf(""%lld\n"",value1 - value2);
+            //PrintMatrix(n);
+
+        }
+
+        if(!strcmp(command,""UPDATE"")) {
+
+            scanf(""%lld %lld %lld %lld"",&x,&y,&z,&val);
+            x0 = x;
+            y0 = y;
+            z0 = z ;
+
+            value1 = calculate_sum(x,y,z)- calculate_sum(x0-1,y,z) 
+                    - calculate_sum(x,y0-1,z) + calculate_sum(x0-1,y0-1,z);
+            value2 = calculate_sum(x,y,z0-1) - calculate_sum(x0-1,y,z0-1)
+                    - calculate_sum(x,y0-1,z0-1)  + calculate_sum(x0-1,y0-1,z0-1);
+
+            update(n,x,y,z,val -(value1 - value2 ));
+
+        }
+
+    }
+}
+int main() {
+    long long cases; scanf(""%lld"",&cases);
+    while(cases--) {
+
+        long long n,m; scanf(""%lld %lld"",&n,&m);
+        process(n,m);
+    }
+    return 0;
+}
+
+ +

Tester's Solution

+ +
#include <bits/stdc++.h>
+using namespace std;
+
+const int sz = 111;
+
+long long tree[sz][sz][sz];
+
+void update(int x, int y, int z, long long val) {
+    int xx = x;
+    while(xx < sz) {
+        int yy = y;
+        while(yy < sz) {
+            int zz = z;
+            while(zz < sz) {
+                tree[xx][yy][zz] += val;    
+                zz += zz & (-zz);
+            }
+            yy += yy & (-yy);
+        }
+        xx += xx&(-xx);
+    }
+}
+
+long long f(int x, int y, int z) {
+    long long ret = 0;
+    int xx = x;
+    while(xx > 0) {
+        int yy = y;
+        while(yy > 0) {
+            int zz = z;
+            while(zz > 0) {
+                ret += tree[xx][yy][zz];
+                zz -= zz & (-zz);
+            }
+            yy -= yy & (-yy);
+        }
+        xx -= xx & (-xx);
+    }
+    return ret;
+}
+
+long long solve(int x1, int y1, int z1, int x2, int y2, int z2){
+    long long j4 = f(x1-1, y1-1, z1-1);
+    long long j1 = f(x2, y1-1, z1-1) - j4;
+    long long j2 = f(x1-1, y2, z1-1) - j4;
+    long long j3 = f(x1-1, y1-1, z2) - j4;
+
+    return f(x2, y2, z2) - f(x2, y1-1, z2) - f(x1-1, y2, z2) - f(x2, y2, z1-1) + 2*j4 + j1 + j2 + j3;
+}
+
+int main()
+{
+    int test;
+    scanf(""%d"", &test);
+    assert(test>=1);
+    assert(test<=50);
+
+    while(test--) {
+        memset(tree, 0, sizeof(tree));
+        int N, M;
+        cin >> N >> M;
+        assert(N>=1);
+        assert(N<=100);
+        assert(M>=1);
+        assert(M<=1000);
+        string st;
+       int x1, y1, z1, x2, y2, z2;
+       long long val;
+        while(M--) {
+            cin >> st;
+            assert(st == ""QUERY"" || st == ""UPDATE"");
+            if(st[0] == 'Q') {
+                cin >> x1 >> y1 >> z1;
+                cin >> x2 >> y2 >> z2;
+
+                assert(1 <= x1);
+                assert(x1 <= x2);
+                assert(x2 <= N);
+
+                assert(1 <= y1);
+                assert(y1 <= y2);
+                assert(y2 <= N);
+
+                assert(1 <= z1);
+                assert(z1 <= z2);
+                assert(z2 <= N);
+
+                cout << solve(x1, y1, z1, x2, y2, z2) << ""\n"";
+            }
+            else if (st[0] == 'U') {
+                cin >> x1 >> y1 >> z1 >> val;
+
+                assert(1 <= x1); assert(x1 <= N);
+                assert(1 <= y1); assert(y1 <= N);
+                assert(1 <= z1); assert(z1 <= N);
+                assert(-1e9 <= val);
+                assert(val <= 1e9);
+
+                long long existingVal = solve(x1, y1, z1, x1, y1, z1);
+                update(x1, y1, z1, val-existingVal);
+            }
+        }
+    }
+
+    return 0;
+}
+
+ +

Now Time Complexity of update and summation operation will be O((logn)^3). Since we have to reduce each x,y,z coordinate.

",0.0,101-hack-jan-cube-summation,2014-02-05T18:23:32,"{""contest_participation"":1791,""challenge_submissions"":401,""successful_submissions"":276}",2014-02-05T18:23:32,2016-05-13T00:03:42,tester," + #include + using namespace std; + + const int sz = 111; + + long long tree[sz][sz][sz]; + + void update(int x, int y, int z, long long val) { + int xx = x; + while(xx < sz) { + int yy = y; + while(yy < sz) { + int zz = z; + while(zz < sz) { + tree[xx][yy][zz] += val; + zz += zz & (-zz); + } + yy += yy & (-yy); + } + xx += xx&(-xx); + } + } + + long long f(int x, int y, int z) { + long long ret = 0; + int xx = x; + while(xx > 0) { + int yy = y; + while(yy > 0) { + int zz = z; + while(zz > 0) { + ret += tree[xx][yy][zz]; + zz -= zz & (-zz); + } + yy -= yy & (-yy); + } + xx -= xx & (-xx); + } + return ret; + } + + long long solve(int x1, int y1, int z1, int x2, int y2, int z2){ + long long j4 = f(x1-1, y1-1, z1-1); + long long j1 = f(x2, y1-1, z1-1) - j4; + long long j2 = f(x1-1, y2, z1-1) - j4; + long long j3 = f(x1-1, y1-1, z2) - j4; + + return f(x2, y2, z2) - f(x2, y1-1, z2) - f(x1-1, y2, z2) - f(x2, y2, z1-1) + 2*j4 + j1 + j2 + j3; + } + + int main() + { + int test; + scanf(""%d"", &test); + assert(test>=1); + assert(test<=50); + + while(test--) { + memset(tree, 0, sizeof(tree)); + int N, M; + cin >> N >> M; + assert(N>=1); + assert(N<=100); + assert(M>=1); + assert(M<=1000); + string st; + int x1, y1, z1, x2, y2, z2; + long long val; + while(M--) { + cin >> st; + assert(st == ""QUERY"" || st == ""UPDATE""); + if(st[0] == 'Q') { + cin >> x1 >> y1 >> z1; + cin >> x2 >> y2 >> z2; + + assert(1 <= x1); + assert(x1 <= x2); + assert(x2 <= N); + + assert(1 <= y1); + assert(y1 <= y2); + assert(y2 <= N); + + assert(1 <= z1); + assert(z1 <= z2); + assert(z2 <= N); + + cout << solve(x1, y1, z1, x2, y2, z2) << ""\n""; + } + else if (st[0] == 'U') { + cin >> x1 >> y1 >> z1 >> val; + + assert(1 <= x1); assert(x1 <= N); + assert(1 <= y1); assert(y1 <= N); + assert(1 <= z1); assert(z1 <= N); + assert(-1e9 <= val); + assert(val <= 1e9); + + long long existingVal = solve(x1, y1, z1, x1, y1, z1); + update(x1, y1, z1, val-existingVal); + } + } + } + + return 0; + } +",not-set,2016-04-24T02:02:15,2016-04-24T02:02:15,C++ +27,1543,bike-racers,Bike Racers,"[Chinese Version](https://hr-filepicker.s3.amazonaws.com/feb14/chinese/1543-chinese.md)
+[Russian Version](https://hr-filepicker.s3.amazonaws.com/feb-14/russian/1543-russian.md)
+ +There are _N_ bikers present in a city (shaped as a grid) having _M_ bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only _K_ bikers can be accommodated in the race. Jack is organizing the HackerRace and wants to start the race as soon as possible. He can instruct any biker to move towards any bike in the city. In order to minimize the time to start the race, Jack instructs the bikers in such a way that first _K_ bikes are acquired in the minimum time. + +Every biker moves with a unit speed and one bike can be acquired by only one biker. *A biker can proceed in any direction*. Consider distance between bike and bikers as euclidean distance. + +Jack would like to know the *square of required time* to start the race as soon as possible. + +**Input Format** +The first line contains three integers - N,M,K separated by a single space. +Following N lines will contain N pairs of integers denoting the co-ordinates of N bikers. Each pair of integers is separated by a single space. The next M pairs of lines will denote the co-ordinates of M bikes. + +**Output Format** +A single line containing the square of required time. + +**Constraints** +1 <= N <= 250 +1 <= M <= 250 +1 <= K <= min(N,M) +0 <= xi,yi <= 107 + +**Sample Input #00:** + + 3 3 2 + 0 1 + 0 2 + 0 3 + 100 1 + 200 2 + 300 3 + +**Sample Output #00:** + + 40000 + +**Explanation #00:** +There's need for two bikers for the race. The first biker (0,1) will be able to reach the first bike (100,1) in 100 time units. The second biker (0,2) will be able to reach the second bike (200,2) in 200 time units. This is the most optimal solution and will take 200 time units. So output will be 2002 = 40000.",code,Calculate the square of the minimum time required to start the bike race.,ai,2013-12-13T23:10:30,2022-08-31T08:14:22,"# +# Complete the 'bikeRacers' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts following parameters: +# 1. 2D_INTEGER_ARRAY bikers +# 2. 2D_INTEGER_ARRAY bikes +# + +def bikeRacers(bikers, bikes): + # 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() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + k = int(first_multiple_input[2]) + + bikers = [] + + for _ in range(n): + bikers.append(list(map(int, input().rstrip().split()))) + + bikes = [] + + for _ in range(n): + bikes.append(list(map(int, input().rstrip().split()))) + + result = bikeRacers(bikers, bikes) + + fptr.write(str(result) + '\n') + + fptr.close() +"," +There are $N$ bikers present in a city (shaped as a grid) having $M$ bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only $K$ bikers can be accommodated in the race. Jack is organizing the HackerRace and wants to start the race as soon as possible. He can instruct any biker to move towards any bike in the city. In order to minimize the time to start the race, Jack instructs the bikers in such a way that the first $K$ bikes are acquired in the minimum time. + +Every biker moves with a unit speed and one bike can be acquired by only one biker. *A biker can proceed in any direction*. Consider distance between bikes and bikers as Euclidean distance. + +Jack would like to know the *square of required time* to start the race as soon as possible. +",0.4065040650406504,"[""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 three integers, $N$, $M$, and $K$, separated by a single space. +The following $N$ lines will contain $N$ pairs of integers denoting the co-ordinates of $N$ bikers. Each pair of integers is separated by a single space. The next $M$ lines will similarly denote the co-ordinates of the $M$ bikes. +","A single line containing the square of required time. +"," 3 3 2 + 0 1 + 0 2 + 0 3 + 100 1 + 200 2 + 300 3 +"," 40000 +",Hard,Bike Racers - 2020 Hack February Editorial,"

Problem : Tell the time by which K bikers will get bike. Read full problem here

+ +

Required Knowledge : Binary Search, Bipartite Matching .

+ +

Time Complexity : O(K^2 * log(10^14 ) )

+ +

Approach :

+ +

This is a problem for which you have to solve 2 subproblems, each subproblem will help you in learning some useful concept.

+ +

Subproblem 1 First try to solve a problem, Given N bikes and M bikers and time T, How many bikers (at max) will be get a bike ? while each bikers can have only one bike and one bike can be accommodated by only one biker.

+ +

Solution : Make a bipartite graph, Having N node in one partite and having M nove in other partite and connect a node X from first partite to a node Y of second partite iff bike Y is reachable from biker X is given amount of time T.

+ +

Value of maxium bipartite matching is the solution of subproblem 1

+ +

Now using this subproblem we can check whether in given amount of Time whether K bikers can get bike or not.

+ +

Now define a function f in given manner

+ +

f(T) = true if K bikers can get in bike in square_root(T) time.
+ else false.

+ +

as it is very obvious that if f(T) = true then f(T1) = true for all T1>=T.

+ +

and f(0) = false and f(10^16) = true. as all co-ordinates X,Y <= 10^7
+Now we can use classical binary search to get the value of exact value of T.

+ +

Subproblem 2 : Binary search can solved using the classical method.

+ +
long long int low = 0;
+long long int high = 10000000000000000;
+
+while(low < high)
+{
+long long int mid = (low + high) / 2;
+if( f( mid ) )
+{
+high = mid;
+}
+else
+{
+low = mid+1 ;
+}
+
+}
+
+ +

Which will give the precise value of Square of Time.

+ +

Setter's code :

+ +
//Hopcraft carp maxium matching algorithm time complexity = E*sqrt(V)
+
+#include<iostream>
+#include<cstdlib>
+#include <cstdio>
+#include <queue>
+#include <vector>
+#include<bits/stdc++.h>
+using namespace std;
+#define SET(x) memset(x, -1, sizeof(x))
+#define CLR(x) memset(x, 0, sizeof(x))
+#define MAX 2001
+#define NIL 0
+#define INF (1<<28)
+
+int N,M,K;
+
+vector< int > edges[MAX]; // edges of left side
+bool visited[MAX];
+int Left[MAX], Right[MAX];
+long long int dist[MAX][MAX];
+
+bool dfs(int u) {
+    if(visited[u]) return false;
+    visited[u] = true;
+    int len = edges[u].size(), i, v;
+    for(i=0; i<len; i++) {
+        v = edges[u][i];
+        if(Right[v]==-1) {
+            Right[v] = u, Left[u] = v;
+            return true;
+        }
+    }
+    for(i=0; i<len; i++) {
+        v = edges[u][i];
+        if(dfs(Right[v])) {
+            Right[v] = u, Left[u] = v;
+            return true;
+        }
+    }
+    return false;
+}
+
+int match() {
+    SET(Left); // left = -1
+    SET(Right); // right = -1
+    int i, ret = 0;
+    bool done;
+    do {
+        done = true;
+        CLR(visited); // visited = 0
+        for(i=1; i<=N; i++) {
+            if(Left[i]==-1 && dfs(i)) {
+                done = false;
+            }
+        }
+    } while(!done);
+    for(i=1; i<=N; i++) ret += (Left[i]!=-1);
+    return ret;
+}
+
+bool check ( long long int val)
+{
+    for(int i=1 ; i<=N ; i++)
+{
+for( int j=1 ; j<=M ; j++)
+{
+if(dist[i][j] <=val)
+{
+edges[i].push_back(j);
+}
+}
+}
+
+long long int num_match = match();
+
+for(int i= 1 ; i<= N ; i++)
+edges[i].clear();
+
+if(num_match >=K)
+return true;
+else
+return false;
+
+}
+
+int main()
+{
+cin>>N>>M>>K;
+    assert(K <= N);
+    assert(K <= M);
+int a,b;
+pair<long long int,long long int> P[N+1];
+pair<long long int,long long int> Q[M+1];
+for(int i=1 ; i<=N; i++)
+cin>>P[i].first>>P[i].second;
+for(int i=1 ; i<=M ; i++)
+cin>>Q[i].first>>Q[i].second;
+for(int i=1 ; i<=N ; i++)
+{
+for(int j=1 ; j<=M ; j++)
+{
+dist[i][j] = (P[i].first - Q[j].first)*(P[i].first - Q[j].first) + (P[i].second - Q[j].second)*(P[i].second - Q[j].second);
+}
+}   
+
+long long int low = 0;
+long long int high = 10000000000000000;
+
+while(low < high)
+{
+long long int mid = (low + high) / 2;
+if( check( mid ) )
+{
+high = mid;
+}
+else
+{
+low = mid+1 ;
+}
+
+}
+cout<<low<<endl;
+return 0;
+}
+
+ +

Tester's Code :

+ +
#include <bits/stdc++.h>
+using namespace std;
+
+const int sz = 2000;
+
+long long userX[sz], userY[sz];
+long long bikeX[sz], bikeY[sz];
+int lt[sz];
+int N, M, K;
+bool vis[sz];
+
+bool validPath(int userId, int bikerId, long long distanceAllowed) {
+    long long distX = userX[userId] - bikeX[bikerId];
+    distX *= distX;
+    long long distY = userY[userId] - bikeY[bikerId];
+    distY *= distY;
+
+    return distX + distY <= distanceAllowed;
+}
+
+bool dfs(int u, long long distanceAllowed) {
+    if(u == -1)
+        return true;
+    if(vis[u])
+        return false;
+    vis[u] = true;
+
+    for(int i = 0; i < (int)M; ++i) {
+        int id = lt[i];
+        if(validPath(u, i, distanceAllowed) && dfs(id, distanceAllowed)) {
+            lt[i] = u;
+            return true;
+        }
+    }
+    return false;
+}
+
+int matching(long long tm) {
+    memset(lt, -1, sizeof(lt));
+
+    int ret = 0;
+    for(int i = 0; i < (int)N; ++i) {
+        memset(vis, 0, sizeof(vis));
+        if(dfs(i, tm))
+            ret++;
+    }
+    return ret;
+}
+
+long long binarySearch(long long l = 0, long long r = 1e17) {
+    if(l == r)
+        return l;
+    long long mid = (l+r)/2;
+    int match = matching(mid);
+    return match >= K ? binarySearch(l, mid) : binarySearch(mid+1, r);
+}
+
+int main()
+{
+    cin >> N >> M >> K;
+    assert(1 <= N); assert(N <= sz);
+    assert(1 <= M); assert(M <= sz);
+    assert(1 <= K); assert(K <= min(N, M));
+
+    for(int i = 0; i < (int)N; ++i) {
+        cin >> userX[i] >> userY[i];
+        assert(0 <= userX[i]); assert(userX[i] <= 1e7);
+        assert(0 <= userY[i]); assert(userY[i] <= 1e7);
+    }
+    for(int i = 0; i < (int)M; ++i) {
+        cin >> bikeX[i] >> bikeY[i];
+        assert(0 <= bikeX[i]); assert(bikeX[i] <= 1e7);
+        assert(0 <= bikeY[i]); assert(bikeY[i] <= 1e7);
+    }
+
+    cout << binarySearch() << endl;
+
+    return 0;
+}
+
",0.0,feb14-bike-racers,2014-02-27T05:02:05,"{""contest_participation"":2769,""challenge_submissions"":556,""successful_submissions"":192}",2014-02-27T05:02:05,2016-12-02T20:11:31,setter,"###C++ +```cpp + +//Hopcraft carp maxium matching algorithm time complexity = E*sqrt(V) + +#include +#include +#include +#include +#include +#include +using namespace std; +#define SET(x) memset(x, -1, sizeof(x)) +#define CLR(x) memset(x, 0, sizeof(x)) +#define MAX 2001 +#define NIL 0 +#define INF (1<<28) + +int N,M,K; + +vector< int > edges[MAX]; // edges of left side +bool visited[MAX]; +int Left[MAX], Right[MAX]; +long long int dist[MAX][MAX]; + +bool dfs(int u) { + if(visited[u]) return false; + visited[u] = true; + int len = edges[u].size(), i, v; + for(i=0; i=K) + return true; + else + return false; +} + +int main() { + cin>>N>>M>>K; + int a,b; + pair P[N+1]; + pair Q[M+1]; + for(int i=1 ; i<=N; i++) + cin>>P[i].first>>P[i].second; + for(int i=1 ; i<=M ; i++) + cin>>Q[i].first>>Q[i].second; + for(int i=1 ; i<=N ; i++) { + for(int j=1 ; j<=M ; j++) { + dist[i][j] = (P[i].first - Q[j].first) + *(P[i].first - Q[j].first) + + (P[i].second - Q[j].second) + *(P[i].second - Q[j].second); + } + } + + long long int low = 0; + long long int high = 10000000000000000; + + while(low < high) { + long long int mid = (low + high) / 2; + if( check( mid ) ) { + high = mid; + } else { + low = mid+1 ; + } + } + cout << low << endl; + return 0; +} +``` +",not-set,2016-04-24T02:02:16,2016-12-02T20:11:31,C++ +28,1543,bike-racers,Bike Racers,"[Chinese Version](https://hr-filepicker.s3.amazonaws.com/feb14/chinese/1543-chinese.md)
+[Russian Version](https://hr-filepicker.s3.amazonaws.com/feb-14/russian/1543-russian.md)
+ +There are _N_ bikers present in a city (shaped as a grid) having _M_ bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only _K_ bikers can be accommodated in the race. Jack is organizing the HackerRace and wants to start the race as soon as possible. He can instruct any biker to move towards any bike in the city. In order to minimize the time to start the race, Jack instructs the bikers in such a way that first _K_ bikes are acquired in the minimum time. + +Every biker moves with a unit speed and one bike can be acquired by only one biker. *A biker can proceed in any direction*. Consider distance between bike and bikers as euclidean distance. + +Jack would like to know the *square of required time* to start the race as soon as possible. + +**Input Format** +The first line contains three integers - N,M,K separated by a single space. +Following N lines will contain N pairs of integers denoting the co-ordinates of N bikers. Each pair of integers is separated by a single space. The next M pairs of lines will denote the co-ordinates of M bikes. + +**Output Format** +A single line containing the square of required time. + +**Constraints** +1 <= N <= 250 +1 <= M <= 250 +1 <= K <= min(N,M) +0 <= xi,yi <= 107 + +**Sample Input #00:** + + 3 3 2 + 0 1 + 0 2 + 0 3 + 100 1 + 200 2 + 300 3 + +**Sample Output #00:** + + 40000 + +**Explanation #00:** +There's need for two bikers for the race. The first biker (0,1) will be able to reach the first bike (100,1) in 100 time units. The second biker (0,2) will be able to reach the second bike (200,2) in 200 time units. This is the most optimal solution and will take 200 time units. So output will be 2002 = 40000.",code,Calculate the square of the minimum time required to start the bike race.,ai,2013-12-13T23:10:30,2022-08-31T08:14:22,"# +# Complete the 'bikeRacers' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts following parameters: +# 1. 2D_INTEGER_ARRAY bikers +# 2. 2D_INTEGER_ARRAY bikes +# + +def bikeRacers(bikers, bikes): + # 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() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + k = int(first_multiple_input[2]) + + bikers = [] + + for _ in range(n): + bikers.append(list(map(int, input().rstrip().split()))) + + bikes = [] + + for _ in range(n): + bikes.append(list(map(int, input().rstrip().split()))) + + result = bikeRacers(bikers, bikes) + + fptr.write(str(result) + '\n') + + fptr.close() +"," +There are $N$ bikers present in a city (shaped as a grid) having $M$ bikes. All the bikers want to participate in the HackerRace competition, but unfortunately only $K$ bikers can be accommodated in the race. Jack is organizing the HackerRace and wants to start the race as soon as possible. He can instruct any biker to move towards any bike in the city. In order to minimize the time to start the race, Jack instructs the bikers in such a way that the first $K$ bikes are acquired in the minimum time. + +Every biker moves with a unit speed and one bike can be acquired by only one biker. *A biker can proceed in any direction*. Consider distance between bikes and bikers as Euclidean distance. + +Jack would like to know the *square of required time* to start the race as soon as possible. +",0.4065040650406504,"[""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 three integers, $N$, $M$, and $K$, separated by a single space. +The following $N$ lines will contain $N$ pairs of integers denoting the co-ordinates of $N$ bikers. Each pair of integers is separated by a single space. The next $M$ lines will similarly denote the co-ordinates of the $M$ bikes. +","A single line containing the square of required time. +"," 3 3 2 + 0 1 + 0 2 + 0 3 + 100 1 + 200 2 + 300 3 +"," 40000 +",Hard,Bike Racers - 2020 Hack February Editorial,"

Problem : Tell the time by which K bikers will get bike. Read full problem here

+ +

Required Knowledge : Binary Search, Bipartite Matching .

+ +

Time Complexity : O(K^2 * log(10^14 ) )

+ +

Approach :

+ +

This is a problem for which you have to solve 2 subproblems, each subproblem will help you in learning some useful concept.

+ +

Subproblem 1 First try to solve a problem, Given N bikes and M bikers and time T, How many bikers (at max) will be get a bike ? while each bikers can have only one bike and one bike can be accommodated by only one biker.

+ +

Solution : Make a bipartite graph, Having N node in one partite and having M nove in other partite and connect a node X from first partite to a node Y of second partite iff bike Y is reachable from biker X is given amount of time T.

+ +

Value of maxium bipartite matching is the solution of subproblem 1

+ +

Now using this subproblem we can check whether in given amount of Time whether K bikers can get bike or not.

+ +

Now define a function f in given manner

+ +

f(T) = true if K bikers can get in bike in square_root(T) time.
+ else false.

+ +

as it is very obvious that if f(T) = true then f(T1) = true for all T1>=T.

+ +

and f(0) = false and f(10^16) = true. as all co-ordinates X,Y <= 10^7
+Now we can use classical binary search to get the value of exact value of T.

+ +

Subproblem 2 : Binary search can solved using the classical method.

+ +
long long int low = 0;
+long long int high = 10000000000000000;
+
+while(low < high)
+{
+long long int mid = (low + high) / 2;
+if( f( mid ) )
+{
+high = mid;
+}
+else
+{
+low = mid+1 ;
+}
+
+}
+
+ +

Which will give the precise value of Square of Time.

+ +

Setter's code :

+ +
//Hopcraft carp maxium matching algorithm time complexity = E*sqrt(V)
+
+#include<iostream>
+#include<cstdlib>
+#include <cstdio>
+#include <queue>
+#include <vector>
+#include<bits/stdc++.h>
+using namespace std;
+#define SET(x) memset(x, -1, sizeof(x))
+#define CLR(x) memset(x, 0, sizeof(x))
+#define MAX 2001
+#define NIL 0
+#define INF (1<<28)
+
+int N,M,K;
+
+vector< int > edges[MAX]; // edges of left side
+bool visited[MAX];
+int Left[MAX], Right[MAX];
+long long int dist[MAX][MAX];
+
+bool dfs(int u) {
+    if(visited[u]) return false;
+    visited[u] = true;
+    int len = edges[u].size(), i, v;
+    for(i=0; i<len; i++) {
+        v = edges[u][i];
+        if(Right[v]==-1) {
+            Right[v] = u, Left[u] = v;
+            return true;
+        }
+    }
+    for(i=0; i<len; i++) {
+        v = edges[u][i];
+        if(dfs(Right[v])) {
+            Right[v] = u, Left[u] = v;
+            return true;
+        }
+    }
+    return false;
+}
+
+int match() {
+    SET(Left); // left = -1
+    SET(Right); // right = -1
+    int i, ret = 0;
+    bool done;
+    do {
+        done = true;
+        CLR(visited); // visited = 0
+        for(i=1; i<=N; i++) {
+            if(Left[i]==-1 && dfs(i)) {
+                done = false;
+            }
+        }
+    } while(!done);
+    for(i=1; i<=N; i++) ret += (Left[i]!=-1);
+    return ret;
+}
+
+bool check ( long long int val)
+{
+    for(int i=1 ; i<=N ; i++)
+{
+for( int j=1 ; j<=M ; j++)
+{
+if(dist[i][j] <=val)
+{
+edges[i].push_back(j);
+}
+}
+}
+
+long long int num_match = match();
+
+for(int i= 1 ; i<= N ; i++)
+edges[i].clear();
+
+if(num_match >=K)
+return true;
+else
+return false;
+
+}
+
+int main()
+{
+cin>>N>>M>>K;
+    assert(K <= N);
+    assert(K <= M);
+int a,b;
+pair<long long int,long long int> P[N+1];
+pair<long long int,long long int> Q[M+1];
+for(int i=1 ; i<=N; i++)
+cin>>P[i].first>>P[i].second;
+for(int i=1 ; i<=M ; i++)
+cin>>Q[i].first>>Q[i].second;
+for(int i=1 ; i<=N ; i++)
+{
+for(int j=1 ; j<=M ; j++)
+{
+dist[i][j] = (P[i].first - Q[j].first)*(P[i].first - Q[j].first) + (P[i].second - Q[j].second)*(P[i].second - Q[j].second);
+}
+}   
+
+long long int low = 0;
+long long int high = 10000000000000000;
+
+while(low < high)
+{
+long long int mid = (low + high) / 2;
+if( check( mid ) )
+{
+high = mid;
+}
+else
+{
+low = mid+1 ;
+}
+
+}
+cout<<low<<endl;
+return 0;
+}
+
+ +

Tester's Code :

+ +
#include <bits/stdc++.h>
+using namespace std;
+
+const int sz = 2000;
+
+long long userX[sz], userY[sz];
+long long bikeX[sz], bikeY[sz];
+int lt[sz];
+int N, M, K;
+bool vis[sz];
+
+bool validPath(int userId, int bikerId, long long distanceAllowed) {
+    long long distX = userX[userId] - bikeX[bikerId];
+    distX *= distX;
+    long long distY = userY[userId] - bikeY[bikerId];
+    distY *= distY;
+
+    return distX + distY <= distanceAllowed;
+}
+
+bool dfs(int u, long long distanceAllowed) {
+    if(u == -1)
+        return true;
+    if(vis[u])
+        return false;
+    vis[u] = true;
+
+    for(int i = 0; i < (int)M; ++i) {
+        int id = lt[i];
+        if(validPath(u, i, distanceAllowed) && dfs(id, distanceAllowed)) {
+            lt[i] = u;
+            return true;
+        }
+    }
+    return false;
+}
+
+int matching(long long tm) {
+    memset(lt, -1, sizeof(lt));
+
+    int ret = 0;
+    for(int i = 0; i < (int)N; ++i) {
+        memset(vis, 0, sizeof(vis));
+        if(dfs(i, tm))
+            ret++;
+    }
+    return ret;
+}
+
+long long binarySearch(long long l = 0, long long r = 1e17) {
+    if(l == r)
+        return l;
+    long long mid = (l+r)/2;
+    int match = matching(mid);
+    return match >= K ? binarySearch(l, mid) : binarySearch(mid+1, r);
+}
+
+int main()
+{
+    cin >> N >> M >> K;
+    assert(1 <= N); assert(N <= sz);
+    assert(1 <= M); assert(M <= sz);
+    assert(1 <= K); assert(K <= min(N, M));
+
+    for(int i = 0; i < (int)N; ++i) {
+        cin >> userX[i] >> userY[i];
+        assert(0 <= userX[i]); assert(userX[i] <= 1e7);
+        assert(0 <= userY[i]); assert(userY[i] <= 1e7);
+    }
+    for(int i = 0; i < (int)M; ++i) {
+        cin >> bikeX[i] >> bikeY[i];
+        assert(0 <= bikeX[i]); assert(bikeX[i] <= 1e7);
+        assert(0 <= bikeY[i]); assert(bikeY[i] <= 1e7);
+    }
+
+    cout << binarySearch() << endl;
+
+    return 0;
+}
+
",0.0,feb14-bike-racers,2014-02-27T05:02:05,"{""contest_participation"":2769,""challenge_submissions"":556,""successful_submissions"":192}",2014-02-27T05:02:05,2016-12-02T20:11:31,tester,"###C++ +```cpp + +#include +using namespace std; + +const int sz = 2000; + +long long userX[sz], userY[sz]; +long long bikeX[sz], bikeY[sz]; +int lt[sz]; +int N, M, K; +bool vis[sz]; + +bool validPath(int userId, int bikerId, long long distanceAllowed) { + long long distX = userX[userId] - bikeX[bikerId]; + distX *= distX; + long long distY = userY[userId] - bikeY[bikerId]; + distY *= distY; + + return distX + distY <= distanceAllowed; +} + +bool dfs(int u, long long distanceAllowed) { + if(u == -1) + return true; + if(vis[u]) + return false; + vis[u] = true; + + for(int i = 0; i < (int)M; ++i) { + int id = lt[i]; + if(validPath(u, i, distanceAllowed) && dfs(id, distanceAllowed)) { + lt[i] = u; + return true; + } + } + return false; +} + +int matching(long long tm) { + memset(lt, -1, sizeof(lt)); + + int ret = 0; + for(int i = 0; i < (int)N; ++i) { + memset(vis, 0, sizeof(vis)); + if(dfs(i, tm)) + ret++; + } + return ret; +} + +long long binarySearch(long long l = 0, long long r = 1e17) { + if(l == r) + return l; + long long mid = (l+r)/2; + int match = matching(mid); + return match >= K ? binarySearch(l, mid) : binarySearch(mid+1, r); +} + +int main() +{ + cin >> N >> M >> K; + assert(1 <= N); assert(N <= sz); + assert(1 <= M); assert(M <= sz); + assert(1 <= K); assert(K <= min(N, M)); + + for(int i = 0; i < (int)N; ++i) { + cin >> userX[i] >> userY[i]; + assert(0 <= userX[i]); assert(userX[i] <= 1e7); + assert(0 <= userY[i]); assert(userY[i] <= 1e7); + } + for(int i = 0; i < (int)M; ++i) { + cin >> bikeX[i] >> bikeY[i]; + assert(0 <= bikeX[i]); assert(bikeX[i] <= 1e7); + assert(0 <= bikeY[i]); assert(bikeY[i] <= 1e7); + } + + cout << binarySearch() << endl; + + return 0; +} + +``` +",not-set,2016-04-24T02:02:16,2016-07-23T13:49:52,C++ +29,1319,board-cutting,Cutting Boards,"[Chinese Version](https://hr-filepicker.s3.amazonaws.com/feb14/chinese/1319-chinese.md)
+[Russian Version](https://hr-filepicker.s3.amazonaws.com/feb-14/russian/1319-russian.md)
+ +Alice gives a wooden board composed of M X N wooden square pieces to Bob and asks him to find the minimal cost of breaking the board into square wooden pieces. +Bob can cut the board along horizontal and vertical lines, and each cut divides the board in smaller parts. Each cut has a cost depending on whether the cut is made along a horizontal or a vertical line. + +Let us denote the costs of cutting it along consecutive vertical lines with x1, x2, ..., xn-1, and the cost of cutting it along horizontal lines with y1, y2, ..., ym-1. If a cut (of cost **c**) is made and it passes through **n** segments, then total cost of this cut will be **n\*c**. + +The cost of cutting the whole board into single squares is the sum of the cost of successive cuts used to cut the whole board into square wooden pieces of size *1x1*. Bob should compute the minimal cost of breaking the whole wooden board into squares of size *1x1*. + +Bob needs your help to find the minimal cost. Can you help Bob with this challenge? + +**Input Format** +A single integer in the first line T, stating the number of test cases. T testcases follow. +For each test case, the first line contains two positive integers M and N separated by a single space. +In the next line, there are integers y1, y2, ..., ym-1, separated by spaces. Following them are integers x1, x2, ..., xn-1, separated by spaces. + +**Output Format** +For each test-case, write an integer in separate line which denotes the minimal cost of cutting the whole wooden board into single wooden squares. Since the answer can be very large, output the answer modulo 109+7. + +**Constraints** +1 <= T <= 20 +2 <= M,N <= 1000000 +0 <= xi <= 109 +0 <= yi <= 109 + +**Sample Input #00** + + 1 + 2 2 + 2 + 1 + +**Sample Output #00** + + 4 + +**Sample Input #01** + + 1 + 6 4 + 2 1 3 1 4 + 4 1 2 + +**Sample Output #01** + + 42 + +**Explanation** +*Sample Case #00:*At first, board should be cut horizontally, where y1 = 2, then it should be cut vertically. So total cost will be 2\*1 + 1\*2 = 4. + +*Sample Case #01:* We should start cutting using y5, x1, y3, y1, x3, y2, y4 and x2, in order. First cut will be a horizontal one where cost = y5 = 4. Next we will do a vertical cut with x1. Since this cut passes through two segments (created by previous vertical cut), it's total cost will be 2\*x1 = 2\*4. Similarly next horizontal cut (y3) will pass through two segments and will cost 2\*y3 = 2\*3. We can proceed in similar way and get overall cost as 4 + 4\*2 + 3\*2 + 2\*2 + 2\*4 + 1\*3 + 1\*3 + 1\*6 = 42.",code,Find the minimum cost of breaking down an m x n board into 1 x 1 pieces.,ai,2013-11-15T11:51:49,2022-08-31T08:14:37,"# +# Complete the 'boardCutting' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER_ARRAY cost_y +# 2. INTEGER_ARRAY cost_x +# + +def boardCutting(cost_y, cost_x): + # 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') + + q = int(input().strip()) + + for q_itr in range(q): + first_multiple_input = input().rstrip().split() + + m = int(first_multiple_input[0]) + + n = int(first_multiple_input[1]) + + cost_y = list(map(int, input().rstrip().split())) + + cost_x = list(map(int, input().rstrip().split())) + + result = boardCutting(cost_y, cost_x) + + fptr.write(str(result) + '\n') + + fptr.close() +","Alice gives Bob a board composed of $1 \times 1$ wooden squares and asks him to find the minimum cost of breaking the board back down into its individual squares. To break the board down, Bob must make cuts along its horizontal and vertical lines. + +To reduce the board to squares, Bob makes horizontal and vertical cuts across the entire board. Each cut has a given cost, $cost\_y[i]$ or $cost\_x[j]$ for each cut along a row or column across one board, so the cost of a cut must be multiplied by the number of segments it crosses. The cost of cutting the whole board down into $1 \times 1$ squares is the sum of the costs of each successive cut. + +Can you help Bob find the minimum cost? The number may be large, so print the value modulo $10^9+7$. + +For example, you start with a $2\times 2$ board. There are two cuts to be made at a cost of $cost\_y[1]=3$ for the horizontal and $cost\_x[1]=1$ for the vertical. Your first cut is across $1$ piece, the whole board. You choose to make the horizontal cut between rows $1$ and $2$ for a cost of $1\times 3=3$. The second cuts are vertical through the two smaller boards created in step $1$ between columns $1$ and $2$. Their cost is $2\times 1=2$. The total cost is $3 + 2=5$ and $5\%(10^9+7)=5$. + +**Function Description** + +Complete the *boardCutting* function in the editor below. It should return an integer. + +boardCutting has the following parameter(s): + +- *cost_x*: an array of integers, the costs of vertical cuts +- *cost_y*: an array of integers, the costs of horizontal cuts ",0.5,"[""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""]","The first line contains an integer $q$, the number of queries. + +The following $q$ sets of lines are as follows: + +- The first line has two positive space-separated integers $m$ and $n$, the number of rows and columns in the board. +- The second line contains $m-1$ space-separated integers cost_y[i], the cost of a horizontal cut between rows $[i]$ and $[i+1]$ of one board. +- The third line contains $n-1$ space-separated integers cost_x[j], the cost of a vertical cut between columns $[j]$ and $[j+1]$ of one board. +","For each of the $q$ queries, find the minimum cost ($minCost$) of cutting the board into $1 \times 1$ squares and print the value of $minCost \text{ % } (10^9+7)$. + +**Sample Input 0** + + 1 + 2 2 + 2 + 1 + +**Sample Output 0** + + 4 + +**Explanation 0** +We have a $2 \times 2$ board, with cut costs $cost\_y[1] = 2$ and $cost\_x[1] = 1$. Our first cut is horizontal between $y[1]$ and $y[2]$, because that is the line with the highest cost ($2$). Our second cut is vertical, at $x[1]$. Our first cut has a $totalCost$ of $2$ because we are making a cut with cost $cost\_y[1]=2$ across $1$ segment, the uncut board. The second cut also has a $totalCost$ of $2$ but we are making a cut of cost $cost\_x[1]=1$ across $2$ segments. Our answer is $minCost = ( (2 \times 1) + (1 \times 2) ) \ \% \ (10^9+7) = 4$. + +**Sample Input 1** + + 1 + 6 4 + 2 1 3 1 4 + 4 1 2 + +**Sample Output 1** + + 42 + +**Explanation 1** +Our sequence of cuts is: $y[5]$, $x[1]$, $y[3]$, $y[1]$, $x[3]$, $y[2]$, $y[4]$ and $x[2]$. +*Cut 1:* Horizontal with cost $cost\_y[5] = 4$ across $1$ segment. $totalCost = 4 \times 1 = 4$. +*Cut 2:* Vertical with cost $cost\_x[1] = 4$ across $2$ segments. $totalCost = 4 \times 2 = 8$. +*Cut 3:* Horizontal with cost $cost\_y[3] = 3$ across $2$ segments. $totalCost = 3 \times 2 = 6$. +*Cut 4:* Horizontal with cost $cost\_y[1] = 2$ across $2$ segments. $totalCost = 2 \times 2 = 4$. +*Cut 5:* Vertical with cost $cost\_x[3] = 2$ across $4$ segments. $totalCost = 2 \times 4 = 8$. +*Cut 6:* Horizontal with cost $cost\_y[2] = 1$ across $3$ segments. $totalCost = 1 \times 3 = 3$. +*Cut 7:* Horizontal with cost $cost\_y[4] = 1$ across $3$ segments. $totalCost = 1 \times 3 = 3$. +*Cut 8:* Vertical with cost $cost\_x[2] = 1$ across $6$ segments. $totalCost = 1 \times 6 = 6$. + +$totalCost =4 + 8 + 6 + 4 + 8 + 3 + 3 + 6 = 42$. We then print the value of $42 \ \% \ (10^9 + 7)$. + +", , ,Hard,Cutting Boards - 2020 Hack February Editorial,"

Cutting Boards

+ +

Difficulty : Easy-Medium

+ +

Required Knowledge : Greedy Algorithm

+ +

Approach

+ +

The board should be broken in square wooden pieces, so that means we have to cut the board along every horizontal and verticle line.The order in which we make the cuts is important here.For minimum cost, sort the lines according to cost in decreasing order.

+ +

Let there be a 5x5 board and the cost along horizontal lines be y1,y2,y3,y4,y5 and along verticle lines be x1,x2,x3,x4,x5

+ +

Sort the lines according to cost in decreasing order.Let the lines be y4,x3,y5,x2,x1,y1,x4,y2,y3,x5 in decreasing order of cost.

+ +
V = number of vertical cuts
+H = number of horizontal cuts
+
+ +

Initially both V and H be zero +minimum_cost=0 +Now traverse the lines in sorted order + if the line is horizontal + minimum_cost+=(cost of cut along that particular line)(V+1) + H++ + if the line is verticle + minimum_cost+=(cost of cut along that particular line)(H+1) + V++

+ +

Setter's Solution

+ +
#include<cstdio>
+#include<iostream>
+#include<algorithm>
+using namespace std;
+struct arr{
+    long long int val;
+    int horv;
+};
+typedef struct arr arr;
+int compare(arr c , arr d){
+    if(c.val > d.val){
+        return 1;
+    }
+    return 0;
+}
+arr a[2000020];
+int main(){
+    int tc;
+    scanf(""%d"",&tc);
+    while(tc--){
+        int n,m;
+        scanf(""%d %d"",&m,&n);
+        int i;
+        int j=0;
+        for(i=1;i<m;i++){
+            scanf(""%lld"",&a[j].val);
+            a[j].horv=1;    // its a horizontal line
+            j++;
+        }
+        for(i=1;i<n;i++){
+            scanf(""%lld"",&a[j].val);
+            a[j].horv=0;  // verticle line
+            j++;
+        }
+        sort(a,a+j,compare);
+        int v=0;
+        int h=0;
+        long long int cost=0;
+        for(i=0;i<j;i++){
+            if(a[i].horv==1){  // making cut along horizontal line
+                cost=(cost+(a[i].val*(v+1))%1000000007)%1000000007;
+                h++;
+            }
+            else if(a[i].horv==0){  // making cut along verticle line
+                cost=(cost+(a[i].val*(h+1))%1000000007)%1000000007;
+                v++;
+            }
+        }
+        printf(""%lld\n"",cost);
+    }
+    return 0;
+}
+
+ +

Tester's Solution

+ +
-- {{{
+module Main where
+---------------------Import-------------------------
+import Data.List
+import qualified Data.Map as Map
+import qualified Data.Set as Set
+import Data.Char
+import Data.Int                                     -- Int32, Int64
+import System.IO
+import Data.Ratio                                   -- x = 5%6
+import Data.Bits                                    -- (.&.), (.|.), shiftL...
+import Text.Printf                                  -- printf ""%0.6f"" (1.0)
+import Control.Monad
+import qualified Data.ByteString.Lazy.Char8 as BS
+import qualified Data.Vector as V
+import System.Directory
+import System.FilePath
+-- }}}
+
+main :: IO ()
+main = BS.getContents >>= mapM_ print. validate. map readIntegerArray. BS.lines
+
+p :: Integer
+p = 10^9+7
+
+validate :: [[Integer]] -> [Integer]
+validate ([t]: arr)
+  | 3 * fromIntegral t /= length arr = error ""t /= 3*length arr""
+  | t < 0 || t > 20                  = error ""t is out of bound""
+  | otherwise                        = parse arr
+
+parse :: [[Integer]] -> [Integer]
+parse [] = []
+parse ([n, m]: a: b: left)
+  | n < 0 || n > 10^6               = error ""n is out of range""
+  | m < 0 || m > 10^6               = error ""m is out of range""
+  | fromIntegral n - 1 /= length a  = error ""n - 1 /= length a""
+  | fromIntegral m - 1 /= length b  = error ""m - 1 /= length b""
+  | any (\x -> x < 0 || x > 10^9) a = error ""element of a is out of bound""
+  | any (\x -> x < 0 || x > 10^9) b = error ""element of a is out of bound""
+  | otherwise = (solve a b): parse left
+
+solve :: [Integer] -> [Integer] -> Integer
+solve aa bb = solve1 1 (reverse. sort`$ aa) 1 (reverse. sort $`bb)
+  where
+    solve1 :: Integer -> [Integer] -> Integer -> [Integer] -> Integer
+    solve1    _          []           _          []         = 0
+    solve1    aCut       []           _          (b:brr)    = b*aCut + solve1 aCut      []  undefined brr
+    solve1    _          (a:arr)      bCut       []         = a*bCut + solve1 undefined arr bCut      []
+    solve1    aCut       (a:arr)      bCut       (b:brr)
+      | a > b     = ((a*bCut) `rem` p + solve1 (aCut+1) arr     bCut    (b:brr)) `rem` p
+      | otherwise = ((b*aCut) `rem` p + solve1 aCut     (a:arr) (bCut+1) brr   ) `rem` p
+
+---------------------Input---------------------------- {{{
+getInteger = (\(Just (x_yzpqr,_)) -> x_yzpqr). BS.readInteger
+getInt     = (\(Just (x_yzpqr,_)) -> x_yzpqr). BS.readInt
+
+getIntArray     = readIntArray
+getIntegerArray = readIntegerArray
+
+readIntArray input_pqr =
+  case x_yzpqr of
+    Just (a_yzpqr, xs_pqr) -> a_yzpqr : readIntArray xs_pqr
+    Nothing                -> []
+  where
+    x_yzpqr = BS.readInt. BS.dropWhile isSpace $ input_pqr
+
+readIntegerArray input_pqr =
+  case x_yzpqr of
+    Nothing               -> []
+    Just (y_zpqr, ys_pqr) -> y_zpqr : readIntegerArray ys_pqr
+  where
+    x_yzpqr = BS.readInteger. BS.dropWhile isSpace $ input_pqr
+------------------------------------------------------ }}}
+
",0.0,feb14-board-cutting,2014-02-27T05:13:32,"{""contest_participation"":2769,""challenge_submissions"":927,""successful_submissions"":696}",2014-02-27T05:13:32,2018-04-17T17:56:40,setter,"###C++ +```cpp + +#include +#include +#include +using namespace std; +struct arr{ + long long int val; + int horv; +}; +typedef struct arr arr; +int compare(arr c , arr d){ + if(c.val > d.val){ + return 1; + } + return 0; +} +arr a[2000020]; +int main(){ + int tc; + scanf(""%d"",&tc); + while(tc--){ + int n,m; + scanf(""%d %d"",&m,&n); + int i; + int j=0; + for(i=1;i +[Russian Version](https://hr-filepicker.s3.amazonaws.com/feb-14/russian/1319-russian.md)
+ +Alice gives a wooden board composed of M X N wooden square pieces to Bob and asks him to find the minimal cost of breaking the board into square wooden pieces. +Bob can cut the board along horizontal and vertical lines, and each cut divides the board in smaller parts. Each cut has a cost depending on whether the cut is made along a horizontal or a vertical line. + +Let us denote the costs of cutting it along consecutive vertical lines with x1, x2, ..., xn-1, and the cost of cutting it along horizontal lines with y1, y2, ..., ym-1. If a cut (of cost **c**) is made and it passes through **n** segments, then total cost of this cut will be **n\*c**. + +The cost of cutting the whole board into single squares is the sum of the cost of successive cuts used to cut the whole board into square wooden pieces of size *1x1*. Bob should compute the minimal cost of breaking the whole wooden board into squares of size *1x1*. + +Bob needs your help to find the minimal cost. Can you help Bob with this challenge? + +**Input Format** +A single integer in the first line T, stating the number of test cases. T testcases follow. +For each test case, the first line contains two positive integers M and N separated by a single space. +In the next line, there are integers y1, y2, ..., ym-1, separated by spaces. Following them are integers x1, x2, ..., xn-1, separated by spaces. + +**Output Format** +For each test-case, write an integer in separate line which denotes the minimal cost of cutting the whole wooden board into single wooden squares. Since the answer can be very large, output the answer modulo 109+7. + +**Constraints** +1 <= T <= 20 +2 <= M,N <= 1000000 +0 <= xi <= 109 +0 <= yi <= 109 + +**Sample Input #00** + + 1 + 2 2 + 2 + 1 + +**Sample Output #00** + + 4 + +**Sample Input #01** + + 1 + 6 4 + 2 1 3 1 4 + 4 1 2 + +**Sample Output #01** + + 42 + +**Explanation** +*Sample Case #00:*At first, board should be cut horizontally, where y1 = 2, then it should be cut vertically. So total cost will be 2\*1 + 1\*2 = 4. + +*Sample Case #01:* We should start cutting using y5, x1, y3, y1, x3, y2, y4 and x2, in order. First cut will be a horizontal one where cost = y5 = 4. Next we will do a vertical cut with x1. Since this cut passes through two segments (created by previous vertical cut), it's total cost will be 2\*x1 = 2\*4. Similarly next horizontal cut (y3) will pass through two segments and will cost 2\*y3 = 2\*3. We can proceed in similar way and get overall cost as 4 + 4\*2 + 3\*2 + 2\*2 + 2\*4 + 1\*3 + 1\*3 + 1\*6 = 42.",code,Find the minimum cost of breaking down an m x n board into 1 x 1 pieces.,ai,2013-11-15T11:51:49,2022-08-31T08:14:37,"# +# Complete the 'boardCutting' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER_ARRAY cost_y +# 2. INTEGER_ARRAY cost_x +# + +def boardCutting(cost_y, cost_x): + # 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') + + q = int(input().strip()) + + for q_itr in range(q): + first_multiple_input = input().rstrip().split() + + m = int(first_multiple_input[0]) + + n = int(first_multiple_input[1]) + + cost_y = list(map(int, input().rstrip().split())) + + cost_x = list(map(int, input().rstrip().split())) + + result = boardCutting(cost_y, cost_x) + + fptr.write(str(result) + '\n') + + fptr.close() +","Alice gives Bob a board composed of $1 \times 1$ wooden squares and asks him to find the minimum cost of breaking the board back down into its individual squares. To break the board down, Bob must make cuts along its horizontal and vertical lines. + +To reduce the board to squares, Bob makes horizontal and vertical cuts across the entire board. Each cut has a given cost, $cost\_y[i]$ or $cost\_x[j]$ for each cut along a row or column across one board, so the cost of a cut must be multiplied by the number of segments it crosses. The cost of cutting the whole board down into $1 \times 1$ squares is the sum of the costs of each successive cut. + +Can you help Bob find the minimum cost? The number may be large, so print the value modulo $10^9+7$. + +For example, you start with a $2\times 2$ board. There are two cuts to be made at a cost of $cost\_y[1]=3$ for the horizontal and $cost\_x[1]=1$ for the vertical. Your first cut is across $1$ piece, the whole board. You choose to make the horizontal cut between rows $1$ and $2$ for a cost of $1\times 3=3$. The second cuts are vertical through the two smaller boards created in step $1$ between columns $1$ and $2$. Their cost is $2\times 1=2$. The total cost is $3 + 2=5$ and $5\%(10^9+7)=5$. + +**Function Description** + +Complete the *boardCutting* function in the editor below. It should return an integer. + +boardCutting has the following parameter(s): + +- *cost_x*: an array of integers, the costs of vertical cuts +- *cost_y*: an array of integers, the costs of horizontal cuts ",0.5,"[""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""]","The first line contains an integer $q$, the number of queries. + +The following $q$ sets of lines are as follows: + +- The first line has two positive space-separated integers $m$ and $n$, the number of rows and columns in the board. +- The second line contains $m-1$ space-separated integers cost_y[i], the cost of a horizontal cut between rows $[i]$ and $[i+1]$ of one board. +- The third line contains $n-1$ space-separated integers cost_x[j], the cost of a vertical cut between columns $[j]$ and $[j+1]$ of one board. +","For each of the $q$ queries, find the minimum cost ($minCost$) of cutting the board into $1 \times 1$ squares and print the value of $minCost \text{ % } (10^9+7)$. + +**Sample Input 0** + + 1 + 2 2 + 2 + 1 + +**Sample Output 0** + + 4 + +**Explanation 0** +We have a $2 \times 2$ board, with cut costs $cost\_y[1] = 2$ and $cost\_x[1] = 1$. Our first cut is horizontal between $y[1]$ and $y[2]$, because that is the line with the highest cost ($2$). Our second cut is vertical, at $x[1]$. Our first cut has a $totalCost$ of $2$ because we are making a cut with cost $cost\_y[1]=2$ across $1$ segment, the uncut board. The second cut also has a $totalCost$ of $2$ but we are making a cut of cost $cost\_x[1]=1$ across $2$ segments. Our answer is $minCost = ( (2 \times 1) + (1 \times 2) ) \ \% \ (10^9+7) = 4$. + +**Sample Input 1** + + 1 + 6 4 + 2 1 3 1 4 + 4 1 2 + +**Sample Output 1** + + 42 + +**Explanation 1** +Our sequence of cuts is: $y[5]$, $x[1]$, $y[3]$, $y[1]$, $x[3]$, $y[2]$, $y[4]$ and $x[2]$. +*Cut 1:* Horizontal with cost $cost\_y[5] = 4$ across $1$ segment. $totalCost = 4 \times 1 = 4$. +*Cut 2:* Vertical with cost $cost\_x[1] = 4$ across $2$ segments. $totalCost = 4 \times 2 = 8$. +*Cut 3:* Horizontal with cost $cost\_y[3] = 3$ across $2$ segments. $totalCost = 3 \times 2 = 6$. +*Cut 4:* Horizontal with cost $cost\_y[1] = 2$ across $2$ segments. $totalCost = 2 \times 2 = 4$. +*Cut 5:* Vertical with cost $cost\_x[3] = 2$ across $4$ segments. $totalCost = 2 \times 4 = 8$. +*Cut 6:* Horizontal with cost $cost\_y[2] = 1$ across $3$ segments. $totalCost = 1 \times 3 = 3$. +*Cut 7:* Horizontal with cost $cost\_y[4] = 1$ across $3$ segments. $totalCost = 1 \times 3 = 3$. +*Cut 8:* Vertical with cost $cost\_x[2] = 1$ across $6$ segments. $totalCost = 1 \times 6 = 6$. + +$totalCost =4 + 8 + 6 + 4 + 8 + 3 + 3 + 6 = 42$. We then print the value of $42 \ \% \ (10^9 + 7)$. + +", , ,Hard,Cutting Boards - 2020 Hack February Editorial,"

Cutting Boards

+ +

Difficulty : Easy-Medium

+ +

Required Knowledge : Greedy Algorithm

+ +

Approach

+ +

The board should be broken in square wooden pieces, so that means we have to cut the board along every horizontal and verticle line.The order in which we make the cuts is important here.For minimum cost, sort the lines according to cost in decreasing order.

+ +

Let there be a 5x5 board and the cost along horizontal lines be y1,y2,y3,y4,y5 and along verticle lines be x1,x2,x3,x4,x5

+ +

Sort the lines according to cost in decreasing order.Let the lines be y4,x3,y5,x2,x1,y1,x4,y2,y3,x5 in decreasing order of cost.

+ +
V = number of vertical cuts
+H = number of horizontal cuts
+
+ +

Initially both V and H be zero +minimum_cost=0 +Now traverse the lines in sorted order + if the line is horizontal + minimum_cost+=(cost of cut along that particular line)(V+1) + H++ + if the line is verticle + minimum_cost+=(cost of cut along that particular line)(H+1) + V++

+ +

Setter's Solution

+ +
#include<cstdio>
+#include<iostream>
+#include<algorithm>
+using namespace std;
+struct arr{
+    long long int val;
+    int horv;
+};
+typedef struct arr arr;
+int compare(arr c , arr d){
+    if(c.val > d.val){
+        return 1;
+    }
+    return 0;
+}
+arr a[2000020];
+int main(){
+    int tc;
+    scanf(""%d"",&tc);
+    while(tc--){
+        int n,m;
+        scanf(""%d %d"",&m,&n);
+        int i;
+        int j=0;
+        for(i=1;i<m;i++){
+            scanf(""%lld"",&a[j].val);
+            a[j].horv=1;    // its a horizontal line
+            j++;
+        }
+        for(i=1;i<n;i++){
+            scanf(""%lld"",&a[j].val);
+            a[j].horv=0;  // verticle line
+            j++;
+        }
+        sort(a,a+j,compare);
+        int v=0;
+        int h=0;
+        long long int cost=0;
+        for(i=0;i<j;i++){
+            if(a[i].horv==1){  // making cut along horizontal line
+                cost=(cost+(a[i].val*(v+1))%1000000007)%1000000007;
+                h++;
+            }
+            else if(a[i].horv==0){  // making cut along verticle line
+                cost=(cost+(a[i].val*(h+1))%1000000007)%1000000007;
+                v++;
+            }
+        }
+        printf(""%lld\n"",cost);
+    }
+    return 0;
+}
+
+ +

Tester's Solution

+ +
-- {{{
+module Main where
+---------------------Import-------------------------
+import Data.List
+import qualified Data.Map as Map
+import qualified Data.Set as Set
+import Data.Char
+import Data.Int                                     -- Int32, Int64
+import System.IO
+import Data.Ratio                                   -- x = 5%6
+import Data.Bits                                    -- (.&.), (.|.), shiftL...
+import Text.Printf                                  -- printf ""%0.6f"" (1.0)
+import Control.Monad
+import qualified Data.ByteString.Lazy.Char8 as BS
+import qualified Data.Vector as V
+import System.Directory
+import System.FilePath
+-- }}}
+
+main :: IO ()
+main = BS.getContents >>= mapM_ print. validate. map readIntegerArray. BS.lines
+
+p :: Integer
+p = 10^9+7
+
+validate :: [[Integer]] -> [Integer]
+validate ([t]: arr)
+  | 3 * fromIntegral t /= length arr = error ""t /= 3*length arr""
+  | t < 0 || t > 20                  = error ""t is out of bound""
+  | otherwise                        = parse arr
+
+parse :: [[Integer]] -> [Integer]
+parse [] = []
+parse ([n, m]: a: b: left)
+  | n < 0 || n > 10^6               = error ""n is out of range""
+  | m < 0 || m > 10^6               = error ""m is out of range""
+  | fromIntegral n - 1 /= length a  = error ""n - 1 /= length a""
+  | fromIntegral m - 1 /= length b  = error ""m - 1 /= length b""
+  | any (\x -> x < 0 || x > 10^9) a = error ""element of a is out of bound""
+  | any (\x -> x < 0 || x > 10^9) b = error ""element of a is out of bound""
+  | otherwise = (solve a b): parse left
+
+solve :: [Integer] -> [Integer] -> Integer
+solve aa bb = solve1 1 (reverse. sort`$ aa) 1 (reverse. sort $`bb)
+  where
+    solve1 :: Integer -> [Integer] -> Integer -> [Integer] -> Integer
+    solve1    _          []           _          []         = 0
+    solve1    aCut       []           _          (b:brr)    = b*aCut + solve1 aCut      []  undefined brr
+    solve1    _          (a:arr)      bCut       []         = a*bCut + solve1 undefined arr bCut      []
+    solve1    aCut       (a:arr)      bCut       (b:brr)
+      | a > b     = ((a*bCut) `rem` p + solve1 (aCut+1) arr     bCut    (b:brr)) `rem` p
+      | otherwise = ((b*aCut) `rem` p + solve1 aCut     (a:arr) (bCut+1) brr   ) `rem` p
+
+---------------------Input---------------------------- {{{
+getInteger = (\(Just (x_yzpqr,_)) -> x_yzpqr). BS.readInteger
+getInt     = (\(Just (x_yzpqr,_)) -> x_yzpqr). BS.readInt
+
+getIntArray     = readIntArray
+getIntegerArray = readIntegerArray
+
+readIntArray input_pqr =
+  case x_yzpqr of
+    Just (a_yzpqr, xs_pqr) -> a_yzpqr : readIntArray xs_pqr
+    Nothing                -> []
+  where
+    x_yzpqr = BS.readInt. BS.dropWhile isSpace $ input_pqr
+
+readIntegerArray input_pqr =
+  case x_yzpqr of
+    Nothing               -> []
+    Just (y_zpqr, ys_pqr) -> y_zpqr : readIntegerArray ys_pqr
+  where
+    x_yzpqr = BS.readInteger. BS.dropWhile isSpace $ input_pqr
+------------------------------------------------------ }}}
+
",0.0,feb14-board-cutting,2014-02-27T05:13:32,"{""contest_participation"":2769,""challenge_submissions"":927,""successful_submissions"":696}",2014-02-27T05:13:32,2018-04-17T17:56:40,tester,"###Haskell +```haskell + + +-- {{{ +module Main where +---------------------Import------------------------- +import Data.List +import qualified Data.Map as Map +import qualified Data.Set as Set +import Data.Char +import Data.Int -- Int32, Int64 +import System.IO +import Data.Ratio -- x = 5%6 +import Data.Bits -- (.&.), (.|.), shiftL... +import Text.Printf -- printf ""%0.6f"" (1.0) +import Control.Monad +import qualified Data.ByteString.Lazy.Char8 as BS +import qualified Data.Vector as V +import System.Directory +import System.FilePath +-- }}} + +main :: IO () +main = BS.getContents >>= mapM_ print. validate. map readIntegerArray. BS.lines + +p :: Integer +p = 10^9+7 + +validate :: [[Integer]] -> [Integer] +validate ([t]: arr) + | 3 * fromIntegral t /= length arr = error ""t /= 3*length arr"" + | t < 0 || t > 20 = error ""t is out of bound"" + | otherwise = parse arr + +parse :: [[Integer]] -> [Integer] +parse [] = [] +parse ([n, m]: a: b: left) + | n < 0 || n > 10^6 = error ""n is out of range"" + | m < 0 || m > 10^6 = error ""m is out of range"" + | fromIntegral n - 1 /= length a = error ""n - 1 /= length a"" + | fromIntegral m - 1 /= length b = error ""m - 1 /= length b"" + | any (\x -> x < 0 || x > 10^9) a = error ""element of a is out of bound"" + | any (\x -> x < 0 || x > 10^9) b = error ""element of a is out of bound"" + | otherwise = (solve a b): parse left + +solve :: [Integer] -> [Integer] -> Integer +solve aa bb = solve1 1 (reverse. sort$ aa) 1 (reverse. sort $bb) + where + solve1 :: Integer -> [Integer] -> Integer -> [Integer] -> Integer + solve1 _ [] _ [] = 0 + solve1 aCut [] _ (b:brr) = b*aCut + solve1 aCut [] undefined brr + solve1 _ (a:arr) bCut [] = a*bCut + solve1 undefined arr bCut [] + solve1 aCut (a:arr) bCut (b:brr) + | a > b = ((a*bCut) `rem` p + solve1 (aCut+1) arr bCut (b:brr)) `rem` p + | otherwise = ((b*aCut) `rem` p + solve1 aCut (a:arr) (bCut+1) brr ) `rem` p + +---------------------Input---------------------------- {{{ +getInteger = (\(Just (x_yzpqr,_)) -> x_yzpqr). BS.readInteger +getInt = (\(Just (x_yzpqr,_)) -> x_yzpqr). BS.readInt + +getIntArray = readIntArray +getIntegerArray = readIntegerArray + +readIntArray input_pqr = + case x_yzpqr of + Just (a_yzpqr, xs_pqr) -> a_yzpqr : readIntArray xs_pqr + Nothing -> [] + where + x_yzpqr = BS.readInt. BS.dropWhile isSpace $ input_pqr + +readIntegerArray input_pqr = + case x_yzpqr of + Nothing -> [] + Just (y_zpqr, ys_pqr) -> y_zpqr : readIntegerArray ys_pqr + where + x_yzpqr = BS.readInteger. BS.dropWhile isSpace $ input_pqr +------------------------------------------------------ }}} + +``` +",not-set,2016-04-24T02:02:16,2016-07-23T14:26:06,Python +31,1857,mathematical-expectation,Mathematical Expectation,"[Chinese Version](https://hr-filepicker.s3.amazonaws.com/feb14/chinese/1857-chinese.md)
+[Russian Version](https://hr-filepicker.s3.amazonaws.com/feb-14/russian/1857-russian.md)
+ +Let's consider a random permutation p1, p2, ..., pN of numbers 1, 2, ..., N and calculate the value F=(X2+...+XN-1)K, where Xi equals 1 if one of the following two conditions holds: pi-1 < pi > pi+1 or pi-1 > pi < pi+1 and Xi equals 0 otherwise. What is the expected value of F? + +**Input Format:** +The first line contains two integers K and N. + +**Output Format:** +Print the expected value of F as an irreducible fraction p / q. Follow sample input for more clarification. + + +**Constraints:** +1000 <= N <= 109 +1 <= K <= 5 + +**Sample input** + + 1 1000 + +**Sample Output** + + 1996 / 3 +",code,Expected value of Seyaua's function,ai,2014-02-06T20:29:14,2022-09-02T09:55:42,,,,"Let's consider a random permutation p1, p2, ..., pN of numbers 1, 2, ..., N and calculate the value F=(X2+...+XN-1)K, where Xi equals 1 if one of the following two conditions holds: pi-1 < pi > pi+1 or pi-1 > pi < pi+1 and Xi equals 0 otherwise. What is the expected value of F? + +**Input Format:** +The first line contains two integers K and N. + +**Output Format:** +Print the expected value of F as an irreducible fraction p / q. Follow sample input for more clarification. + + +**Constraints:** +1000 <= N <= 109 +1 <= K <= 5 + +**Sample input** + + 1 1000 + +**Sample Output** + + 1996 / 3 +",0.5862068965517241,"[""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,Mathematical Expectation - 2020 Hack February Editorial,"

Mathematical Expectation

+ +

Difficulty : Medium-Hard
+Problem Setter : Levgen Soboliev

+ +

Approach

+ +
    +
  1. Let's write simple bruteforce solution and generate all answers for small N (N<=20). After that one can observe, that for each K the answer is P_K(N), where P_K is a polynom of K-th power. So, after generating small answer we can interpolate the results and get needed polynom. So, now we obtain a solution where we need to keep just the coefficients of each P_K. Do not forget that the answer can be very big, so we have to use something like BigIntegers.

  2. +
  3. We can look at random variable (X_1+X_2+..+X_N)^K open the parentheses and use the linearity of mathematical expectation. In this case we have to work with this variables very careful, because some of them are not independent. This way is much harder than previous, so this is just an idea :) But with this idea one can solve this problem for bigger K.

  4. +
+ +

Setter's Solution

+ +
import java.io.*;
+import java.util.*;
+import java.math.*;
+
+public class Solution {
+    public static void main(String[] args) {
+        new Solution().run();
+    }
+
+    // 1 : +2/3*n^1-4/3*n^0
+    // 2 : 40*n^2-144*n+131 / 90
+    // 3 : 280*n^3-1344*n^2+2063*n-1038 / 945
+    // 4 : 2800*n^4-15680*n^3+28844*n^2-19288*n+4263 / 14175
+    // 5 : 12320*n^5-73920*n^4+130328*n^3-29568*n^2-64150*n-5124 / 93555
+    // 6 : 44844800*n^6-269068800*n^5+322081760*n^4+706113408*n^3-1344748912*n^2-329275872*n+957888513 / 510810300
+
+    void output(BigInteger num, BigInteger denom) {
+        BigInteger gcd = num.gcd(denom);
+        num = num.divide(gcd);
+        denom = denom.divide(gcd);
+        System.out.println(num + "" / "" + denom);
+    }
+
+    void solve(int k, BigInteger n) {
+        if (k == 1) {
+            BigInteger num = BigInteger.valueOf(2).multiply(n).subtract(BigInteger.valueOf(4));
+            BigInteger denom = BigInteger.valueOf(3);
+            output(num, denom);
+        } else if (k == 2) {
+            BigInteger n2 = n.pow(2);
+            BigInteger num = BigInteger.valueOf(40).multiply(n2).subtract(BigInteger.valueOf(144).multiply(n)).add(BigInteger.valueOf(131));
+            BigInteger denom = BigInteger.valueOf(90);
+            output(num, denom);
+        } else if (k == 3) {
+            BigInteger n2 = n.pow(2);
+            BigInteger n3 = n.pow(3);
+            BigInteger num = BigInteger.valueOf(280).multiply(n3).subtract(BigInteger.valueOf(1344).multiply(n2)).add(BigInteger.valueOf(2063).multiply(n)).subtract(BigInteger.valueOf(1038));
+            BigInteger denom = BigInteger.valueOf(945);
+            output(num, denom);
+        } else if (k == 4) {
+            BigInteger n2 = n.pow(2);
+            BigInteger n3 = n.pow(3);
+            BigInteger n4 = n.pow(4);
+            BigInteger num = BigInteger.valueOf(2800).multiply(n4).subtract(BigInteger.valueOf(15680).multiply(n3)).add(BigInteger.valueOf(28844).multiply(n2)).subtract(BigInteger.valueOf(19288).multiply(n)).add(BigInteger.valueOf(4263));
+            BigInteger denom = BigInteger.valueOf(14175);
+            output(num, denom);
+        } else if (k == 5) {
+            BigInteger n2 = n.pow(2);
+            BigInteger n3 = n.pow(3);
+            BigInteger n4 = n.pow(4);
+            BigInteger n5 = n.pow(5);
+
+            BigInteger num = BigInteger.valueOf(12320).multiply(n5).subtract(BigInteger.valueOf(73920).multiply(n4)).add(BigInteger.valueOf(130328).multiply(n3)).subtract(BigInteger.valueOf(29568).multiply(n2)).subtract(BigInteger.valueOf(64150).multiply(n)).subtract(BigInteger.valueOf(5124));
+            BigInteger denom = BigInteger.valueOf(93555);
+            output(num, denom);
+        } else if (k == 6) {
+            BigInteger n2 = n.pow(2);
+            BigInteger n3 = n.pow(3);
+            BigInteger n4 = n.pow(4);
+            BigInteger n5 = n.pow(5);
+            BigInteger n6 = n.pow(6);
+
+            BigInteger num = BigInteger.valueOf(44844800).multiply(n6).subtract(BigInteger.valueOf(269068800).multiply(n5)).add(BigInteger.valueOf(322081760).multiply(n4)).add(BigInteger.valueOf(706113408).multiply(n3)).subtract(BigInteger.valueOf(1344748912).multiply(n2)).subtract(BigInteger.valueOf(329275872).multiply(n)).add(BigInteger.valueOf(957888513));
+            BigInteger denom = BigInteger.valueOf(510810300);
+            output(num, denom);
+        }
+    }
+
+    void run() {
+        Scanner in = new Scanner(System.in);
+        int k = in.nextInt();
+
+        BigInteger n = in.nextBigInteger();
+
+        solve(k, n);
+    }
+}
+
",0.0,feb14-mathematical-expectation,2014-03-03T12:02:38,"{""contest_participation"":2769,""challenge_submissions"":187,""successful_submissions"":38}",2014-03-03T12:02:38,2016-07-23T19:18:53,setter,"###Java +```java + +import java.io.*; +import java.util.*; +import java.math.*; + +public class Solution { + public static void main(String[] args) { + new Solution().run(); + } + + // 1 : +2/3*n^1-4/3*n^0 + // 2 : 40*n^2-144*n+131 / 90 + // 3 : 280*n^3-1344*n^2+2063*n-1038 / 945 + // 4 : 2800*n^4-15680*n^3+28844*n^2-19288*n+4263 / 14175 + // 5 : 12320*n^5-73920*n^4+130328*n^3-29568*n^2-64150*n-5124 / 93555 + // 6 : 44844800*n^6-269068800*n^5+322081760*n^4+706113408*n^3-1344748912*n^2-329275872*n+957888513 / 510810300 + + void output(BigInteger num, BigInteger denom) { + BigInteger gcd = num.gcd(denom); + num = num.divide(gcd); + denom = denom.divide(gcd); + System.out.println(num + "" / "" + denom); + } + + void solve(int k, BigInteger n) { + if (k == 1) { + BigInteger num = BigInteger.valueOf(2).multiply(n).subtract(BigInteger.valueOf(4)); + BigInteger denom = BigInteger.valueOf(3); + output(num, denom); + } else if (k == 2) { + BigInteger n2 = n.pow(2); + BigInteger num = BigInteger.valueOf(40).multiply(n2).subtract(BigInteger.valueOf(144).multiply(n)).add(BigInteger.valueOf(131)); + BigInteger denom = BigInteger.valueOf(90); + output(num, denom); + } else if (k == 3) { + BigInteger n2 = n.pow(2); + BigInteger n3 = n.pow(3); + BigInteger num = BigInteger.valueOf(280).multiply(n3).subtract(BigInteger.valueOf(1344).multiply(n2)).add(BigInteger.valueOf(2063).multiply(n)).subtract(BigInteger.valueOf(1038)); + BigInteger denom = BigInteger.valueOf(945); + output(num, denom); + } else if (k == 4) { + BigInteger n2 = n.pow(2); + BigInteger n3 = n.pow(3); + BigInteger n4 = n.pow(4); + BigInteger num = BigInteger.valueOf(2800).multiply(n4).subtract(BigInteger.valueOf(15680).multiply(n3)).add(BigInteger.valueOf(28844).multiply(n2)).subtract(BigInteger.valueOf(19288).multiply(n)).add(BigInteger.valueOf(4263)); + BigInteger denom = BigInteger.valueOf(14175); + output(num, denom); + } else if (k == 5) { + BigInteger n2 = n.pow(2); + BigInteger n3 = n.pow(3); + BigInteger n4 = n.pow(4); + BigInteger n5 = n.pow(5); + + BigInteger num = BigInteger.valueOf(12320).multiply(n5).subtract(BigInteger.valueOf(73920).multiply(n4)).add(BigInteger.valueOf(130328).multiply(n3)).subtract(BigInteger.valueOf(29568).multiply(n2)).subtract(BigInteger.valueOf(64150).multiply(n)).subtract(BigInteger.valueOf(5124)); + BigInteger denom = BigInteger.valueOf(93555); + output(num, denom); + } else if (k == 6) { + BigInteger n2 = n.pow(2); + BigInteger n3 = n.pow(3); + BigInteger n4 = n.pow(4); + BigInteger n5 = n.pow(5); + BigInteger n6 = n.pow(6); + + BigInteger num = BigInteger.valueOf(44844800).multiply(n6).subtract(BigInteger.valueOf(269068800).multiply(n5)).add(BigInteger.valueOf(322081760).multiply(n4)).add(BigInteger.valueOf(706113408).multiply(n3)).subtract(BigInteger.valueOf(1344748912).multiply(n2)).subtract(BigInteger.valueOf(329275872).multiply(n)).add(BigInteger.valueOf(957888513)); + BigInteger denom = BigInteger.valueOf(510810300); + output(num, denom); + } + } + + void run() { + Scanner in = new Scanner(System.in); + int k = in.nextInt(); + + BigInteger n = in.nextBigInteger(); + + solve(k, n); + } +} +``` +",not-set,2016-04-24T02:02:16,2016-07-23T19:18:54,Java +32,1828,isosceles-triangles,Isosceles Triangles,"[Sevenkplus](http://sevenkplus.com/) has a regular polygon. Each vertex of the polygon has a color, either white or black. Sevenkplus wants to count the number of isosceles triangles whose vertices are vertices of the regular polygon and have the same color. + +**Input Format** +The first line contains an integer T. T testcases follow. +For each test case, there is only one line, which consists of a 01-string with length >= 3. Number of vertices `n` of the regular polygon equals length of the string. The string represents color of vertices in clockwise order. `0` represents white and `1` represents black. + +**Output Format** +For each test case, output one line in the format `Case #t: ans`, where `t` is the case number (starting from 1), and `ans` is the answer. + +**Constraints** +Sum of all n in the input <= 10^6. + +**Sample Input** + + 5 + 001 + 0001 + 10001 + 111010 + 1101010 + +**Sample Output** + + Case 1: 0 + Case 2: 1 + Case 3: 1 + Case 4: 2 + Case 5: 3 + +**Explanation** + +In case 5, indices of vertices of the three monochromatic isosceles triangles are (0,3,5), (1,3,5) and (2,4,6) (assuming indices start from 0). + +**Timelimits** +Timelimits for this challenge is given [here](https://www.hackerrank.com/environment)",code,How many monochromatic isosceles triangles are there?,ai,2014-02-02T04:29:46,2022-09-02T09:55:24,,,,"[Sevenkplus](http://sevenkplus.com/) has a regular polygon. Each vertex of the polygon has a color, either white or black. Sevenkplus wants to count the number of isosceles triangles whose vertices are vertices of the regular polygon and have the same color. + +**Input Format** +The first line contains an integer T. T testcases follow. +For each test case, there is only one line, which consists of a 01-string with length >= 3. Number of vertices `n` of the regular polygon equals length of the string. The string represents color of vertices in clockwise order. `0` represents white and `1` represents black. + +**Output Format** +For each test case, output one line in the format `Case #t: ans`, where `t` is the case number (starting from 1), and `ans` is the answer. + +**Constraints** +Sum of all n in the input <= 10^6. + +**Sample Input** + + 5 + 001 + 0001 + 10001 + 111010 + 1101010 + +**Sample Output** + + Case 1: 0 + Case 2: 1 + Case 3: 1 + Case 4: 2 + Case 5: 3 + +**Explanation** + +In case 5, indices of vertices of the three monochromatic isosceles triangles are (0,3,5), (1,3,5) and (2,4,6) (assuming indices start from 0). + +**Timelimits** +Timelimits for this challenge is given [here](https://www.hackerrank.com/environment)",0.4886363636363636,"[""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,Isosceles Triangles - 101 Hack February Editorial,"

Isosceles Triangles

+ +

Difficulty : Medium-Hard
+Required Knowledge : Bichromatic Isosceles Triangles
+Problem Setter : Yuzhou Gu
+Problem Tester : Dmytro Soboliev

+ +

Approach

+ +
# of monochromatic isosceles triangl = # of triangle - # of bichromatic isosceles triangle
+
+ +

Each bichromatic isosceles triangle has two bichromatic edges, so we only need to count # of bichromatic edges.

+ +

Consider a pair (i,j) of vertices with different colors. +Then its contribution to number of bichromatic edges in isosceles triangles is determined by distance between the vertices. +With some analysis we find that this is easy to calculate.

+ +
when n is odd and n%3 != 0: 
+  each pair is in 3 iso tri
+when n is odd and n%3 == 0: 
+  each pair, except for O(n) pairs, is in 3 iso tri
+when n is even and n%3 != 0:
+  each pair, except for O(n) of them, 
+     if dis is even, is in 4 iso tri
+     if dis is odd, is in 2 iso tri
+when n is even and n%3 == 0:
+  each pair, except for O(n) of them, 
+     if dis is even, is in 4 iso tri
+     if dis is odd, is in 2 iso tri
+
+
+ +

Setter's Solution

+ +
#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <cassert>
+#include <ctime>
+#include <set>
+#include <map>
+#include <vector>
+#include <string>
+#include <sstream>
+#include <numeric>
+#include <iostream>
+#include <algorithm>
+
+using namespace std;
+
+typedef long long ll;
+typedef pair<int, int> PII;
+
+#define fi first
+#define se second
+#define mp make_pair
+#define pb push_back
+
+#define N 1000010
+char a[N]; int n;
+
+ll ff() {
+    ll S = 0;
+    if (n&1) {
+        S = (ll)n*(n-1)/2;
+        if (n%3 == 0) S -= n/3*2;
+    } else {
+        S = (ll)n*(n/2-1);
+        if (n%3 == 0) S -= n/3*2;
+    }
+    return S;
+}
+
+ll gg() {
+    ll S = 0;
+    if (n&1) {
+        int S0 = 0, S1 = 0;
+        for (int i = 0; i < n; i ++)
+            if (a[i] == '0') S0 ++;
+            else S1 ++;
+        S = (ll) S0*S1*6;
+        if (n%3 == 0) {
+            int n1 = n/3, n2 = n1*2;
+            for (int i = 0; i < n; i ++) {
+                if (a[i] != a[(i+n1)%n]) S -= 2;
+                if (a[i] != a[(i+n2)%n]) S -= 2;
+            }
+        }
+    } else {
+        int S00 = 0, S01 = 0, S10 = 0, S11 = 0;
+        for (int i = 0; i < n; i += 2)
+            if (a[i] == '0') S00 ++;
+            else S01 ++;
+        for (int i = 1; i < n; i += 2)
+            if (a[i] == '0') S10 ++;
+            else S11 ++;
+        S += (ll)S00*S01*8;
+        S += (ll)S10*S11*8;
+        S += (ll)S00*S11*4;
+        S += (ll)S10*S01*4;
+        int n1 = n/2;
+        for (int i = 0; i < n; i ++)
+            if (a[i] != a[(i+n1)%n]) S -= 2;
+        if (n%3 == 0) {
+            int n1 = n/3, n2 = n1*2;
+            for (int i = 0; i < n; i ++) {
+                if (a[i] != a[(i+n1)%n]) S -= 2;
+                if (a[i] != a[(i+n2)%n]) S -= 2;
+            }
+        }
+    }
+    return S/2;
+}
+
+int main() {
+    int __; scanf(""%d"", &__);
+    int _ = 0;
+    while (scanf(""%s"", a) != EOF) {
+        _ ++;
+        n = strlen(a);
+        cout << ""Case "" << _ << "": "" << ff()-gg()/2 << endl;
+    }
+    return 0;
+}
+
+ +

Tester's Solution

+ +
#include <iostream>
+#include <cstdio>
+#include <vector>
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <string>
+#include <ctime>
+#include <complex>
+#pragma comment (linker, ""/STACK:256000000"")
+
+using namespace std;
+
+struct base {
+    double x, y;
+    base() { x = y = 0;}
+    base(int x_) { x = x_, y = 0;}
+    base(double x_) { x = x_, y = 0;}
+    base(double x, double y): x(x), y(y) {}
+    double imag() const { return y;}
+    double real() const { return x;}
+    void imag(double value) { y = value;}
+    void real(double value) { x = value;}
+    base& operator *= (const base& other) { return *this = base(x * other.x - y * other.y, y * other.x + x * other.y);}
+    base& operator /= (double value) { return *this = base(x / value, y / value);}
+    base& operator += (const base& other) { return *this = base(x + other.x, y + other.y);}
+    base& operator -= (const base& other) { return *this = base(x - other.x, y - other.y);}
+};
+base operator * (const base& a, const base& b) { return base(a.x * b.x - a.y * b.y, a.y * b.x + a.x * b.y);}
+base operator * (const base& a, double value) { return base(a.x * value, a.y * value);}
+base operator + (const base& a, const base& b) { return base(a.x + b.x, a.y + b.y);}
+base operator - (const base& a, const base& b) { return base(a.x - b.x, a.y - b.y);}
+base operator / (const base& a, double value) { return base(a.x / value, a.y / value);}
+
+const double pi = 2 * acos(0.);
+const int maxC = 4500000;
+int rev[maxC];
+base na[maxC], nb[maxC];
+
+void shuffle(base* data, int n) {
+    for (int i = 0; i < n; ++i) {
+        if (i < rev[i]) {
+            swap(data[i], data[rev[i]]);
+        }
+    }
+}
+
+void Step(base* data, int N) {
+    if (N == 1) return;
+    Step(data, N / 2);
+    Step(data + N / 2, N / 2);
+    base w(cos(2. * pi / N), sin(2. * pi / N));
+    base cur(1), buf;
+    for (int i = 0; i < N / 2; ++i, cur *= w) {
+        buf = cur * data[i + N / 2];
+        data[i + N / 2] = data[i] - buf;
+        data[i] += buf;
+    }
+}
+
+void multiply(int a[], int n, int b[], int m, long long res[], int& len) {
+    int q = n + m;
+    int sz = 1;
+    while (sz < q) sz *= 2;
+    for (int i = 0; i < n; ++i) na[i].x = a[i];
+    for (int i = 0; i < m; ++i) na[i].y = b[i];
+    for (int i = n; i < sz; ++i) na[i].x = 0.0;
+    for (int i = m; i < sz; ++i) na[i].y = 0.0;
+    for (int i = 0; i < sz; ++i) nb[i] = 0;
+    int bits = 0;
+    while ((1 << bits) < sz) ++bits;
+    for (int i = 0; i < sz; ++i) {
+        *(rev + i) = 0;
+        for (int j = 0; j < bits; ++j) {
+            if (i & (1 << j)) {
+                *(rev + i) += 1 << (bits - j - 1);
+            }
+        }
+    }
+    int index = 0;
+    for (int i = 0;;++i) if ((1 << i) == sz) { index = i; break;}
+    shuffle(na, sz);
+    Step(na, sz);
+
+    nb[0] = na[0].x * na[0].y;
+    for (int i = 1; i < sz; ++i) {
+        base buf1 = na[i], buf2 = base(na[sz - i].x, -na[sz - i].y);
+        base tx = (buf1 + buf2) / 2.;
+        base ty = base(0, -1) * (buf1 - buf2) / 2.;
+        nb[i] = tx * ty;
+    }
+    shuffle(nb, sz);
+
+    Step(nb, sz);
+    reverse(nb + 1, nb + sz);
+    for (int i = 0; i < sz; ++i) {
+        nb[i] /= (double)(sz);
+    }
+    for (int i = 0; i < sz; ++i) {
+        res[i] = (long long)(nb[i].real() + 0.5);
+    }
+
+    len = sz;
+    while (len > 1 && res[len - 1] == 0) --len;
+}
+
+const int maxL = 1100000;
+int c[maxL];
+long long res[4 * maxL];
+long long resO[4 * maxL];
+int ps[maxL];
+
+void buildResO(int c[], int n) {
+    for (int i = 0; i < 4 * n; ++i) {
+        resO[i] = 0;
+    }
+
+    for (int i = 0; i < 2 * n; ++i) {
+        resO[i] = res[i];
+    }
+
+    for (int i = 0; i + 1 < 2 * n; ++i) {
+        if (i < n) {
+            resO[i] += (i + 1);
+        } else {
+            resO[i] += 2 * n - 1 - i;
+        }
+    }
+
+    for (int i = 0; i < n; ++i) {
+        ps[i] = c[i];
+        if (i > 0) {
+            ps[i] += ps[i - 1];
+        }
+    }
+
+    for (int i = 0; i < n; ++i) {
+        resO[i] -= 2 * ps[i];
+    }
+
+    int current = ps[n - 1];
+    for (int i = n; i + 1 < 2 * n; ++i) {
+        current -= c[i - n];
+        resO[i] -= 2 * current;
+    }
+
+    for (int i = n + n - 1; i >= 0; --i) {
+        resO[i + n] += resO[i];
+    }
+}
+
+long long getAnswer(int c[], int n) {
+    int m;
+    for (int i = 0; i < 4 * n; ++i) {
+        res[i] = 0;
+    }
+    multiply(c, n, c, n, res, m);
+    buildResO(c, n);
+
+    for (int i = n + n - 1; i >= 0; --i) {
+        res[i + n] += res[i];
+    }
+
+    long long ways = 0LL;
+    for (int i = 0; i < n; ++i) {
+        if (c[i] == 1) {
+            ways += (res[2 * i] + res[2 * (i + n)] - 1LL) / 2LL;
+        } else {
+            ways += (resO[2 * i] + resO[2 * (i + n)] - 1LL) / 2LL;
+        }
+    }
+
+    if (n % 3 == 0) {
+        for (int i = 0; i < n / 3; ++i) {
+            if (c[i] == 1 && c[i + n / 3] == 1 && c[i + 2 * n / 3] == 1) {
+                ways -= 2LL;
+            }
+            if (c[i] == 0 && c[i + n / 3] == 0 && c[i + 2 * n / 3] == 0) {
+                ways -= 2LL;
+            }
+        }
+    }
+
+    return ways;
+}
+
+char colors[maxL];
+
+void solve(int test) {
+    scanf(""%s"", &colors);
+    int n = strlen(colors);
+    for (int i = 0; i < n; ++i) {
+        c[i] = colors[i] - '0';
+    }
+    printf(""Case %d: %lld\n"", test, getAnswer(c, n));
+    for (int i = 0; i < n; ++i) {
+        colors[i] = 0;
+    }
+}
+
+int main() {
+    //freopen(""input.txt"", ""r"", stdin);
+    //freopen(""output.txt"", ""w"", stdout);
+
+    int tests;
+    scanf(""%d\n"", &tests);
+    for (int i = 0; i < tests; ++i) {
+        solve(i + 1);
+        //cerr << (i + 1) << "": "" << clock() << endl;
+    }
+    return 0;
+}
+
",0.0,101feb14-isosceles-triangles,2014-03-03T12:39:18,"{""contest_participation"":1550,""challenge_submissions"":54,""successful_submissions"":9}",2014-03-03T12:39:18,2016-07-23T19:10:55,setter,"###C++ +```cpp + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +typedef long long ll; +typedef pair PII; + +#define fi first +#define se second +#define mp make_pair +#define pb push_back + +#define N 1000010 +char a[N]; int n; + +ll ff() { + ll S = 0; + if (n&1) { + S = (ll)n*(n-1)/2; + if (n%3 == 0) S -= n/3*2; + } else { + S = (ll)n*(n/2-1); + if (n%3 == 0) S -= n/3*2; + } + return S; +} + +ll gg() { + ll S = 0; + if (n&1) { + int S0 = 0, S1 = 0; + for (int i = 0; i < n; i ++) + if (a[i] == '0') S0 ++; + else S1 ++; + S = (ll) S0*S1*6; + if (n%3 == 0) { + int n1 = n/3, n2 = n1*2; + for (int i = 0; i < n; i ++) { + if (a[i] != a[(i+n1)%n]) S -= 2; + if (a[i] != a[(i+n2)%n]) S -= 2; + } + } + } else { + int S00 = 0, S01 = 0, S10 = 0, S11 = 0; + for (int i = 0; i < n; i += 2) + if (a[i] == '0') S00 ++; + else S01 ++; + for (int i = 1; i < n; i += 2) + if (a[i] == '0') S10 ++; + else S11 ++; + S += (ll)S00*S01*8; + S += (ll)S10*S11*8; + S += (ll)S00*S11*4; + S += (ll)S10*S01*4; + int n1 = n/2; + for (int i = 0; i < n; i ++) + if (a[i] != a[(i+n1)%n]) S -= 2; + if (n%3 == 0) { + int n1 = n/3, n2 = n1*2; + for (int i = 0; i < n; i ++) { + if (a[i] != a[(i+n1)%n]) S -= 2; + if (a[i] != a[(i+n2)%n]) S -= 2; + } + } + } + return S/2; +} + +int main() { + int __; scanf(""%d"", &__); + int _ = 0; + while (scanf(""%s"", a) != EOF) { + _ ++; + n = strlen(a); + cout << ""Case "" << _ << "": "" << ff()-gg()/2 << endl; + } + return 0; +} +``` +",not-set,2016-04-24T02:02:16,2016-07-23T19:10:40,C++ +33,1828,isosceles-triangles,Isosceles Triangles,"[Sevenkplus](http://sevenkplus.com/) has a regular polygon. Each vertex of the polygon has a color, either white or black. Sevenkplus wants to count the number of isosceles triangles whose vertices are vertices of the regular polygon and have the same color. + +**Input Format** +The first line contains an integer T. T testcases follow. +For each test case, there is only one line, which consists of a 01-string with length >= 3. Number of vertices `n` of the regular polygon equals length of the string. The string represents color of vertices in clockwise order. `0` represents white and `1` represents black. + +**Output Format** +For each test case, output one line in the format `Case #t: ans`, where `t` is the case number (starting from 1), and `ans` is the answer. + +**Constraints** +Sum of all n in the input <= 10^6. + +**Sample Input** + + 5 + 001 + 0001 + 10001 + 111010 + 1101010 + +**Sample Output** + + Case 1: 0 + Case 2: 1 + Case 3: 1 + Case 4: 2 + Case 5: 3 + +**Explanation** + +In case 5, indices of vertices of the three monochromatic isosceles triangles are (0,3,5), (1,3,5) and (2,4,6) (assuming indices start from 0). + +**Timelimits** +Timelimits for this challenge is given [here](https://www.hackerrank.com/environment)",code,How many monochromatic isosceles triangles are there?,ai,2014-02-02T04:29:46,2022-09-02T09:55:24,,,,"[Sevenkplus](http://sevenkplus.com/) has a regular polygon. Each vertex of the polygon has a color, either white or black. Sevenkplus wants to count the number of isosceles triangles whose vertices are vertices of the regular polygon and have the same color. + +**Input Format** +The first line contains an integer T. T testcases follow. +For each test case, there is only one line, which consists of a 01-string with length >= 3. Number of vertices `n` of the regular polygon equals length of the string. The string represents color of vertices in clockwise order. `0` represents white and `1` represents black. + +**Output Format** +For each test case, output one line in the format `Case #t: ans`, where `t` is the case number (starting from 1), and `ans` is the answer. + +**Constraints** +Sum of all n in the input <= 10^6. + +**Sample Input** + + 5 + 001 + 0001 + 10001 + 111010 + 1101010 + +**Sample Output** + + Case 1: 0 + Case 2: 1 + Case 3: 1 + Case 4: 2 + Case 5: 3 + +**Explanation** + +In case 5, indices of vertices of the three monochromatic isosceles triangles are (0,3,5), (1,3,5) and (2,4,6) (assuming indices start from 0). + +**Timelimits** +Timelimits for this challenge is given [here](https://www.hackerrank.com/environment)",0.4886363636363636,"[""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,Isosceles Triangles - 101 Hack February Editorial,"

Isosceles Triangles

+ +

Difficulty : Medium-Hard
+Required Knowledge : Bichromatic Isosceles Triangles
+Problem Setter : Yuzhou Gu
+Problem Tester : Dmytro Soboliev

+ +

Approach

+ +
# of monochromatic isosceles triangl = # of triangle - # of bichromatic isosceles triangle
+
+ +

Each bichromatic isosceles triangle has two bichromatic edges, so we only need to count # of bichromatic edges.

+ +

Consider a pair (i,j) of vertices with different colors. +Then its contribution to number of bichromatic edges in isosceles triangles is determined by distance between the vertices. +With some analysis we find that this is easy to calculate.

+ +
when n is odd and n%3 != 0: 
+  each pair is in 3 iso tri
+when n is odd and n%3 == 0: 
+  each pair, except for O(n) pairs, is in 3 iso tri
+when n is even and n%3 != 0:
+  each pair, except for O(n) of them, 
+     if dis is even, is in 4 iso tri
+     if dis is odd, is in 2 iso tri
+when n is even and n%3 == 0:
+  each pair, except for O(n) of them, 
+     if dis is even, is in 4 iso tri
+     if dis is odd, is in 2 iso tri
+
+
+ +

Setter's Solution

+ +
#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <cassert>
+#include <ctime>
+#include <set>
+#include <map>
+#include <vector>
+#include <string>
+#include <sstream>
+#include <numeric>
+#include <iostream>
+#include <algorithm>
+
+using namespace std;
+
+typedef long long ll;
+typedef pair<int, int> PII;
+
+#define fi first
+#define se second
+#define mp make_pair
+#define pb push_back
+
+#define N 1000010
+char a[N]; int n;
+
+ll ff() {
+    ll S = 0;
+    if (n&1) {
+        S = (ll)n*(n-1)/2;
+        if (n%3 == 0) S -= n/3*2;
+    } else {
+        S = (ll)n*(n/2-1);
+        if (n%3 == 0) S -= n/3*2;
+    }
+    return S;
+}
+
+ll gg() {
+    ll S = 0;
+    if (n&1) {
+        int S0 = 0, S1 = 0;
+        for (int i = 0; i < n; i ++)
+            if (a[i] == '0') S0 ++;
+            else S1 ++;
+        S = (ll) S0*S1*6;
+        if (n%3 == 0) {
+            int n1 = n/3, n2 = n1*2;
+            for (int i = 0; i < n; i ++) {
+                if (a[i] != a[(i+n1)%n]) S -= 2;
+                if (a[i] != a[(i+n2)%n]) S -= 2;
+            }
+        }
+    } else {
+        int S00 = 0, S01 = 0, S10 = 0, S11 = 0;
+        for (int i = 0; i < n; i += 2)
+            if (a[i] == '0') S00 ++;
+            else S01 ++;
+        for (int i = 1; i < n; i += 2)
+            if (a[i] == '0') S10 ++;
+            else S11 ++;
+        S += (ll)S00*S01*8;
+        S += (ll)S10*S11*8;
+        S += (ll)S00*S11*4;
+        S += (ll)S10*S01*4;
+        int n1 = n/2;
+        for (int i = 0; i < n; i ++)
+            if (a[i] != a[(i+n1)%n]) S -= 2;
+        if (n%3 == 0) {
+            int n1 = n/3, n2 = n1*2;
+            for (int i = 0; i < n; i ++) {
+                if (a[i] != a[(i+n1)%n]) S -= 2;
+                if (a[i] != a[(i+n2)%n]) S -= 2;
+            }
+        }
+    }
+    return S/2;
+}
+
+int main() {
+    int __; scanf(""%d"", &__);
+    int _ = 0;
+    while (scanf(""%s"", a) != EOF) {
+        _ ++;
+        n = strlen(a);
+        cout << ""Case "" << _ << "": "" << ff()-gg()/2 << endl;
+    }
+    return 0;
+}
+
+ +

Tester's Solution

+ +
#include <iostream>
+#include <cstdio>
+#include <vector>
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <string>
+#include <ctime>
+#include <complex>
+#pragma comment (linker, ""/STACK:256000000"")
+
+using namespace std;
+
+struct base {
+    double x, y;
+    base() { x = y = 0;}
+    base(int x_) { x = x_, y = 0;}
+    base(double x_) { x = x_, y = 0;}
+    base(double x, double y): x(x), y(y) {}
+    double imag() const { return y;}
+    double real() const { return x;}
+    void imag(double value) { y = value;}
+    void real(double value) { x = value;}
+    base& operator *= (const base& other) { return *this = base(x * other.x - y * other.y, y * other.x + x * other.y);}
+    base& operator /= (double value) { return *this = base(x / value, y / value);}
+    base& operator += (const base& other) { return *this = base(x + other.x, y + other.y);}
+    base& operator -= (const base& other) { return *this = base(x - other.x, y - other.y);}
+};
+base operator * (const base& a, const base& b) { return base(a.x * b.x - a.y * b.y, a.y * b.x + a.x * b.y);}
+base operator * (const base& a, double value) { return base(a.x * value, a.y * value);}
+base operator + (const base& a, const base& b) { return base(a.x + b.x, a.y + b.y);}
+base operator - (const base& a, const base& b) { return base(a.x - b.x, a.y - b.y);}
+base operator / (const base& a, double value) { return base(a.x / value, a.y / value);}
+
+const double pi = 2 * acos(0.);
+const int maxC = 4500000;
+int rev[maxC];
+base na[maxC], nb[maxC];
+
+void shuffle(base* data, int n) {
+    for (int i = 0; i < n; ++i) {
+        if (i < rev[i]) {
+            swap(data[i], data[rev[i]]);
+        }
+    }
+}
+
+void Step(base* data, int N) {
+    if (N == 1) return;
+    Step(data, N / 2);
+    Step(data + N / 2, N / 2);
+    base w(cos(2. * pi / N), sin(2. * pi / N));
+    base cur(1), buf;
+    for (int i = 0; i < N / 2; ++i, cur *= w) {
+        buf = cur * data[i + N / 2];
+        data[i + N / 2] = data[i] - buf;
+        data[i] += buf;
+    }
+}
+
+void multiply(int a[], int n, int b[], int m, long long res[], int& len) {
+    int q = n + m;
+    int sz = 1;
+    while (sz < q) sz *= 2;
+    for (int i = 0; i < n; ++i) na[i].x = a[i];
+    for (int i = 0; i < m; ++i) na[i].y = b[i];
+    for (int i = n; i < sz; ++i) na[i].x = 0.0;
+    for (int i = m; i < sz; ++i) na[i].y = 0.0;
+    for (int i = 0; i < sz; ++i) nb[i] = 0;
+    int bits = 0;
+    while ((1 << bits) < sz) ++bits;
+    for (int i = 0; i < sz; ++i) {
+        *(rev + i) = 0;
+        for (int j = 0; j < bits; ++j) {
+            if (i & (1 << j)) {
+                *(rev + i) += 1 << (bits - j - 1);
+            }
+        }
+    }
+    int index = 0;
+    for (int i = 0;;++i) if ((1 << i) == sz) { index = i; break;}
+    shuffle(na, sz);
+    Step(na, sz);
+
+    nb[0] = na[0].x * na[0].y;
+    for (int i = 1; i < sz; ++i) {
+        base buf1 = na[i], buf2 = base(na[sz - i].x, -na[sz - i].y);
+        base tx = (buf1 + buf2) / 2.;
+        base ty = base(0, -1) * (buf1 - buf2) / 2.;
+        nb[i] = tx * ty;
+    }
+    shuffle(nb, sz);
+
+    Step(nb, sz);
+    reverse(nb + 1, nb + sz);
+    for (int i = 0; i < sz; ++i) {
+        nb[i] /= (double)(sz);
+    }
+    for (int i = 0; i < sz; ++i) {
+        res[i] = (long long)(nb[i].real() + 0.5);
+    }
+
+    len = sz;
+    while (len > 1 && res[len - 1] == 0) --len;
+}
+
+const int maxL = 1100000;
+int c[maxL];
+long long res[4 * maxL];
+long long resO[4 * maxL];
+int ps[maxL];
+
+void buildResO(int c[], int n) {
+    for (int i = 0; i < 4 * n; ++i) {
+        resO[i] = 0;
+    }
+
+    for (int i = 0; i < 2 * n; ++i) {
+        resO[i] = res[i];
+    }
+
+    for (int i = 0; i + 1 < 2 * n; ++i) {
+        if (i < n) {
+            resO[i] += (i + 1);
+        } else {
+            resO[i] += 2 * n - 1 - i;
+        }
+    }
+
+    for (int i = 0; i < n; ++i) {
+        ps[i] = c[i];
+        if (i > 0) {
+            ps[i] += ps[i - 1];
+        }
+    }
+
+    for (int i = 0; i < n; ++i) {
+        resO[i] -= 2 * ps[i];
+    }
+
+    int current = ps[n - 1];
+    for (int i = n; i + 1 < 2 * n; ++i) {
+        current -= c[i - n];
+        resO[i] -= 2 * current;
+    }
+
+    for (int i = n + n - 1; i >= 0; --i) {
+        resO[i + n] += resO[i];
+    }
+}
+
+long long getAnswer(int c[], int n) {
+    int m;
+    for (int i = 0; i < 4 * n; ++i) {
+        res[i] = 0;
+    }
+    multiply(c, n, c, n, res, m);
+    buildResO(c, n);
+
+    for (int i = n + n - 1; i >= 0; --i) {
+        res[i + n] += res[i];
+    }
+
+    long long ways = 0LL;
+    for (int i = 0; i < n; ++i) {
+        if (c[i] == 1) {
+            ways += (res[2 * i] + res[2 * (i + n)] - 1LL) / 2LL;
+        } else {
+            ways += (resO[2 * i] + resO[2 * (i + n)] - 1LL) / 2LL;
+        }
+    }
+
+    if (n % 3 == 0) {
+        for (int i = 0; i < n / 3; ++i) {
+            if (c[i] == 1 && c[i + n / 3] == 1 && c[i + 2 * n / 3] == 1) {
+                ways -= 2LL;
+            }
+            if (c[i] == 0 && c[i + n / 3] == 0 && c[i + 2 * n / 3] == 0) {
+                ways -= 2LL;
+            }
+        }
+    }
+
+    return ways;
+}
+
+char colors[maxL];
+
+void solve(int test) {
+    scanf(""%s"", &colors);
+    int n = strlen(colors);
+    for (int i = 0; i < n; ++i) {
+        c[i] = colors[i] - '0';
+    }
+    printf(""Case %d: %lld\n"", test, getAnswer(c, n));
+    for (int i = 0; i < n; ++i) {
+        colors[i] = 0;
+    }
+}
+
+int main() {
+    //freopen(""input.txt"", ""r"", stdin);
+    //freopen(""output.txt"", ""w"", stdout);
+
+    int tests;
+    scanf(""%d\n"", &tests);
+    for (int i = 0; i < tests; ++i) {
+        solve(i + 1);
+        //cerr << (i + 1) << "": "" << clock() << endl;
+    }
+    return 0;
+}
+
",0.0,101feb14-isosceles-triangles,2014-03-03T12:39:18,"{""contest_participation"":1550,""challenge_submissions"":54,""successful_submissions"":9}",2014-03-03T12:39:18,2016-07-23T19:10:55,tester,"###C++ +```cpp + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#pragma comment (linker, ""/STACK:256000000"") + +using namespace std; + +struct base { + double x, y; + base() { x = y = 0;} + base(int x_) { x = x_, y = 0;} + base(double x_) { x = x_, y = 0;} + base(double x, double y): x(x), y(y) {} + double imag() const { return y;} + double real() const { return x;} + void imag(double value) { y = value;} + void real(double value) { x = value;} + base& operator *= (const base& other) { return *this = base(x * other.x - y * other.y, y * other.x + x * other.y);} + base& operator /= (double value) { return *this = base(x / value, y / value);} + base& operator += (const base& other) { return *this = base(x + other.x, y + other.y);} + base& operator -= (const base& other) { return *this = base(x - other.x, y - other.y);} +}; +base operator * (const base& a, const base& b) { return base(a.x * b.x - a.y * b.y, a.y * b.x + a.x * b.y);} +base operator * (const base& a, double value) { return base(a.x * value, a.y * value);} +base operator + (const base& a, const base& b) { return base(a.x + b.x, a.y + b.y);} +base operator - (const base& a, const base& b) { return base(a.x - b.x, a.y - b.y);} +base operator / (const base& a, double value) { return base(a.x / value, a.y / value);} + +const double pi = 2 * acos(0.); +const int maxC = 4500000; +int rev[maxC]; +base na[maxC], nb[maxC]; + +void shuffle(base* data, int n) { + for (int i = 0; i < n; ++i) { + if (i < rev[i]) { + swap(data[i], data[rev[i]]); + } + } +} + +void Step(base* data, int N) { + if (N == 1) return; + Step(data, N / 2); + Step(data + N / 2, N / 2); + base w(cos(2. * pi / N), sin(2. * pi / N)); + base cur(1), buf; + for (int i = 0; i < N / 2; ++i, cur *= w) { + buf = cur * data[i + N / 2]; + data[i + N / 2] = data[i] - buf; + data[i] += buf; + } +} + +void multiply(int a[], int n, int b[], int m, long long res[], int& len) { + int q = n + m; + int sz = 1; + while (sz < q) sz *= 2; + for (int i = 0; i < n; ++i) na[i].x = a[i]; + for (int i = 0; i < m; ++i) na[i].y = b[i]; + for (int i = n; i < sz; ++i) na[i].x = 0.0; + for (int i = m; i < sz; ++i) na[i].y = 0.0; + for (int i = 0; i < sz; ++i) nb[i] = 0; + int bits = 0; + while ((1 << bits) < sz) ++bits; + for (int i = 0; i < sz; ++i) { + *(rev + i) = 0; + for (int j = 0; j < bits; ++j) { + if (i & (1 << j)) { + *(rev + i) += 1 << (bits - j - 1); + } + } + } + int index = 0; + for (int i = 0;;++i) if ((1 << i) == sz) { index = i; break;} + shuffle(na, sz); + Step(na, sz); + + nb[0] = na[0].x * na[0].y; + for (int i = 1; i < sz; ++i) { + base buf1 = na[i], buf2 = base(na[sz - i].x, -na[sz - i].y); + base tx = (buf1 + buf2) / 2.; + base ty = base(0, -1) * (buf1 - buf2) / 2.; + nb[i] = tx * ty; + } + shuffle(nb, sz); + + Step(nb, sz); + reverse(nb + 1, nb + sz); + for (int i = 0; i < sz; ++i) { + nb[i] /= (double)(sz); + } + for (int i = 0; i < sz; ++i) { + res[i] = (long long)(nb[i].real() + 0.5); + } + + len = sz; + while (len > 1 && res[len - 1] == 0) --len; +} + +const int maxL = 1100000; +int c[maxL]; +long long res[4 * maxL]; +long long resO[4 * maxL]; +int ps[maxL]; + +void buildResO(int c[], int n) { + for (int i = 0; i < 4 * n; ++i) { + resO[i] = 0; + } + + for (int i = 0; i < 2 * n; ++i) { + resO[i] = res[i]; + } + + for (int i = 0; i + 1 < 2 * n; ++i) { + if (i < n) { + resO[i] += (i + 1); + } else { + resO[i] += 2 * n - 1 - i; + } + } + + for (int i = 0; i < n; ++i) { + ps[i] = c[i]; + if (i > 0) { + ps[i] += ps[i - 1]; + } + } + + for (int i = 0; i < n; ++i) { + resO[i] -= 2 * ps[i]; + } + + int current = ps[n - 1]; + for (int i = n; i + 1 < 2 * n; ++i) { + current -= c[i - n]; + resO[i] -= 2 * current; + } + + for (int i = n + n - 1; i >= 0; --i) { + resO[i + n] += resO[i]; + } +} + +long long getAnswer(int c[], int n) { + int m; + for (int i = 0; i < 4 * n; ++i) { + res[i] = 0; + } + multiply(c, n, c, n, res, m); + buildResO(c, n); + + for (int i = n + n - 1; i >= 0; --i) { + res[i + n] += res[i]; + } + + long long ways = 0LL; + for (int i = 0; i < n; ++i) { + if (c[i] == 1) { + ways += (res[2 * i] + res[2 * (i + n)] - 1LL) / 2LL; + } else { + ways += (resO[2 * i] + resO[2 * (i + n)] - 1LL) / 2LL; + } + } + + if (n % 3 == 0) { + for (int i = 0; i < n / 3; ++i) { + if (c[i] == 1 && c[i + n / 3] == 1 && c[i + 2 * n / 3] == 1) { + ways -= 2LL; + } + if (c[i] == 0 && c[i + n / 3] == 0 && c[i + 2 * n / 3] == 0) { + ways -= 2LL; + } + } + } + + return ways; +} + +char colors[maxL]; + +void solve(int test) { + scanf(""%s"", &colors); + int n = strlen(colors); + for (int i = 0; i < n; ++i) { + c[i] = colors[i] - '0'; + } + printf(""Case %d: %lld\n"", test, getAnswer(c, n)); + for (int i = 0; i < n; ++i) { + colors[i] = 0; + } +} + +int main() { + //freopen(""input.txt"", ""r"", stdin); + //freopen(""output.txt"", ""w"", stdout); + + int tests; + scanf(""%d\n"", &tests); + for (int i = 0; i < tests; ++i) { + solve(i + 1); + //cerr << (i + 1) << "": "" << clock() << endl; + } + return 0; +} +``` +",not-set,2016-04-24T02:02:16,2016-07-23T19:10:55,C++ +34,1071,coloring-tree,Coloring Tree," + +You are given a tree with **N** nodes with every node being colored. A color is represented by an integer ranging from 1 to 109. Can you find the number of distinct colors available in a subtree rooted at the node **s**? + +**Input Format** +The first line contains three space separated integers representing the number of nodes in the tree (**N**), number of queries to answer (**M**) and the root of the tree. + +In each of the next N-1 lines, there are two space separated integers(a b) representing an edge from node a to Node b. + +N lines follow: N+ith line contains the color of the ith node. + +M lines follow: Each line containg a single integer s. + +**Output Format** +Output exactly M lines, each line containing the output of the ith query. + +**Constraints** +0=< M <= 105
+1=< N <= 105
+1=< root <= N
+1=< color of the Node <= 109
+ +**Example** + +**Sample Input** + + 4 2 1 + 1 2 + 2 4 + 2 3 + 10 + 20 + 20 + 30 + 1 + 2 + +**Sample Output** + + 3 + 2 + +**Explanation** + +Query 1-Subtree rooted at 1 is the entire tree and colors used are 10 20 20 30 , so the answer is 3(10,20 and 30) + +Query 2-Subtree rooted at 2 contains color 20 20 30, so the answer is 2(20 and 30) +",code,"Given a tree with all nodes colored, find the number of distinct colors rooted at a given node.",ai,2013-10-12T06:23:17,2022-09-02T10:00:36,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. 2D_INTEGER_ARRAY tree +# 2. INTEGER_ARRAY color +# 3. INTEGER_ARRAY s +# + +def solve(tree, color, s): + # 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() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + r = int(first_multiple_input[2]) + + tree = [] + + for _ in range(n - 1): + tree.append(list(map(int, input().rstrip().split()))) + + color = [] + + for _ in range(n): + color_item = int(input().strip()) + color.append(color_item) + + s = [] + + for _ in range(m): + s_item = int(input().strip()) + s.append(s_item) + + result = solve(tree, color, s) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() +"," + +You are given a tree with **N** nodes with every node being colored. A color is represented by an integer ranging from 1 to 109. Can you find the number of distinct colors available in a subtree rooted at the node **s**? + +**Input Format** +The first line contains three space separated integers representing the number of nodes in the tree (**N**), number of queries to answer (**M**) and the root of the tree. + +In each of the next N-1 lines, there are two space separated integers(a b) representing an edge from node a to Node b and vice-versa. + +N lines follow: N+ith line contains the color of the ith node. + +M lines follow: Each line containg a single integer s. + +**Output Format** +Output exactly M lines, each line containing the output of the ith query. + +**Constraints** +0 <= M <= 105
+1 <= N <= 105
+1 <= root <= N
+1 <= color of the Node <= 109
+ +**Example** + +**Sample Input** + + 4 2 1 + 1 2 + 2 4 + 2 3 + 10 + 20 + 20 + 30 + 1 + 2 + +**Sample Output** + + 3 + 2 + +**Explanation** + +Query 1-Subtree rooted at 1 is the entire tree and colors used are 10 20 20 30 , so the answer is 3(10,20 and 30) + +Query 2-Subtree rooted at 2 contains color 20 20 30, so the answer is 2(20 and 30) +",0.4137931034482758,"[""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,Coloring Tree - 101 Hack February Editorial,"

Difficulty Level : Medium
+Required Knowledge : DFS and Segment Trees
+Problem Setter : Devendra Agarwal
+Problem Tester : Lalit Kundu

+ +

Store the order in which you execute DFS starting from the given root.Now observe that each subtree will correspond to the sub-array of the array formed by DFS. Store the starting and ending position for each subtree in the array.

+ +

Now the question reduces to finding the number of distinct value in the sub-array.

+ +

Note that atmax 10^5 different colors are used as N<=10^5 ,so store the colors used in the tree and map it to an integer from 1 to 10^5.Now the question is to find number of distinct values in the sub-array given that all the values are from 1 to 10^5.

+ +

The result of a query [a, b] is number of integers whose last occurrence in [1, b] is >= a(Last Occurence in [1,b] is in [a,b]).

+ +

Let's have two kinds of events: QueryEvent and NumberEvent. First we read whole input and sort all events, the key for QueryEvents are their end (i.e. b for query [a, b]), and for NumberEvents the key is their position in array.

+ +

We also have a segment tree which answers the queries of kind: how many elements are at position range [x, y]. Initially the tree is empty.

+ +

Then we process events in order:
+a. When we meet a NumberEvent:
+ 1. If number has occurred before ,then we put 0 in that position of seg tree and update the tree.
+ 2. We put 1 in position of number in the segment tree.
+b.When we meet a QueryEvent:
+ - Query the segment tree (for finding number of 1's in the range), and find the answer.

+ +

Setter's Code

+ +
#include<stdio.h>
+#include<stdlib.h>
+#include<iostream>
+#include<algorithm>
+#include<vector>
+#include<string.h>
+using namespace std;
+#define Max_N 1000001
+#define INF 1000000000
+int N,color[Max_N],root,from,to,counter,parent[Max_N],s,q,search_here[Max_N],highest,last_occurence[Max_N],where,val,ind ,seg[1<<21],power[25],level,answer[Max_N];
+vector<int> myvector[Max_N];
+struct transfer
+{
+    int start,end;
+}Node[Max_N];
+typedef struct queries qu;
+struct queries
+{
+    int ind ,left,right;
+    bool operator<(const qu q)const{
+        return right<q.right;
+    }
+}Q[Max_N];
+void DFS(int rooti)
+{
+    Node[rooti].start=counter;
+    counter++;
+    while(!myvector[rooti].empty()){
+        to=myvector[rooti].back();
+        if(to!=parent[rooti]){
+            parent[to]=rooti;
+            DFS(to);
+        }
+        myvector[rooti].pop_back();
+    }
+    Node[rooti].end=counter-1;
+}
+int search(int low,int high,int s)
+{
+    int mid=(low+high)>>1;
+    if(search_here[mid]==s) return mid;
+    else if(search_here[mid]>s) return search(low,mid-1,s);
+    else    return search(mid+1,high,s);
+}
+void constant()
+{
+    power[0]=1;
+    for(int i=1;i<=23;i++)  power[i]=power[i-1]<<1;
+}
+void obtain(int x)
+{
+    int y=x;
+    level=0;
+    while(x){
+        x>>=1;
+        level++;
+    }
+    if(power[level-1]!=y)   level++;
+}
+void update(int pos,int val)
+{
+    seg[pos]=val;
+    pos=pos>>1;
+    while(pos){
+        seg[pos]=seg[pos<<1]+seg[(pos<<1)+1];
+        pos>>=1;
+    }
+    return;
+}
+int Query(int s,int e,int i,int j,int node)
+{
+    if(i>e || s>j)  return 0;
+    if(s>=i && j>=e)    return seg[node];
+    return (Query(s,((s+e)>>1),i,j,(node<<1))+Query(((s+e)>>1)+1,e,i,j,(node<<1)+1));
+}
+int main()
+{
+    int v;
+    scanf(""%d%d%d"",&N,&q,&root);
+    //connections
+    for(int i=1;i<N;i++){
+        scanf(""%d%d"",&from,&to);
+        myvector[from].push_back(to);
+        myvector[to].push_back(from);
+    }
+    counter=1;
+    parent[root]=root;
+    DFS(root);
+    //color of the graph
+    for(int i=1;i<=N;i++){
+        scanf(""%d"",&v);
+        color[Node[i].start]=v;
+        search_here[i]=v;   //finally i need to sort so no troubles
+    }
+
+
+    for(int i=0;i<q;i++){
+        scanf(""%d"",&s);
+        Q[i].ind =i;
+        Q[i].left=Node[s].start;
+        Q[i].right=Node[s].end;
+    }
+    sort(Q,Q+q);
+    sort(search_here+1,search_here+N+1);
+    highest=2;
+    for(int i=2;i<=N;i++){  
+        if(search_here[i]==search_here[highest-1])  continue;
+        else{
+            search_here[highest]=search_here[i];
+            highest++;
+        }
+    }
+    highest--;
+    where=0;
+    constant();
+    obtain(N);
+    for(int i=0;i<=N;i++)   last_occurence[i]=-INF;
+    memset(seg,0,sizeof(seg));
+    //search in search_here from 1 to highest ind ed
+    for(int i=1;i<=N;i++){
+        val=color[i];
+        ind =search(1,highest,val);
+        if(last_occurence[ind ]<0){
+            last_occurence[ind]=i;
+            update(power[level-1]+last_occurence[ind]-1,1);
+        }
+        else{
+            update(power[level-1]-1+last_occurence[ind ],0);
+            last_occurence[ind]=i;
+            update(power[level-1]-1+last_occurence[ind ],1);
+        }
+        while(Q[where].right==i){
+            answer[Q[where].ind]=Query(1,power[level-1],Q[where].left,Q[where].right,1);
+            where++;
+        }
+    }
+    for(int i=0;i<q;i++)    printf(""%d\n"",answer[i]);
+    return 0;
+}
+
+ +

Tester's Code

+ +
/*
+Author:
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%   LALIT KUNDU      %%%%%%%% 
+%%%%%%%%   IIIT HYDERABAD   %%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+*/
+#include<stdio.h>
+#include<stdlib.h>
+#include<string.h>
+#include<math.h>
+#include<iostream>
+#include<vector>
+#include<cassert>
+#include<sstream>
+#include<map>
+#include<set>
+#include<stack>
+#include<queue>
+#include<algorithm>
+using namespace std;
+#define pb push_back
+#define mp make_pair
+#define clr(x) x.clear()
+#define sz(x) ((int)(x).size())
+#define F first
+#define S second
+#define REP(i,a,b) for(i=a;i<b;i++)
+#define rep(i,b) for(i=0;i<b;i++)
+#define rep1(i,b) for(i=1;i<=b;i++)
+#define mod 1000000007
+#define pdn(n) printf(""%d\n"",n)
+#define sl(n) scanf(""%d"",&n)
+#define sd(n) scanf(""%d"",&n)
+#define pn printf(""\n"")
+typedef pair<int,int> PII;
+typedef vector<PII> VPII;
+typedef vector<int> VI;
+typedef vector<VI> VVI;
+typedef long long LL;
+#define INF 1000000007
+int LMITR[1000009];
+map < int ,int > PI;
+#define MAX 10000009
+int tree[MAX+1]={};
+void update(int idx, int val) {
+    while (idx <= MAX) {
+        tree[idx] += val;
+        idx += (idx & -idx);
+    }
+}
+int readi(int idx) {
+    int sum = 0;
+    while (idx > 0) {
+        sum +=(int) tree[idx];
+        idx -= (idx & -idx);
+    }
+    return sum;
+}
+int to[1000005],ar[1000009];
+void foo(int n, int q, vector < pair < pair < int,int >, int >  >  qu)
+{
+    int i;
+    for(i=n; i>=1; i--)
+    {
+        if(PI.count(ar[i])==0)
+            LMITR[i]=INF;
+        else LMITR[i]=PI[ar[i]];
+        PI[ar[i]]=i;
+    }
+    PI.clear();
+    for(i=1; i<=n; i++)
+        if(PI.count(ar[i])==0)
+            PI[ar[i]]=1,update(i,1);
+    sort(qu.begin(),qu.end());
+    int cur=0,ans[1000007];
+    for(i=1; i<=n; i++)
+    {
+        while(cur<q && qu[cur].F.F==i)
+        {
+            ans[qu[cur].S]=readi(qu[cur].F.S);
+            cur++;
+        }
+        if(LMITR[i]!=INF)
+            update(LMITR[i],1);
+        if(i==1)
+        {
+            if(readi(1))
+                update(1,-readi(1));
+        }
+        else
+            update(i,readi(i-1)-readi(i));
+    }
+    for(i=0; i<q; i++)
+        printf(""%d\n"",ans[i]);
+}
+VI arr[1000009];
+int mymap[1000009]={},counter=0,flag[1000009]={},siz[1000009]={};
+string str;
+int dfs1(int p)
+{
+    flag[p]=1;
+    if(siz[p]!=-1)return siz[p];
+    int i,ret=1;
+    for(i=0; i<arr[p].size(); i++)
+        if(flag[arr[p][i]]==0)ret+=dfs1(arr[p][i]);
+    siz[p]=ret;
+    return ret;
+}
+void dfs(int p)
+{
+    int j,i;
+    stack < int > mystack;
+    mystack.push(p);
+    flag[p]=1;
+    while(!mystack.empty())
+    {
+        i=mystack.top();
+        mystack.pop();
+        mymap[i]=counter;
+        counter++;
+        for(int j=0;j<arr[i].size();j++)
+        {
+            if(flag[arr[i][j]]==0)
+                mystack.push(arr[i][j]),flag[arr[i][j]]=1;
+        }
+    }
+}
+int temp[1000009]={};
+int main()
+{
+    int n,q,i,j,u,v,root,k;
+    sl(n),sl(q),sl(root);
+    root--;
+    for(i=1; i<n; i++)
+    {
+        sl(u),sl(v);
+        u--,v--;
+        arr[u].pb(v);
+        arr[v].pb(u);
+    }
+    for(i=0; i<n; i++)
+        sl(temp[i]);
+    dfs(root);
+    memset(siz,-1,sizeof(siz));
+    memset(flag,0,sizeof(flag));
+    dfs1(root);
+    for(i=1; i<=n; i++)
+    {
+        ar[mymap[i-1]+1]=temp[i-1];
+    }
+    vector < pair < pair < int ,int > , int > > query;
+    for(i=0; i<q; i++)
+    {
+        scanf(""%d"",&j);
+    query.pb(mp(mp(mymap[j-1]+1,mymap[j-1]+siz[j-1]),i));
+
+    }
+    foo(n,q,query);
+    return 0;
+}
+
",0.0,101feb14-coloring-tree,2014-03-03T16:23:22,"{""contest_participation"":1550,""challenge_submissions"":146,""successful_submissions"":86}",2014-03-03T16:23:22,2016-05-13T00:03:32,setter," + #include + #include + #include + #include + #include + #include + using namespace std; + #define Max_N 1000001 + #define INF 1000000000 + int N,color[Max_N],root,from,to,counter,parent[Max_N],s,q,search_here[Max_N],highest,last_occurence[Max_N],where,val,ind ,seg[1<<21],power[25],level,answer[Max_N]; + vector myvector[Max_N]; + struct transfer + { + int start,end; + }Node[Max_N]; + typedef struct queries qu; + struct queries + { + int ind ,left,right; + bool operator<(const qu q)const{ + return right>1; + if(search_here[mid]==s) return mid; + else if(search_here[mid]>s) return search(low,mid-1,s); + else return search(mid+1,high,s); + } + void constant() + { + power[0]=1; + for(int i=1;i<=23;i++) power[i]=power[i-1]<<1; + } + void obtain(int x) + { + int y=x; + level=0; + while(x){ + x>>=1; + level++; + } + if(power[level-1]!=y) level++; + } + void update(int pos,int val) + { + seg[pos]=val; + pos=pos>>1; + while(pos){ + seg[pos]=seg[pos<<1]+seg[(pos<<1)+1]; + pos>>=1; + } + return; + } + int Query(int s,int e,int i,int j,int node) + { + if(i>e || s>j) return 0; + if(s>=i && j>=e) return seg[node]; + return (Query(s,((s+e)>>1),i,j,(node<<1))+Query(((s+e)>>1)+1,e,i,j,(node<<1)+1)); + } + int main() + { + int v; + scanf(""%d%d%d"",&N,&q,&root); + //connections + for(int i=1;i9. Can you find the number of distinct colors available in a subtree rooted at the node **s**? + +**Input Format** +The first line contains three space separated integers representing the number of nodes in the tree (**N**), number of queries to answer (**M**) and the root of the tree. + +In each of the next N-1 lines, there are two space separated integers(a b) representing an edge from node a to Node b. + +N lines follow: N+ith line contains the color of the ith node. + +M lines follow: Each line containg a single integer s. + +**Output Format** +Output exactly M lines, each line containing the output of the ith query. + +**Constraints** +0=< M <= 105
+1=< N <= 105
+1=< root <= N
+1=< color of the Node <= 109
+ +**Example** + +**Sample Input** + + 4 2 1 + 1 2 + 2 4 + 2 3 + 10 + 20 + 20 + 30 + 1 + 2 + +**Sample Output** + + 3 + 2 + +**Explanation** + +Query 1-Subtree rooted at 1 is the entire tree and colors used are 10 20 20 30 , so the answer is 3(10,20 and 30) + +Query 2-Subtree rooted at 2 contains color 20 20 30, so the answer is 2(20 and 30) +",code,"Given a tree with all nodes colored, find the number of distinct colors rooted at a given node.",ai,2013-10-12T06:23:17,2022-09-02T10:00:36,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. 2D_INTEGER_ARRAY tree +# 2. INTEGER_ARRAY color +# 3. INTEGER_ARRAY s +# + +def solve(tree, color, s): + # 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() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + r = int(first_multiple_input[2]) + + tree = [] + + for _ in range(n - 1): + tree.append(list(map(int, input().rstrip().split()))) + + color = [] + + for _ in range(n): + color_item = int(input().strip()) + color.append(color_item) + + s = [] + + for _ in range(m): + s_item = int(input().strip()) + s.append(s_item) + + result = solve(tree, color, s) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() +"," + +You are given a tree with **N** nodes with every node being colored. A color is represented by an integer ranging from 1 to 109. Can you find the number of distinct colors available in a subtree rooted at the node **s**? + +**Input Format** +The first line contains three space separated integers representing the number of nodes in the tree (**N**), number of queries to answer (**M**) and the root of the tree. + +In each of the next N-1 lines, there are two space separated integers(a b) representing an edge from node a to Node b and vice-versa. + +N lines follow: N+ith line contains the color of the ith node. + +M lines follow: Each line containg a single integer s. + +**Output Format** +Output exactly M lines, each line containing the output of the ith query. + +**Constraints** +0 <= M <= 105
+1 <= N <= 105
+1 <= root <= N
+1 <= color of the Node <= 109
+ +**Example** + +**Sample Input** + + 4 2 1 + 1 2 + 2 4 + 2 3 + 10 + 20 + 20 + 30 + 1 + 2 + +**Sample Output** + + 3 + 2 + +**Explanation** + +Query 1-Subtree rooted at 1 is the entire tree and colors used are 10 20 20 30 , so the answer is 3(10,20 and 30) + +Query 2-Subtree rooted at 2 contains color 20 20 30, so the answer is 2(20 and 30) +",0.4137931034482758,"[""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,Coloring Tree - 101 Hack February Editorial,"

Difficulty Level : Medium
+Required Knowledge : DFS and Segment Trees
+Problem Setter : Devendra Agarwal
+Problem Tester : Lalit Kundu

+ +

Store the order in which you execute DFS starting from the given root.Now observe that each subtree will correspond to the sub-array of the array formed by DFS. Store the starting and ending position for each subtree in the array.

+ +

Now the question reduces to finding the number of distinct value in the sub-array.

+ +

Note that atmax 10^5 different colors are used as N<=10^5 ,so store the colors used in the tree and map it to an integer from 1 to 10^5.Now the question is to find number of distinct values in the sub-array given that all the values are from 1 to 10^5.

+ +

The result of a query [a, b] is number of integers whose last occurrence in [1, b] is >= a(Last Occurence in [1,b] is in [a,b]).

+ +

Let's have two kinds of events: QueryEvent and NumberEvent. First we read whole input and sort all events, the key for QueryEvents are their end (i.e. b for query [a, b]), and for NumberEvents the key is their position in array.

+ +

We also have a segment tree which answers the queries of kind: how many elements are at position range [x, y]. Initially the tree is empty.

+ +

Then we process events in order:
+a. When we meet a NumberEvent:
+ 1. If number has occurred before ,then we put 0 in that position of seg tree and update the tree.
+ 2. We put 1 in position of number in the segment tree.
+b.When we meet a QueryEvent:
+ - Query the segment tree (for finding number of 1's in the range), and find the answer.

+ +

Setter's Code

+ +
#include<stdio.h>
+#include<stdlib.h>
+#include<iostream>
+#include<algorithm>
+#include<vector>
+#include<string.h>
+using namespace std;
+#define Max_N 1000001
+#define INF 1000000000
+int N,color[Max_N],root,from,to,counter,parent[Max_N],s,q,search_here[Max_N],highest,last_occurence[Max_N],where,val,ind ,seg[1<<21],power[25],level,answer[Max_N];
+vector<int> myvector[Max_N];
+struct transfer
+{
+    int start,end;
+}Node[Max_N];
+typedef struct queries qu;
+struct queries
+{
+    int ind ,left,right;
+    bool operator<(const qu q)const{
+        return right<q.right;
+    }
+}Q[Max_N];
+void DFS(int rooti)
+{
+    Node[rooti].start=counter;
+    counter++;
+    while(!myvector[rooti].empty()){
+        to=myvector[rooti].back();
+        if(to!=parent[rooti]){
+            parent[to]=rooti;
+            DFS(to);
+        }
+        myvector[rooti].pop_back();
+    }
+    Node[rooti].end=counter-1;
+}
+int search(int low,int high,int s)
+{
+    int mid=(low+high)>>1;
+    if(search_here[mid]==s) return mid;
+    else if(search_here[mid]>s) return search(low,mid-1,s);
+    else    return search(mid+1,high,s);
+}
+void constant()
+{
+    power[0]=1;
+    for(int i=1;i<=23;i++)  power[i]=power[i-1]<<1;
+}
+void obtain(int x)
+{
+    int y=x;
+    level=0;
+    while(x){
+        x>>=1;
+        level++;
+    }
+    if(power[level-1]!=y)   level++;
+}
+void update(int pos,int val)
+{
+    seg[pos]=val;
+    pos=pos>>1;
+    while(pos){
+        seg[pos]=seg[pos<<1]+seg[(pos<<1)+1];
+        pos>>=1;
+    }
+    return;
+}
+int Query(int s,int e,int i,int j,int node)
+{
+    if(i>e || s>j)  return 0;
+    if(s>=i && j>=e)    return seg[node];
+    return (Query(s,((s+e)>>1),i,j,(node<<1))+Query(((s+e)>>1)+1,e,i,j,(node<<1)+1));
+}
+int main()
+{
+    int v;
+    scanf(""%d%d%d"",&N,&q,&root);
+    //connections
+    for(int i=1;i<N;i++){
+        scanf(""%d%d"",&from,&to);
+        myvector[from].push_back(to);
+        myvector[to].push_back(from);
+    }
+    counter=1;
+    parent[root]=root;
+    DFS(root);
+    //color of the graph
+    for(int i=1;i<=N;i++){
+        scanf(""%d"",&v);
+        color[Node[i].start]=v;
+        search_here[i]=v;   //finally i need to sort so no troubles
+    }
+
+
+    for(int i=0;i<q;i++){
+        scanf(""%d"",&s);
+        Q[i].ind =i;
+        Q[i].left=Node[s].start;
+        Q[i].right=Node[s].end;
+    }
+    sort(Q,Q+q);
+    sort(search_here+1,search_here+N+1);
+    highest=2;
+    for(int i=2;i<=N;i++){  
+        if(search_here[i]==search_here[highest-1])  continue;
+        else{
+            search_here[highest]=search_here[i];
+            highest++;
+        }
+    }
+    highest--;
+    where=0;
+    constant();
+    obtain(N);
+    for(int i=0;i<=N;i++)   last_occurence[i]=-INF;
+    memset(seg,0,sizeof(seg));
+    //search in search_here from 1 to highest ind ed
+    for(int i=1;i<=N;i++){
+        val=color[i];
+        ind =search(1,highest,val);
+        if(last_occurence[ind ]<0){
+            last_occurence[ind]=i;
+            update(power[level-1]+last_occurence[ind]-1,1);
+        }
+        else{
+            update(power[level-1]-1+last_occurence[ind ],0);
+            last_occurence[ind]=i;
+            update(power[level-1]-1+last_occurence[ind ],1);
+        }
+        while(Q[where].right==i){
+            answer[Q[where].ind]=Query(1,power[level-1],Q[where].left,Q[where].right,1);
+            where++;
+        }
+    }
+    for(int i=0;i<q;i++)    printf(""%d\n"",answer[i]);
+    return 0;
+}
+
+ +

Tester's Code

+ +
/*
+Author:
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%   LALIT KUNDU      %%%%%%%% 
+%%%%%%%%   IIIT HYDERABAD   %%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+*/
+#include<stdio.h>
+#include<stdlib.h>
+#include<string.h>
+#include<math.h>
+#include<iostream>
+#include<vector>
+#include<cassert>
+#include<sstream>
+#include<map>
+#include<set>
+#include<stack>
+#include<queue>
+#include<algorithm>
+using namespace std;
+#define pb push_back
+#define mp make_pair
+#define clr(x) x.clear()
+#define sz(x) ((int)(x).size())
+#define F first
+#define S second
+#define REP(i,a,b) for(i=a;i<b;i++)
+#define rep(i,b) for(i=0;i<b;i++)
+#define rep1(i,b) for(i=1;i<=b;i++)
+#define mod 1000000007
+#define pdn(n) printf(""%d\n"",n)
+#define sl(n) scanf(""%d"",&n)
+#define sd(n) scanf(""%d"",&n)
+#define pn printf(""\n"")
+typedef pair<int,int> PII;
+typedef vector<PII> VPII;
+typedef vector<int> VI;
+typedef vector<VI> VVI;
+typedef long long LL;
+#define INF 1000000007
+int LMITR[1000009];
+map < int ,int > PI;
+#define MAX 10000009
+int tree[MAX+1]={};
+void update(int idx, int val) {
+    while (idx <= MAX) {
+        tree[idx] += val;
+        idx += (idx & -idx);
+    }
+}
+int readi(int idx) {
+    int sum = 0;
+    while (idx > 0) {
+        sum +=(int) tree[idx];
+        idx -= (idx & -idx);
+    }
+    return sum;
+}
+int to[1000005],ar[1000009];
+void foo(int n, int q, vector < pair < pair < int,int >, int >  >  qu)
+{
+    int i;
+    for(i=n; i>=1; i--)
+    {
+        if(PI.count(ar[i])==0)
+            LMITR[i]=INF;
+        else LMITR[i]=PI[ar[i]];
+        PI[ar[i]]=i;
+    }
+    PI.clear();
+    for(i=1; i<=n; i++)
+        if(PI.count(ar[i])==0)
+            PI[ar[i]]=1,update(i,1);
+    sort(qu.begin(),qu.end());
+    int cur=0,ans[1000007];
+    for(i=1; i<=n; i++)
+    {
+        while(cur<q && qu[cur].F.F==i)
+        {
+            ans[qu[cur].S]=readi(qu[cur].F.S);
+            cur++;
+        }
+        if(LMITR[i]!=INF)
+            update(LMITR[i],1);
+        if(i==1)
+        {
+            if(readi(1))
+                update(1,-readi(1));
+        }
+        else
+            update(i,readi(i-1)-readi(i));
+    }
+    for(i=0; i<q; i++)
+        printf(""%d\n"",ans[i]);
+}
+VI arr[1000009];
+int mymap[1000009]={},counter=0,flag[1000009]={},siz[1000009]={};
+string str;
+int dfs1(int p)
+{
+    flag[p]=1;
+    if(siz[p]!=-1)return siz[p];
+    int i,ret=1;
+    for(i=0; i<arr[p].size(); i++)
+        if(flag[arr[p][i]]==0)ret+=dfs1(arr[p][i]);
+    siz[p]=ret;
+    return ret;
+}
+void dfs(int p)
+{
+    int j,i;
+    stack < int > mystack;
+    mystack.push(p);
+    flag[p]=1;
+    while(!mystack.empty())
+    {
+        i=mystack.top();
+        mystack.pop();
+        mymap[i]=counter;
+        counter++;
+        for(int j=0;j<arr[i].size();j++)
+        {
+            if(flag[arr[i][j]]==0)
+                mystack.push(arr[i][j]),flag[arr[i][j]]=1;
+        }
+    }
+}
+int temp[1000009]={};
+int main()
+{
+    int n,q,i,j,u,v,root,k;
+    sl(n),sl(q),sl(root);
+    root--;
+    for(i=1; i<n; i++)
+    {
+        sl(u),sl(v);
+        u--,v--;
+        arr[u].pb(v);
+        arr[v].pb(u);
+    }
+    for(i=0; i<n; i++)
+        sl(temp[i]);
+    dfs(root);
+    memset(siz,-1,sizeof(siz));
+    memset(flag,0,sizeof(flag));
+    dfs1(root);
+    for(i=1; i<=n; i++)
+    {
+        ar[mymap[i-1]+1]=temp[i-1];
+    }
+    vector < pair < pair < int ,int > , int > > query;
+    for(i=0; i<q; i++)
+    {
+        scanf(""%d"",&j);
+    query.pb(mp(mp(mymap[j-1]+1,mymap[j-1]+siz[j-1]),i));
+
+    }
+    foo(n,q,query);
+    return 0;
+}
+
",0.0,101feb14-coloring-tree,2014-03-03T16:23:22,"{""contest_participation"":1550,""challenge_submissions"":146,""successful_submissions"":86}",2014-03-03T16:23:22,2016-05-13T00:03:32,tester," + /* + Author: + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + %%%%%%%% LALIT KUNDU %%%%%%%% + %%%%%%%% IIIT HYDERABAD %%%%%%%% + %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + */ + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + using namespace std; + #define pb push_back + #define mp make_pair + #define clr(x) x.clear() + #define sz(x) ((int)(x).size()) + #define F first + #define S second + #define REP(i,a,b) for(i=a;i PII; + typedef vector VPII; + typedef vector VI; + typedef vector VVI; + typedef long long LL; + #define INF 1000000007 + int LMITR[1000009]; + map < int ,int > PI; + #define MAX 10000009 + int tree[MAX+1]={}; + void update(int idx, int val) { + while (idx <= MAX) { + tree[idx] += val; + idx += (idx & -idx); + } + } + int readi(int idx) { + int sum = 0; + while (idx > 0) { + sum +=(int) tree[idx]; + idx -= (idx & -idx); + } + return sum; + } + int to[1000005],ar[1000009]; + void foo(int n, int q, vector < pair < pair < int,int >, int > > qu) + { + int i; + for(i=n; i>=1; i--) + { + if(PI.count(ar[i])==0) + LMITR[i]=INF; + else LMITR[i]=PI[ar[i]]; + PI[ar[i]]=i; + } + PI.clear(); + for(i=1; i<=n; i++) + if(PI.count(ar[i])==0) + PI[ar[i]]=1,update(i,1); + sort(qu.begin(),qu.end()); + int cur=0,ans[1000007]; + for(i=1; i<=n; i++) + { + while(cur mystack; + mystack.push(p); + flag[p]=1; + while(!mystack.empty()) + { + i=mystack.top(); + mystack.pop(); + mymap[i]=counter; + counter++; + for(int j=0;j , int > > query; + for(i=0; i9 + 7). + +XOR operation on a list (or a subset of the list) is defined as the XOR of all the elements present in it.
+E.g. XOR of list containing elements {A,B,C} = ((A^B)^C), where ^ represents `XOR`. + +E.g. XOR\_SUM of list A having three elements {X1, X2, X3} can be given as follows.
+All non-empty subsets will be *{X1, X2, X3, (X1,X2), (X2,X3), (X1,X3), (X1,X2,X3)}* + +XOR\_SUM(A) = X1 + X2 + X3 + X1^X2 + X2^X3 + X1^X3 + ((X1^X2)^X3) + +**Input Format** +An integer T, denoting the number of testcases. 2T lines follow.
+Each testcase contains two lines, first line will contains an integer N +followed by second line containing N integers separated by a single space.
+ +**Output Format** +T lines, ith line containing the output of the ith testcase.
+ +**Constraints** +1 <= T <= 5
+1 <= N <= 105
+0 <= A[i] <= 109
+ +**Sample Input #00** + + 1 + 3 + 1 2 3 + +**Sample Output #00** + + 12 + +**Explanation** +The given case will have 7 non-empty subsets whose XOR is given below
+1 = 1 +2 = 2 +3 = 3 +1^2 = 3 +2^3 = 1 +3^1 = 2 +1^2^3 = 0 +So sum of all such XORs is 12.",code,"Given a list of integers, sum the XORs of all the list's non-empty subsets and mod your answer by 10^9 + 7.",ai,2013-10-22T17:20:15,2022-08-31T08:14:58,"# +# Complete the 'xoringNinja' function below. +# +# The function is expected to return an INTEGER. +# The function accepts INTEGER_ARRAY arr as parameter. +# + +def xoringNinja(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') + + t = int(input().strip()) + + for t_itr in range(t): + arr_count = int(input().strip()) + + arr = list(map(int, input().rstrip().split())) + + result = xoringNinja(arr) + + fptr.write(str(result) + '\n') + + fptr.close() +","An [XOR](https://en.wikipedia.org/wiki/Exclusive_or) operation on a list is defined here as the *xor* ($\oplus$) of all its elements (e.g.: $XOR(\{A, B, C\}) = A \oplus B \oplus C$). + +The $XorSum$ of set $arr$ is defined here as the sum of the $XOR$s of all non-empty subsets of $arr$ known as $arr'$. The set $arr'$ can be expressed as: + +$\begin{eqnarray} XorSum(arr) = \sum_{i = 1}^{2^n-1} XOR(arr'_i) = XOR(arr'_1) + XOR(arr'_2) + \dots + XOR(arr'_{2^n-2}) + XOR(arr'_{2^n-1}) \end{eqnarray}$ + +**For example:** Given set $arr = \{n_1, n_2, n_3\}$ + +- The set of possible non-empty subsets is: $arr' = \{\{n_1\}, \{n_2\}, \{n_3\}, \{n_1, n_2\}, \{n_1, n_3\}, \{n_2, n_3\}, \{n_1, n_2, n_3\}\}$ + +- The $XorSum$ of these non-empty subsets is then calculated as follows: +$XorSum(arr)$ = $ n_1 + n_2 + n_3 + (n_1 \oplus n_2) + (n_1 \oplus n_3) + (n_2 \oplus n_3) + (n_1 \oplus n_2 \oplus n_3)$ + +Given a list of $n$ space-separated integers, determine and print $XorSum\ \%\ (10^9+7)$. + +For example, $arr = \{3,4\}$. There are three possible subsets, $arr' = \{\{3\},\{4\},\{3,4\}\}$. The XOR of $arr'[1] = 3$, of $arr'[2] = 4$ and of $arr[3] = 3 \oplus 4 = 7$. The XorSum is the sum of these: $3 + 4 + 7 = 14$ and $14\ \%\ (10^9+7) = 14$. + +**Note:** The cardinality of [powerset](https://en.wikipedia.org/wiki/Power_set)$(n)$ is $2^n$, so the set of non-empty subsets of set $arr$ of size $n$ contains $2^n-1$ subsets. + +**Function Description** + +Complete the *xoringNinja* function in the editor below. It should return an integer that represents the XorSum of the input array, modulo $(10^9+7)$. + +xoringNinja has the following parameter(s): + +- *arr*: an integer array",0.4924078091106291,"[""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 $T$, the number of test cases. + +Each test case consists of two lines: +- The first line contains an integer $n$, the size of the set $arr$. +- The second line contains $n$ space-separated integers $arr[i]$. +","For each test case, print its $XorSum\ \%\ (10^9+7)$ on a new line. The $i^{th}$ line should contain the output for the $i^{th}$ test case."," 1 + 3 + 1 2 3",12,Hard,Xoring Ninja 2020 Hack March Editorial,"

Description: We have to find the sum of all subsets in which elements of each subset are XORed together. Fint it here.

+ +

Problem Tester : Shashank Sharma

+ +

Problem Editorialist : Tusshar Singh

+ +

Time Complexity : O(N) per test cases.

+ +

Solution: Find OR of all the elements and multiply it with 2^(n-1) where n is the total number of elements. This gives us the answer.

+ +

Idea:

+ +

There will be total 2^n subsets.
+If ith bit of any element is set, then that bit will be set in xor of half of the total subsets which is 2^(n-1).
+To find out all the set bits in all the numbers we find OR of all the numbers.
+Since each set bit appears in half of the total subsets we multiply OR of all numbers with 2^n-1 to get the final result.

+ +

Code:

+ +
#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+#define MOD 1000000007
+
+long long int power(long long int n, long long int k)
+{
+  long long int result, pow;
+  if(k==0)
+    return 1;
+  if(n==0)
+    return 0;
+  if(n==1)
+    return 1;
+  result=n%MOD;
+  pow=1;
+  while(pow*2<=k)
+  {
+    pow=pow*2;
+    result=(result*result);
+    result=result%MOD;
+  }
+
+  if(k-pow!=0)
+  result=result*power(n, k-pow);
+  result=result%MOD;
+
+  return result;
+}
+
+int main() {
+  int t;
+  cin>>t;
+  while(t--)
+    {
+    int n;
+    cin>>n;
+    long long ans=0,temp;
+    for(int i=0;i<n;i++)
+      {
+      cin>>temp;
+      ans|=temp;
+      }
+    ans*=power(2,n-1);
+    ans%=MOD;
+    cout<<ans<<""\n"";
+   }
+    return 0;
+}
+
+ +

Tester's Code :

+ +
#!/usr/bin
+from math import *
+t=int(raw_input())
+assert(t<=5)
+assert(t>=1)
+for i in range(0,t):
+    n=int(raw_input())
+    assert(n<=10**5)
+    assert(n>=1)
+    a=[]
+    b=[]
+    for j in range(0,int(log(10**9,2)+1)):
+        b=[0]*n
+        a.append(b)
+    number=map(int, raw_input().split())
+    for j in range(0,n):
+        z=number[j]
+        assert(z>=0)
+        assert(z<=10**9)
+        k=0
+        while(z>0):
+            a[k][j]=z&1
+            z>>=1
+            k+=1
+    sum1=0
+    for j in range(0,int(log(10**9,2)+1)):
+        od=0
+        for k in range(0,n):
+            if(a[j][k]==1):
+                od=1
+                break
+        if od!=0:
+            sum1=(sum1+ 2**(j+n-1))%1000000007
+    print sum1
+
",0.0,mar14-xoring-ninja,2014-03-23T17:52:57,"{""contest_participation"":2080,""challenge_submissions"":577,""successful_submissions"":438}",2014-03-23T17:52:57,2018-05-08T18:32:33,setter,"###C++ +```cpp + +#include +#include +#include +#include +#include +using namespace std; + +#define MOD 1000000007 + +long long int power(long long int n, long long int k) +{ + long long int result, pow; + if(k==0) + return 1; + if(n==0) + return 0; + if(n==1) + return 1; + result=n%MOD; + pow=1; + while(pow*2<=k) + { + pow=pow*2; + result=(result*result); + result=result%MOD; + } + + if(k-pow!=0) + result=result*power(n, k-pow); + result=result%MOD; + + return result; +} + +int main() { + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + long long ans=0,temp; + for(int i=0;i>temp; + ans|=temp; + } + ans*=power(2,n-1); + ans%=MOD; + cout<9 + 7). + +XOR operation on a list (or a subset of the list) is defined as the XOR of all the elements present in it.
+E.g. XOR of list containing elements {A,B,C} = ((A^B)^C), where ^ represents `XOR`. + +E.g. XOR\_SUM of list A having three elements {X1, X2, X3} can be given as follows.
+All non-empty subsets will be *{X1, X2, X3, (X1,X2), (X2,X3), (X1,X3), (X1,X2,X3)}* + +XOR\_SUM(A) = X1 + X2 + X3 + X1^X2 + X2^X3 + X1^X3 + ((X1^X2)^X3) + +**Input Format** +An integer T, denoting the number of testcases. 2T lines follow.
+Each testcase contains two lines, first line will contains an integer N +followed by second line containing N integers separated by a single space.
+ +**Output Format** +T lines, ith line containing the output of the ith testcase.
+ +**Constraints** +1 <= T <= 5
+1 <= N <= 105
+0 <= A[i] <= 109
+ +**Sample Input #00** + + 1 + 3 + 1 2 3 + +**Sample Output #00** + + 12 + +**Explanation** +The given case will have 7 non-empty subsets whose XOR is given below
+1 = 1 +2 = 2 +3 = 3 +1^2 = 3 +2^3 = 1 +3^1 = 2 +1^2^3 = 0 +So sum of all such XORs is 12.",code,"Given a list of integers, sum the XORs of all the list's non-empty subsets and mod your answer by 10^9 + 7.",ai,2013-10-22T17:20:15,2022-08-31T08:14:58,"# +# Complete the 'xoringNinja' function below. +# +# The function is expected to return an INTEGER. +# The function accepts INTEGER_ARRAY arr as parameter. +# + +def xoringNinja(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') + + t = int(input().strip()) + + for t_itr in range(t): + arr_count = int(input().strip()) + + arr = list(map(int, input().rstrip().split())) + + result = xoringNinja(arr) + + fptr.write(str(result) + '\n') + + fptr.close() +","An [XOR](https://en.wikipedia.org/wiki/Exclusive_or) operation on a list is defined here as the *xor* ($\oplus$) of all its elements (e.g.: $XOR(\{A, B, C\}) = A \oplus B \oplus C$). + +The $XorSum$ of set $arr$ is defined here as the sum of the $XOR$s of all non-empty subsets of $arr$ known as $arr'$. The set $arr'$ can be expressed as: + +$\begin{eqnarray} XorSum(arr) = \sum_{i = 1}^{2^n-1} XOR(arr'_i) = XOR(arr'_1) + XOR(arr'_2) + \dots + XOR(arr'_{2^n-2}) + XOR(arr'_{2^n-1}) \end{eqnarray}$ + +**For example:** Given set $arr = \{n_1, n_2, n_3\}$ + +- The set of possible non-empty subsets is: $arr' = \{\{n_1\}, \{n_2\}, \{n_3\}, \{n_1, n_2\}, \{n_1, n_3\}, \{n_2, n_3\}, \{n_1, n_2, n_3\}\}$ + +- The $XorSum$ of these non-empty subsets is then calculated as follows: +$XorSum(arr)$ = $ n_1 + n_2 + n_3 + (n_1 \oplus n_2) + (n_1 \oplus n_3) + (n_2 \oplus n_3) + (n_1 \oplus n_2 \oplus n_3)$ + +Given a list of $n$ space-separated integers, determine and print $XorSum\ \%\ (10^9+7)$. + +For example, $arr = \{3,4\}$. There are three possible subsets, $arr' = \{\{3\},\{4\},\{3,4\}\}$. The XOR of $arr'[1] = 3$, of $arr'[2] = 4$ and of $arr[3] = 3 \oplus 4 = 7$. The XorSum is the sum of these: $3 + 4 + 7 = 14$ and $14\ \%\ (10^9+7) = 14$. + +**Note:** The cardinality of [powerset](https://en.wikipedia.org/wiki/Power_set)$(n)$ is $2^n$, so the set of non-empty subsets of set $arr$ of size $n$ contains $2^n-1$ subsets. + +**Function Description** + +Complete the *xoringNinja* function in the editor below. It should return an integer that represents the XorSum of the input array, modulo $(10^9+7)$. + +xoringNinja has the following parameter(s): + +- *arr*: an integer array",0.4924078091106291,"[""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 $T$, the number of test cases. + +Each test case consists of two lines: +- The first line contains an integer $n$, the size of the set $arr$. +- The second line contains $n$ space-separated integers $arr[i]$. +","For each test case, print its $XorSum\ \%\ (10^9+7)$ on a new line. The $i^{th}$ line should contain the output for the $i^{th}$ test case."," 1 + 3 + 1 2 3",12,Hard,Xoring Ninja 2020 Hack March Editorial,"

Description: We have to find the sum of all subsets in which elements of each subset are XORed together. Fint it here.

+ +

Problem Tester : Shashank Sharma

+ +

Problem Editorialist : Tusshar Singh

+ +

Time Complexity : O(N) per test cases.

+ +

Solution: Find OR of all the elements and multiply it with 2^(n-1) where n is the total number of elements. This gives us the answer.

+ +

Idea:

+ +

There will be total 2^n subsets.
+If ith bit of any element is set, then that bit will be set in xor of half of the total subsets which is 2^(n-1).
+To find out all the set bits in all the numbers we find OR of all the numbers.
+Since each set bit appears in half of the total subsets we multiply OR of all numbers with 2^n-1 to get the final result.

+ +

Code:

+ +
#include <cmath>
+#include <cstdio>
+#include <vector>
+#include <iostream>
+#include <algorithm>
+using namespace std;
+
+#define MOD 1000000007
+
+long long int power(long long int n, long long int k)
+{
+  long long int result, pow;
+  if(k==0)
+    return 1;
+  if(n==0)
+    return 0;
+  if(n==1)
+    return 1;
+  result=n%MOD;
+  pow=1;
+  while(pow*2<=k)
+  {
+    pow=pow*2;
+    result=(result*result);
+    result=result%MOD;
+  }
+
+  if(k-pow!=0)
+  result=result*power(n, k-pow);
+  result=result%MOD;
+
+  return result;
+}
+
+int main() {
+  int t;
+  cin>>t;
+  while(t--)
+    {
+    int n;
+    cin>>n;
+    long long ans=0,temp;
+    for(int i=0;i<n;i++)
+      {
+      cin>>temp;
+      ans|=temp;
+      }
+    ans*=power(2,n-1);
+    ans%=MOD;
+    cout<<ans<<""\n"";
+   }
+    return 0;
+}
+
+ +

Tester's Code :

+ +
#!/usr/bin
+from math import *
+t=int(raw_input())
+assert(t<=5)
+assert(t>=1)
+for i in range(0,t):
+    n=int(raw_input())
+    assert(n<=10**5)
+    assert(n>=1)
+    a=[]
+    b=[]
+    for j in range(0,int(log(10**9,2)+1)):
+        b=[0]*n
+        a.append(b)
+    number=map(int, raw_input().split())
+    for j in range(0,n):
+        z=number[j]
+        assert(z>=0)
+        assert(z<=10**9)
+        k=0
+        while(z>0):
+            a[k][j]=z&1
+            z>>=1
+            k+=1
+    sum1=0
+    for j in range(0,int(log(10**9,2)+1)):
+        od=0
+        for k in range(0,n):
+            if(a[j][k]==1):
+                od=1
+                break
+        if od!=0:
+            sum1=(sum1+ 2**(j+n-1))%1000000007
+    print sum1
+
",0.0,mar14-xoring-ninja,2014-03-23T17:52:57,"{""contest_participation"":2080,""challenge_submissions"":577,""successful_submissions"":438}",2014-03-23T17:52:57,2018-05-08T18:32:33,tester,"###Python 2 +```python + +#!/usr/bin +from math import * +t=int(raw_input()) +assert(t<=5) +assert(t>=1) +for i in range(0,t): + n=int(raw_input()) + assert(n<=10**5) + assert(n>=1) + a=[] + b=[] + for j in range(0,int(log(10**9,2)+1)): + b=[0]*n + a.append(b) + number=map(int, raw_input().split()) + for j in range(0,n): + z=number[j] + assert(z>=0) + assert(z<=10**9) + k=0 + while(z>0): + a[k][j]=z&1 + z>>=1 + k+=1 + sum1=0 + for j in range(0,int(log(10**9,2)+1)): + od=0 + for k in range(0,n): + if(a[j][k]==1): + od=1 + break + if od!=0: + sum1=(sum1+ 2**(j+n-1))%1000000007 + print sum1 + +``` +",not-set,2016-04-24T02:02:35,2016-07-23T16:10:46,Python +38,1767,ones-and-twos,Ones and Twos," + +You are using at most **A** number of 1s and at most **B** number of 2s. How many different evaluation results are possible when they are formed in an expression containing only addition `+` sign and multiplication `*` sign are allowed? + +Note that, multiplication takes precedence over addition. + +For example, if **A=2** and **B=2**, then we have the following expressions: + +* `1`, `1*1` = 1 +* `2`, `1*2`, `1*1*2`, `1+1` = 2 +* `1+2`, `1+1*2` = 3 +* `2+2`, `2*2`, `1+1+2`, `1*2*2`, `1*1*2*2`, `1*2+1*2`, `1*1*2+2`, `1*2+2` = 4 +* `1+2+2`, `1+1*2+2` = 5 +* `1+1+2+2`, `1+1+2*2` = 6 + +So there are 6 unique results that can be formed if A = 2 and B = 2. + +**Input Format** +The first line contains the number of test cases T, T testcases follow each in a newline. +Each testcase contains 2 integers A and B separated by a single space. + +**Output Format** +Print the number of different evaluations modulo (%) (109+7.) + +**Constraints** +1 <= T <= 105 +0<=A<=1000000000 +0<=B<=1000 + +**Sample Input** + + 4 + 0 0 + 2 2 + 0 2 + 2 0 + +**Sample Output** + + 0 + 6 + 2 + 2 + +**Explanation** + ++ When A = 0, B = 0, there are no expressions, hence 0. ++ When A = 2, B = 2, as explained in the problem statement above, expressions leads to 6 possible solutions. ++ When A = 0, B = 2, we have `2`, `2+2` or `2*2`, hence 2. ++ When A = 2, B = 0, we have `1` or `1*1`, `1+1` hence 2. ",code,Using A 1's and B 2's how many different evaluations are possible only by performing addition and multiplication,ai,2014-01-29T15:42:24,2022-08-31T08:14:53,"# +# Complete the 'onesAndTwos' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER a +# 2. INTEGER b +# + +def onesAndTwos(a, b): + # 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() + + a = int(first_multiple_input[0]) + + b = int(first_multiple_input[1]) + + result = onesAndTwos(a, b) + + fptr.write(str(result) + '\n') + + fptr.close() +"," + +You are using at most **A** number of 1s and at most **B** number of 2s. How many different evaluation results are possible when they are formed in an expression containing only addition `+` sign and multiplication `*` sign are allowed? + +Note that, multiplication takes precedence over addition. + +For example, if **A=2** and **B=2**, then we have the following expressions: + +* `1`, `1*1` = 1 +* `2`, `1*2`, `1*1*2`, `1+1` = 2 +* `1+2`, `1+1*2` = 3 +* `2+2`, `2*2`, `1+1+2`, `1*2*2`, `1*1*2*2`, `1*2+1*2`, `1*1*2+2`, `1*2+2` = 4 +* `1+2+2`, `1+1*2+2` = 5 +* `1+1+2+2`, `1+1+2*2` = 6 + +So there are 6 unique results that can be formed if A = 2 and B = 2. +",0.5454545454545454,"[""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 the number of test cases T, T testcases follow each in a newline. +Each testcase contains 2 integers A and B separated by a single space. +","Print the number of different evaluations modulo (%) (109+7.) +"," 4 + 0 0 + 2 2 + 0 2 + 2 0 +"," 0 + 6 + 2 + 2 +",Hard,Ones and Twos - 2020 Hack March Editorial,"

Ones and Twos
+Difficulty Level : Medium-Hard
+Required Knowledge : DP
+Problem Setter : Shang En Huang
+Problem Tester : Dmytro Soboliev

+ +

Solution

+ +

If you are still getting wrong answer but don't know why, please try this test case:

+ +
 2
+ 6 14
+ 2 1
+
+ +

The answer should be

+ +
 301
+ 4
+
+ +

Part I.

+ +

Let's consider simple cases, say when A = 0. In this case, all numbers will be generated by using all 2's. For each integer X, consider its binary representation (a0 + a1*2 + a2*4+a3*8+...). It's not hard to prove you need at least (a1*1 + a2*2+a3*3+...) number of 2's to produce this number.

+ +

Hence when given the value of B the answer should be:

+ +
+

The number of ways partitioning i <= B into distinct sum of positive integers.

+
+ +

This can be solved by O(B2) dynamic programming: Just let dp[i][j] be the number of ways partitioning i into distinct sum of positive integers with last term (highest bit) equal or less than j. So if we consider the state dp[i][j], into two situations: the last term is j or not. If yes, there are exactly dp[i-j][j-1] ways. Otherwise it would be dp[i][j-1]. Please consider the following code:

+ +

Language : C++

+ +
for (int j = 0; j <= B; j++) dp[0][j] = 1;
+for (int i = 1; i <= B; i++)
+    for (int j = 1; j <= B; j++)
+        dp[i][j] = (i>j? dp[i-j][j-1] : 0) + dp[i][j-1];
+
+ +

Then in the case A=0, the solution can be calculated from dp[1][B] + dp[2][B] + ... + dp[B][B]. (Don't forget to mod.)

+ +

Part II: O(T A lg A + B2)

+ +

From now on, when we consider an integer, we only consider the representation with fewest 2's.

+ +

What if we have some 1's? If using only twos can make a number X, then we can build all integers in the ranage [X, X+A]. Suppose we have a number 2K, where 2A < 2K. We split the terms by ""Terms less than*2K* and terms no less than 2K"". For terms less than 2K. We will know that the sum of all parts contributed by 2's will be less than 2K (Why?).

+ +

Hence, if we choose minimal K with 2A < 2K, then we can guarantee that the sum of whole part less than 2K will still less than 2K. (Given the condition that we use least number of 2's.)

+ +

+ +

For each t, 0 <= t < 2K, let R[t] be the least number of 2's which can build t. Modify the DP table from part I: dp[i][j] be the number of ways partitioning i into distinct sum of positive integers with last term (highest bit) equal or less than j and with first term (lowest bit) at least K.

+ +
cpp
+for (int j = 0; j <= B; j++) dp[0][j] = 1;
+for (int i = 1; i <= B; i++)
+    for (int j = 1; j <= B; j++)
+        dp[i][j] = (j>=K && i>j ? dp[i-j][j-1] : 0) + dp[i][j-1];
+
+ +

In this t, the ways to make numbers that modulo 2K equals t is exactly dp[1][B] + dp[2][B] + ... + dp[B - R[t]][B]. (Please mod.)

+ +

We can easily get the relations R[0] = R[1] = ... = R[A] = 0, and for t > A, +R[t] = min0 <= j < K{ R[t-2j] + j }

+ +

In conclusion, for each test case, we can go over each 0 <= t < 2K. Then the time complexity is O(T K 2K + B^2) = O(T A lg A + B^2).

+ +

Part III: O(T lg A + B^2)

+ +

The remaining parts:

+ +
    +
  1. calculate R[0]..R[2K-1] efficiently
  2. +
  3. calculate the sum dp[ B-R[i] ][ B-R[i] ] efficiently
  4. +
+ +

In order to solve (2), we need to count ""How many i's are there such that R[i] = r?"" for each r = 0, 1, ..., 2K-1.

+ +

(Maybe not) Surprisingly, we have the following properties:

+ +

+ +
+

Prop: for any integer no more than 2K-1, we only need at most one ""2 term"".

+ +

Prop2: for any integer in (2K-1, 2K) we use at most two ""2 terms"".

+
+ +

Hence we can find the sum with a single loop enumerating from 0 to K-1.

+ +

Happy thinking & happy coding :)

+ +

Setter's Code

+ +
#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+#include <vector>
+using namespace std;
+
+#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(c) ((int)(c).size())
+
+typedef long long LL;
+int MOD = 1e9+7;
+
+int p[33][1005], up[33]={};
+void add(int &x, LL v) {
+    x = (x+v)%MOD;
+}
+
+const int MXB = 1000;
+void pre(int S) {
+    if(up[S]) return;
+    up[S] = 1;
+    p[S][0] = 1;
+    for(int l=S;l<=MXB;l++) {
+        for(int j=MXB;j>=l;j--)
+            add(p[S][j], p[S][j-l]);
+    }
+    for(int j=1;j<=MXB;j++) add(p[S][j], p[S][j-1]);
+    //printf(""build: ""); for(int j=0;j<=MXB;j++) printf(""%d "", p[S][j]); puts("""");
+}
+
+void solve() {
+    int A, B, s;
+    LL t;
+    scanf(""%d%d"", &A, &B);
+
+    if (A == 0) {
+        pre(1);
+        printf(""%d\n"", (p[1][B]+MOD-1)%MOD);
+        return;
+    }
+
+    for(t=2,s=1;t<=A;t*=2,s++);
+    t *= 2; s++;
+    pre(s);
+
+    //printf(""s=%d\n"", s);
+
+    int ans = 0;
+    LL last = 0, last2 = t/2+A+1;
+    for(int u=0;u<s && u<=B;u++) {
+        LL nxt = min(t, (1LL<<u) + A + (u>0));
+        LL nxt2 = min(t, (1LL<<u) + A + t/2 + (u>0));
+        add(ans, (nxt-last)*1LL*p[s][B-u]);
+        if(u+s-1<=B) add(ans, (nxt2-last2)*1LL*p[s][B-(u+s-1)]);
+        //printf(""u=%d: [%I64d, %I64d)  %d; [%I64d, %I64d)  \n"", u, last, nxt, p[s][B-u], last2, nxt2);
+        last = nxt;
+        last2 = nxt2;
+    }
+    //printf(""nxt=%I64d\n"", last);
+    printf(""%d\n"", (ans+MOD-1)%MOD);
+}
+
+int main(void) {
+    int T;
+    scanf(""%d"", &T);
+    while(T--) solve();
+    return 0;
+}
+
+ +

Tester's Code

+ +
#include <iostream>
+#include <cstdio>
+#include <vector>
+#include <algorithm>
+#include <ctime>
+#include <set>
+#include <cassert>
+
+using namespace std;
+
+const int P = 1000000007;
+const int maxN = 1100;
+int d[maxN][maxN], s[maxN][maxN];
+
+void precalc() {
+    d[maxN - 1][0] = 1;
+    for (int i = maxN - 1; i > 0; --i) {
+        for (int j = 0; j < maxN; ++j) {
+            if (d[i][j] == 0) {
+                continue;
+            }
+
+            d[i - 1][j] += d[i][j];
+            if (d[i - 1][j] >= P) {
+                d[i - 1][j] -= P;
+            }
+
+            if (j + (i - 1) < maxN) {
+                d[i - 1][j + (i - 1)] += d[i][j];
+                if (d[i - 1][j + (i - 1)] >= P) {
+                    d[i - 1][j + (i - 1)] -= P;
+                }
+            }
+        }
+    }
+
+    for (int i = 0; i < maxN; ++i) {
+        for (int j = 0; j < maxN; ++j) {
+            s[i][j] = d[i][j];
+            if (j > 0) {
+                s[i][j] += s[i][j - 1];
+                if (s[i][j] >= P) {
+                    s[i][j] -= P;
+                }
+            }
+        }
+    }
+}
+
+void rec(int left, int position, int current, vector < long long >* numbers) {
+    if (position == 0) {
+        numbers->push_back(current);
+        return ;
+    }
+    rec(left, position - 1, current, numbers);
+    if (left >= position) {
+        rec(left - position, position - 1, current + (1 << position), numbers);
+    }
+}
+
+long long getWays(int a, int n, int up, long long& no_next) {
+    vector < long long > numbers;
+    rec(n, up - 1, 0, &numbers);
+    sort(numbers.begin(), numbers.end());
+
+    long long res = 1;
+    long long last = 0;
+    for (int i = 0; i < numbers.size(); ++i) {
+        if (numbers[i] > last + a) {
+            res += a;
+            last = numbers[i];
+            ++res;
+        } else {
+            res += numbers[i] - last;
+            last = numbers[i];
+        }
+    }
+
+    no_next = (res + a) % P;
+
+    long long bound = (1 << up) - 1;
+    if (bound > last + a) {
+        res += a;
+    } else {
+        res += bound - last;
+    }
+    res %= P;
+    return res;
+}
+
+const int maxM = 40;
+vector < int > bounds[maxM][maxM];
+vector < int > scores[maxM][maxM];
+vector < int > add[maxM][maxM];
+int up_bound[maxM][maxM];
+
+void prebuild() {
+    for (int up = 1; up <= 30; ++up) {
+        for (int n = 1; n <= up; ++n) {
+            vector < long long > numbers;
+            rec(n, up - 1, 0, &numbers);
+            sort(numbers.begin(), numbers.end());
+
+            set < long long > diff;
+            for (int i = 1; i < numbers.size(); ++i) {
+                if (numbers[i] != numbers[i - 1] + 1) {
+                    diff.insert(numbers[i] - numbers[i - 1] - 1);
+                }
+            }
+            if ((1 << up) - 1 != numbers.back() + 1) {
+                diff.insert((1 << up) - numbers.back() - 2);
+            }
+            for (set < long long > :: iterator it = diff.begin(); it != diff.end(); ++it) {
+                bounds[up][n].push_back(*it);
+                scores[up][n].push_back(0);
+                add[up][n].push_back(0);
+            }
+
+            for (int index = 0; index < bounds[up][n].size(); ++index) {
+                long long value = bounds[up][n][index];
+                long long last = 0;
+                scores[up][n][index] = 1;
+                for (int i = 0; i < numbers.size(); ++i) {
+                    if (numbers[i] > last + value) {
+                        ++add[up][n][index];
+                        ++scores[up][n][index];
+                        last = numbers[i];
+                    } else {
+                        scores[up][n][index] += numbers[i] - last;
+                        last = numbers[i];
+                    }
+                }
+                ++add[up][n][index];
+            }
+            up_bound[up][n] = numbers.back();
+        }
+    }
+}
+
+long long getWaysFast(int a, int n, int up, long long& no_next) {
+    int index = lower_bound(bounds[up][n].begin(), bounds[up][n].end(), a) - bounds[up][n].begin();
+    if (index == bounds[up][n].size()) {
+        no_next = (up_bound[up][n] + a + 1) % P;
+        return min((1 << up) - 1, up_bound[up][n] + a) + 1;
+    }
+
+    long long score = scores[up][n][index];
+    score += (long long)(a) * (long long)(add[up][n][index]);
+    score %= P;
+
+    no_next = score;
+    if (up_bound[up][n] + a > (1 << up) - 1) {
+        score -= up_bound[up][n] + a - ((1 << up) - 1);
+    }
+    return score;
+}
+
+void solve() {
+    int a, b;
+    scanf(""%d%d"", &a, &b);
+    assert(0 <= a && a <= 1e9);
+    assert(0 <= b && b <= 1e3);
+    if (a == 0) {
+        printf(""%d\n"", (s[1][b] + P - 1) % P);
+        return ;
+    }
+
+    int up = 0;
+    for (int i = 1; ; ++i) {
+        if ((1 << i) > a) {
+            up = i;
+            break;
+        }
+    }
+
+    long long res = 0;
+    if (b >= up + 5) {
+        res += (long long)(s[up][b - up - 4]) * (long long)(1 << up);
+        res %= P;
+    }
+    for (int i = (b >= up + 5 ? (b - up - 3) : 0); i < b; ++i) {
+        int current = d[up][i];
+        if (current == 0) {
+            continue;
+        }
+        int n = b - i;
+
+        long long up_on = d[up][i] - d[up + 1][i];
+        if (up_on < 0) {
+            up_on += P;
+        }
+        long long up_off = d[up + 1][i];
+
+        long long has_next = up_on;
+        long long no_next = up_off;
+
+        if (i + up <= b) {
+            has_next = (up_on + up_off) % P;
+            no_next = 0;
+        }
+
+        if (n > up) {
+            res += has_next * (long long)(1 << up);
+            res %= P;
+            res += no_next * (long long)((1 << up) + a);
+            res %= P;
+        } else {
+            long long q;
+            res += has_next * getWaysFast(a, n, up, q);
+            res %= P;
+            res += no_next * q;
+            res %= P;
+        }
+    }
+
+    {
+        res += (long long)(d[up][b]) * (long long)(a + 1);
+        res %= P;
+    }
+
+    res = (res + P - 1) % P;
+
+    printf(""%d\n"", (int)(res));
+}
+
+int main() {
+    //freopen(""input.txt"", ""r"", stdin);
+    //freopen(""output.txt"", ""w"", stdout);
+
+    precalc();
+    prebuild();
+
+    int tests;
+    scanf(""%d"", &tests);
+    assert(1 <= tests && tests <= 1e5);
+    for (int i = 0; i < tests; ++i) {
+        solve();
+    }
+    return 0;
+}
+
",0.0,mar14-ones-and-twos,2014-03-27T19:47:34,"{""contest_participation"":2080,""challenge_submissions"":137,""successful_submissions"":15}",2014-03-27T19:47:34,2016-07-23T15:23:45,setter,"###C++ +```cpp + +#include +#include +#include +#include +#include +using namespace std; + +#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) +#define SZ(c) ((int)(c).size()) + +typedef long long LL; +int MOD = 1e9+7; + +int p[33][1005], up[33]={}; +void add(int &x, LL v) { + x = (x+v)%MOD; +} + +const int MXB = 1000; +void pre(int S) { + if(up[S]) return; + up[S] = 1; + p[S][0] = 1; + for(int l=S;l<=MXB;l++) { + for(int j=MXB;j>=l;j--) + add(p[S][j], p[S][j-l]); + } + for(int j=1;j<=MXB;j++) add(p[S][j], p[S][j-1]); + //printf(""build: ""); for(int j=0;j<=MXB;j++) printf(""%d "", p[S][j]); puts(""""); +} + +void solve() { + int A, B, s; + LL t; + scanf(""%d%d"", &A, &B); + + if (A == 0) { + pre(1); + printf(""%d\n"", (p[1][B]+MOD-1)%MOD); + return; + } + + for(t=2,s=1;t<=A;t*=2,s++); + t *= 2; s++; + pre(s); + + //printf(""s=%d\n"", s); + + int ans = 0; + LL last = 0, last2 = t/2+A+1; + for(int u=0;u0)); + LL nxt2 = min(t, (1LL<0)); + add(ans, (nxt-last)*1LL*p[s][B-u]); + if(u+s-1<=B) add(ans, (nxt2-last2)*1LL*p[s][B-(u+s-1)]); + //printf(""u=%d: [%I64d, %I64d) %d; [%I64d, %I64d) \n"", u, last, nxt, p[s][B-u], last2, nxt2); + last = nxt; + last2 = nxt2; + } + //printf(""nxt=%I64d\n"", last); + printf(""%d\n"", (ans+MOD-1)%MOD); +} + +int main(void) { + int T; + scanf(""%d"", &T); + while(T--) solve(); + return 0; +} + +``` +",not-set,2016-04-24T02:02:35,2016-07-23T15:23:27,C++ +39,1767,ones-and-twos,Ones and Twos," + +You are using at most **A** number of 1s and at most **B** number of 2s. How many different evaluation results are possible when they are formed in an expression containing only addition `+` sign and multiplication `*` sign are allowed? + +Note that, multiplication takes precedence over addition. + +For example, if **A=2** and **B=2**, then we have the following expressions: + +* `1`, `1*1` = 1 +* `2`, `1*2`, `1*1*2`, `1+1` = 2 +* `1+2`, `1+1*2` = 3 +* `2+2`, `2*2`, `1+1+2`, `1*2*2`, `1*1*2*2`, `1*2+1*2`, `1*1*2+2`, `1*2+2` = 4 +* `1+2+2`, `1+1*2+2` = 5 +* `1+1+2+2`, `1+1+2*2` = 6 + +So there are 6 unique results that can be formed if A = 2 and B = 2. + +**Input Format** +The first line contains the number of test cases T, T testcases follow each in a newline. +Each testcase contains 2 integers A and B separated by a single space. + +**Output Format** +Print the number of different evaluations modulo (%) (109+7.) + +**Constraints** +1 <= T <= 105 +0<=A<=1000000000 +0<=B<=1000 + +**Sample Input** + + 4 + 0 0 + 2 2 + 0 2 + 2 0 + +**Sample Output** + + 0 + 6 + 2 + 2 + +**Explanation** + ++ When A = 0, B = 0, there are no expressions, hence 0. ++ When A = 2, B = 2, as explained in the problem statement above, expressions leads to 6 possible solutions. ++ When A = 0, B = 2, we have `2`, `2+2` or `2*2`, hence 2. ++ When A = 2, B = 0, we have `1` or `1*1`, `1+1` hence 2. ",code,Using A 1's and B 2's how many different evaluations are possible only by performing addition and multiplication,ai,2014-01-29T15:42:24,2022-08-31T08:14:53,"# +# Complete the 'onesAndTwos' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER a +# 2. INTEGER b +# + +def onesAndTwos(a, b): + # 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() + + a = int(first_multiple_input[0]) + + b = int(first_multiple_input[1]) + + result = onesAndTwos(a, b) + + fptr.write(str(result) + '\n') + + fptr.close() +"," + +You are using at most **A** number of 1s and at most **B** number of 2s. How many different evaluation results are possible when they are formed in an expression containing only addition `+` sign and multiplication `*` sign are allowed? + +Note that, multiplication takes precedence over addition. + +For example, if **A=2** and **B=2**, then we have the following expressions: + +* `1`, `1*1` = 1 +* `2`, `1*2`, `1*1*2`, `1+1` = 2 +* `1+2`, `1+1*2` = 3 +* `2+2`, `2*2`, `1+1+2`, `1*2*2`, `1*1*2*2`, `1*2+1*2`, `1*1*2+2`, `1*2+2` = 4 +* `1+2+2`, `1+1*2+2` = 5 +* `1+1+2+2`, `1+1+2*2` = 6 + +So there are 6 unique results that can be formed if A = 2 and B = 2. +",0.5454545454545454,"[""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 the number of test cases T, T testcases follow each in a newline. +Each testcase contains 2 integers A and B separated by a single space. +","Print the number of different evaluations modulo (%) (109+7.) +"," 4 + 0 0 + 2 2 + 0 2 + 2 0 +"," 0 + 6 + 2 + 2 +",Hard,Ones and Twos - 2020 Hack March Editorial,"

Ones and Twos
+Difficulty Level : Medium-Hard
+Required Knowledge : DP
+Problem Setter : Shang En Huang
+Problem Tester : Dmytro Soboliev

+ +

Solution

+ +

If you are still getting wrong answer but don't know why, please try this test case:

+ +
 2
+ 6 14
+ 2 1
+
+ +

The answer should be

+ +
 301
+ 4
+
+ +

Part I.

+ +

Let's consider simple cases, say when A = 0. In this case, all numbers will be generated by using all 2's. For each integer X, consider its binary representation (a0 + a1*2 + a2*4+a3*8+...). It's not hard to prove you need at least (a1*1 + a2*2+a3*3+...) number of 2's to produce this number.

+ +

Hence when given the value of B the answer should be:

+ +
+

The number of ways partitioning i <= B into distinct sum of positive integers.

+
+ +

This can be solved by O(B2) dynamic programming: Just let dp[i][j] be the number of ways partitioning i into distinct sum of positive integers with last term (highest bit) equal or less than j. So if we consider the state dp[i][j], into two situations: the last term is j or not. If yes, there are exactly dp[i-j][j-1] ways. Otherwise it would be dp[i][j-1]. Please consider the following code:

+ +

Language : C++

+ +
for (int j = 0; j <= B; j++) dp[0][j] = 1;
+for (int i = 1; i <= B; i++)
+    for (int j = 1; j <= B; j++)
+        dp[i][j] = (i>j? dp[i-j][j-1] : 0) + dp[i][j-1];
+
+ +

Then in the case A=0, the solution can be calculated from dp[1][B] + dp[2][B] + ... + dp[B][B]. (Don't forget to mod.)

+ +

Part II: O(T A lg A + B2)

+ +

From now on, when we consider an integer, we only consider the representation with fewest 2's.

+ +

What if we have some 1's? If using only twos can make a number X, then we can build all integers in the ranage [X, X+A]. Suppose we have a number 2K, where 2A < 2K. We split the terms by ""Terms less than*2K* and terms no less than 2K"". For terms less than 2K. We will know that the sum of all parts contributed by 2's will be less than 2K (Why?).

+ +

Hence, if we choose minimal K with 2A < 2K, then we can guarantee that the sum of whole part less than 2K will still less than 2K. (Given the condition that we use least number of 2's.)

+ +

+ +

For each t, 0 <= t < 2K, let R[t] be the least number of 2's which can build t. Modify the DP table from part I: dp[i][j] be the number of ways partitioning i into distinct sum of positive integers with last term (highest bit) equal or less than j and with first term (lowest bit) at least K.

+ +
cpp
+for (int j = 0; j <= B; j++) dp[0][j] = 1;
+for (int i = 1; i <= B; i++)
+    for (int j = 1; j <= B; j++)
+        dp[i][j] = (j>=K && i>j ? dp[i-j][j-1] : 0) + dp[i][j-1];
+
+ +

In this t, the ways to make numbers that modulo 2K equals t is exactly dp[1][B] + dp[2][B] + ... + dp[B - R[t]][B]. (Please mod.)

+ +

We can easily get the relations R[0] = R[1] = ... = R[A] = 0, and for t > A, +R[t] = min0 <= j < K{ R[t-2j] + j }

+ +

In conclusion, for each test case, we can go over each 0 <= t < 2K. Then the time complexity is O(T K 2K + B^2) = O(T A lg A + B^2).

+ +

Part III: O(T lg A + B^2)

+ +

The remaining parts:

+ +
    +
  1. calculate R[0]..R[2K-1] efficiently
  2. +
  3. calculate the sum dp[ B-R[i] ][ B-R[i] ] efficiently
  4. +
+ +

In order to solve (2), we need to count ""How many i's are there such that R[i] = r?"" for each r = 0, 1, ..., 2K-1.

+ +

(Maybe not) Surprisingly, we have the following properties:

+ +

+ +
+

Prop: for any integer no more than 2K-1, we only need at most one ""2 term"".

+ +

Prop2: for any integer in (2K-1, 2K) we use at most two ""2 terms"".

+
+ +

Hence we can find the sum with a single loop enumerating from 0 to K-1.

+ +

Happy thinking & happy coding :)

+ +

Setter's Code

+ +
#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+#include <vector>
+using namespace std;
+
+#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(c) ((int)(c).size())
+
+typedef long long LL;
+int MOD = 1e9+7;
+
+int p[33][1005], up[33]={};
+void add(int &x, LL v) {
+    x = (x+v)%MOD;
+}
+
+const int MXB = 1000;
+void pre(int S) {
+    if(up[S]) return;
+    up[S] = 1;
+    p[S][0] = 1;
+    for(int l=S;l<=MXB;l++) {
+        for(int j=MXB;j>=l;j--)
+            add(p[S][j], p[S][j-l]);
+    }
+    for(int j=1;j<=MXB;j++) add(p[S][j], p[S][j-1]);
+    //printf(""build: ""); for(int j=0;j<=MXB;j++) printf(""%d "", p[S][j]); puts("""");
+}
+
+void solve() {
+    int A, B, s;
+    LL t;
+    scanf(""%d%d"", &A, &B);
+
+    if (A == 0) {
+        pre(1);
+        printf(""%d\n"", (p[1][B]+MOD-1)%MOD);
+        return;
+    }
+
+    for(t=2,s=1;t<=A;t*=2,s++);
+    t *= 2; s++;
+    pre(s);
+
+    //printf(""s=%d\n"", s);
+
+    int ans = 0;
+    LL last = 0, last2 = t/2+A+1;
+    for(int u=0;u<s && u<=B;u++) {
+        LL nxt = min(t, (1LL<<u) + A + (u>0));
+        LL nxt2 = min(t, (1LL<<u) + A + t/2 + (u>0));
+        add(ans, (nxt-last)*1LL*p[s][B-u]);
+        if(u+s-1<=B) add(ans, (nxt2-last2)*1LL*p[s][B-(u+s-1)]);
+        //printf(""u=%d: [%I64d, %I64d)  %d; [%I64d, %I64d)  \n"", u, last, nxt, p[s][B-u], last2, nxt2);
+        last = nxt;
+        last2 = nxt2;
+    }
+    //printf(""nxt=%I64d\n"", last);
+    printf(""%d\n"", (ans+MOD-1)%MOD);
+}
+
+int main(void) {
+    int T;
+    scanf(""%d"", &T);
+    while(T--) solve();
+    return 0;
+}
+
+ +

Tester's Code

+ +
#include <iostream>
+#include <cstdio>
+#include <vector>
+#include <algorithm>
+#include <ctime>
+#include <set>
+#include <cassert>
+
+using namespace std;
+
+const int P = 1000000007;
+const int maxN = 1100;
+int d[maxN][maxN], s[maxN][maxN];
+
+void precalc() {
+    d[maxN - 1][0] = 1;
+    for (int i = maxN - 1; i > 0; --i) {
+        for (int j = 0; j < maxN; ++j) {
+            if (d[i][j] == 0) {
+                continue;
+            }
+
+            d[i - 1][j] += d[i][j];
+            if (d[i - 1][j] >= P) {
+                d[i - 1][j] -= P;
+            }
+
+            if (j + (i - 1) < maxN) {
+                d[i - 1][j + (i - 1)] += d[i][j];
+                if (d[i - 1][j + (i - 1)] >= P) {
+                    d[i - 1][j + (i - 1)] -= P;
+                }
+            }
+        }
+    }
+
+    for (int i = 0; i < maxN; ++i) {
+        for (int j = 0; j < maxN; ++j) {
+            s[i][j] = d[i][j];
+            if (j > 0) {
+                s[i][j] += s[i][j - 1];
+                if (s[i][j] >= P) {
+                    s[i][j] -= P;
+                }
+            }
+        }
+    }
+}
+
+void rec(int left, int position, int current, vector < long long >* numbers) {
+    if (position == 0) {
+        numbers->push_back(current);
+        return ;
+    }
+    rec(left, position - 1, current, numbers);
+    if (left >= position) {
+        rec(left - position, position - 1, current + (1 << position), numbers);
+    }
+}
+
+long long getWays(int a, int n, int up, long long& no_next) {
+    vector < long long > numbers;
+    rec(n, up - 1, 0, &numbers);
+    sort(numbers.begin(), numbers.end());
+
+    long long res = 1;
+    long long last = 0;
+    for (int i = 0; i < numbers.size(); ++i) {
+        if (numbers[i] > last + a) {
+            res += a;
+            last = numbers[i];
+            ++res;
+        } else {
+            res += numbers[i] - last;
+            last = numbers[i];
+        }
+    }
+
+    no_next = (res + a) % P;
+
+    long long bound = (1 << up) - 1;
+    if (bound > last + a) {
+        res += a;
+    } else {
+        res += bound - last;
+    }
+    res %= P;
+    return res;
+}
+
+const int maxM = 40;
+vector < int > bounds[maxM][maxM];
+vector < int > scores[maxM][maxM];
+vector < int > add[maxM][maxM];
+int up_bound[maxM][maxM];
+
+void prebuild() {
+    for (int up = 1; up <= 30; ++up) {
+        for (int n = 1; n <= up; ++n) {
+            vector < long long > numbers;
+            rec(n, up - 1, 0, &numbers);
+            sort(numbers.begin(), numbers.end());
+
+            set < long long > diff;
+            for (int i = 1; i < numbers.size(); ++i) {
+                if (numbers[i] != numbers[i - 1] + 1) {
+                    diff.insert(numbers[i] - numbers[i - 1] - 1);
+                }
+            }
+            if ((1 << up) - 1 != numbers.back() + 1) {
+                diff.insert((1 << up) - numbers.back() - 2);
+            }
+            for (set < long long > :: iterator it = diff.begin(); it != diff.end(); ++it) {
+                bounds[up][n].push_back(*it);
+                scores[up][n].push_back(0);
+                add[up][n].push_back(0);
+            }
+
+            for (int index = 0; index < bounds[up][n].size(); ++index) {
+                long long value = bounds[up][n][index];
+                long long last = 0;
+                scores[up][n][index] = 1;
+                for (int i = 0; i < numbers.size(); ++i) {
+                    if (numbers[i] > last + value) {
+                        ++add[up][n][index];
+                        ++scores[up][n][index];
+                        last = numbers[i];
+                    } else {
+                        scores[up][n][index] += numbers[i] - last;
+                        last = numbers[i];
+                    }
+                }
+                ++add[up][n][index];
+            }
+            up_bound[up][n] = numbers.back();
+        }
+    }
+}
+
+long long getWaysFast(int a, int n, int up, long long& no_next) {
+    int index = lower_bound(bounds[up][n].begin(), bounds[up][n].end(), a) - bounds[up][n].begin();
+    if (index == bounds[up][n].size()) {
+        no_next = (up_bound[up][n] + a + 1) % P;
+        return min((1 << up) - 1, up_bound[up][n] + a) + 1;
+    }
+
+    long long score = scores[up][n][index];
+    score += (long long)(a) * (long long)(add[up][n][index]);
+    score %= P;
+
+    no_next = score;
+    if (up_bound[up][n] + a > (1 << up) - 1) {
+        score -= up_bound[up][n] + a - ((1 << up) - 1);
+    }
+    return score;
+}
+
+void solve() {
+    int a, b;
+    scanf(""%d%d"", &a, &b);
+    assert(0 <= a && a <= 1e9);
+    assert(0 <= b && b <= 1e3);
+    if (a == 0) {
+        printf(""%d\n"", (s[1][b] + P - 1) % P);
+        return ;
+    }
+
+    int up = 0;
+    for (int i = 1; ; ++i) {
+        if ((1 << i) > a) {
+            up = i;
+            break;
+        }
+    }
+
+    long long res = 0;
+    if (b >= up + 5) {
+        res += (long long)(s[up][b - up - 4]) * (long long)(1 << up);
+        res %= P;
+    }
+    for (int i = (b >= up + 5 ? (b - up - 3) : 0); i < b; ++i) {
+        int current = d[up][i];
+        if (current == 0) {
+            continue;
+        }
+        int n = b - i;
+
+        long long up_on = d[up][i] - d[up + 1][i];
+        if (up_on < 0) {
+            up_on += P;
+        }
+        long long up_off = d[up + 1][i];
+
+        long long has_next = up_on;
+        long long no_next = up_off;
+
+        if (i + up <= b) {
+            has_next = (up_on + up_off) % P;
+            no_next = 0;
+        }
+
+        if (n > up) {
+            res += has_next * (long long)(1 << up);
+            res %= P;
+            res += no_next * (long long)((1 << up) + a);
+            res %= P;
+        } else {
+            long long q;
+            res += has_next * getWaysFast(a, n, up, q);
+            res %= P;
+            res += no_next * q;
+            res %= P;
+        }
+    }
+
+    {
+        res += (long long)(d[up][b]) * (long long)(a + 1);
+        res %= P;
+    }
+
+    res = (res + P - 1) % P;
+
+    printf(""%d\n"", (int)(res));
+}
+
+int main() {
+    //freopen(""input.txt"", ""r"", stdin);
+    //freopen(""output.txt"", ""w"", stdout);
+
+    precalc();
+    prebuild();
+
+    int tests;
+    scanf(""%d"", &tests);
+    assert(1 <= tests && tests <= 1e5);
+    for (int i = 0; i < tests; ++i) {
+        solve();
+    }
+    return 0;
+}
+
",0.0,mar14-ones-and-twos,2014-03-27T19:47:34,"{""contest_participation"":2080,""challenge_submissions"":137,""successful_submissions"":15}",2014-03-27T19:47:34,2016-07-23T15:23:45,tester,"###C++ +```cpp +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +const int P = 1000000007; +const int maxN = 1100; +int d[maxN][maxN], s[maxN][maxN]; + +void precalc() { + d[maxN - 1][0] = 1; + for (int i = maxN - 1; i > 0; --i) { + for (int j = 0; j < maxN; ++j) { + if (d[i][j] == 0) { + continue; + } + + d[i - 1][j] += d[i][j]; + if (d[i - 1][j] >= P) { + d[i - 1][j] -= P; + } + + if (j + (i - 1) < maxN) { + d[i - 1][j + (i - 1)] += d[i][j]; + if (d[i - 1][j + (i - 1)] >= P) { + d[i - 1][j + (i - 1)] -= P; + } + } + } + } + + for (int i = 0; i < maxN; ++i) { + for (int j = 0; j < maxN; ++j) { + s[i][j] = d[i][j]; + if (j > 0) { + s[i][j] += s[i][j - 1]; + if (s[i][j] >= P) { + s[i][j] -= P; + } + } + } + } +} + +void rec(int left, int position, int current, vector < long long >* numbers) { + if (position == 0) { + numbers->push_back(current); + return ; + } + rec(left, position - 1, current, numbers); + if (left >= position) { + rec(left - position, position - 1, current + (1 << position), numbers); + } +} + +long long getWays(int a, int n, int up, long long& no_next) { + vector < long long > numbers; + rec(n, up - 1, 0, &numbers); + sort(numbers.begin(), numbers.end()); + + long long res = 1; + long long last = 0; + for (int i = 0; i < numbers.size(); ++i) { + if (numbers[i] > last + a) { + res += a; + last = numbers[i]; + ++res; + } else { + res += numbers[i] - last; + last = numbers[i]; + } + } + + no_next = (res + a) % P; + + long long bound = (1 << up) - 1; + if (bound > last + a) { + res += a; + } else { + res += bound - last; + } + res %= P; + return res; +} + +const int maxM = 40; +vector < int > bounds[maxM][maxM]; +vector < int > scores[maxM][maxM]; +vector < int > add[maxM][maxM]; +int up_bound[maxM][maxM]; + +void prebuild() { + for (int up = 1; up <= 30; ++up) { + for (int n = 1; n <= up; ++n) { + vector < long long > numbers; + rec(n, up - 1, 0, &numbers); + sort(numbers.begin(), numbers.end()); + + set < long long > diff; + for (int i = 1; i < numbers.size(); ++i) { + if (numbers[i] != numbers[i - 1] + 1) { + diff.insert(numbers[i] - numbers[i - 1] - 1); + } + } + if ((1 << up) - 1 != numbers.back() + 1) { + diff.insert((1 << up) - numbers.back() - 2); + } + for (set < long long > :: iterator it = diff.begin(); it != diff.end(); ++it) { + bounds[up][n].push_back(*it); + scores[up][n].push_back(0); + add[up][n].push_back(0); + } + + for (int index = 0; index < bounds[up][n].size(); ++index) { + long long value = bounds[up][n][index]; + long long last = 0; + scores[up][n][index] = 1; + for (int i = 0; i < numbers.size(); ++i) { + if (numbers[i] > last + value) { + ++add[up][n][index]; + ++scores[up][n][index]; + last = numbers[i]; + } else { + scores[up][n][index] += numbers[i] - last; + last = numbers[i]; + } + } + ++add[up][n][index]; + } + up_bound[up][n] = numbers.back(); + } + } +} + +long long getWaysFast(int a, int n, int up, long long& no_next) { + int index = lower_bound(bounds[up][n].begin(), bounds[up][n].end(), a) - bounds[up][n].begin(); + if (index == bounds[up][n].size()) { + no_next = (up_bound[up][n] + a + 1) % P; + return min((1 << up) - 1, up_bound[up][n] + a) + 1; + } + + long long score = scores[up][n][index]; + score += (long long)(a) * (long long)(add[up][n][index]); + score %= P; + + no_next = score; + if (up_bound[up][n] + a > (1 << up) - 1) { + score -= up_bound[up][n] + a - ((1 << up) - 1); + } + return score; +} + +void solve() { + int a, b; + scanf(""%d%d"", &a, &b); + assert(0 <= a && a <= 1e9); + assert(0 <= b && b <= 1e3); + if (a == 0) { + printf(""%d\n"", (s[1][b] + P - 1) % P); + return ; + } + + int up = 0; + for (int i = 1; ; ++i) { + if ((1 << i) > a) { + up = i; + break; + } + } + + long long res = 0; + if (b >= up + 5) { + res += (long long)(s[up][b - up - 4]) * (long long)(1 << up); + res %= P; + } + for (int i = (b >= up + 5 ? (b - up - 3) : 0); i < b; ++i) { + int current = d[up][i]; + if (current == 0) { + continue; + } + int n = b - i; + + long long up_on = d[up][i] - d[up + 1][i]; + if (up_on < 0) { + up_on += P; + } + long long up_off = d[up + 1][i]; + + long long has_next = up_on; + long long no_next = up_off; + + if (i + up <= b) { + has_next = (up_on + up_off) % P; + no_next = 0; + } + + if (n > up) { + res += has_next * (long long)(1 << up); + res %= P; + res += no_next * (long long)((1 << up) + a); + res %= P; + } else { + long long q; + res += has_next * getWaysFast(a, n, up, q); + res %= P; + res += no_next * q; + res %= P; + } + } + + { + res += (long long)(d[up][b]) * (long long)(a + 1); + res %= P; + } + + res = (res + P - 1) % P; + + printf(""%d\n"", (int)(res)); +} + +int main() { + //freopen(""input.txt"", ""r"", stdin); + //freopen(""output.txt"", ""w"", stdout); + + precalc(); + prebuild(); + + int tests; + scanf(""%d"", &tests); + assert(1 <= tests && tests <= 1e5); + for (int i = 0; i < tests; ++i) { + solve(); + } + return 0; +} + +``` +",not-set,2016-04-24T02:02:35,2016-07-23T15:23:45,C++ +40,1050,devu-police,Devu Vs Police,"[Mandarin-Chinese](https://hr-filepicker.s3.amazonaws.com/infinitum-mar14/mandarin/1050-devupolice.md) +[Russian](https://hr-filepicker.s3.amazonaws.com/infinitum-mar14/russian/1050-devupolice.md) + +It is holi festival, festival of colors. Devu is having fun playing holi and is throwing balloons with his girlfriend Glynis. Police saw this mischief and tried arresting his girlfriend, Devu being a mathematician asked police not to arrest his girlfriend and instead torture him with brain teaser. Devu was a young engineering fellow and he did not knew that policeman was equally good in mathematics, policeman gave Devu a problem which is as follows: + +Let f(n,k) = nk + +Your aim is to answer f(n1,k1)f(n2,k2) % n + +Can you help devu and his girlfriend rescue from modern police. + +**Input Format** + +You are given `T` which is the number of queries to solve. + +Each Query consist of 5 space separated integers `n1 k1 n2 k2 n` + + +**Output Format** + +Output contains exactly T lines. ith line containing the answer for the ith query. + +**Constraints** + +1 <= T <= 10000 +0 <= n1,k1,n2,k2 <= 109 +1 <= n <= 107 + +**Note** The output to 00 should be 1. + +**Sample Input** + + 1 + 2 1 2 2 15 + +**Sample Output** + + 1 + +**Explanation** + +f(2,1) = 2 + +f(2,2) = 4 + +so answer is 16 mod 15 = 1 + + +[Editorial](https://www.hackerrank.com/blog/infinitum-mar14-devu-police)",code,Help Devu escape from police,ai,2013-10-09T04:59:51,2022-09-02T09:54:38,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER n1 +# 2. INTEGER k1 +# 3. INTEGER n2 +# 4. INTEGER k2 +# 5. INTEGER n +# + +def solve(n1, k1, n2, k2, n): + # 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() + + n1 = int(first_multiple_input[0]) + + k1 = int(first_multiple_input[1]) + + n2 = int(first_multiple_input[2]) + + k2 = int(first_multiple_input[3]) + + n = int(first_multiple_input[4]) + + result = solve(n1, k1, n2, k2, n) + + fptr.write(str(result) + '\n') + + fptr.close() +"," +It is holi festival, festival of colors. Devu is having fun playing holi and is throwing balloons with his girlfriend Glynis. Police saw this mischief and tried arresting his girlfriend, Devu being a mathematician asked police not to arrest his girlfriend and instead torture him with brain teaser. Devu was a young engineering fellow and he did not knew that policeman was equally good in mathematics, policeman gave Devu a problem which is as follows: + +Let $f(n,k) = n^k$ + +Your aim is to answer $f(n_1,k_1)^{f(n_2,k_2)} \bmod n$ + +Can you help devu and his girlfriend rescue from modern police. +",0.4318181818181818,"[""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""]","You are given $T$ which is the number of queries to solve. + +Each Query consist of 5 space separated integers $n_1,k_1,n_2,k_2,n$",Output contains exactly $T$ lines. $i^{\text{th}}$ line containing the answer for the $i^{\text{th}}$ query.," 1 + 2 1 2 2 15", 1,Hard,Devu Vs Police Infinitum Mar14 Editorial,"

Problem Statement

+ +

Problem Setter : Devendra
+Problem Tester : Cao Peng
+Required Knowledge: Chinese Remainder Theorm

+ +

The Basic Idea Exploited here is Chinese Remainder Theorom.
+let n = p[1]^e[1] * p[2]^e[2] * p[3]^e[3] ... p[k]^e[k] where p[i] is prime.
+let expr = A[1]^A[2]^A[3] where A[1] = f(n1,k1) , A[2] = n2, A[3] = k2
+so, calculating expr mod n is equivalent in calculating
+CRT ( expr mod p[1]^e[1] , expr mod p[2]^[e_2] ,......., expr mod p[k]^e[k] )
+Now lets see the case when e[i] = 1, then calculating expr mod p[i] is equivalent to A[1]^( A[2]^A[3] mod (p[i] -1 ) ) mod p[i].
+Euler Totient Period for p[i] is p[i] - 1.
+Now for the case of p[i]^e[i] where e[i]!=1, euler totient period is given by p[i]^e[i] - p[i]^(e[i]-1)
+Note: :Be carefull with Euler Totient period concept which is valid only if A[1] is coprime to p[i]. It is left as an exercise for the reader to figure it out how to procede then.

+ +

Solution by cpcs

+ +

Let a = n1k1 % n and b = n2k2, we need to calculate a^b mod n. We can judge whether a = 0/1 or b = 0,1 first to deal with the special conditions like 0^0, 1^p...etc.
+Then we can suppose a > 1 and b > 1.
+The solution is based on that although n may not be a prime, the period of the n1x % n is phi(n) , where phi is the euler function.
+But the starting point of the first period may be starts from phi(n). That means for any y >= phi(n) we have n1(y) == n1(y + phi(n)) (mod n)

+ +

So if we found b is smaller enough, namely if b < phi(n), we can directly calculate the result using O(logb) algorithm. Otherwise we have b>=phi(n) then n1k1 == n1(b % phi(n) + phi(n)) mod n, so we just calculate n1 (b % phi(n) + phi(n)) % n.

+ +

Setter's Code

+ +
#include<stdio.h>
+#include<iostream>
+#include<string.h>
+#include<vector>
+#include<assert.h>
+using namespace std;
+typedef long long int ll;
+int sieve_par=3162;
+int prime[3162] , array[3162],counter=0;
+ll inverse(ll a,ll b)                   //b>a
+{
+    ll Remainder,p0=0,p1=1,pcurr=1,q,m=b;
+    while(a!=0)
+    {
+        Remainder=b%a;
+        q=b/a;
+        if(Remainder!=0)
+        {
+            pcurr=p0-(p1*q)%m;
+            if(pcurr<0)
+                pcurr+=m;
+            p0=p1;
+            p1=pcurr;
+        }
+        b=a;
+        a=Remainder;
+    }
+    return pcurr;
+}
+ll binpow(ll a,ll b,ll mod)
+{
+    ll ans=1;
+    while(b)
+        if(b&1){
+            ans=(ans*a)%mod;
+            b--;
+
+        }
+        else{   
+            a=(a*a)%mod;
+            b>>=1;
+        }
+    return ans%mod;
+}
+ll CRT(ll mod[],ll rem[],int t)         //t is the number of pairs of rem and mod
+{
+    ll ans = rem[0],m = mod[0];
+
+    for(int i = 1;i < t;++i)
+    {
+        ll a = inverse(m,mod[i]);
+        ll b = inverse(mod[i],m);
+        ans = (ans * b * mod[i] + rem[i] * a * m) % (m * mod[i]);
+        m *= mod[i];
+    }   
+    return ans;
+}
+void sieve()
+{
+    for(int i=1;i<sieve_par;i++)
+        array[i]=1;
+    array[0]=0;
+    int j;
+    for(int i=2;i<=sieve_par;i++)
+    {
+        if(array[i-1]==1)
+        {
+            prime[counter]=i;
+            for(j=i*i;j<=sieve_par;j+=i)
+                array[j-1]=0;
+            counter++;
+        }
+    }
+}
+int check(ll a,ll b,ll n)
+{
+    ll ans=1;
+    while(b)
+        if(b&1){
+            ans=ans*a;
+            if(ans>n)   return -1;
+            b--;
+        }
+        else{
+            a=a*a;
+            if(a>n)     return -1;
+            b>>=1;  
+        }
+    return ans;
+}
+ll solveit(int n1,int k1,int n2,int k2,int m,int p)
+{
+    ll x=1,y=0;
+    if(n1==0){
+        if(n2==0 && k2==0 && k1==0) return 1;
+        if(n2==0 && k2==0 && k1!=0) return 0;
+        if(k1==0 || n2==0)  return 1;
+        return 0;
+    }
+    if(n1 % p == 0 ){
+        ll ans;
+        while(n1%p == 0){
+            n1/=p;
+            x=x*p;
+            y++;
+        }
+        ans= check(n2,k2,m);
+        ans= ans* k1*y;
+        if(ans>=0)  ans= check(p,ans,m);
+        if(ans<0)   return 0;
+        else x= ans;
+    }
+    ll a=binpow(n2,k2,m-(m/p));
+    ll b=binpow(n1,k1,m);
+    ll c= binpow(b,a,m);
+    return (c*x)%m;
+}
+int main()
+{
+    sieve();
+    int test,n1,n2,n,k1,k2,t;
+    ll mod[15],rem[15],ans;
+    //printf(""%d is counter\n"",counter);    
+    scanf(""%d"",&test);
+    assert(test<=10000);
+    while(test--){
+        scanf(""%d%d%d%d%d"",&n1,&k1,&n2,&k2,&n);
+        assert(n1<=1000000000 &&  k1<=1000000000 && n2<=1000000000 && k2<=1000000000 && n<=10000000);
+        assert(n1>=0 && k1>=0 && n2>=0 && k2>=0 && n>=1);
+        if(n==1){
+            printf(""0\n"");
+            continue;
+        }
+        t=0;
+        for(int i=0;i<counter;i++){
+            if(n< prime[i]*prime[i])    break;
+            if(n%prime[i]==0){
+                mod[t]=1;
+                while(n%prime[i]==0){
+                    n/=prime[i];
+                    mod[t]*=prime[i];
+                }
+                rem[t]=solveit(n1,k1,n2,k2,mod[t],prime[i]);
+                t++;
+            }
+        }
+        if(n>1){
+            mod[t]=n;
+            rem[t]=solveit(n1,k1,n2,k2,mod[t],n);
+            t++;
+        }
+        printf(""%lld\n"",CRT(mod,rem,t));
+    }
+    return 0;
+}
+
+ +

Tester's Code

+ +
import java.math.*;
+import java.util.*;
+
+
+
+public class Solution {
+    public static long powermod(long x,long y,long M) {
+      x %= M;
+
+      if (y == 0) {
+        return 1;
+      }
+      if (x == 0) {
+        return 0;
+      }
+      long r = 1L;
+      for (;y > 0; y >>= 1) {
+        if ((y & 1) > 0) {
+            r = r * x % M;
+        }
+        x = x * x % M;
+      }
+      return r;
+    }
+    public static long phi(long m) {
+      long p = 1L;
+       for (long i = 2L; i * i <= m; ++i) {
+        if (m % i == 0) {
+            long j = 1L;
+             while (m % i == 0) {
+                m /= i;
+                j *= i;
+             }
+
+             p *= j - j / i;
+        }
+      }
+      return (m > 1)?(p * (m - 1)):p;
+    }
+    public static long cmp(long n,long k,long x) {  //n ^ k > x < x = x
+    long i = 0L, temp = 1L;
+        while ((i < k) && (temp < x)) {
+           i++;
+           temp *= n;
+        }
+        if ((i >= k) && (temp <= x)) {
+          return temp;
+        }
+        return -1;
+
+    }
+    public static void main(String[] args) {
+        Scanner scanner = new Scanner(System.in);
+        for (int cases = scanner.nextInt(); cases > 0; cases--) {
+          long n1 = scanner.nextLong();
+          long k1 = scanner.nextLong();
+          long n2 = scanner.nextLong();
+          long k2 = scanner.nextLong();
+          long n = scanner.nextLong();
+          if (n == 1) {
+            System.out.println(0);
+          }
+          else {
+            long x = powermod(n1,k1,n);
+            if ((k2 == 0) || (n2 == 1)) {
+              System.out.println(x);
+            }
+            else if (n2 == 0) {
+              System.out.println(1);
+            }
+            else if (x <= 1) {
+                 System.out.println(x);
+            }
+            else {  // n2 > 1, k2 > 0, x > 1
+              long p = phi(n);
+              long y = cmp(n2,k2,p);
+              System.out.println(powermod(x, (y >= 0)?y:(powermod(n2,k2,p) + p),n));
+
+            }
+
+          }
+        }
+
+    }
+}
+
",0.0,infinitum-mar14-devu-police,2014-04-01T21:20:47,"{""contest_participation"":1667,""challenge_submissions"":241,""successful_submissions"":76}",2014-04-01T21:20:47,2016-12-09T10:05:33,setter,"###C++ +```cpp + + +#include +#include +#include +#include +#include +using namespace std; +typedef long long int ll; +int sieve_par=3162; +int prime[3162] , array[3162],counter=0; +ll inverse(ll a,ll b) //b>a +{ + ll Remainder,p0=0,p1=1,pcurr=1,q,m=b; + while(a!=0) + { + Remainder=b%a; + q=b/a; + if(Remainder!=0) + { + pcurr=p0-(p1*q)%m; + if(pcurr<0) + pcurr+=m; + p0=p1; + p1=pcurr; + } + b=a; + a=Remainder; + } + return pcurr; +} +ll binpow(ll a,ll b,ll mod) +{ + ll ans=1; + while(b) + if(b&1){ + ans=(ans*a)%mod; + b--; + + } + else{ + a=(a*a)%mod; + b>>=1; + } + return ans%mod; +} +ll CRT(ll mod[],ll rem[],int t) //t is the number of pairs of rem and mod +{ + ll ans = rem[0],m = mod[0]; + + for(int i = 1;i < t;++i) + { + ll a = inverse(m,mod[i]); + ll b = inverse(mod[i],m); + ans = (ans * b * mod[i] + rem[i] * a * m) % (m * mod[i]); + m *= mod[i]; + } + return ans; +} +void sieve() +{ + for(int i=1;in) return -1; + b--; + } + else{ + a=a*a; + if(a>n) return -1; + b>>=1; + } + return ans; +} +ll solveit(int n1,int k1,int n2,int k2,int m,int p) +{ + ll x=1,y=0; + if(n1==0){ + if(n2==0 && k2==0 && k1==0) return 1; + if(n2==0 && k2==0 && k1!=0) return 0; + if(k1==0 || n2==0) return 1; + return 0; + } + if(n1 % p == 0 ){ + ll ans; + while(n1%p == 0){ + n1/=p; + x=x*p; + y++; + } + ans= check(n2,k2,m); + ans= ans* k1*y; + if(ans>=0) ans= check(p,ans,m); + if(ans<0) return 0; + else x= ans; + } + ll a=binpow(n2,k2,m-(m/p)); + ll b=binpow(n1,k1,m); + ll c= binpow(b,a,m); + return (c*x)%m; +} +int main() +{ + sieve(); + int test,n1,n2,n,k1,k2,t; + ll mod[15],rem[15],ans; + //printf(""%d is counter\n"",counter); + scanf(""%d"",&test); + assert(test<=10000); + while(test--){ + scanf(""%d%d%d%d%d"",&n1,&k1,&n2,&k2,&n); + assert(n1<=1000000000 && k1<=1000000000 && n2<=1000000000 && k2<=1000000000 && n<=10000000); + assert(n1>=0 && k1>=0 && n2>=0 && k2>=0 && n>=1); + if(n==1){ + printf(""0\n""); + continue; + } + t=0; + for(int i=0;i1){ + mod[t]=n; + rem[t]=solveit(n1,k1,n2,k2,mod[t],n); + t++; + } + printf(""%lld\n"",CRT(mod,rem,t)); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:35,2016-07-23T18:01:09,C++ +41,1050,devu-police,Devu Vs Police,"[Mandarin-Chinese](https://hr-filepicker.s3.amazonaws.com/infinitum-mar14/mandarin/1050-devupolice.md) +[Russian](https://hr-filepicker.s3.amazonaws.com/infinitum-mar14/russian/1050-devupolice.md) + +It is holi festival, festival of colors. Devu is having fun playing holi and is throwing balloons with his girlfriend Glynis. Police saw this mischief and tried arresting his girlfriend, Devu being a mathematician asked police not to arrest his girlfriend and instead torture him with brain teaser. Devu was a young engineering fellow and he did not knew that policeman was equally good in mathematics, policeman gave Devu a problem which is as follows: + +Let f(n,k) = nk + +Your aim is to answer f(n1,k1)f(n2,k2) % n + +Can you help devu and his girlfriend rescue from modern police. + +**Input Format** + +You are given `T` which is the number of queries to solve. + +Each Query consist of 5 space separated integers `n1 k1 n2 k2 n` + + +**Output Format** + +Output contains exactly T lines. ith line containing the answer for the ith query. + +**Constraints** + +1 <= T <= 10000 +0 <= n1,k1,n2,k2 <= 109 +1 <= n <= 107 + +**Note** The output to 00 should be 1. + +**Sample Input** + + 1 + 2 1 2 2 15 + +**Sample Output** + + 1 + +**Explanation** + +f(2,1) = 2 + +f(2,2) = 4 + +so answer is 16 mod 15 = 1 + + +[Editorial](https://www.hackerrank.com/blog/infinitum-mar14-devu-police)",code,Help Devu escape from police,ai,2013-10-09T04:59:51,2022-09-02T09:54:38,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER n1 +# 2. INTEGER k1 +# 3. INTEGER n2 +# 4. INTEGER k2 +# 5. INTEGER n +# + +def solve(n1, k1, n2, k2, n): + # 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() + + n1 = int(first_multiple_input[0]) + + k1 = int(first_multiple_input[1]) + + n2 = int(first_multiple_input[2]) + + k2 = int(first_multiple_input[3]) + + n = int(first_multiple_input[4]) + + result = solve(n1, k1, n2, k2, n) + + fptr.write(str(result) + '\n') + + fptr.close() +"," +It is holi festival, festival of colors. Devu is having fun playing holi and is throwing balloons with his girlfriend Glynis. Police saw this mischief and tried arresting his girlfriend, Devu being a mathematician asked police not to arrest his girlfriend and instead torture him with brain teaser. Devu was a young engineering fellow and he did not knew that policeman was equally good in mathematics, policeman gave Devu a problem which is as follows: + +Let $f(n,k) = n^k$ + +Your aim is to answer $f(n_1,k_1)^{f(n_2,k_2)} \bmod n$ + +Can you help devu and his girlfriend rescue from modern police. +",0.4318181818181818,"[""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""]","You are given $T$ which is the number of queries to solve. + +Each Query consist of 5 space separated integers $n_1,k_1,n_2,k_2,n$",Output contains exactly $T$ lines. $i^{\text{th}}$ line containing the answer for the $i^{\text{th}}$ query.," 1 + 2 1 2 2 15", 1,Hard,Devu Vs Police Infinitum Mar14 Editorial,"

Problem Statement

+ +

Problem Setter : Devendra
+Problem Tester : Cao Peng
+Required Knowledge: Chinese Remainder Theorm

+ +

The Basic Idea Exploited here is Chinese Remainder Theorom.
+let n = p[1]^e[1] * p[2]^e[2] * p[3]^e[3] ... p[k]^e[k] where p[i] is prime.
+let expr = A[1]^A[2]^A[3] where A[1] = f(n1,k1) , A[2] = n2, A[3] = k2
+so, calculating expr mod n is equivalent in calculating
+CRT ( expr mod p[1]^e[1] , expr mod p[2]^[e_2] ,......., expr mod p[k]^e[k] )
+Now lets see the case when e[i] = 1, then calculating expr mod p[i] is equivalent to A[1]^( A[2]^A[3] mod (p[i] -1 ) ) mod p[i].
+Euler Totient Period for p[i] is p[i] - 1.
+Now for the case of p[i]^e[i] where e[i]!=1, euler totient period is given by p[i]^e[i] - p[i]^(e[i]-1)
+Note: :Be carefull with Euler Totient period concept which is valid only if A[1] is coprime to p[i]. It is left as an exercise for the reader to figure it out how to procede then.

+ +

Solution by cpcs

+ +

Let a = n1k1 % n and b = n2k2, we need to calculate a^b mod n. We can judge whether a = 0/1 or b = 0,1 first to deal with the special conditions like 0^0, 1^p...etc.
+Then we can suppose a > 1 and b > 1.
+The solution is based on that although n may not be a prime, the period of the n1x % n is phi(n) , where phi is the euler function.
+But the starting point of the first period may be starts from phi(n). That means for any y >= phi(n) we have n1(y) == n1(y + phi(n)) (mod n)

+ +

So if we found b is smaller enough, namely if b < phi(n), we can directly calculate the result using O(logb) algorithm. Otherwise we have b>=phi(n) then n1k1 == n1(b % phi(n) + phi(n)) mod n, so we just calculate n1 (b % phi(n) + phi(n)) % n.

+ +

Setter's Code

+ +
#include<stdio.h>
+#include<iostream>
+#include<string.h>
+#include<vector>
+#include<assert.h>
+using namespace std;
+typedef long long int ll;
+int sieve_par=3162;
+int prime[3162] , array[3162],counter=0;
+ll inverse(ll a,ll b)                   //b>a
+{
+    ll Remainder,p0=0,p1=1,pcurr=1,q,m=b;
+    while(a!=0)
+    {
+        Remainder=b%a;
+        q=b/a;
+        if(Remainder!=0)
+        {
+            pcurr=p0-(p1*q)%m;
+            if(pcurr<0)
+                pcurr+=m;
+            p0=p1;
+            p1=pcurr;
+        }
+        b=a;
+        a=Remainder;
+    }
+    return pcurr;
+}
+ll binpow(ll a,ll b,ll mod)
+{
+    ll ans=1;
+    while(b)
+        if(b&1){
+            ans=(ans*a)%mod;
+            b--;
+
+        }
+        else{   
+            a=(a*a)%mod;
+            b>>=1;
+        }
+    return ans%mod;
+}
+ll CRT(ll mod[],ll rem[],int t)         //t is the number of pairs of rem and mod
+{
+    ll ans = rem[0],m = mod[0];
+
+    for(int i = 1;i < t;++i)
+    {
+        ll a = inverse(m,mod[i]);
+        ll b = inverse(mod[i],m);
+        ans = (ans * b * mod[i] + rem[i] * a * m) % (m * mod[i]);
+        m *= mod[i];
+    }   
+    return ans;
+}
+void sieve()
+{
+    for(int i=1;i<sieve_par;i++)
+        array[i]=1;
+    array[0]=0;
+    int j;
+    for(int i=2;i<=sieve_par;i++)
+    {
+        if(array[i-1]==1)
+        {
+            prime[counter]=i;
+            for(j=i*i;j<=sieve_par;j+=i)
+                array[j-1]=0;
+            counter++;
+        }
+    }
+}
+int check(ll a,ll b,ll n)
+{
+    ll ans=1;
+    while(b)
+        if(b&1){
+            ans=ans*a;
+            if(ans>n)   return -1;
+            b--;
+        }
+        else{
+            a=a*a;
+            if(a>n)     return -1;
+            b>>=1;  
+        }
+    return ans;
+}
+ll solveit(int n1,int k1,int n2,int k2,int m,int p)
+{
+    ll x=1,y=0;
+    if(n1==0){
+        if(n2==0 && k2==0 && k1==0) return 1;
+        if(n2==0 && k2==0 && k1!=0) return 0;
+        if(k1==0 || n2==0)  return 1;
+        return 0;
+    }
+    if(n1 % p == 0 ){
+        ll ans;
+        while(n1%p == 0){
+            n1/=p;
+            x=x*p;
+            y++;
+        }
+        ans= check(n2,k2,m);
+        ans= ans* k1*y;
+        if(ans>=0)  ans= check(p,ans,m);
+        if(ans<0)   return 0;
+        else x= ans;
+    }
+    ll a=binpow(n2,k2,m-(m/p));
+    ll b=binpow(n1,k1,m);
+    ll c= binpow(b,a,m);
+    return (c*x)%m;
+}
+int main()
+{
+    sieve();
+    int test,n1,n2,n,k1,k2,t;
+    ll mod[15],rem[15],ans;
+    //printf(""%d is counter\n"",counter);    
+    scanf(""%d"",&test);
+    assert(test<=10000);
+    while(test--){
+        scanf(""%d%d%d%d%d"",&n1,&k1,&n2,&k2,&n);
+        assert(n1<=1000000000 &&  k1<=1000000000 && n2<=1000000000 && k2<=1000000000 && n<=10000000);
+        assert(n1>=0 && k1>=0 && n2>=0 && k2>=0 && n>=1);
+        if(n==1){
+            printf(""0\n"");
+            continue;
+        }
+        t=0;
+        for(int i=0;i<counter;i++){
+            if(n< prime[i]*prime[i])    break;
+            if(n%prime[i]==0){
+                mod[t]=1;
+                while(n%prime[i]==0){
+                    n/=prime[i];
+                    mod[t]*=prime[i];
+                }
+                rem[t]=solveit(n1,k1,n2,k2,mod[t],prime[i]);
+                t++;
+            }
+        }
+        if(n>1){
+            mod[t]=n;
+            rem[t]=solveit(n1,k1,n2,k2,mod[t],n);
+            t++;
+        }
+        printf(""%lld\n"",CRT(mod,rem,t));
+    }
+    return 0;
+}
+
+ +

Tester's Code

+ +
import java.math.*;
+import java.util.*;
+
+
+
+public class Solution {
+    public static long powermod(long x,long y,long M) {
+      x %= M;
+
+      if (y == 0) {
+        return 1;
+      }
+      if (x == 0) {
+        return 0;
+      }
+      long r = 1L;
+      for (;y > 0; y >>= 1) {
+        if ((y & 1) > 0) {
+            r = r * x % M;
+        }
+        x = x * x % M;
+      }
+      return r;
+    }
+    public static long phi(long m) {
+      long p = 1L;
+       for (long i = 2L; i * i <= m; ++i) {
+        if (m % i == 0) {
+            long j = 1L;
+             while (m % i == 0) {
+                m /= i;
+                j *= i;
+             }
+
+             p *= j - j / i;
+        }
+      }
+      return (m > 1)?(p * (m - 1)):p;
+    }
+    public static long cmp(long n,long k,long x) {  //n ^ k > x < x = x
+    long i = 0L, temp = 1L;
+        while ((i < k) && (temp < x)) {
+           i++;
+           temp *= n;
+        }
+        if ((i >= k) && (temp <= x)) {
+          return temp;
+        }
+        return -1;
+
+    }
+    public static void main(String[] args) {
+        Scanner scanner = new Scanner(System.in);
+        for (int cases = scanner.nextInt(); cases > 0; cases--) {
+          long n1 = scanner.nextLong();
+          long k1 = scanner.nextLong();
+          long n2 = scanner.nextLong();
+          long k2 = scanner.nextLong();
+          long n = scanner.nextLong();
+          if (n == 1) {
+            System.out.println(0);
+          }
+          else {
+            long x = powermod(n1,k1,n);
+            if ((k2 == 0) || (n2 == 1)) {
+              System.out.println(x);
+            }
+            else if (n2 == 0) {
+              System.out.println(1);
+            }
+            else if (x <= 1) {
+                 System.out.println(x);
+            }
+            else {  // n2 > 1, k2 > 0, x > 1
+              long p = phi(n);
+              long y = cmp(n2,k2,p);
+              System.out.println(powermod(x, (y >= 0)?y:(powermod(n2,k2,p) + p),n));
+
+            }
+
+          }
+        }
+
+    }
+}
+
",0.0,infinitum-mar14-devu-police,2014-04-01T21:20:47,"{""contest_participation"":1667,""challenge_submissions"":241,""successful_submissions"":76}",2014-04-01T21:20:47,2016-12-09T10:05:33,tester,"###Java +```java + + +import java.math.*; +import java.util.*; + + + +public class Solution { + public static long powermod(long x,long y,long M) { + x %= M; + + if (y == 0) { + return 1; + } + if (x == 0) { + return 0; + } + long r = 1L; + for (;y > 0; y >>= 1) { + if ((y & 1) > 0) { + r = r * x % M; + } + x = x * x % M; + } + return r; + } + public static long phi(long m) { + long p = 1L; + for (long i = 2L; i * i <= m; ++i) { + if (m % i == 0) { + long j = 1L; + while (m % i == 0) { + m /= i; + j *= i; + } + + p *= j - j / i; + } + } + return (m > 1)?(p * (m - 1)):p; + } + public static long cmp(long n,long k,long x) { //n ^ k > x < x = x + long i = 0L, temp = 1L; + while ((i < k) && (temp < x)) { + i++; + temp *= n; + } + if ((i >= k) && (temp <= x)) { + return temp; + } + return -1; + + } + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + for (int cases = scanner.nextInt(); cases > 0; cases--) { + long n1 = scanner.nextLong(); + long k1 = scanner.nextLong(); + long n2 = scanner.nextLong(); + long k2 = scanner.nextLong(); + long n = scanner.nextLong(); + if (n == 1) { + System.out.println(0); + } + else { + long x = powermod(n1,k1,n); + if ((k2 == 0) || (n2 == 1)) { + System.out.println(x); + } + else if (n2 == 0) { + System.out.println(1); + } + else if (x <= 1) { + System.out.println(x); + } + else { // n2 > 1, k2 > 0, x > 1 + long p = phi(n); + long y = cmp(n2,k2,p); + System.out.println(powermod(x, (y >= 0)?y:(powermod(n2,k2,p) + p),n)); + + } + + } + } + + } +} +``` +",not-set,2016-04-24T02:02:35,2016-07-23T18:01:49,Java +42,1329,a-very-special-multiple,A Very Special Multiple,"[Mandarin](http://hr-filepicker.s3.amazonaws.com/infinitum-mar14/mandarin/1329-veryspecialmultiple.md) \| [Russian](http://hr-filepicker.s3.amazonaws.com/infinitum-mar14/russian/1329-veryspecialmultiple.md) \| [Japanese](http://hr-filepicker.s3.amazonaws.com/infinitum-mar14/japanese/1329-veryspecialmultiple.md) + +Charlie and Johnny play a game. For every integer _X_ Charlie gives, Johnny has to find the smallest positive integer _Y_, such that X x Y (X multiplied by Y) contains only 4's and 0's and starts with one or more 4's followed by zero or more 0's. (i.e.), 404 is an invalid number but 4400, 440, and 444 are valid numbers. + +If _a_ is the number of 4's and _b_ is the number of 0's, can you print the value of (2 x a) + b. + +**Input Format** +The first line contains an integer `T`. +`T` lines follow, each line containing the integer `X` as stated above. + +**Output Format** +For every X, print the output (2 x a) + b in a newline as stated in the problem statement. + +**Constraints** + +1 <= T <= 100 +1 <= X <= 1010 + +**Sample Input** + + 3 + 4 + 5 + 80 + +**Sample Output** + + 2 + 3 + 4 + +**Explanation** +For the 1st test-case, the smallest such multiple of 4 is **4** itself. Hence value of a will be 1 and and value of b will be 0. The required value of (2 x a) + b is 2. + +For the 2nd test-case, **Y** = 8 and 40 is the minimum such multiple of 5. Hence value of a,b and (2 x a) + b will be 1, 1 and 3 respectively. + +[Editorial](https://www.hackerrank.com/blog/infinitum-mar14-a-very-special-multiple)",code,Find the number of 4's and 0's in the multiple,ai,2013-11-18T07:44:55,2022-09-02T09:54:43,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts LONG_INTEGER x as parameter. +# + +def solve(x): + # 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): + x = int(input().strip()) + + result = solve(x) + + fptr.write(str(result) + '\n') + + fptr.close() +","Charlie and Johnny play a game. For every integer $X$ Charlie gives, Johnny has to find the smallest positive integer $Y$ such that $X \times Y$ ($X$ multiplied by $Y$) contains only 4s and 0s and starts with one or more 4s followed by zero or more 0s. For example, 404 is an invalid number but 4400, 440, and 444 are valid numbers. + +If $a$ is the number of 4s and $b$ is the number of 0s, can you print the value of $(2\times a) + b$? + +**Input Format** + +The first line of input contains a single integer $T$, the number of test cases. + +$T$ lines follow, each line containing the integer $X$ as stated above. + +**Output Format** + +For every $X$, print the output $(2\times a) + b$ in a newline as stated in the problem statement. + +**Constraints** + +$1 \le T \le 100$ +$1 \le X \le 10^{10}$ + +**Sample Input** + + 3 + 4 + 5 + 80 + +**Sample Output** + + 2 + 3 + 4 + +**Explanation** + +For the 1st test case, the smallest such multiple of $4$ is 4 itself. Hence the value of $a$ will be $1$ and and the value of $b$ will be $0$, and the answer is $(2\times a) + b = 2$. + +For the 2nd test case, $Y = 8$ and 40 is the minimum such multiple of $5$. Hence the values of $a$, $b$ and $(2 \times a) + b$ will be $1$, $1$ and $3$ respectively. +",0.5641025641025641,"[""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,A Very Special Multiple Infinitum Mar14 Editorial,"

Problem Statement

+ +

Problem Setter : Shashank Sharma
+Problem Tester : Satvik Gupta
+Required Knowledge: Fermat's Theorm, Sieve of Eratosthenes, Totient Function, Division +Time Complexity : O(root(N))

+ +

Approach

+ +

The Multiple X*Y can be divided into 4*(1111....00000...)
+Now 0's are made up of all multiple of 2/5.

+ +

now our multiple (1111...)is rid of all 2,5 hence it is coprime to 10, so Fermat's theorm holds

+ +

1111...n times can be written as (10n - 1)/9, so

+ +

+ +

hence phi(9x) is a solution but it is not the smallest.
+We take the divisors of 9x, minimum of those which solves it is the required number.

+ +

but 9x can be a large number. Hence we solve for prime factors of 9x and get solutions s1,s2 etc. We take lcm of those values to get the right answer.

+ +

in the end we return 2*a + b

+ +

Tester's Code

+ +
#include <bits/stdc++.h>
+using namespace std;
+typedef long long int ll;
+
+ll sieve(ll a[],ll b[],ll n)
+{
+    ll i,k,j;
+    for(i=0;i<n;i++)
+    {        
+       a[i]=i,b[i]=0;
+    }
+    for (j=2;j*j<n;j++)
+    { 
+       k=j;
+       if(a[j]!=0)
+       { 
+           while(k*j<n)
+           {                
+               a[k*j]=0;
+               k=k+1;
+           }
+       }
+    }
+    i=2;j=0;
+    while(i<n)
+    {
+       if(a[i]!=0)
+       {
+           b[j]=a[i];
+           j++;
+       }
+       i++;
+    }
+    return j;
+}
+
+ll gcd(ll a,ll b)
+{
+   ll d;
+   a=a>=0?a:-a;
+   b=b>=0?b:-b;
+   while(b!=0)
+   {
+       d=a%b;
+       a=b;
+       b=d;
+   }
+   return a;
+}
+
+ll abmodP(ll a, ll b,ll mod)
+{
+   ll aprod = a;
+   ll ans = 0;
+   while(b > 0) {
+       if(b & 1) ans = (ans + aprod) % mod;
+       b = b >> 1;
+       aprod = (aprod << 1) % mod;
+   }
+   return ans;
+}
+long long int power(long long int a,long long int b,long long int c)//To calculate A^B%C
+{
+   long long int res=1,apower=a;
+   while(b > 0)
+   {
+       if(b%2 == 1)
+       {
+           res=abmodP(res,apower,c);
+       }
+       apower = abmodP(apower,apower,c);
+       b=b/2 ;
+   }
+
+   return res%c;
+}
+
+
+
+ll a[100005],b[100005];
+
+int main()
+{
+   ll n = 100000;
+   ll k = sieve(a,b,n);
+   ll t,x;
+   ll i,j;
+   scanf(""%lld"",&t);
+   while(t--)
+   {
+       ll d[20][3];
+       scanf(""%lld"",&x);
+       if(x==0)
+           cout << 0 << endl;
+       else if(x==1)
+           cout << 2 << endl;
+       else
+       {
+           x = x*9;
+           ll len=0;
+           for(i=0;b[i]*b[i] <= x && i<k ; i++)
+           {
+               ll count=0;
+               if(x%b[i]==0)
+               {
+                   ll an1=1;
+                   d[len][0]=b[i];
+                   while(x%b[i]==0)
+                       x=x/b[i],count+=1,an1*=b[i];
+                       d[len][1]=count,d[len][2]=an1;
+                   len+=1;
+               }
+           }
+           if(x!=1)
+               d[len][0]=x,d[len][1]=1,d[len][2]=x,len=len+1;
+           ll c2=0,c5=0,c3=0;
+           if(d[0][0]==2)
+               c2=d[0][1];
+           if(d[0][0]==5)
+               c5=d[0][1];
+           if(len > 1 && d[1][0]==5)
+               c5=d[1][1];
+           if(len > 2 && d[2][0]==5)
+               c5=d[2][1];
+           ll y=max(c5,c2-2);
+           ll e[20];
+           ll len1=0;
+           for(i=0;i<len;i++)
+           {
+               if(d[i][0]!=2 && d[i][0]!=5)
+               {
+                   ll a1 = d[i][2]/d[i][0];
+                   a1 = a1 * (d[i][0]-1);
+                   ll  min1=a1;
+                   for(j=1;j*j<a1;j++)
+                   {
+                       if(a1%j==0)
+                       {
+                           ll po= power((ll)10,j,d[i][2]);
+                           if(po < 0)
+                                   po+=d[i][2];
+                           if(po==1)
+                               min1 = min(j,min1);
+                           else
+                           {
+                               po= power((ll)10,(a1/j),d[i][2]);
+                               if(po < 0)
+                                   po+=d[i][2];
+                               if(po==1)
+                                   min1 = min(a1/j,min1);
+                           }
+
+                       }
+                   }
+                   e[len1]=min1;
+                   len1+=1;
+               }
+           }
+           ll lcm = e[0];
+           for(i=1;i<len1;i++)
+           {
+               lcm = (lcm * e[i])/gcd(lcm,e[i]);   
+           }
+           printf(""%lld\n"",2*lcm + y);    
+       }
+
+   }
+
+   return 0;
+}
+
",0.0,infinitum-mar14-a-very-special-multiple,2014-04-01T21:24:58,"{""contest_participation"":1667,""challenge_submissions"":122,""successful_submissions"":48}",2014-04-01T21:24:58,2016-12-02T17:29:23,tester,"###C++ +```cpp + +#include +using namespace std; +typedef long long int ll; + +ll sieve(ll a[],ll b[],ll n) +{ + ll i,k,j; + for(i=0;i=0?a:-a; + b=b>=0?b:-b; + while(b!=0) + { + d=a%b; + a=b; + b=d; + } + return a; +} + +ll abmodP(ll a, ll b,ll mod) +{ + ll aprod = a; + ll ans = 0; + while(b > 0) { + if(b & 1) ans = (ans + aprod) % mod; + b = b >> 1; + aprod = (aprod << 1) % mod; + } + return ans; +} +long long int power(long long int a,long long int b,long long int c)//To calculate A^B%C +{ + long long int res=1,apower=a; + while(b > 0) + { + if(b%2 == 1) + { + res=abmodP(res,apower,c); + } + apower = abmodP(apower,apower,c); + b=b/2 ; + } + + return res%c; +} + + + +ll a[100005],b[100005]; + +int main() +{ + ll n = 100000; + ll k = sieve(a,b,n); + ll t,x; + ll i,j; + scanf(""%lld"",&t); + while(t--) + { + ll d[20][3]; + scanf(""%lld"",&x); + if(x==0) + cout << 0 << endl; + else if(x==1) + cout << 2 << endl; + else + { + x = x*9; + ll len=0; + for(i=0;b[i]*b[i] <= x && i 1 && d[1][0]==5) + c5=d[1][1]; + if(len > 2 && d[2][0]==5) + c5=d[2][1]; + ll y=max(c5,c2-2); + ll e[20]; + ll len1=0; + for(i=0;i1, a2,..., aK}_, and an integer `N`. They need to find the a way to reach `N`, starting from `1`, and at each step multiplying current value by any element of `A`. But soon they realise that there may exist more than one way to reach `N`. So they decided to find a way in which number of states are least. All of sudden they started on this new problem. People solved it and then started shouting their answer. CRAP!!!. There still exists multiple answers. So finally after much consideration, they settled on the lexicographically smallest series among those solutions which contains the least number of states. + +For example, if `N = 12` and `A = {2, 3, 4}` then following ways exists + + (a) 1 -> 2 -> 4 -> 12 + x2 x2 x3 + + (b) 1 -> 4 -> 12 + x4 x3 + + (c) 1 -> 3 -> 12 + x3 x4 + +Here `(a)` is not the minimal state, as it has 4 states in total. While `(b)` and `(c)` are contenders for answer, both having 3 states, `(c)` is lexicographically smaller than `(b)` so it is the answer. In this case you have to print `1 3 12`. If there exists no way to reach `N` print `-1`. + +**Input** +Input contains two lines where first line contains two space separated integer, `N K`, representing the final value to reach and the size of set `A`, respectively. Next line contains `K` space integers representing the set `A` = _{a1, a2,..., aK}_. + +**Output** +Print the steps to reach `N` if it exists. Otherwise print `-1`. + +**Constraints** +1 ≤ N ≤ 109 +1 ≤ K ≤ 20 +2 ≤ ai ≤ 20, where _i ∈ [1..K]_ +ai ≠ aj, where 1 <= i, j <= K AND _i_ ≠ _j_ + +**Note:** + +* _Lexicographical order:_ If `list1` = _[p1, p2, ...pm]_ and `list2` = _[q1, q2,...qn]_ are two ordered lists, then `list1` is lexicographically smaller than `list2` if any one of the following condition satisfies. + + + _pi = qi_, for _i_ ∈ [1..m] AND _m < n_. + + _pi = qi_, for _i_ ∈ _[1..k]_ AND _k_ < min(_m_, _n_) AND _pk+1 < qk+1_. + +* You need to find the _lexigraphically smallest_ series among those solutions which contains the least number of states. + +**Sample Input #00** + + 12 3 + 2 3 4 + +**Sample Output #00** + + 1 3 12 + +**Sample Input #01** + + 15 5 + 2 10 6 9 11 + +**Sample Output #01** + + -1 + +**Sample Input #02** + + 72 9 + 2 4 6 9 3 7 16 10 5 + +**Sample Output #02** + + 1 2 8 72 + +**Explanation** +*Test Case #00:* This is the same case which is explaned above. +*Test Case #01:* Here no way exists so that we can reach `15` starting from `1`. +*Test Case #02:* There are multiple ways to reach `72` using these 8 numbers. Out of which following 6 ways consists of minimal states (4). + + States => Multiplication operation + 1 9 18 72 => (x9, x2, x4) + 1 4 36 72 => (x4, x9, x2) + 1 2 8 72 => (x2, x4, x9) + 1 2 18 72 => (x2, x9, x4) + 1 4 8 72 => (x4, x2, x9) + 1 9 36 72 => (x9, x4, x2) + +As series `1 2 8 72` is lexicographically smallest, it is the answer. + +",code,Find multiples to reach `N`.,ai,2014-03-17T22:45:59,2017-03-10T08:53:18,,,,"At the time when Pythagoreanism was prevalent, people were also focused on different ways to factorize a number. In one class, Pythagoras asked his disciples to solve one such problem, _Reverse Factorization_. They were given a set of integer, $A = \{a_1, a_2, \cdots, a_K\}$, and an integer $N$. They need to find the a way to reach $N$, starting from $1$, and at each step multiplying current value by any element of $A$. But soon they realised that there may exist more than one way to reach $N$. So they decided to find a way in which number of states are least. All of sudden they started on this new problem. People solved it and then started shouting their answer. CRAP!!!. There still exists multiple answers. So finally after much consideration, they settled on the lexicographically smallest series among those solutions which contains the least number of states. + +For example, if $N = 12$ and $A = {2, 3, 4}$ then following ways exists + +``` +(a) 1 -> 2 -> 4 -> 12 + x2 x2 x3 + +(b) 1 -> 4 -> 12 + x4 x3 + +(c) 1 -> 3 -> 12 + x3 x4 +``` + +Here `(a)` is not the minimal state, as it has $4$ states in total. While `(b)` and `(c)` are contenders for answer, both having 3 states, `(c)` is lexicographically smaller than `(b)` so it is the answer. In this case you have to print `1 3 12`. If there exists no way to reach $N$ print `-1`. +",0.5,"[""haskell"",""clojure"",""scala"",""erlang"",""sbcl"",""ocaml"",""fsharp"",""racket"",""elixir""]","Input contains two lines where first line contains two space separated integer, $N$ and $K$, representing the final value to reach and the size of set $A$, respectively. Next line contains `K` space integers representing the set $A = \{a_1, a_2, \cdots, a_K\}$. + +","Print the steps to reach $N$ if it exists. Otherwise print `-1`. + +", , ,Hard,"Reverse Factorization, Functional Programming Contest - March'14","

Problem Statement
+Difficulty Level : Medium-Hard
+Required Knowledge : Breadth First Search, Simple Maths
+Problem Setter : Abhiranjan

+ +

It was a decoy problem from the author. Initially it appears to be a factorization problem, but when looking closely it became clear that even a simple BFS can be used to solved this problem. Following two properties should help in solving this problem via BFS.

+ +
    +
  1. Find the solution with minimum number of steps. Elements of set A = {a1, a2, ..., aK} acts as the edge between an integer/node P and _{P*a1, P*a2, ..., P*aK}_
  2. +
  3. In order to find the lexicographically smallest solution, we need to enqueue smaller element earlier larger element, i.e., sort the elements of set A before multiplying it with the current number in BFS.
  4. +
+ +

PS: Implementing queue and BFS can be a tricky task in few languages.

+ +

We need to start from 1 and then multiplying current number with the elements of A. We need to store the parent node of the current node, as it is required to trace the path from 1 to N.

+ +

Setter's Code

+ +

*Language : *

+ +
import Data.List
+import qualified Data.Map as Map
+
+data Queue a = Queue {
+      active    :: [a]
+    , inactive  :: [a]
+  } deriving (Show)
+
+emptyQ :: Queue a
+emptyQ = Queue [] []
+
+swapQ :: Queue a -> Queue a
+swapQ q = Queue {active = inactive q, inactive = active q}
+
+isEmptyQ :: Queue a -> Bool
+isEmptyQ q = null (active q) && null (inactive q)
+
+peekQ :: Queue a -> (a, Queue a)
+peekQ q
+  | isEmptyQ q         = error ""queue is empty, can't look""
+  | null. inactive $ q = (head q1, Queue {active = [], inactive = q1})
+  | otherwise          = (head. inactive $ q, q)
+      where
+        q1 = reverse. active $ q
+
+popQ :: Queue a -> (a, Queue a)
+popQ q = (h, q1 {inactive = tail. inactive $ q1})
+  where
+    (h, q1) = peekQ q
+
+enqueue :: a -> Queue a -> Queue a
+enqueue x q = q {active = x: active q}
+
+bfs :: Integer -> [Integer] -> Map.Map Integer Integer
+bfs n arr1 =  snd. bfs1 $ (enqueue 1 emptyQ, Map.empty)
+  where
+    arr = sort arr1
+    bfs1 :: (Queue Integer, Map.Map Integer Integer) -> (Queue Integer, Map.Map Integer Integer)
+    bfs1 (q, st)
+      | isEmptyQ q = (q, st)
+      | otherwise  = bfs1 nextState
+        where
+          (x, q1) = popQ q
+          nextState = foldl' foldFunc (q1,st) arr
+          foldFunc acc@(qq, sst) mul =
+            let
+              m = mul*x
+            in
+              if (m > n) || Map.member m sst
+                then acc
+                else (enqueue m qq, Map.insert m  x sst)
+
+tracePath :: Integer -> Map.Map Integer Integer -> Maybe [Integer]
+tracePath n mp
+  | not (Map.member n mp) = Nothing
+  | otherwise             = Just. reverse. traverse $ n
+    where
+      traverse 1 = [1]
+      traverse x = x : traverse (Map.findWithDefault (-1) x mp)
+
+printPath :: Maybe [Integer] -> String
+printPath Nothing    = show (-1)
+printPath (Just arr) = unwords. map show $ arr
+
+main :: IO ()
+main = getContents >>= putStrLn. printPath. (\[[n, k], arr] -> tracePath n (bfs n arr)). map (map read. words). lines
+
",0.0,lambda-calculi-mar14-reverse-factorization,2014-04-02T19:30:44,"{""contest_participation"":797,""challenge_submissions"":56,""successful_submissions"":46}",2014-04-02T19:30:44,2016-05-13T00:03:08,setter," import Data.List + import qualified Data.Map as Map + + data Queue a = Queue { + active :: [a] + , inactive :: [a] + } deriving (Show) + + emptyQ :: Queue a + emptyQ = Queue [] [] + + swapQ :: Queue a -> Queue a + swapQ q = Queue {active = inactive q, inactive = active q} + + isEmptyQ :: Queue a -> Bool + isEmptyQ q = null (active q) && null (inactive q) + + peekQ :: Queue a -> (a, Queue a) + peekQ q + | isEmptyQ q = error ""queue is empty, can't look"" + | null. inactive $ q = (head q1, Queue {active = [], inactive = q1}) + | otherwise = (head. inactive $ q, q) + where + q1 = reverse. active $ q + + popQ :: Queue a -> (a, Queue a) + popQ q = (h, q1 {inactive = tail. inactive $ q1}) + where + (h, q1) = peekQ q + + enqueue :: a -> Queue a -> Queue a + enqueue x q = q {active = x: active q} + + bfs :: Integer -> [Integer] -> Map.Map Integer Integer + bfs n arr1 = snd. bfs1 $ (enqueue 1 emptyQ, Map.empty) + where + arr = sort arr1 + bfs1 :: (Queue Integer, Map.Map Integer Integer) -> (Queue Integer, Map.Map Integer Integer) + bfs1 (q, st) + | isEmptyQ q = (q, st) + | otherwise = bfs1 nextState + where + (x, q1) = popQ q + nextState = foldl' foldFunc (q1,st) arr + foldFunc acc@(qq, sst) mul = + let + m = mul*x + in + if (m > n) || Map.member m sst + then acc + else (enqueue m qq, Map.insert m x sst) + + tracePath :: Integer -> Map.Map Integer Integer -> Maybe [Integer] + tracePath n mp + | not (Map.member n mp) = Nothing + | otherwise = Just. reverse. traverse $ n + where + traverse 1 = [1] + traverse x = x : traverse (Map.findWithDefault (-1) x mp) + + printPath :: Maybe [Integer] -> String + printPath Nothing = show (-1) + printPath (Just arr) = unwords. map show $ arr + + main :: IO () + main = getContents >>= putStrLn. printPath. (\[[n, k], arr] -> tracePath n (bfs n arr)). map (map read. words). lines + + +",not-set,2016-04-24T02:02:36,2016-04-24T02:02:36,Python +44,2176,hexagonal-grid,Hexagonal Grid," + +You are given a hexagonal grid of size _2xN_. Your task is to construct the grid with _2x1_ dominoes. The dominoes can be arranged in any of the three orientations shown below. To add to the woes, certain cells of the hexogonal grid are blackened i.e., no domino can occupy that cell. Can you construct such a hexagonal grid? The blackened cell and the 3 dominoes are shown in the figure below. + + +![Example figure](https://hr-filepicker.s3.amazonaws.com/2176-hexagonal-grid.png) + +**Input Format** +The first line contains a single integer _T_, the number of testcases. +_T_ testcases follow. +Each testcase contains three lines. The first line of the testcase contains a single integer _N_, size of the hexagonal grid. +The next two lines describe the grid and have _N_ characters each (0 corresponds to cell to be filled with domino and 1 corresponds to blackened cell). + +**Output Format** +For each testcase output `YES` if there exists at least one way to fill structure with dominoes and output `NO` otherwise. + +**Constraints** +1 ≤ _T_ ≤ 100 +1 ≤ _N_ ≤ 10 + +**Note** +There must be no domino above black cells. +All other cells should have only one domino above it. + +**Sample input** + + 6 + 6 + 010000 + 000010 + 2 + 00 + 00 + 2 + 00 + 10 + 2 + 00 + 01 + 2 + 00 + 11 + 2 + 10 + 00 + +**Sample Output** + + YES + YES + NO + NO + YES + NO + + +**Explanation** +First testcase in sample input describes grid from the picture. +For second testcase, there are two ways to fill it. Either place two red dominoes horizontally side-by-side or place two yellow dominoes vertically side-by-side.",code,"You are given a hexagonal grid of size 2xN. Your task is to +construct the grid with dominoes of given size.",ai,2014-03-20T21:45:12,2022-08-31T08:14:47,"# +# Complete the 'hexagonalGrid' function below. +# +# The function is expected to return a STRING. +# The function accepts following parameters: +# 1. STRING a +# 2. STRING b +# + +def hexagonalGrid(a, b): + # 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): + n = int(input().strip()) + + a = input() + + b = input() + + result = hexagonalGrid(a, b) + + fptr.write(result + '\n') + + fptr.close() +","You are given a hexagonal grid consisting of two rows, each row consisting of $n$ cells. The cells of the first row are labelled $a_1, a_2, \ldots a_n$ and the cells of the second row are labelled $b_1, b_2, \ldots, b_n$. + +For example, for $n = 6$: + +![Grid Shape](https://s3.amazonaws.com/hr-assets/0/1495564532-9e16e289ea-3.png ""The grid shape."") + +(Note that the $b_i$ is connected with $a_{i+1}$.) + +Your task is to tile this grid with $2\times 1$ *tiles* that look like the following: + +![Orientations](https://s3.amazonaws.com/hr-assets/0/1495564517-f725e11e0b-1.png ""Orientations of the 2x1 tile."") + +As you can see above, there are three possible orientations in which a tile can be placed. + +Your goal is to tile the whole grid such that every cell is covered by a tile, and no two tiles occupy the same cell. To add to the woes, certain cells of the hexagonal grid are *blackened*. No tile must occupy a blackened cell. + +Is it possible to tile the grid? + +Here's an example. Suppose we want to tile this grid: + +![Example Blank](https://s3.amazonaws.com/hr-assets/0/1495564538-9a59a63208-4.png ""Example of a grid with some blackened cells."") + +Then we can do the tiling as follows: + +![Example Tiled](https://s3.amazonaws.com/hr-assets/0/1495564526-f0c430b796-2.png ""Example of a tiled grid."")",0.5,"[""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 a single integer $t$, the number of test cases. + +The first line of each test case contains a single integer $n$ denoting the length of the grid. +The second line contains a binary string of length $n$. The $i^\text{th}$ character describes whether cell $a_i$ is blackened. +The third line contains a binary string of length $n$. The $i^\text{th}$ character describes whether cell $b_i$ is blackened. +A `0` corresponds to an empty cell and a `1` corresponds to blackened cell. ","For each test case, print `YES` if there exists at least one way to tile the grid, and `NO` otherwise."," 6 + 6 + 010000 + 000010 + 2 + 00 + 00 + 2 + 00 + 10 + 2 + 00 + 01 + 2 + 00 + 11 + 2 + 10 + 00 +"," YES + YES + NO + NO + YES + NO +",Hard,Hexagonal Grid - 101 Hack March Editorial,"

Hexagonal Grid
+Difficulty Level : Easy-Medium
+Required Knowledge : Recursion or DP
+Problem Setter : Seyaua
+Problem Tester : Abhiranjan Kumar

+ +

Solution
+There are a lot of ways to solve this problem. The easiest one is to just run a recursion, where in each step we will try to fill just two empty cells. The constraints are very small, so this solution works very fast. As an alternative solution you can write something like dynamic programming by submasks.

+ +

Setter's Code

+ +
#include <iostream>
+#include <cstdio>
+#include <string>
+#include <cstring>
+#include <set>
+#include <map>
+#include <vector>
+#include <cmath>
+#include <ctime>
+#include <algorithm>
+#include <bitset>
+#include <queue>
+#pragma comment(linker, ""/STACK:256000000"")
+
+using namespace std;
+
+const int maxN = 12;
+
+int a[2][maxN];
+int n;
+bool fnd = false;
+
+bool is_in(int i, int j) {
+  return (0 <= i && i < 2 && j >= 0 && j < n);
+}
+
+int dx[] = {0, 1, 1};
+int dy[] = {1, 0, -1};
+
+void rec() {
+  if (fnd) return;
+  int change = false;
+  for (int i = 0; i < 2 && !change && !fnd; ++i) {
+    for (int j = 0; j < n && !change && !fnd; ++j) {
+      if (a[i][j] == 0) {
+        change = true;
+        for (int k = 0; k < 3 && !fnd; ++k) {
+          if (is_in(i + dx[k], j + dy[k]) && a[i + dx[k]][j + dy[k]] == 0) {
+            a[i][j] = 1;
+            a[i + dx[k]][j + dy[k]] = 1;
+            rec();
+            a[i][j] = 0;
+            a[i + dx[k]][j + dy[k]] = 0;
+          }
+        }
+      }
+    }
+  }
+  if (!change) {
+    fnd = true;
+  }
+}
+
+void solve() {
+  scanf(""%d"", &n);
+  string s1, s2;
+  cin >> s1 >> s2;
+
+  for (int i = 0; i < n; ++i) {
+    a[0][i] = s1[i] - '0';
+    a[1][i] = s2[i] - '0';
+  }
+
+  fnd = false;
+  rec();
+  if (fnd) {
+    cout << ""YES"" << endl;
+  } else {
+    cout << ""NO"" << endl;
+  }
+}
+
+int main() {
+  //freopen(""input.txt"", ""r"", stdin);
+  //freopen(""output.txt"", ""w"", stdout);
+
+  int t;
+  scanf(""%d"", &t);
+  for (int i = 0; i < t; ++i) {
+    solve();
+  }
+
+  return 0;
+}
+
+ +

Tester's Code

+ +
#include <bits/stdc++.h>
+using namespace std;
+
+int a[2][101];
+int dp[105][105];
+int N;
+
+bool solve(int l, int r) {
+    if(l == -1 && r == -1)
+        return 1;
+    if(l < -1 ||r < -1)
+        return 0;
+    if(l < 0 && r >= 0 && a[1][r] == 1)
+        return solve(l, r-1);
+    if(r < 0 && l >= 0 && a[0][l] == 1)
+        return solve(l-1, r);
+    if(l < 0 || r < 0)
+        return 0;
+
+    int &ret = dp[l][r];
+    if(ret != -1)
+        return ret;
+
+    ret = 0;
+
+    if(a[0][l] == 1)
+        ret |= solve(l-1, r);
+    if(a[1][r] == 1)
+        ret |= solve(l, r-1);
+
+    if(l > 0 && a[0][l] == 0 && a[0][l-1] == 0)
+        ret |= solve(l-2, r);
+    if(r > 0 && a[1][r] == 0 && a[1][r-1] == 0)
+        ret |= solve(l, r-2);
+
+    if(l == r && a[0][l] == 0 && a[1][r] == 0)
+        ret |= solve(l-1, r-1);
+
+    if(l == r+1 && a[0][l] == 0 && a[1][r] == 0)
+        ret |= solve(l-1, r-1);
+
+    return ret;
+}
+
+int main()
+{
+    int t;
+    scanf(""%d"", &t);
+    assert(t >= 1 && t <= 100);
+
+    while(t--) {
+        memset(dp, -1, sizeof(dp));
+        cin >> N;
+        assert( N >= 1 && N <= 10);
+
+        string st[2];
+        cin >> st[0] >> st[1];
+        assert((int)st[0].length() == N);
+        assert((int)st[1].length() == N);
+
+        for(int i = 0; i < (int)N; ++i) {
+            assert(st[0][i] == '0' || st[0][i] == '1');
+            assert(st[1][i] == '0' || st[1][i] == '1');
+
+            a[0][i] = st[0][i] == '0' ? 0 : 1;
+            a[1][i] = st[1][i] == '0' ? 0 : 1;
+        }
+        cout << (solve(N-1, N-1) == 1 ? ""YES"" : ""NO"") << ""\n"";
+    }
+
+    return 0;
+}
+
",0.0,101mar14-hexagonal-grid,2014-04-04T08:43:27,"{""contest_participation"":1218,""challenge_submissions"":208,""successful_submissions"":134}",2014-04-04T08:43:27,2016-07-23T14:48:42,setter,"###C++ +```cpp + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#pragma comment(linker, ""/STACK:256000000"") + +using namespace std; + +const int maxN = 12; + +int a[2][maxN]; +int n; +bool fnd = false; + +bool is_in(int i, int j) { + return (0 <= i && i < 2 && j >= 0 && j < n); +} + +int dx[] = {0, 1, 1}; +int dy[] = {1, 0, -1}; + +void rec() { + if (fnd) return; + int change = false; + for (int i = 0; i < 2 && !change && !fnd; ++i) { + for (int j = 0; j < n && !change && !fnd; ++j) { + if (a[i][j] == 0) { + change = true; + for (int k = 0; k < 3 && !fnd; ++k) { + if (is_in(i + dx[k], j + dy[k]) && a[i + dx[k]][j + dy[k]] == 0) { + a[i][j] = 1; + a[i + dx[k]][j + dy[k]] = 1; + rec(); + a[i][j] = 0; + a[i + dx[k]][j + dy[k]] = 0; + } + } + } + } + } + if (!change) { + fnd = true; + } +} + +void solve() { + scanf(""%d"", &n); + string s1, s2; + cin >> s1 >> s2; + + for (int i = 0; i < n; ++i) { + a[0][i] = s1[i] - '0'; + a[1][i] = s2[i] - '0'; + } + + fnd = false; + rec(); + if (fnd) { + cout << ""YES"" << endl; + } else { + cout << ""NO"" << endl; + } +} + +int main() { + //freopen(""input.txt"", ""r"", stdin); + //freopen(""output.txt"", ""w"", stdout); + + int t; + scanf(""%d"", &t); + for (int i = 0; i < t; ++i) { + solve(); + } + + return 0; +} +``` +",not-set,2016-04-24T02:02:36,2016-07-23T14:48:30,C++ +45,2176,hexagonal-grid,Hexagonal Grid," + +You are given a hexagonal grid of size _2xN_. Your task is to construct the grid with _2x1_ dominoes. The dominoes can be arranged in any of the three orientations shown below. To add to the woes, certain cells of the hexogonal grid are blackened i.e., no domino can occupy that cell. Can you construct such a hexagonal grid? The blackened cell and the 3 dominoes are shown in the figure below. + + +![Example figure](https://hr-filepicker.s3.amazonaws.com/2176-hexagonal-grid.png) + +**Input Format** +The first line contains a single integer _T_, the number of testcases. +_T_ testcases follow. +Each testcase contains three lines. The first line of the testcase contains a single integer _N_, size of the hexagonal grid. +The next two lines describe the grid and have _N_ characters each (0 corresponds to cell to be filled with domino and 1 corresponds to blackened cell). + +**Output Format** +For each testcase output `YES` if there exists at least one way to fill structure with dominoes and output `NO` otherwise. + +**Constraints** +1 ≤ _T_ ≤ 100 +1 ≤ _N_ ≤ 10 + +**Note** +There must be no domino above black cells. +All other cells should have only one domino above it. + +**Sample input** + + 6 + 6 + 010000 + 000010 + 2 + 00 + 00 + 2 + 00 + 10 + 2 + 00 + 01 + 2 + 00 + 11 + 2 + 10 + 00 + +**Sample Output** + + YES + YES + NO + NO + YES + NO + + +**Explanation** +First testcase in sample input describes grid from the picture. +For second testcase, there are two ways to fill it. Either place two red dominoes horizontally side-by-side or place two yellow dominoes vertically side-by-side.",code,"You are given a hexagonal grid of size 2xN. Your task is to +construct the grid with dominoes of given size.",ai,2014-03-20T21:45:12,2022-08-31T08:14:47,"# +# Complete the 'hexagonalGrid' function below. +# +# The function is expected to return a STRING. +# The function accepts following parameters: +# 1. STRING a +# 2. STRING b +# + +def hexagonalGrid(a, b): + # 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): + n = int(input().strip()) + + a = input() + + b = input() + + result = hexagonalGrid(a, b) + + fptr.write(result + '\n') + + fptr.close() +","You are given a hexagonal grid consisting of two rows, each row consisting of $n$ cells. The cells of the first row are labelled $a_1, a_2, \ldots a_n$ and the cells of the second row are labelled $b_1, b_2, \ldots, b_n$. + +For example, for $n = 6$: + +![Grid Shape](https://s3.amazonaws.com/hr-assets/0/1495564532-9e16e289ea-3.png ""The grid shape."") + +(Note that the $b_i$ is connected with $a_{i+1}$.) + +Your task is to tile this grid with $2\times 1$ *tiles* that look like the following: + +![Orientations](https://s3.amazonaws.com/hr-assets/0/1495564517-f725e11e0b-1.png ""Orientations of the 2x1 tile."") + +As you can see above, there are three possible orientations in which a tile can be placed. + +Your goal is to tile the whole grid such that every cell is covered by a tile, and no two tiles occupy the same cell. To add to the woes, certain cells of the hexagonal grid are *blackened*. No tile must occupy a blackened cell. + +Is it possible to tile the grid? + +Here's an example. Suppose we want to tile this grid: + +![Example Blank](https://s3.amazonaws.com/hr-assets/0/1495564538-9a59a63208-4.png ""Example of a grid with some blackened cells."") + +Then we can do the tiling as follows: + +![Example Tiled](https://s3.amazonaws.com/hr-assets/0/1495564526-f0c430b796-2.png ""Example of a tiled grid."")",0.5,"[""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 a single integer $t$, the number of test cases. + +The first line of each test case contains a single integer $n$ denoting the length of the grid. +The second line contains a binary string of length $n$. The $i^\text{th}$ character describes whether cell $a_i$ is blackened. +The third line contains a binary string of length $n$. The $i^\text{th}$ character describes whether cell $b_i$ is blackened. +A `0` corresponds to an empty cell and a `1` corresponds to blackened cell. ","For each test case, print `YES` if there exists at least one way to tile the grid, and `NO` otherwise."," 6 + 6 + 010000 + 000010 + 2 + 00 + 00 + 2 + 00 + 10 + 2 + 00 + 01 + 2 + 00 + 11 + 2 + 10 + 00 +"," YES + YES + NO + NO + YES + NO +",Hard,Hexagonal Grid - 101 Hack March Editorial,"

Hexagonal Grid
+Difficulty Level : Easy-Medium
+Required Knowledge : Recursion or DP
+Problem Setter : Seyaua
+Problem Tester : Abhiranjan Kumar

+ +

Solution
+There are a lot of ways to solve this problem. The easiest one is to just run a recursion, where in each step we will try to fill just two empty cells. The constraints are very small, so this solution works very fast. As an alternative solution you can write something like dynamic programming by submasks.

+ +

Setter's Code

+ +
#include <iostream>
+#include <cstdio>
+#include <string>
+#include <cstring>
+#include <set>
+#include <map>
+#include <vector>
+#include <cmath>
+#include <ctime>
+#include <algorithm>
+#include <bitset>
+#include <queue>
+#pragma comment(linker, ""/STACK:256000000"")
+
+using namespace std;
+
+const int maxN = 12;
+
+int a[2][maxN];
+int n;
+bool fnd = false;
+
+bool is_in(int i, int j) {
+  return (0 <= i && i < 2 && j >= 0 && j < n);
+}
+
+int dx[] = {0, 1, 1};
+int dy[] = {1, 0, -1};
+
+void rec() {
+  if (fnd) return;
+  int change = false;
+  for (int i = 0; i < 2 && !change && !fnd; ++i) {
+    for (int j = 0; j < n && !change && !fnd; ++j) {
+      if (a[i][j] == 0) {
+        change = true;
+        for (int k = 0; k < 3 && !fnd; ++k) {
+          if (is_in(i + dx[k], j + dy[k]) && a[i + dx[k]][j + dy[k]] == 0) {
+            a[i][j] = 1;
+            a[i + dx[k]][j + dy[k]] = 1;
+            rec();
+            a[i][j] = 0;
+            a[i + dx[k]][j + dy[k]] = 0;
+          }
+        }
+      }
+    }
+  }
+  if (!change) {
+    fnd = true;
+  }
+}
+
+void solve() {
+  scanf(""%d"", &n);
+  string s1, s2;
+  cin >> s1 >> s2;
+
+  for (int i = 0; i < n; ++i) {
+    a[0][i] = s1[i] - '0';
+    a[1][i] = s2[i] - '0';
+  }
+
+  fnd = false;
+  rec();
+  if (fnd) {
+    cout << ""YES"" << endl;
+  } else {
+    cout << ""NO"" << endl;
+  }
+}
+
+int main() {
+  //freopen(""input.txt"", ""r"", stdin);
+  //freopen(""output.txt"", ""w"", stdout);
+
+  int t;
+  scanf(""%d"", &t);
+  for (int i = 0; i < t; ++i) {
+    solve();
+  }
+
+  return 0;
+}
+
+ +

Tester's Code

+ +
#include <bits/stdc++.h>
+using namespace std;
+
+int a[2][101];
+int dp[105][105];
+int N;
+
+bool solve(int l, int r) {
+    if(l == -1 && r == -1)
+        return 1;
+    if(l < -1 ||r < -1)
+        return 0;
+    if(l < 0 && r >= 0 && a[1][r] == 1)
+        return solve(l, r-1);
+    if(r < 0 && l >= 0 && a[0][l] == 1)
+        return solve(l-1, r);
+    if(l < 0 || r < 0)
+        return 0;
+
+    int &ret = dp[l][r];
+    if(ret != -1)
+        return ret;
+
+    ret = 0;
+
+    if(a[0][l] == 1)
+        ret |= solve(l-1, r);
+    if(a[1][r] == 1)
+        ret |= solve(l, r-1);
+
+    if(l > 0 && a[0][l] == 0 && a[0][l-1] == 0)
+        ret |= solve(l-2, r);
+    if(r > 0 && a[1][r] == 0 && a[1][r-1] == 0)
+        ret |= solve(l, r-2);
+
+    if(l == r && a[0][l] == 0 && a[1][r] == 0)
+        ret |= solve(l-1, r-1);
+
+    if(l == r+1 && a[0][l] == 0 && a[1][r] == 0)
+        ret |= solve(l-1, r-1);
+
+    return ret;
+}
+
+int main()
+{
+    int t;
+    scanf(""%d"", &t);
+    assert(t >= 1 && t <= 100);
+
+    while(t--) {
+        memset(dp, -1, sizeof(dp));
+        cin >> N;
+        assert( N >= 1 && N <= 10);
+
+        string st[2];
+        cin >> st[0] >> st[1];
+        assert((int)st[0].length() == N);
+        assert((int)st[1].length() == N);
+
+        for(int i = 0; i < (int)N; ++i) {
+            assert(st[0][i] == '0' || st[0][i] == '1');
+            assert(st[1][i] == '0' || st[1][i] == '1');
+
+            a[0][i] = st[0][i] == '0' ? 0 : 1;
+            a[1][i] = st[1][i] == '0' ? 0 : 1;
+        }
+        cout << (solve(N-1, N-1) == 1 ? ""YES"" : ""NO"") << ""\n"";
+    }
+
+    return 0;
+}
+
",0.0,101mar14-hexagonal-grid,2014-04-04T08:43:27,"{""contest_participation"":1218,""challenge_submissions"":208,""successful_submissions"":134}",2014-04-04T08:43:27,2016-07-23T14:48:42,tester,"###C++ +```cpp + + +#include +using namespace std; + +int a[2][101]; +int dp[105][105]; +int N; + +bool solve(int l, int r) { + if(l == -1 && r == -1) + return 1; + if(l < -1 ||r < -1) + return 0; + if(l < 0 && r >= 0 && a[1][r] == 1) + return solve(l, r-1); + if(r < 0 && l >= 0 && a[0][l] == 1) + return solve(l-1, r); + if(l < 0 || r < 0) + return 0; + + int &ret = dp[l][r]; + if(ret != -1) + return ret; + + ret = 0; + + if(a[0][l] == 1) + ret |= solve(l-1, r); + if(a[1][r] == 1) + ret |= solve(l, r-1); + + if(l > 0 && a[0][l] == 0 && a[0][l-1] == 0) + ret |= solve(l-2, r); + if(r > 0 && a[1][r] == 0 && a[1][r-1] == 0) + ret |= solve(l, r-2); + + if(l == r && a[0][l] == 0 && a[1][r] == 0) + ret |= solve(l-1, r-1); + + if(l == r+1 && a[0][l] == 0 && a[1][r] == 0) + ret |= solve(l-1, r-1); + + return ret; +} + +int main() +{ + int t; + scanf(""%d"", &t); + assert(t >= 1 && t <= 100); + + while(t--) { + memset(dp, -1, sizeof(dp)); + cin >> N; + assert( N >= 1 && N <= 10); + + string st[2]; + cin >> st[0] >> st[1]; + assert((int)st[0].length() == N); + assert((int)st[1].length() == N); + + for(int i = 0; i < (int)N; ++i) { + assert(st[0][i] == '0' || st[0][i] == '1'); + assert(st[1][i] == '0' || st[1][i] == '1'); + + a[0][i] = st[0][i] == '0' ? 0 : 1; + a[1][i] = st[1][i] == '0' ? 0 : 1; + } + cout << (solve(N-1, N-1) == 1 ? ""YES"" : ""NO"") << ""\n""; + } + + return 0; +} +``` +",not-set,2016-04-24T02:02:36,2016-07-23T14:48:42,C++ +46,2135,count-palindromes,Count Palindromes," + +A string is made of only lowercase latin letters (a,b,c,d,.....,z). Can you find the length of the lexicographically smallest string such that it has exactly **K** sub-strings, each of which are palindromes? + + +**Input Format** +The first line of input contains single integer **T** - the number of testcases. +T lines follow, each containing the integer K. + +**Output Format** +Output exactly T lines. Each line should contain single integer - the length of the lexicographically smallest string. + + +**Constraints:** +1 <= T <= 100 +1 <= K <= 1012 + +**Sample input** + + 2 + 10 + 17 + +**Sample Output** + + 4 + 7 + +**Explanation** + +for K = 10, one of the smallest possible strings that satisfies the property is `aaaa`. +All 10 palindromes are + ++ a,a,a,a ++ aa, aa, aa ++ aaa, aaa ++ aaaa + +**Note** + +Two sub-strings with different indices are both counted. ",code,What is the smallest string that contains exactly K palindromes?,ai,2014-03-15T11:46:14,2022-09-02T10:08:05,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts LONG_INTEGER k as parameter. +# + +def solve(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): + k = int(input().strip()) + + result = solve(k) + + fptr.write(str(result) + '\n') + + fptr.close() +","A string is made of only lowercase latin letters (a,b,c,d,.....,z). Can you find the length of the lexicographically smallest string such that it has exactly $K$ sub-strings, each of which are palindromes? ",0.4268292682926829,"[""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""]","The first line of input contains single integer $T$ - the number of testcases. +T lines follow, each containing the integer $K$. +","Output exactly $T$ lines. Each line should contain single integer - the length of the lexicographically smallest string. +"," 2 + 10 + 17 +"," 4 + 7 +",Hard,Count Palindromes - 101 Hack March Editorial,"

Count Palindromes
+Difficulty Level : Medium-Hard
+Problem Setter : Levgen Soboliev
+Problem Tester : Shang-En Huang +

+ +

Solution

+ +

Let the string s has X sub-strings, which are palindromes. Let's look at s+'a'. If it has more than K sub-strings, which are palindromes - let's look at s+'b'. The point is that if we start from empty string in such recursive way we will get the smallest lexicographically string which has exactly K palindromes. So, now we have a solution - just add the smallest possible symbol and maintain the total number of sub-strings which are palindromes no more than K. But this solution is slow. We need some clever observation. At first, if K is big - we will have a lot of 'a' at the beginning of resulting string. More precise we will have exactly S number of 'a' at the beginning of the resulting string, where S * (S + 1) / 2 <= K. So, this part we can make using O(1) time. After that, if the difference Y = K - S * (S + 1) / 2 is big, than we will just add 'b' to resulting string and will have a lot 'a' again. If the difference Y is small, than we can just add the smallest possible symbol and count the number of new sub-strings which are palindromes. In each of this two cases we will get the difference between current number of sub-strings-palindromes less than 1000 and just go with simple recursive procedure to find next symbols.

+ +

Setter's Code

+ +
#include <iostream>
+#include <cstdio>
+#include <algorithm>
+#include <set>
+#include <map>
+#include <vector>
+#include <cmath>
+#include <queue>
+#include <bitset>
+#include <ctime>
+#include <string>
+#include <cstring>
+#pragma comment(linker, ""/STACK:256000000"")
+
+using namespace std;
+
+const int maxN = 20000;
+const int BOUND = 2000;
+
+long long find_limit(long long k) {
+ long long l = 0, r = 5000000;
+ long long result = 0;
+ while (l <= r) {
+   long long key = (l + r) / 2;
+   long long total = (key * (key + 1)) / 2;
+   if (total <= k) {
+     result = key;
+     l = key + 1;
+   } else {
+     r = key - 1;
+   }
+ }
+ return result;
+}
+
+char s[maxN];
+
+void solvebig(long long k) {
+ int MID = 10000;
+ long long counta = find_limit(k);
+ long long total = (counta * (counta + 1)) / 2;
+
+ k -= total;
+
+ if (k == 0) {
+   cout << counta << endl;
+   return;
+ }
+ if (k == 1) {
+   cout << counta + 1 << endl;
+   return;
+ }
+
+ MID = min(MID, (int)counta);
+ for (int i = 0; i < MID; ++i) {
+   s[i] = 'a';
+ }
+
+ int res = counta;
+ s[MID] = 'b';
+
+ --k;
+
+ bool addonly_a = true;
+ for (int i = MID + 1; ; ++i) {
+   for (char c = 'a'; c <= 'z'; ++c) {
+     s[i] = c;
+     if (c != 'a') {
+       addonly_a = false;
+     }
+     long long cur = 0;
+     if (addonly_a) {
+       cur = i - MID + 1;
+     } else {
+       int bound = min(MID, 2 * (i - MID + 10));
+       bound = min(bound, i + 1);
+       for (int j = 1; j <= bound; ++j) {
+         bool good = true;
+         for (int k = 0; k < j / 2; ++k) {
+           if (s[i - k] != s[i - j + 1 + k]) {
+             good = false;
+             break;
+           }
+         }
+         if (good) {
+           ++cur;
+         }
+       }
+     }
+     if (cur == k) {
+       cout << counta + (i - MID + 1) << endl;
+       return;
+     }
+     if (cur < k) {
+       k -= cur;
+       break;
+     }
+   }
+ }
+}
+
+int main() {
+ //freopen(""input.txt"", ""r"", stdin);
+ //freopen(""output2.txt"", ""w"", stdout);
+
+ int t;
+ cin >> t;
+ for (int i = 0; i < t; ++i) {
+   //cerr << i << endl;
+   long long k;
+   cin >> k;
+   solvebig(k);
+ }
+
+ return 0;
+}
+
+ +

Tester's Code

+ +
//by tmt514
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+#include <vector>
+#include <iostream>
+#include <cassert>
+using namespace std;
+
+#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(c) ((int)(c).size())
+
+typedef long long LL;
+
+int main(void) {
+    int T;
+    scanf(""%d"", &T);
+    assert(1 <= T && T <= 100);
+    while(T--) {
+        LL n;
+        cin >> n;
+        assert(1 <= n && n <= 1e12);
+        vector<int> B;
+        B.push_back(0);
+        int m=0;
+        while(n>0) {
+            ++m;
+            //try 'a'
+            LL p = m-B.back();
+            if(SZ(B)>=2) p += (m-B.back() <= B.back()-B[SZ(B)-2]-1);
+            if(SZ(B)>=3) p += (m-B.back() <= B[SZ(B)-2]-B[SZ(B)-3]-1);
+            if(p <= n) { n -= p; continue; }
+            //try 'b'
+            p = 1;
+            if(SZ(B)>=2) p += 1;
+            if(p <= n) { n -= p; B.push_back(m); continue; }
+            //try 'c' (assert n == 1)
+            p = 1;
+            if(p <= n) { n -= p; continue; }
+        }
+        printf(""%d\n"", (int)m);
+    }
+    return 0;
+}
+
",0.0,101mar14-count-palindromes,2014-04-08T07:38:59,"{""contest_participation"":1218,""challenge_submissions"":58,""successful_submissions"":14}",2014-04-08T07:38:58,2016-07-23T18:40:52,setter,"###C++ +```cpp + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#pragma comment(linker, ""/STACK:256000000"") + +using namespace std; + +const int maxN = 20000; +const int BOUND = 2000; + +long long find_limit(long long k) { + long long l = 0, r = 5000000; + long long result = 0; + while (l <= r) { + long long key = (l + r) / 2; + long long total = (key * (key + 1)) / 2; + if (total <= k) { + result = key; + l = key + 1; + } else { + r = key - 1; + } + } + return result; +} + +char s[maxN]; + +void solvebig(long long k) { + int MID = 10000; + long long counta = find_limit(k); + long long total = (counta * (counta + 1)) / 2; + + k -= total; + + if (k == 0) { + cout << counta << endl; + return; + } + if (k == 1) { + cout << counta + 1 << endl; + return; + } + + MID = min(MID, (int)counta); + for (int i = 0; i < MID; ++i) { + s[i] = 'a'; + } + + int res = counta; + s[MID] = 'b'; + + --k; + + bool addonly_a = true; + for (int i = MID + 1; ; ++i) { + for (char c = 'a'; c <= 'z'; ++c) { + s[i] = c; + if (c != 'a') { + addonly_a = false; + } + long long cur = 0; + if (addonly_a) { + cur = i - MID + 1; + } else { + int bound = min(MID, 2 * (i - MID + 10)); + bound = min(bound, i + 1); + for (int j = 1; j <= bound; ++j) { + bool good = true; + for (int k = 0; k < j / 2; ++k) { + if (s[i - k] != s[i - j + 1 + k]) { + good = false; + break; + } + } + if (good) { + ++cur; + } + } + } + if (cur == k) { + cout << counta + (i - MID + 1) << endl; + return; + } + if (cur < k) { + k -= cur; + break; + } + } + } +} + +int main() { + //freopen(""input.txt"", ""r"", stdin); + //freopen(""output2.txt"", ""w"", stdout); + + int t; + cin >> t; + for (int i = 0; i < t; ++i) { + //cerr << i << endl; + long long k; + cin >> k; + solvebig(k); + } + + return 0; +} +``` +",not-set,2016-04-24T02:02:36,2016-07-23T18:40:45,C++ +47,2135,count-palindromes,Count Palindromes," + +A string is made of only lowercase latin letters (a,b,c,d,.....,z). Can you find the length of the lexicographically smallest string such that it has exactly **K** sub-strings, each of which are palindromes? + + +**Input Format** +The first line of input contains single integer **T** - the number of testcases. +T lines follow, each containing the integer K. + +**Output Format** +Output exactly T lines. Each line should contain single integer - the length of the lexicographically smallest string. + + +**Constraints:** +1 <= T <= 100 +1 <= K <= 1012 + +**Sample input** + + 2 + 10 + 17 + +**Sample Output** + + 4 + 7 + +**Explanation** + +for K = 10, one of the smallest possible strings that satisfies the property is `aaaa`. +All 10 palindromes are + ++ a,a,a,a ++ aa, aa, aa ++ aaa, aaa ++ aaaa + +**Note** + +Two sub-strings with different indices are both counted. ",code,What is the smallest string that contains exactly K palindromes?,ai,2014-03-15T11:46:14,2022-09-02T10:08:05,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts LONG_INTEGER k as parameter. +# + +def solve(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): + k = int(input().strip()) + + result = solve(k) + + fptr.write(str(result) + '\n') + + fptr.close() +","A string is made of only lowercase latin letters (a,b,c,d,.....,z). Can you find the length of the lexicographically smallest string such that it has exactly $K$ sub-strings, each of which are palindromes? ",0.4268292682926829,"[""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""]","The first line of input contains single integer $T$ - the number of testcases. +T lines follow, each containing the integer $K$. +","Output exactly $T$ lines. Each line should contain single integer - the length of the lexicographically smallest string. +"," 2 + 10 + 17 +"," 4 + 7 +",Hard,Count Palindromes - 101 Hack March Editorial,"

Count Palindromes
+Difficulty Level : Medium-Hard
+Problem Setter : Levgen Soboliev
+Problem Tester : Shang-En Huang +

+ +

Solution

+ +

Let the string s has X sub-strings, which are palindromes. Let's look at s+'a'. If it has more than K sub-strings, which are palindromes - let's look at s+'b'. The point is that if we start from empty string in such recursive way we will get the smallest lexicographically string which has exactly K palindromes. So, now we have a solution - just add the smallest possible symbol and maintain the total number of sub-strings which are palindromes no more than K. But this solution is slow. We need some clever observation. At first, if K is big - we will have a lot of 'a' at the beginning of resulting string. More precise we will have exactly S number of 'a' at the beginning of the resulting string, where S * (S + 1) / 2 <= K. So, this part we can make using O(1) time. After that, if the difference Y = K - S * (S + 1) / 2 is big, than we will just add 'b' to resulting string and will have a lot 'a' again. If the difference Y is small, than we can just add the smallest possible symbol and count the number of new sub-strings which are palindromes. In each of this two cases we will get the difference between current number of sub-strings-palindromes less than 1000 and just go with simple recursive procedure to find next symbols.

+ +

Setter's Code

+ +
#include <iostream>
+#include <cstdio>
+#include <algorithm>
+#include <set>
+#include <map>
+#include <vector>
+#include <cmath>
+#include <queue>
+#include <bitset>
+#include <ctime>
+#include <string>
+#include <cstring>
+#pragma comment(linker, ""/STACK:256000000"")
+
+using namespace std;
+
+const int maxN = 20000;
+const int BOUND = 2000;
+
+long long find_limit(long long k) {
+ long long l = 0, r = 5000000;
+ long long result = 0;
+ while (l <= r) {
+   long long key = (l + r) / 2;
+   long long total = (key * (key + 1)) / 2;
+   if (total <= k) {
+     result = key;
+     l = key + 1;
+   } else {
+     r = key - 1;
+   }
+ }
+ return result;
+}
+
+char s[maxN];
+
+void solvebig(long long k) {
+ int MID = 10000;
+ long long counta = find_limit(k);
+ long long total = (counta * (counta + 1)) / 2;
+
+ k -= total;
+
+ if (k == 0) {
+   cout << counta << endl;
+   return;
+ }
+ if (k == 1) {
+   cout << counta + 1 << endl;
+   return;
+ }
+
+ MID = min(MID, (int)counta);
+ for (int i = 0; i < MID; ++i) {
+   s[i] = 'a';
+ }
+
+ int res = counta;
+ s[MID] = 'b';
+
+ --k;
+
+ bool addonly_a = true;
+ for (int i = MID + 1; ; ++i) {
+   for (char c = 'a'; c <= 'z'; ++c) {
+     s[i] = c;
+     if (c != 'a') {
+       addonly_a = false;
+     }
+     long long cur = 0;
+     if (addonly_a) {
+       cur = i - MID + 1;
+     } else {
+       int bound = min(MID, 2 * (i - MID + 10));
+       bound = min(bound, i + 1);
+       for (int j = 1; j <= bound; ++j) {
+         bool good = true;
+         for (int k = 0; k < j / 2; ++k) {
+           if (s[i - k] != s[i - j + 1 + k]) {
+             good = false;
+             break;
+           }
+         }
+         if (good) {
+           ++cur;
+         }
+       }
+     }
+     if (cur == k) {
+       cout << counta + (i - MID + 1) << endl;
+       return;
+     }
+     if (cur < k) {
+       k -= cur;
+       break;
+     }
+   }
+ }
+}
+
+int main() {
+ //freopen(""input.txt"", ""r"", stdin);
+ //freopen(""output2.txt"", ""w"", stdout);
+
+ int t;
+ cin >> t;
+ for (int i = 0; i < t; ++i) {
+   //cerr << i << endl;
+   long long k;
+   cin >> k;
+   solvebig(k);
+ }
+
+ return 0;
+}
+
+ +

Tester's Code

+ +
//by tmt514
+#include <cstdio>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+#include <vector>
+#include <iostream>
+#include <cassert>
+using namespace std;
+
+#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(c) ((int)(c).size())
+
+typedef long long LL;
+
+int main(void) {
+    int T;
+    scanf(""%d"", &T);
+    assert(1 <= T && T <= 100);
+    while(T--) {
+        LL n;
+        cin >> n;
+        assert(1 <= n && n <= 1e12);
+        vector<int> B;
+        B.push_back(0);
+        int m=0;
+        while(n>0) {
+            ++m;
+            //try 'a'
+            LL p = m-B.back();
+            if(SZ(B)>=2) p += (m-B.back() <= B.back()-B[SZ(B)-2]-1);
+            if(SZ(B)>=3) p += (m-B.back() <= B[SZ(B)-2]-B[SZ(B)-3]-1);
+            if(p <= n) { n -= p; continue; }
+            //try 'b'
+            p = 1;
+            if(SZ(B)>=2) p += 1;
+            if(p <= n) { n -= p; B.push_back(m); continue; }
+            //try 'c' (assert n == 1)
+            p = 1;
+            if(p <= n) { n -= p; continue; }
+        }
+        printf(""%d\n"", (int)m);
+    }
+    return 0;
+}
+
",0.0,101mar14-count-palindromes,2014-04-08T07:38:59,"{""contest_participation"":1218,""challenge_submissions"":58,""successful_submissions"":14}",2014-04-08T07:38:58,2016-07-23T18:40:52,tester,"###C++ +```cpp +//by tmt514 +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) +#define SZ(c) ((int)(c).size()) + +typedef long long LL; + +int main(void) { + int T; + scanf(""%d"", &T); + assert(1 <= T && T <= 100); + while(T--) { + LL n; + cin >> n; + assert(1 <= n && n <= 1e12); + vector B; + B.push_back(0); + int m=0; + while(n>0) { + ++m; + //try 'a' + LL p = m-B.back(); + if(SZ(B)>=2) p += (m-B.back() <= B.back()-B[SZ(B)-2]-1); + if(SZ(B)>=3) p += (m-B.back() <= B[SZ(B)-2]-B[SZ(B)-3]-1); + if(p <= n) { n -= p; continue; } + //try 'b' + p = 1; + if(SZ(B)>=2) p += 1; + if(p <= n) { n -= p; B.push_back(m); continue; } + //try 'c' (assert n == 1) + p = 1; + if(p <= n) { n -= p; continue; } + } + printf(""%d\n"", (int)m); + } + return 0; +} + +``` +",not-set,2016-04-24T02:02:36,2016-07-23T18:40:52,C++ +48,1768,the-bouncing-flying-ball,The Bouncing Flying Ball," + +Sergey and Chen are locked in a rectangular box of Dimension L\*W\*H. Evil Larry has put a machine which is located at a point inside the box (p,q,r) which starts shooting balls in every direction (dx,dy,dz) where + +-N ≤ dx, dy, dz ≤ N except (0, 0, 0) + +such that the ball goes through (p, q, r) -> (p + dx, q + dy, r + dz) -> (p + 2dx, q + 2dy, r + 2dz) and so on. + +so, a total of (2N + 1)3 - 1 balls are fired. Sergey is standing at (a,b,c) and Chen is standing at (d,e,f). Provided all the balls follow reflection property and have constant velocity and gravity is not taken into account, can you tell how many balls are caught by Sergey and Chen? Sergey and Chen can catch the ball if it passes through the point at which they are standing. + +**Input Format** +The first line contains the number of test cases, T lines follow, each containing a testcase. +Each testcase contains 13 integers in the following order + + L W H a b c d e f p q r N + +**Output Format** +For each test case please output two integers indicating the number of balls that are caught by Sergey and C, respectively. + +**Constraints** +T = 1 +1 ≤ L, W, H, a, b, c, d, e, f, p, q, r, N ≤ 50 + +**Sample Input** + + 1 + 3 3 3 1 1 1 1 1 2 2 2 2 1 + +**Sample Output** + + 8 4 + +**Explanation** + +Here, L, W, H = (3, 3, 3), Sergey is at (1, 1, 1) and Chen is at (1, 1, 2) and the machine Larry put is at (2, 2, 2). +Balls are thrown at -1 ≤ x, y, z ≤ 1 from (2, 2, 2). + ++ (-1, -1, -1): (2, 2, 2)->(1, 1, 1) Sergey ++ (-1, -1, 0): (2, 2, 2)->(1, 1, 2) Chen ++ (-1, -1, 1): (2, 2, 2)->(1, 1, 3)->(0, 0, 2)->(1, 1, 1) Sergey ++ (-1, 0, -1): (2, 2, 2)->(1, 2, 1)->(0, 2, 0)->(1, 2, 1)->(2, 2, 2)->(3, 2, 3)->... ++ (-1, 0, 0): (2, 2, 2)->(1, 2, 2)->(0, 2, 2)->(1, 2, 2)->(2, 2, 2)->(3, 2, 2)->... ++ (-1, 0, 1): (2, 2, 2)->(1, 2, 3)->(0, 2, 2)->(1, 2, 1)->(2, 2, 0)->(3, 2, 1)->... ++ (-1, 1, -1): (2, 2, 2)->(1, 3, 1)->(0, 2, 0)->(1, 1, 1) Sergey ++ (-1, 1, 0): (2, 2, 2)->(1, 3, 2)->(0, 2, 2)->(1, 1, 2) Chen ++ (-1, 1, 1): (2, 2, 2)->(1, 3, 3)->(0, 2, 2)->(1, 1, 1) Sergey ++ (0, *, *): x-coordinate never changed ++ (1, -1, -1): (2, 2, 2)->(3, 1, 1)->(2, 0, 0)->(1, 1, 1) Sergey ++ (1, -1, 0): (2, 2, 2)->(3, 1, 2)->(2, 0, 2)->(1, 1, 2) Chen ++ (1, -1, 1): (2, 2, 2)->(3, 1, 3)->(2, 0, 2)->(1, 1, 1) Sergey ++ (1, 0, -1): (2, 2, 2)->(3, 2, 1)->(2, 2, 0)->(1, 2, 1)->(0, 2, 2)->... ++ (1, 0, 0): (2, 2, 2)->(3, 2, 2)->(2, 2, 2)->(1, 2, 2)->(0, 2, 2)->... ++ (1, 0, 1): (2, 2, 2)->(3, 2, 3)->(2, 2, 2)->(1, 2, 1)->(0, 2, 0)->... ++ (1, 1, -1): (2, 2, 2)->(3, 3, 1)->(2, 2, 0)->(1, 1, 1) Sergey ++ (1, 1, 0): (2, 2, 2)->(3, 3, 2)->(2, 2, 2)->(1, 1, 2) Chen ++ (1, 1, 1): (2, 2, 2)->(3, 3, 3)->(2, 2, 2)->(1, 1, 1) Sergey",code,Some bouncing balls are flying from a single source in a rectangular box. You are going to count how many balls passes through point A and point B,ai,2014-01-29T16:38:17,2022-09-02T09:54:45,,,," + +Sergey and Chen are locked in a rectangular box of Dimension L\*W\*H. Evil Larry has put a machine which is located at a point inside the box (p,q,r) which starts shooting balls in every direction (dx,dy,dz) where + +-N ≤ dx, dy, dz ≤ N except (0, 0, 0) + +such that the ball goes through (p, q, r) -> (p + dx, q + dy, r + dz) -> (p + 2dx, q + 2dy, r + 2dz) and so on. + +so, a total of (2N + 1)3 - 1 balls are fired. Sergey is standing at (a,b,c) and Chen is standing at (d,e,f). Provided all the balls follow reflection property and have constant velocity and gravity is not taken into account, can you tell how many balls are caught by Sergey and Chen? Sergey and Chen can catch the ball if it passes through the point at which they are standing. + +**Input Format** +The first line contains the number of test cases, T lines follow, each containing a testcase. +Each testcase contains 13 integers in the following order + + L W H a b c d e f p q r N + +**Output Format** +For each test case please output two integers indicating the number of balls that are caught by Sergey and C, respectively. + +**Constraints** +T = 1 +1 ≤ L, W, H, a, b, c, d, e, f, p, q, r, N ≤ 50 + +**Sample Input** + + 1 + 3 3 3 1 1 1 1 1 2 2 2 2 1 + +**Sample Output** + + 8 4 + +**Explanation** + +Here, L, W, H = (3, 3, 3), Sergey is at (1, 1, 1) and Chen is at (1, 1, 2) and the machine Larry put is at (2, 2, 2). +Balls are thrown at -1 ≤ x, y, z ≤ 1 from (2, 2, 2). + ++ (-1, -1, -1): (2, 2, 2)->(1, 1, 1) Sergey ++ (-1, -1, 0): (2, 2, 2)->(1, 1, 2) Chen ++ (-1, -1, 1): (2, 2, 2)->(1, 1, 3)->(0, 0, 2)->(1, 1, 1) Sergey ++ (-1, 0, -1): (2, 2, 2)->(1, 2, 1)->(0, 2, 0)->(1, 2, 1)->(2, 2, 2)->(3, 2, 3)->... ++ (-1, 0, 0): (2, 2, 2)->(1, 2, 2)->(0, 2, 2)->(1, 2, 2)->(2, 2, 2)->(3, 2, 2)->... ++ (-1, 0, 1): (2, 2, 2)->(1, 2, 3)->(0, 2, 2)->(1, 2, 1)->(2, 2, 0)->(3, 2, 1)->... ++ (-1, 1, -1): (2, 2, 2)->(1, 3, 1)->(0, 2, 0)->(1, 1, 1) Sergey ++ (-1, 1, 0): (2, 2, 2)->(1, 3, 2)->(0, 2, 2)->(1, 1, 2) Chen ++ (-1, 1, 1): (2, 2, 2)->(1, 3, 3)->(0, 2, 2)->(1, 1, 1) Sergey ++ (0, *, *): x-coordinate never changed ++ (1, -1, -1): (2, 2, 2)->(3, 1, 1)->(2, 0, 0)->(1, 1, 1) Sergey ++ (1, -1, 0): (2, 2, 2)->(3, 1, 2)->(2, 0, 2)->(1, 1, 2) Chen ++ (1, -1, 1): (2, 2, 2)->(3, 1, 3)->(2, 0, 2)->(1, 1, 1) Sergey ++ (1, 0, -1): (2, 2, 2)->(3, 2, 1)->(2, 2, 0)->(1, 2, 1)->(0, 2, 2)->... ++ (1, 0, 0): (2, 2, 2)->(3, 2, 2)->(2, 2, 2)->(1, 2, 2)->(0, 2, 2)->... ++ (1, 0, 1): (2, 2, 2)->(3, 2, 3)->(2, 2, 2)->(1, 2, 1)->(0, 2, 0)->... ++ (1, 1, -1): (2, 2, 2)->(3, 3, 1)->(2, 2, 0)->(1, 1, 1) Sergey ++ (1, 1, 0): (2, 2, 2)->(3, 3, 2)->(2, 2, 2)->(1, 1, 2) Chen ++ (1, 1, 1): (2, 2, 2)->(3, 3, 3)->(2, 2, 2)->(1, 1, 1) Sergey",0.5384615384615384,"[""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,The bouncing flying ball - March'14 Editorial,"

The bouncing flying ball
+Difficulty Level : Hard
+Required Knowledge : Chinese Remainder Theorem
+Problem Setter : Shang-En Huang
+Problem Tester : sdya

+ +

Approach

+ +

For each direction (dx, dy, dz), the ball is flying through (p, q, r) -> (p+dx, p+dy, p+dz) -> ... as a line segment. +We need to determine whether the ball touches (a, b, c) first or (d, e, f) first. This is equivalent to solve an integral equation using Chinese Remainder Theorem:

+ +
    +
  • p + t * (dx / g) = a or -a (mod 2L)
  • +
  • q + t * (dy / g) = b or -b (mod 2W)
  • +
  • r + t * (dz / g) = c or -c (mod 2H)
  • +
+ +

where g > 0 is the greatest common divisor of (dx, dy, dz). The minimum positive t > 0 is the variable that we want to know.

+ +

There are a few ways to calculate with more efficiency:

+ +
    +
  1. Use less multiplicity & division. (aka. use less ""%"" operations)
    +For example, we can cache the inversion calculation (pre-caculate something like v-1 modulo M)
  2. +
  3. For same (dx/g, dy/g, dz/g) directions we can calculate the solution only once, and add the multiplicity that Sergey or Chen get.
  4. +
  5. Calculate the solution to (-dx, -dy, -dz) when calculating (dx, dy, dz)'s solution: when we handling (dx, dy, dz) we are finding minimum t > 0 that satisfying the equations; but when we handling (-dx, -dy, -dz) we are finding the maximum t < LCM(2L, 2W, 2H) that satisfying the same equations.
  6. +
  7. To solve the system of equations above, there is no need to seperate the equation system into 8 system of equations.
  8. +
+ +

Setter's Code

+ +
/ by tmt514
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+#include <vector>
+using namespace std;
+
+#define FOR(it,c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(x) ((int)(x).size())
+
+int L, W, H, a, b, c, d, e, f, p, q, r, N;
+int inv_tbl[105][105], u_inv_tbl[105][105];
+
+int inv(int x, int y, int P, int Q, int R, int S) {
+if(y==0) return P;
+return inv(y, x%y, R, S, P-R*(x/y), Q-S*(x/y));
+}
+
+//cache the inversion results (note that 1 <= M <= 200)
+int inv(int x, int M) {
+if(!u_inv_tbl[x][M]) {
+u_inv_tbl[x][M] = 1;
+inv_tbl[x][M] = (inv(x, M, 1, 0, 0, 1)%M+M)%M;
+}
+return inv_tbl[x][M];
+}
+
+int sol[105], qb, qe;
+void getsol(int ql, int qr, int &modulo, int u, int x, int p, int M) {
+// u + ?x = p or -p (mod) M
+// ? = sol (mod) modulo
+
+if (x < 0) { u = -u; x = -x; }
+int p1 = ((p-u)%M+M)%M;
+int p2 = ((-p-u)%M+M)%M;
+
+int G = __gcd(M, x);
+M/=G; x/=G;
+int g = __gcd(modulo, M), MM = M / g;
+int ret_modulo = modulo * MM;
+modulo /= g;
+int MMInv = inv(modulo%MM, MM);
+
+if (p1 % G == 0) {
+p1 = p1/G * inv(x, M);
+for(int it=ql;it<qr;it++) {
+int t = sol[it];
+// ? = p1 (mod) MM
+// ? = t (mod) modulo
+if ((p1 - t) % g) continue;
+int tmp = ((p1 - t) * MMInv * modulo + t) % ret_modulo;
+tmp = (tmp+ret_modulo)%ret_modulo;
+sol[qe++] = tmp;
+}
+}
+if (p2 % G == 0) {
+p2 = p2/G * inv(x, M);
+for(int it=ql;it<qr;it++) {
+int t = sol[it];
+// ? = p2 (mod) M
+// ? = t (mod) modulo
+if ((p2 - t) % g) continue;
+int tmp = ((p2 - t) * MMInv * modulo + t) % ret_modulo;
+tmp = (tmp+ret_modulo)%ret_modulo;
+sol[qe++] = tmp;
+}
+}
+qb = qr;
+modulo = ret_modulo;
+}
+
+void ask(int &min_pos, int &min_neg, int u, int v, int w, int x, int y, int z) {
+int modulo = 1;
+// initialize the solution queue
+sol[0] = 0;
+qb = 0, qe = 1;
+
+// p + ?x = u or -u (mod) 2L
+// q + ?y = v or -v (mod) 2W
+// r + ?z = w or -w (mod) 2H
+getsol(qb, qe, modulo, p, x, u, 2*L);
+getsol(qb, qe, modulo, q, y, v, 2*W);
+getsol(qb, qe, modulo, r, z, w, 2*H);
+
+if (qb == qe) { min_pos = min_neg = -1; return; }
+min_pos = *min_element(sol + qb, sol + qe);
+min_neg = modulo - *max_element(sol + qb, sol + qe);
+}
+
+int muls[105][105][105];
+int main(void) {
+int T;
+scanf(""%d"", &T);
+while(T--) {
+scanf(""%d%d%d"", &L, &W, &H);
+scanf(""%d%d%d"", &a, &b, &c);
+scanf(""%d%d%d"", &d, &e, &f);
+scanf(""%d%d%d"", &p, &q, &r);
+scanf(""%d"", &N);
+memset(muls, 0, sizeof(muls));
+
+const int offset = 50;
+int cSergey = 0, cChen = 0;
+// caculate multiplicity
+for(int x=-N;x<=N;x++) for(int y=-N;y<=N;y++) for(int z=-N;z<=N;z++) {
+int g = __gcd(abs(x), __gcd(abs(y), abs(z)));
+if(g) muls[x/g+offset][y/g+offset][z/g+offset]++;
+}
+// caculate positive (x, y, z) and negative (-x, -y, -z) at same time
+for(int x=0;x<=N;x++) for(int y=-N;y<=N;y++) for(int z=-N;z<=N;z++) {
+if((x==0&&y<0) || (x==0 && y==0 && z<0)) continue;
+int g = __gcd(abs(x), __gcd(abs(y), abs(z)));
+if(!g) continue;
+if(g == 1) {
+int S_pos, S_neg, C_pos, C_neg;
+ask(S_pos, S_neg, a, b, c, x, y, z);
+ask(C_pos, C_neg, d, e, f, x, y, z);
+
+int m_pos = muls[x+offset][y+offset][z+offset];
+int m_neg = muls[-x+offset][-y+offset][-z+offset];
+if(S_pos != -1 && C_pos != -1) (S_pos < C_pos? cSergey+=m_pos: cChen+=m_pos);
+else if(S_pos != -1) cSergey+=m_pos;
+else if(C_pos != -1) cChen+=m_pos;
+
+if(S_neg != -1 && C_neg != -1) (S_neg < C_neg? cSergey+=m_neg: cChen+=m_neg);
+else if(S_neg != -1) cSergey+=m_neg;
+else if(C_neg != -1) cChen+=m_neg;
+}
+}
+printf(""%d %d\n"", cSergey, cChen);
+}
+return 0;
+}
+
+ +

Tester's Code

+ +
#include <cstdio>
+#include <cstring>
+#include <vector>
+#include <algorithm>
+#include <cmath>
+#include <iostream>
+using namespace std;
+
+#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(c) ((long long)(c).size())
+typedef long long LL;
+
+long long L, W, H, x, y, z, a, b, c, p, q, r, N;
+const long long INF = 1000000000000000000LL;
+
+long long gcdtbl[105][10005];
+long long gcd3[105][105][105];
+long long inv[105][10005];
+long long cache[105][105][105];
+long long fac[105][105][105][7];
+
+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);
+    }
+}
+
+long long pre() {
+for(long long i=0;i<=100;i++) for(long long j=0;j<=10000;j++) gcdtbl[i][j] = gcd(i, j);
+for(long long i=0;i<=100;i++) for(long long j=0;j<=100;j++) for(long long k=0;k<=100;k++) gcd3[i][j][k] = gcd(gcd(i, j), k);
+for(long long i=2;i<=100;i++) for(long long j=0;j<=10000;j++) if(gcd(i, j) > 1) inv[i][j] = 0;
+else for(long long k=0;k<=100;k++) if(j*k%i==1) { inv[i][j] = k; break; }
+for(long long i=1;i<=100;i++) for(long long j=1;j<=100;j++) for(long long k=1;k<=100;k++) {
+static long long p[15]={64,9,25,49,11,13,17,19,23,29,31,37,41,43,47};
+static long long q[15]={2, 3, 5, 7,11,13,17,19,23,29,31,37,41,43,47};
+long long t=0;
+for(long long l=0;l<15;l++) if(i%q[l]==0 || j%q[l]==0 || k%q[l]==0) fac[i][j][k][t++] = p[l];
+}
+return 0;
+}
+
+long long solve(long long gx, long long gy, long long gz, long long u, long long v, int w) {
+//gx * t = u   2L
+//gy * t = v   2W
+//gz * t = w   2H
+
+long long A = 2*L, B = 2*W, C = 2*H;
+long long gA = gcdtbl[A][gx], gB = gcdtbl[B][gy], gC = gcdtbl[C][gz];
+if (u % gA || v % gB || w % gC) return INF;
+u /= gA; A /= gA; gx /= gA; u = u * inv[A][gx];
+v /= gB; B /= gB; gy /= gB; v = v * inv[B][gy];
+w /= gC; C /= gC; gz /= gC; w = w * inv[C][gz];
+
+// t = u (mod A)
+// t = v (mod B)
+// t = w (mod C)
+
+for(long long *it = &fac[A][B][C][0]; *it; it++) {
+long long p = *it;
+long long pa = gcdtbl[A][p], pb = gcdtbl[B][p], pc = gcdtbl[C][p];
+if(pa>=pb&&pa>=pc) { if((u-v)%pb||(u-w)%pc) return INF; else { B/=pb; C/=pc; }}
+else if(pb>=pa&&pb>=pc) { if((v-u)%pa||(v-w)%pc) return INF; else { A/=pa; C/=pc; }}
+else if(pc>=pa&&pc>=pb) { if((w-u)%pa||(w-v)%pb) return INF; else { A/=pa; B/=pb; }}
+}
+
+long long ABC = A*B*C, t = ((v-u)*inv[B][A]*A+u);
+t = ((w-t)*inv[C][A*B]*A*B+t);
+t = (t%ABC+ABC)%ABC;
+return t;
+}
+
+long long hit(long long vx, long long vy, long long vz, long long u, long long v, long long w) {
+long long tx = gcdtbl[2*L][abs(vx)], ty = gcdtbl[2*W][abs(vy)], tz = gcdtbl[2*H][abs(vz)];
+if(((u-p)%tx && (u+p)%tx) || ((v-q)%ty && (v+q)%ty) || ((w-r)%tz && (w+r)%tz)) return INF;
+vx = (vx % (2*L) + 2*L) % (2*L);
+vy = (vy % (2*W) + 2*W) % (2*W);
+vz = (vz % (2*H) + 2*H) % (2*H);
+long long t = INF;
+for(long long i=0;i<8;i++) t = min(t, solve(vx, vy, vz, (i&1? 4*L-u-p: 2*L+u-p), (i&2? 4*W-v-q: 2*W+v-q), (i&4? 4*H-w-r: 2*H+w-r)));
+return t;
+}
+
+void solve() {
+    cin >> L >> W >> H >> x >> y >> z >> a >> b >> c >> p >> q >> r >> N;
+//scanf(""%d%d%d%d%d%d%d%d%d%d%d%d%d"", &L, &W, &H, &x, &y, &z, &a, &b, &c, &p, &q, &r, &N);
+long long pi = 0, kel = 0;
+memset(cache, 0, sizeof(cache));
+for (long long vx = -N; vx <= N; vx++)
+for(long long vy = -N; vy <= N; vy++)
+for(long long vz = -N; vz <= N; vz++) {
+if(vx==0 && vy==0 && vz==0) continue;
+
+long long cx = vx, cy = vy, cz = vz;
+long long g = gcd3[abs(cx)][abs(cy)][abs(cz)];
+cx /= g; cy /= g; cz /= g;
+long long &tmp = cache[cx+50][cy+50][cz+50];
+if (tmp) {
+if (tmp == 1) ++pi;
+if (tmp == 2) ++kel;
+continue;
+}
+
+long long tp = hit(cx, cy, cz, x, y, z);
+long long th = hit(cx, cy, cz, a, b, c);
+
+if (tp < th) ++pi, tmp = 1;
+if (tp > th) ++kel, tmp = 2;
+if (tp == th) tmp = 3;
+}
+cout << pi << "" "" << kel << endl;
+//printf(""%d %d\n"", pi, kel);
+static long long cs=0;
+//cerr << ++cs << endl;
+//fprintf(stderr, ""Case #%d: %d %d\n"", ++cs, pi, kel);
+}
+
+int main(void) {
+    //freopen(""input.txt"", ""r"", stdin);
+    //freopen(""output.txt"", ""w"", stdout);
+long long T;
+pre();
+cin >> T;
+while(T--) solve();
+return 0;
+}
+
",0.0,mar14-the-bouncing-flying-ball,2014-04-15T09:40:26,"{""contest_participation"":2080,""challenge_submissions"":74,""successful_submissions"":19}",2014-04-15T09:40:26,2016-07-23T18:17:52,setter,"###C++ +```cpp +/ by tmt514 +#include +#include +#include +#include +#include +#include +using namespace std; + +#define FOR(it,c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) +#define SZ(x) ((int)(x).size()) + +int L, W, H, a, b, c, d, e, f, p, q, r, N; +int inv_tbl[105][105], u_inv_tbl[105][105]; + +int inv(int x, int y, int P, int Q, int R, int S) { +if(y==0) return P; + return inv(y, x%y, R, S, P-R*(x/y), Q-S*(x/y)); +} + +//cache the inversion results (note that 1 <= M <= 200) +int inv(int x, int M) { + if(!u_inv_tbl[x][M]) { + u_inv_tbl[x][M] = 1; + inv_tbl[x][M] = (inv(x, M, 1, 0, 0, 1)%M+M)%M; + } + return inv_tbl[x][M]; +} + +int sol[105], qb, qe; +void getsol(int ql, int qr, int &modulo, int u, int x, int p, int M) { +// u + ?x = p or -p (mod) M +// ? = sol (mod) modulo + +if (x < 0) { u = -u; x = -x; } +int p1 = ((p-u)%M+M)%M; +int p2 = ((-p-u)%M+M)%M; + +int G = __gcd(M, x); +M/=G; x/=G; +int g = __gcd(modulo, M), MM = M / g; +int ret_modulo = modulo * MM; +modulo /= g; +int MMInv = inv(modulo%MM, MM); + +if (p1 % G == 0) { + p1 = p1/G * inv(x, M); + for(int it=ql;it (p + dx, q + dy, r + dz) -> (p + 2dx, q + 2dy, r + 2dz) and so on. + +so, a total of (2N + 1)3 - 1 balls are fired. Sergey is standing at (a,b,c) and Chen is standing at (d,e,f). Provided all the balls follow reflection property and have constant velocity and gravity is not taken into account, can you tell how many balls are caught by Sergey and Chen? Sergey and Chen can catch the ball if it passes through the point at which they are standing. + +**Input Format** +The first line contains the number of test cases, T lines follow, each containing a testcase. +Each testcase contains 13 integers in the following order + + L W H a b c d e f p q r N + +**Output Format** +For each test case please output two integers indicating the number of balls that are caught by Sergey and C, respectively. + +**Constraints** +T = 1 +1 ≤ L, W, H, a, b, c, d, e, f, p, q, r, N ≤ 50 + +**Sample Input** + + 1 + 3 3 3 1 1 1 1 1 2 2 2 2 1 + +**Sample Output** + + 8 4 + +**Explanation** + +Here, L, W, H = (3, 3, 3), Sergey is at (1, 1, 1) and Chen is at (1, 1, 2) and the machine Larry put is at (2, 2, 2). +Balls are thrown at -1 ≤ x, y, z ≤ 1 from (2, 2, 2). + ++ (-1, -1, -1): (2, 2, 2)->(1, 1, 1) Sergey ++ (-1, -1, 0): (2, 2, 2)->(1, 1, 2) Chen ++ (-1, -1, 1): (2, 2, 2)->(1, 1, 3)->(0, 0, 2)->(1, 1, 1) Sergey ++ (-1, 0, -1): (2, 2, 2)->(1, 2, 1)->(0, 2, 0)->(1, 2, 1)->(2, 2, 2)->(3, 2, 3)->... ++ (-1, 0, 0): (2, 2, 2)->(1, 2, 2)->(0, 2, 2)->(1, 2, 2)->(2, 2, 2)->(3, 2, 2)->... ++ (-1, 0, 1): (2, 2, 2)->(1, 2, 3)->(0, 2, 2)->(1, 2, 1)->(2, 2, 0)->(3, 2, 1)->... ++ (-1, 1, -1): (2, 2, 2)->(1, 3, 1)->(0, 2, 0)->(1, 1, 1) Sergey ++ (-1, 1, 0): (2, 2, 2)->(1, 3, 2)->(0, 2, 2)->(1, 1, 2) Chen ++ (-1, 1, 1): (2, 2, 2)->(1, 3, 3)->(0, 2, 2)->(1, 1, 1) Sergey ++ (0, *, *): x-coordinate never changed ++ (1, -1, -1): (2, 2, 2)->(3, 1, 1)->(2, 0, 0)->(1, 1, 1) Sergey ++ (1, -1, 0): (2, 2, 2)->(3, 1, 2)->(2, 0, 2)->(1, 1, 2) Chen ++ (1, -1, 1): (2, 2, 2)->(3, 1, 3)->(2, 0, 2)->(1, 1, 1) Sergey ++ (1, 0, -1): (2, 2, 2)->(3, 2, 1)->(2, 2, 0)->(1, 2, 1)->(0, 2, 2)->... ++ (1, 0, 0): (2, 2, 2)->(3, 2, 2)->(2, 2, 2)->(1, 2, 2)->(0, 2, 2)->... ++ (1, 0, 1): (2, 2, 2)->(3, 2, 3)->(2, 2, 2)->(1, 2, 1)->(0, 2, 0)->... ++ (1, 1, -1): (2, 2, 2)->(3, 3, 1)->(2, 2, 0)->(1, 1, 1) Sergey ++ (1, 1, 0): (2, 2, 2)->(3, 3, 2)->(2, 2, 2)->(1, 1, 2) Chen ++ (1, 1, 1): (2, 2, 2)->(3, 3, 3)->(2, 2, 2)->(1, 1, 1) Sergey",code,Some bouncing balls are flying from a single source in a rectangular box. You are going to count how many balls passes through point A and point B,ai,2014-01-29T16:38:17,2022-09-02T09:54:45,,,," + +Sergey and Chen are locked in a rectangular box of Dimension L\*W\*H. Evil Larry has put a machine which is located at a point inside the box (p,q,r) which starts shooting balls in every direction (dx,dy,dz) where + +-N ≤ dx, dy, dz ≤ N except (0, 0, 0) + +such that the ball goes through (p, q, r) -> (p + dx, q + dy, r + dz) -> (p + 2dx, q + 2dy, r + 2dz) and so on. + +so, a total of (2N + 1)3 - 1 balls are fired. Sergey is standing at (a,b,c) and Chen is standing at (d,e,f). Provided all the balls follow reflection property and have constant velocity and gravity is not taken into account, can you tell how many balls are caught by Sergey and Chen? Sergey and Chen can catch the ball if it passes through the point at which they are standing. + +**Input Format** +The first line contains the number of test cases, T lines follow, each containing a testcase. +Each testcase contains 13 integers in the following order + + L W H a b c d e f p q r N + +**Output Format** +For each test case please output two integers indicating the number of balls that are caught by Sergey and C, respectively. + +**Constraints** +T = 1 +1 ≤ L, W, H, a, b, c, d, e, f, p, q, r, N ≤ 50 + +**Sample Input** + + 1 + 3 3 3 1 1 1 1 1 2 2 2 2 1 + +**Sample Output** + + 8 4 + +**Explanation** + +Here, L, W, H = (3, 3, 3), Sergey is at (1, 1, 1) and Chen is at (1, 1, 2) and the machine Larry put is at (2, 2, 2). +Balls are thrown at -1 ≤ x, y, z ≤ 1 from (2, 2, 2). + ++ (-1, -1, -1): (2, 2, 2)->(1, 1, 1) Sergey ++ (-1, -1, 0): (2, 2, 2)->(1, 1, 2) Chen ++ (-1, -1, 1): (2, 2, 2)->(1, 1, 3)->(0, 0, 2)->(1, 1, 1) Sergey ++ (-1, 0, -1): (2, 2, 2)->(1, 2, 1)->(0, 2, 0)->(1, 2, 1)->(2, 2, 2)->(3, 2, 3)->... ++ (-1, 0, 0): (2, 2, 2)->(1, 2, 2)->(0, 2, 2)->(1, 2, 2)->(2, 2, 2)->(3, 2, 2)->... ++ (-1, 0, 1): (2, 2, 2)->(1, 2, 3)->(0, 2, 2)->(1, 2, 1)->(2, 2, 0)->(3, 2, 1)->... ++ (-1, 1, -1): (2, 2, 2)->(1, 3, 1)->(0, 2, 0)->(1, 1, 1) Sergey ++ (-1, 1, 0): (2, 2, 2)->(1, 3, 2)->(0, 2, 2)->(1, 1, 2) Chen ++ (-1, 1, 1): (2, 2, 2)->(1, 3, 3)->(0, 2, 2)->(1, 1, 1) Sergey ++ (0, *, *): x-coordinate never changed ++ (1, -1, -1): (2, 2, 2)->(3, 1, 1)->(2, 0, 0)->(1, 1, 1) Sergey ++ (1, -1, 0): (2, 2, 2)->(3, 1, 2)->(2, 0, 2)->(1, 1, 2) Chen ++ (1, -1, 1): (2, 2, 2)->(3, 1, 3)->(2, 0, 2)->(1, 1, 1) Sergey ++ (1, 0, -1): (2, 2, 2)->(3, 2, 1)->(2, 2, 0)->(1, 2, 1)->(0, 2, 2)->... ++ (1, 0, 0): (2, 2, 2)->(3, 2, 2)->(2, 2, 2)->(1, 2, 2)->(0, 2, 2)->... ++ (1, 0, 1): (2, 2, 2)->(3, 2, 3)->(2, 2, 2)->(1, 2, 1)->(0, 2, 0)->... ++ (1, 1, -1): (2, 2, 2)->(3, 3, 1)->(2, 2, 0)->(1, 1, 1) Sergey ++ (1, 1, 0): (2, 2, 2)->(3, 3, 2)->(2, 2, 2)->(1, 1, 2) Chen ++ (1, 1, 1): (2, 2, 2)->(3, 3, 3)->(2, 2, 2)->(1, 1, 1) Sergey",0.5384615384615384,"[""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,The bouncing flying ball - March'14 Editorial,"

The bouncing flying ball
+Difficulty Level : Hard
+Required Knowledge : Chinese Remainder Theorem
+Problem Setter : Shang-En Huang
+Problem Tester : sdya

+ +

Approach

+ +

For each direction (dx, dy, dz), the ball is flying through (p, q, r) -> (p+dx, p+dy, p+dz) -> ... as a line segment. +We need to determine whether the ball touches (a, b, c) first or (d, e, f) first. This is equivalent to solve an integral equation using Chinese Remainder Theorem:

+ +
    +
  • p + t * (dx / g) = a or -a (mod 2L)
  • +
  • q + t * (dy / g) = b or -b (mod 2W)
  • +
  • r + t * (dz / g) = c or -c (mod 2H)
  • +
+ +

where g > 0 is the greatest common divisor of (dx, dy, dz). The minimum positive t > 0 is the variable that we want to know.

+ +

There are a few ways to calculate with more efficiency:

+ +
    +
  1. Use less multiplicity & division. (aka. use less ""%"" operations)
    +For example, we can cache the inversion calculation (pre-caculate something like v-1 modulo M)
  2. +
  3. For same (dx/g, dy/g, dz/g) directions we can calculate the solution only once, and add the multiplicity that Sergey or Chen get.
  4. +
  5. Calculate the solution to (-dx, -dy, -dz) when calculating (dx, dy, dz)'s solution: when we handling (dx, dy, dz) we are finding minimum t > 0 that satisfying the equations; but when we handling (-dx, -dy, -dz) we are finding the maximum t < LCM(2L, 2W, 2H) that satisfying the same equations.
  6. +
  7. To solve the system of equations above, there is no need to seperate the equation system into 8 system of equations.
  8. +
+ +

Setter's Code

+ +
/ by tmt514
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+#include <algorithm>
+#include <vector>
+using namespace std;
+
+#define FOR(it,c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(x) ((int)(x).size())
+
+int L, W, H, a, b, c, d, e, f, p, q, r, N;
+int inv_tbl[105][105], u_inv_tbl[105][105];
+
+int inv(int x, int y, int P, int Q, int R, int S) {
+if(y==0) return P;
+return inv(y, x%y, R, S, P-R*(x/y), Q-S*(x/y));
+}
+
+//cache the inversion results (note that 1 <= M <= 200)
+int inv(int x, int M) {
+if(!u_inv_tbl[x][M]) {
+u_inv_tbl[x][M] = 1;
+inv_tbl[x][M] = (inv(x, M, 1, 0, 0, 1)%M+M)%M;
+}
+return inv_tbl[x][M];
+}
+
+int sol[105], qb, qe;
+void getsol(int ql, int qr, int &modulo, int u, int x, int p, int M) {
+// u + ?x = p or -p (mod) M
+// ? = sol (mod) modulo
+
+if (x < 0) { u = -u; x = -x; }
+int p1 = ((p-u)%M+M)%M;
+int p2 = ((-p-u)%M+M)%M;
+
+int G = __gcd(M, x);
+M/=G; x/=G;
+int g = __gcd(modulo, M), MM = M / g;
+int ret_modulo = modulo * MM;
+modulo /= g;
+int MMInv = inv(modulo%MM, MM);
+
+if (p1 % G == 0) {
+p1 = p1/G * inv(x, M);
+for(int it=ql;it<qr;it++) {
+int t = sol[it];
+// ? = p1 (mod) MM
+// ? = t (mod) modulo
+if ((p1 - t) % g) continue;
+int tmp = ((p1 - t) * MMInv * modulo + t) % ret_modulo;
+tmp = (tmp+ret_modulo)%ret_modulo;
+sol[qe++] = tmp;
+}
+}
+if (p2 % G == 0) {
+p2 = p2/G * inv(x, M);
+for(int it=ql;it<qr;it++) {
+int t = sol[it];
+// ? = p2 (mod) M
+// ? = t (mod) modulo
+if ((p2 - t) % g) continue;
+int tmp = ((p2 - t) * MMInv * modulo + t) % ret_modulo;
+tmp = (tmp+ret_modulo)%ret_modulo;
+sol[qe++] = tmp;
+}
+}
+qb = qr;
+modulo = ret_modulo;
+}
+
+void ask(int &min_pos, int &min_neg, int u, int v, int w, int x, int y, int z) {
+int modulo = 1;
+// initialize the solution queue
+sol[0] = 0;
+qb = 0, qe = 1;
+
+// p + ?x = u or -u (mod) 2L
+// q + ?y = v or -v (mod) 2W
+// r + ?z = w or -w (mod) 2H
+getsol(qb, qe, modulo, p, x, u, 2*L);
+getsol(qb, qe, modulo, q, y, v, 2*W);
+getsol(qb, qe, modulo, r, z, w, 2*H);
+
+if (qb == qe) { min_pos = min_neg = -1; return; }
+min_pos = *min_element(sol + qb, sol + qe);
+min_neg = modulo - *max_element(sol + qb, sol + qe);
+}
+
+int muls[105][105][105];
+int main(void) {
+int T;
+scanf(""%d"", &T);
+while(T--) {
+scanf(""%d%d%d"", &L, &W, &H);
+scanf(""%d%d%d"", &a, &b, &c);
+scanf(""%d%d%d"", &d, &e, &f);
+scanf(""%d%d%d"", &p, &q, &r);
+scanf(""%d"", &N);
+memset(muls, 0, sizeof(muls));
+
+const int offset = 50;
+int cSergey = 0, cChen = 0;
+// caculate multiplicity
+for(int x=-N;x<=N;x++) for(int y=-N;y<=N;y++) for(int z=-N;z<=N;z++) {
+int g = __gcd(abs(x), __gcd(abs(y), abs(z)));
+if(g) muls[x/g+offset][y/g+offset][z/g+offset]++;
+}
+// caculate positive (x, y, z) and negative (-x, -y, -z) at same time
+for(int x=0;x<=N;x++) for(int y=-N;y<=N;y++) for(int z=-N;z<=N;z++) {
+if((x==0&&y<0) || (x==0 && y==0 && z<0)) continue;
+int g = __gcd(abs(x), __gcd(abs(y), abs(z)));
+if(!g) continue;
+if(g == 1) {
+int S_pos, S_neg, C_pos, C_neg;
+ask(S_pos, S_neg, a, b, c, x, y, z);
+ask(C_pos, C_neg, d, e, f, x, y, z);
+
+int m_pos = muls[x+offset][y+offset][z+offset];
+int m_neg = muls[-x+offset][-y+offset][-z+offset];
+if(S_pos != -1 && C_pos != -1) (S_pos < C_pos? cSergey+=m_pos: cChen+=m_pos);
+else if(S_pos != -1) cSergey+=m_pos;
+else if(C_pos != -1) cChen+=m_pos;
+
+if(S_neg != -1 && C_neg != -1) (S_neg < C_neg? cSergey+=m_neg: cChen+=m_neg);
+else if(S_neg != -1) cSergey+=m_neg;
+else if(C_neg != -1) cChen+=m_neg;
+}
+}
+printf(""%d %d\n"", cSergey, cChen);
+}
+return 0;
+}
+
+ +

Tester's Code

+ +
#include <cstdio>
+#include <cstring>
+#include <vector>
+#include <algorithm>
+#include <cmath>
+#include <iostream>
+using namespace std;
+
+#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
+#define SZ(c) ((long long)(c).size())
+typedef long long LL;
+
+long long L, W, H, x, y, z, a, b, c, p, q, r, N;
+const long long INF = 1000000000000000000LL;
+
+long long gcdtbl[105][10005];
+long long gcd3[105][105][105];
+long long inv[105][10005];
+long long cache[105][105][105];
+long long fac[105][105][105][7];
+
+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);
+    }
+}
+
+long long pre() {
+for(long long i=0;i<=100;i++) for(long long j=0;j<=10000;j++) gcdtbl[i][j] = gcd(i, j);
+for(long long i=0;i<=100;i++) for(long long j=0;j<=100;j++) for(long long k=0;k<=100;k++) gcd3[i][j][k] = gcd(gcd(i, j), k);
+for(long long i=2;i<=100;i++) for(long long j=0;j<=10000;j++) if(gcd(i, j) > 1) inv[i][j] = 0;
+else for(long long k=0;k<=100;k++) if(j*k%i==1) { inv[i][j] = k; break; }
+for(long long i=1;i<=100;i++) for(long long j=1;j<=100;j++) for(long long k=1;k<=100;k++) {
+static long long p[15]={64,9,25,49,11,13,17,19,23,29,31,37,41,43,47};
+static long long q[15]={2, 3, 5, 7,11,13,17,19,23,29,31,37,41,43,47};
+long long t=0;
+for(long long l=0;l<15;l++) if(i%q[l]==0 || j%q[l]==0 || k%q[l]==0) fac[i][j][k][t++] = p[l];
+}
+return 0;
+}
+
+long long solve(long long gx, long long gy, long long gz, long long u, long long v, int w) {
+//gx * t = u   2L
+//gy * t = v   2W
+//gz * t = w   2H
+
+long long A = 2*L, B = 2*W, C = 2*H;
+long long gA = gcdtbl[A][gx], gB = gcdtbl[B][gy], gC = gcdtbl[C][gz];
+if (u % gA || v % gB || w % gC) return INF;
+u /= gA; A /= gA; gx /= gA; u = u * inv[A][gx];
+v /= gB; B /= gB; gy /= gB; v = v * inv[B][gy];
+w /= gC; C /= gC; gz /= gC; w = w * inv[C][gz];
+
+// t = u (mod A)
+// t = v (mod B)
+// t = w (mod C)
+
+for(long long *it = &fac[A][B][C][0]; *it; it++) {
+long long p = *it;
+long long pa = gcdtbl[A][p], pb = gcdtbl[B][p], pc = gcdtbl[C][p];
+if(pa>=pb&&pa>=pc) { if((u-v)%pb||(u-w)%pc) return INF; else { B/=pb; C/=pc; }}
+else if(pb>=pa&&pb>=pc) { if((v-u)%pa||(v-w)%pc) return INF; else { A/=pa; C/=pc; }}
+else if(pc>=pa&&pc>=pb) { if((w-u)%pa||(w-v)%pb) return INF; else { A/=pa; B/=pb; }}
+}
+
+long long ABC = A*B*C, t = ((v-u)*inv[B][A]*A+u);
+t = ((w-t)*inv[C][A*B]*A*B+t);
+t = (t%ABC+ABC)%ABC;
+return t;
+}
+
+long long hit(long long vx, long long vy, long long vz, long long u, long long v, long long w) {
+long long tx = gcdtbl[2*L][abs(vx)], ty = gcdtbl[2*W][abs(vy)], tz = gcdtbl[2*H][abs(vz)];
+if(((u-p)%tx && (u+p)%tx) || ((v-q)%ty && (v+q)%ty) || ((w-r)%tz && (w+r)%tz)) return INF;
+vx = (vx % (2*L) + 2*L) % (2*L);
+vy = (vy % (2*W) + 2*W) % (2*W);
+vz = (vz % (2*H) + 2*H) % (2*H);
+long long t = INF;
+for(long long i=0;i<8;i++) t = min(t, solve(vx, vy, vz, (i&1? 4*L-u-p: 2*L+u-p), (i&2? 4*W-v-q: 2*W+v-q), (i&4? 4*H-w-r: 2*H+w-r)));
+return t;
+}
+
+void solve() {
+    cin >> L >> W >> H >> x >> y >> z >> a >> b >> c >> p >> q >> r >> N;
+//scanf(""%d%d%d%d%d%d%d%d%d%d%d%d%d"", &L, &W, &H, &x, &y, &z, &a, &b, &c, &p, &q, &r, &N);
+long long pi = 0, kel = 0;
+memset(cache, 0, sizeof(cache));
+for (long long vx = -N; vx <= N; vx++)
+for(long long vy = -N; vy <= N; vy++)
+for(long long vz = -N; vz <= N; vz++) {
+if(vx==0 && vy==0 && vz==0) continue;
+
+long long cx = vx, cy = vy, cz = vz;
+long long g = gcd3[abs(cx)][abs(cy)][abs(cz)];
+cx /= g; cy /= g; cz /= g;
+long long &tmp = cache[cx+50][cy+50][cz+50];
+if (tmp) {
+if (tmp == 1) ++pi;
+if (tmp == 2) ++kel;
+continue;
+}
+
+long long tp = hit(cx, cy, cz, x, y, z);
+long long th = hit(cx, cy, cz, a, b, c);
+
+if (tp < th) ++pi, tmp = 1;
+if (tp > th) ++kel, tmp = 2;
+if (tp == th) tmp = 3;
+}
+cout << pi << "" "" << kel << endl;
+//printf(""%d %d\n"", pi, kel);
+static long long cs=0;
+//cerr << ++cs << endl;
+//fprintf(stderr, ""Case #%d: %d %d\n"", ++cs, pi, kel);
+}
+
+int main(void) {
+    //freopen(""input.txt"", ""r"", stdin);
+    //freopen(""output.txt"", ""w"", stdout);
+long long T;
+pre();
+cin >> T;
+while(T--) solve();
+return 0;
+}
+
",0.0,mar14-the-bouncing-flying-ball,2014-04-15T09:40:26,"{""contest_participation"":2080,""challenge_submissions"":74,""successful_submissions"":19}",2014-04-15T09:40:26,2016-07-23T18:17:52,tester,"###C++ +```cpp + +#include +#include +#include +#include +#include +#include +using namespace std; + +#define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++) +#define SZ(c) ((long long)(c).size()) +typedef long long LL; + +long long L, W, H, x, y, z, a, b, c, p, q, r, N; +const long long INF = 1000000000000000000LL; + +long long gcdtbl[105][10005]; +long long gcd3[105][105][105]; +long long inv[105][10005]; +long long cache[105][105][105]; +long long fac[105][105][105][7]; + +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); + } +} + +long long pre() { +for(long long i=0;i<=100;i++) for(long long j=0;j<=10000;j++) gcdtbl[i][j] = gcd(i, j); +for(long long i=0;i<=100;i++) for(long long j=0;j<=100;j++) for(long long k=0;k<=100;k++) gcd3[i][j][k] = gcd(gcd(i, j), k); +for(long long i=2;i<=100;i++) for(long long j=0;j<=10000;j++) if(gcd(i, j) > 1) inv[i][j] = 0; +else for(long long k=0;k<=100;k++) if(j*k%i==1) { inv[i][j] = k; break; } +for(long long i=1;i<=100;i++) for(long long j=1;j<=100;j++) for(long long k=1;k<=100;k++) { +static long long p[15]={64,9,25,49,11,13,17,19,23,29,31,37,41,43,47}; +static long long q[15]={2, 3, 5, 7,11,13,17,19,23,29,31,37,41,43,47}; +long long t=0; +for(long long l=0;l<15;l++) if(i%q[l]==0 || j%q[l]==0 || k%q[l]==0) fac[i][j][k][t++] = p[l]; +} +return 0; +} + +long long solve(long long gx, long long gy, long long gz, long long u, long long v, int w) { +//gx * t = u 2L +//gy * t = v 2W +//gz * t = w 2H + +long long A = 2*L, B = 2*W, C = 2*H; +long long gA = gcdtbl[A][gx], gB = gcdtbl[B][gy], gC = gcdtbl[C][gz]; +if (u % gA || v % gB || w % gC) return INF; +u /= gA; A /= gA; gx /= gA; u = u * inv[A][gx]; +v /= gB; B /= gB; gy /= gB; v = v * inv[B][gy]; +w /= gC; C /= gC; gz /= gC; w = w * inv[C][gz]; + +// t = u (mod A) +// t = v (mod B) +// t = w (mod C) + +for(long long *it = &fac[A][B][C][0]; *it; it++) { +long long p = *it; +long long pa = gcdtbl[A][p], pb = gcdtbl[B][p], pc = gcdtbl[C][p]; +if(pa>=pb&&pa>=pc) { if((u-v)%pb||(u-w)%pc) return INF; else { B/=pb; C/=pc; }} +else if(pb>=pa&&pb>=pc) { if((v-u)%pa||(v-w)%pc) return INF; else { A/=pa; C/=pc; }} +else if(pc>=pa&&pc>=pb) { if((w-u)%pa||(w-v)%pb) return INF; else { A/=pa; B/=pb; }} +} + +long long ABC = A*B*C, t = ((v-u)*inv[B][A]*A+u); +t = ((w-t)*inv[C][A*B]*A*B+t); +t = (t%ABC+ABC)%ABC; +return t; +} + +long long hit(long long vx, long long vy, long long vz, long long u, long long v, long long w) { +long long tx = gcdtbl[2*L][abs(vx)], ty = gcdtbl[2*W][abs(vy)], tz = gcdtbl[2*H][abs(vz)]; +if(((u-p)%tx && (u+p)%tx) || ((v-q)%ty && (v+q)%ty) || ((w-r)%tz && (w+r)%tz)) return INF; +vx = (vx % (2*L) + 2*L) % (2*L); +vy = (vy % (2*W) + 2*W) % (2*W); +vz = (vz % (2*H) + 2*H) % (2*H); +long long t = INF; +for(long long i=0;i<8;i++) t = min(t, solve(vx, vy, vz, (i&1? 4*L-u-p: 2*L+u-p), (i&2? 4*W-v-q: 2*W+v-q), (i&4? 4*H-w-r: 2*H+w-r))); +return t; +} + +void solve() { + cin >> L >> W >> H >> x >> y >> z >> a >> b >> c >> p >> q >> r >> N; +//scanf(""%d%d%d%d%d%d%d%d%d%d%d%d%d"", &L, &W, &H, &x, &y, &z, &a, &b, &c, &p, &q, &r, &N); +long long pi = 0, kel = 0; +memset(cache, 0, sizeof(cache)); +for (long long vx = -N; vx <= N; vx++) +for(long long vy = -N; vy <= N; vy++) +for(long long vz = -N; vz <= N; vz++) { +if(vx==0 && vy==0 && vz==0) continue; + +long long cx = vx, cy = vy, cz = vz; +long long g = gcd3[abs(cx)][abs(cy)][abs(cz)]; +cx /= g; cy /= g; cz /= g; +long long &tmp = cache[cx+50][cy+50][cz+50]; +if (tmp) { +if (tmp == 1) ++pi; +if (tmp == 2) ++kel; +continue; +} + +long long tp = hit(cx, cy, cz, x, y, z); +long long th = hit(cx, cy, cz, a, b, c); + +if (tp < th) ++pi, tmp = 1; +if (tp > th) ++kel, tmp = 2; +if (tp == th) tmp = 3; +} +cout << pi << "" "" << kel << endl; +//printf(""%d %d\n"", pi, kel); +static long long cs=0; +//cerr << ++cs << endl; +//fprintf(stderr, ""Case #%d: %d %d\n"", ++cs, pi, kel); +} + +int main(void) { + //freopen(""input.txt"", ""r"", stdin); + //freopen(""output.txt"", ""w"", stdout); +long long T; +pre(); +cin >> T; +while(T--) solve(); +return 0; +} + +``` +",not-set,2016-04-24T02:02:36,2016-07-23T18:17:52,C++ +50,486,k-balance,k-balance number,"Your task is to calculate the sum (indicated by S) of all the k-balanced integers between [L, R]. An integer is called k-balanced when either of #1 or #2 below holds true. + +1. The length of the integer <= k +2. Sum of the first k digits (with no leading zeros) is equal to the sum of the last k digits. + +**Input format** +L R k + +**Output format** +S % 1000000007 + +**Constraints** +0 < L <= R < 10^18 +0 < k <= 18 + +**Sample Input** +9 23 1 + +**Sample Output** +42 + +**Explanation** +9, 11 and 22 are the only 3 integers between 9 and 23 ( both included ) that are k-balanced. Hence, the answer is 9+11+22=42 +",code,"Your task is to calculate the sum(indicated by S) of all the k-balanced integers between [L,R].",ai,2013-03-14T16:03:43,2022-09-02T09:55:00,,,,"Your task is to calculate the sum (indicated by S) of all the k-balanced integers between [L, R]. An integer is called k-balanced when either of #1 or #2 below holds true. + +1. The length of the integer <= k +2. Sum of the first k digits (with no leading zeros) is equal to the sum of the last k digits. + +**Input format** +L R k + +**Output format** +S % 1000000007 + +**Constraints** +0 < L <= R < 10^18 +0 < k <= 18 + +**Sample Input** +9 23 1 + +**Sample Output** +42 + +**Explanation** +9, 11 and 22 are the only 3 integers between 9 and 23 ( both included ) that are k-balanced. Hence, the answer is 9+11+22=42 +",0.5263157894736842,"[""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,May 20-20 Hack Editorial: K-Balance,"

K Balance

+ +

Find the sum of numbers between L and R having either <= K digits or having sum of first K digits equal to sum of last K digits.

+ +

Difficulty Level

+ +

Hard

+ +

Problem Setter

+ +

Wanbo
+Editorial by Piyush

+ +

Required Knowledge

+ +

Combinatorics, Dynamic Programming

+ +

Approach

+ +

Let's reduce the problem to finding

+ +
f(n) = the sum of K-balance numbers <= N
+
+ +

The answer to the problem will then be

+ +
f(r) - f(l-1)
+
+
+
+f(N){
+    // D is the number of digits of N.
+    D = Digits(N);
+    ans = 0;
+    //For numbers with lesser number of digits.
+    for(I = 1; I < |D|;I++) ans += f(I);
+    //For numbers with equal number of digits.
+    ans += Sum(); // what is sum?
+}
+
+ +

We can reduce K if the first K digits overlap with last K digits, so that they don't overlap. +To find Sum() , we can break our sum into sum at individual digit position and then sum it as :

+ +
10^(d-1) * S(d-1) + 10^(d-2)*S(d-2) + .. 10^(0) * S(0) // S(i) is the sum of digits at position i
+
+ +

For finding sum at individual digit position i, we can again break it into as :

+ +
0*Count(0) + 1*Count(1) + 2*Count(2) + ... + 9*Count(9) // Count(j) is the count of numbers having digit j at position i. 
+
+ +

So our approach looks like :

+ +
Sum()
+{
+    ans = 0;
+    for(I = 0;I <= |D|;I++){
+        SumAtI = 0;
+        for(J=1;J<=9;J++){
+            SumAtI += J*Count(I , J);
+        }
+        ans += SumAtI * 10^(I);
+    }
+}
+
+ +

Finding Count(p , x)
+We have simply fixed the digit at some position 'p' to be 'x' , and we have to find the count of numbers which have digit at position 'p' as 'x'. There have to be |D| - p digits before p , and p - 1 after p that will form a number . Also sum of first K digits should be equal to last K . Another condition is that since the number of digits is equal to |D| , we need to take care of the fact that the number does not exceed N itself. For doing this , we take a function: F(I , State , Sum) . This means that we are at the Ith digit , and State tells us that if all the digits taken before are equal to corresponding digits of N (if true would imply that Ith digit has to be <= Ith digit of N) , Sum stores the sum of digits taken in the first K digits.We will increase sum if Ith digit is in first K digits , decrease if it is in the last K digits , and make no change if it is between .This way if we get 0 sum in the end , that means our number satisfies all conditions.

+ +
F(I,state,sum){
+    //Base Case
+    if(N == -1) return (Sum == 0);
+    //If Ith is first digit , we can't take 0 .
+    //If state variable is true , that means we are in prefix of N , so Ith digit has to be less than Dig[I]
+    for(J = ((I == |D| - 1) ? 1 : 0) ;J <= (state ? Dig[I] : 9); J++){
+        //digit is in first K digits.
+        if(I >= |D| - K)
+            r += F(I - 1, state && (Dig[I] == J) , sum + J);
+        //digit is in last K digits.
+        else if(n < K){
+            if(sum >= i)
+                ans += F(I - 1, state && (Dig[I] == J), sum - J);
+        }
+        //digit is in between
+        else ans += F(I - 1, state && (Dig[I] == J), sum);        
+    }
+    return ans;
+}
+
+ +

Returning to Count(p, x) +We only have the pth digit as x, but depending on starting |D|-p digits , we can have different values of (state,sum) at pth digit, so we will try all such values of (state,sum), and count the total numbers.

+ +
Count(p, x){
+    for(State = 0 ; State <= 1; State ++){
+        for(Sum = 0; Sum <= (|D| - p)*9 ;Sum++){
+            ans += [ Numbers With (|D|-p)_Digits And Reach (State,Sum) ] * [ F(p,state,sum) and x as the pth digit] ;
+        }
+    }
+}
+
+ +

Finding the count of numbers with \|D\|-P digits and reaching (state,sum) as required can be done either using another recursive function , or using function F itself . This completes our Sum() function . Find(x) function is easy to implement as well if you have understood the basic idea developed above( would be good exercise infact) . It can be also be eliminated, but at the cost of one more variable in the state of function F.

+ +

Problem Setter's Code: C++

+ +

Setter's code

+ +

Problem Tester's Code: C++

+ +

Tester's code

",0.0,may-2020-editorial-k-balance,2013-06-11T15:00:56,"{""contest_participation"":3663,""challenge_submissions"":242,""successful_submissions"":69}",2013-06-11T15:00:56,2016-07-23T18:44:37,setter,"###C++ +```cpp +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +typedef long long LL; +#define MM(a,x) memset(a, x, sizeof(a)) +#define P(x) cout<<#x<<"" = ""<""<<#b<<"": ""<<1.*(b-a)/CLOCKS_PER_SEC<<""s\n""; + +const LL MD = LL(1e9) + 7; + +LL ten[51]; +LL p10[51]; +LL h(LL m); + +LL brute(LL L, LL R, int k) { + LL ret = 0; + for(int i = L; i <= R; i++) { + int s[100], ct; + if(i % 100000000 == 0) P(i); + LL T = i; + ct = 0; + while(T) { + s[ct++] = T % 10; + T /= 10; + } + if(ct < k) {ret += i; continue;} + int sL = 0, sR = 0; + for(int j = 0; j < k; j++) { + sL += s[j]; + sR += s[ct - j - 1]; + } + if(sL == sR) + ret = (ret + i) % MD; + } + return ret % MD; +} + +vector toD(LL n) { + vector r; + while(n) { + r.push_back(n % 10); + n /= 10; + } + reverse(r.begin(), r.end()); + return r; +} + +LL h(LL m) { + LL L = 1, R = LL(pow(10., (int)m) + 0.5) - 1; + LL t1 = L + R; + LL n = R - L + 1; + if(t1 % 2 == 0) t1 /= 2; + else if(n % 2 == 0) n /= 2; + t1 %= MD; + n %= MD; + LL ret = t1 * n % MD; + return ret; +} + + +LL g(int cur, int sz, int p[], int k, bool allZero) { +// PV(p, sz); +// P(cur); + LL ret = 0; + int pZero = 0; + for(int i = 0; i < cur; i++) { + if(p[i] == 0) { + pZero = i + 1; + } else { + break; + } + } + + vector d; + for(int i = pZero; i < cur; i++) d.push_back(p[i]); + sz -= pZero; + + int nsure = d.size(), L, R, M; + + if(sz <= k) { + LL sure = 0; + for(int i = 0; i < nsure; i++) { + sure = (10 * sure + d[i]) % MD; + } + int nosure = sz - nsure; + int minus = allZero && (nosure > 0); + ret = (h(nosure) - minus * h(nosure - 1) % MD + (ten[nosure] - minus * ten[nosure - 1]) % MD * ten[nosure] % MD * sure % MD) % MD; + if(ret < 0) ret += MD; + return ret; + } + + if(2 * k <= sz) { + M = sz - 2 * k, L = R = k; + } else { + M = 2 * k - sz, L = R = sz - k; + } + + LL dL[10][100] = {}; + LL X[10][100] = {}; + X[0][0] = 1; + for(int i = 1; i <= 9; i++) { + int st = (i == 1 && allZero) ? 1 : 0; + for(int j = 0; j < 100; j++) { + for(int l = st; l <= 9 && l <= j; l++) { + X[i][j] += X[i - 1][j - l]; + } + X[i][j] %= MD; + } + } + + LL dR[10][100] = {}; + LL Y[10][100] = {}; + Y[0][0] = 1; + for(int i = 1; i <= 9; i++) { + for(int j = 0; j < 100; j++) { + for(int l = 0; l <= 9 && l <= j; l++) { + Y[i][j] += Y[i - 1][j - l]; + } + Y[i][j] %= MD; + } + } + + for(int i = 1; i <= 9; i++) + for(int j = 0; j < 100; j++) { + for(int x = i - 1; x >= 0; x--) { + for(int y = (allZero && x == i - 1); y <= 9 && y <= j; y++) { + if(x != i - 1) + dL[i][j] += X[i - 1][j - y] * y % MD * ten[x] % MD; + else + dL[i][j] += Y[i - 1][j - y] * y % MD * ten[x] % MD; + } + } + dL[i][j] %= MD; + } + for(int i = 1; i <= 9; i++) + for(int j = 0; j < 100; j++) { + for(int x = i - 1; x >= 0; x--) { + for(int y = 0; y <= 9 && y <= j; y++) { + dR[i][j] += Y[i - 1][j - y] * y % MD * ten[x] % MD; + } + } + dR[i][j] %= MD; + } + if(nsure < L) { + // cout << ""1)"" << endl; + int nL = L - nsure; + int sL = 0; + LL sure = 0; + for(int i = 0; i < nsure; i++) { + sure = (10 * sure + d[i]) % MD; + sL += d[i]; + } + + for(int ds = 0; ds + sL < 100; ds++) { + LL cL = ten[M] * Y[R][ds + sL] % MD; + LL vL = (dL[nL][ds] + X[nL][ds] * sure % MD * ten[nL]) % MD * ten[M + R] % MD; + ret += cL * vL % MD; + + LL cM = X[nL][ds] * Y[R][ds + sL] % MD; + LL vM = h(M) * ten[R] % MD; + ret += cM * vM % MD; + + LL cR = X[nL][ds] * ten[M]; + LL vR = dR[R][ds + sL]; + ret += cR * vR % MD; + } + ret %= MD; + } else if(nsure <= L + M) { + // cout << ""2)"" << endl; + int sL = 0; + int nM = L + M - nsure; + LL vL = 0, vM = 0; + for(int i = 0; i < L; i++) { + sL += d[i]; + vL = (10 * vL + d[i]) % MD; + } + for(int i = L; i < nsure; i++) { + vM = (10 * vM + d[i]) % MD; + } + + LL cL = ten[nM] * Y[R][sL] % MD; + vL = vL * ten[M + R] % MD; + ret += cL * vL % MD; + + LL cM = Y[R][sL] % MD; + vM = vM * ten[nM] % MD; + vM = (h(nM) + vM * ten[nM]) % MD * ten[R] % MD; + ret += cM * vM % MD; + + LL cR = ten[nM]; + LL vR = dR[R][sL]; + ret += cR * vR % MD; + ret %= MD; + } else { + // cout << ""3)"" << endl; + LL sure = 0; + int sL = 0, sR = 0; + for(int i = 0; i < L; i++) sL += d[i]; + for(int i = L + M; i < nsure; i++) sR += d[i]; + for(int i = 0; i < nsure; i++) sure = (10 * sure + d[i]) % MD; + + int nR = R - (nsure - (L + M)); + if(sL >= sR) { + LL cR = Y[nR][sL - sR]; + LL vR = dR[nR][sL - sR]; + ret += (vR + sure * ten[nR] % MD * cR) % MD; + ret %= MD; + } + } + //P(ret); + //cout << endl; + return ret; +} + +void dfs(int cur, vector& D, int p[], int k, bool isEqual, bool allZero, LL & r) { + int sz = (int) D.size(); + if(cur == sz) { + if(isEqual) return; + else r += g(cur, D.size(), p, k, allZero); + return; + } + if(isEqual) { + for(int i = 0; i <= D[cur]; i++) { + p[cur] = i; + dfs(cur + 1, D, p, k, i == D[cur], allZero && (i == 0), r); + } + } else { + if(allZero) { + for(int i = cur; i < D.size(); i++) { + r += g(i, D.size(), p, k, 1); + p[i] = 0; + } + } else { + r += g(cur, D.size(), p, k, 0); + } + } +} + +//1,2,...,n +LL f(LL n, LL k) { + vector D = toD(n); + LL r = 0; + int p[50] = {}; + dfs(0, D, p, k, 1, 1, r); + r %= MD; + return r; +} + +int main() { + p10[0] = ten[0] = 1; + for(int i = 1; i < 50; i++) { + p10[i] = 10 * p10[i - 1]; + ten[i] = 10 * ten[i - 1] % MD; + } + LL L, R, k; + cin >> L >> R >> k; + assert(L <= R && R < LL(1e18)); + LL rL = f(L, k); + LL rR = f(R + 1, k); +// P(rL); +// P(rR); + LL r = (rR - rL + MD) % MD; + cout << r << endl; + //P(brute(L, R, k)); + return 0; +} +``` +",not-set,2016-04-24T02:02:36,2016-07-23T18:44:37,C++ +51,2293,p-sequences,P-sequences," + + +We call a sequence of `N` natural numbers (*a*1, *a*2, ..., *a*N) a *P-sequence*, if the product of any two adjacent numbers in it is not greater than *P*. In other words, if a sequence (*a*1, *a*2, ..., *a*N) is a *P-sequence*, then *a*i * *a*i+1 ≤ `P` ∀ 1 ≤ i < N + +You are given `N` and `P`. Your task is to find the number of such *P-sequences* of `N` integers modulo 109+7. + +**Input Format** +The first line of input consists of `N` +The second line of the input consists of `P`. + +**Constraints** +2 ≤ N ≤ 103 +1 ≤ P ≤ 109 +1 ≤ ai + +**Output Format** +Output the number of *P-sequences* of `N` integers modulo 109+7. + +**Sample Input #00** + + 2 + 2 + +**Sample Output #00** + + 3 + +**Explanation #00** + +3 such sequences are {1,1},{1,2} and {2,1}",code,How many sequences of N elements are there if product of two adjacent elements is not greater than P,ai,2014-03-31T21:26:34,2022-08-31T08:14:51,"# +# Complete the 'pSequences' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER n +# 2. INTEGER p +# + +def pSequences(n, p): + # 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()) + + p = int(input().strip()) + + result = pSequences(n, p) + + fptr.write(str(result) + '\n') + + fptr.close() +","We call a sequence of `N` natural numbers (*a*1, *a*2, ..., *a*N) a *P-sequence*, if the product of any two adjacent numbers in it is not greater than *P*. In other words, if a sequence (*a*1, *a*2, ..., *a*N) is a *P-sequence*, then *a*i * *a*i+1 ≤ `P` ∀ 1 ≤ i < N + +You are given `N` and `P`. Your task is to find the number of such *P-sequences* of `N` integers modulo 109+7. +",0.550561798,"[""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 input consists of `N` +The second line of the input consists of `P`. +","Output the number of *P-sequences* of `N` integers modulo 109+7. +"," 2 + 2 +"," 3 +",Hard,P-Sequences - Week 1 Editorial,"

Difficulty level : Medium
+Required knowledge : Partial sums trick, DP
+Problem setter : Sergey Kulik
+Problem tester : Dmytro Soboliev

+ +

Approach

+ +

Consider a valid P-sequence of N integers: (a1, a2, ..., aN). If you take some i (1 <= i < N) and take a pair (ai, ai+1) from this sequence, at least one of the following statements will be true:

+ +
    +
  • ai is not greater than the square root (in future, to be short, sqrt) of P.
  • +
  • ai+1 is not greater than the square root of P.
  • +
+ +

And this fact gives a rise to the key idea of the solution. Let's have a DP F(N, R, t). The meaning of the DP state is: the number of P-sequences of N integer numbers, where:

+ +
    +
  • if t is false, then R is the N-th term of a P-sequence.
  • +
  • if t is true, then R is the maximal possible number that can be the N+1-th term of a P-sequence.
  • +
+ +

Basically, false value of t corresponds to the above case where ai isn't greater than sqrt(P) and true value of t corresponds to the case where ai is actually greater than sqrt(P), but ai+1 is not greater than sqrt(P).

+ +

We have O(N * sqrt(P)) states here, so we can calculate this DP in affordable time.

+ +

When we calculate the DP, we should take care of the initial DP values and about the DP transitions.

+ +

The initial DP values are the values of F(N, R, t) where N is equal to one. Here

+ +
    +
  • F(1, R, false) equals to one because R is the the only term of a P-sequence sequence here.

  • +
  • F(1, R, true) equals to the number of such integers K from the range [1; P] such that N divided by K equals to R. This number can be obtained by solving the corresponding equation, see the solution for the details.

  • +
+ +

When t (that means that ai+1 is not greater than sqrt(P)) is false you should take the sum of the following values in order to get F(N, R, t):

+ +
    +
  • the sum of F(N - 1, R', false), where R' for R' from 1 to sqrt(P). This corresponds to the case where the both ai and ai+1 are not greater than sqrt(P).

  • +
  • the sum of F(N - 1, R', true), where R' is greater or equal to R. This follows derives from the above DP state definition and corresponds to the case when ai is greater than sqrt(P) but ai+1 is smaller than sqrt(P).

  • +
+ +

When we have the true value of t, the transition is simpler. Here the value of F(N, R, t) equals to the sum of F(N - 1, R', t), where R' is not greater than R and then multiplied by the amount of such numbers K in the range [1; P] that P divided by K is R.

+ +

Here we're taking a sum of a multiple previously calculated DP states, but using, for example, the partial sums trick, we can do it in O(1).

+ +

Setter's solution

+ +
#include <iostream>
+#include <cstdio>
+#include <algorithm>
+using namespace std;
+
+#define maxn 1000 + 5
+#define max_sqrt_k 32000
+#define mod 1000000007
+
+int dp[2][max_sqrt_k][2], n, k, sqrt_k, i, j, t, ret, pref, sum0, sum1, count_lr[max_sqrt_k], le, ri, l, p;
+
+void upd (int &a, int b) {
+    a += b;
+    if (a >= mod) a -= mod;
+}
+
+int main (int argc, char * const argv[]) {
+    scanf(""%d %d"", &n, &k);
+    while (sqrt_k * sqrt_k < k) ++sqrt_k;
+    for(i = 1; i <= sqrt_k; i++) dp[1][i][0] = 1;
+    for(i = 1; i < sqrt_k; i++) {
+        le = k / (i + 1) + 1;
+        ri = k / i;
+        if (ri <= sqrt_k) continue;
+        le = max(le, sqrt_k + 1);
+        count_lr[i] = ri - le + 1;
+    }
+    for(i = 1; i < sqrt_k; i++) dp[1][i][1] = count_lr[i];
+    l = 1;
+    for(i = 2; i <= n; i++) {
+        p = l;
+        l ^= 1;
+        sum0 = sum1 = 0;
+        for(j = 1; j <= sqrt_k; j++) {
+            upd(sum0, dp[p][j][0]);
+            upd(sum1, dp[p][j][1]);
+        }
+        t = sqrt_k;
+        for(j = 1; j <= sqrt_k; j++) {
+            while (j * t > k) upd(sum0, mod - dp[p][t--][0]);
+            dp[l][j][0] = sum1 + sum0;
+            if (dp[l][j][0] >= mod) dp[l][j][0] -= mod;
+            upd(sum1, mod - dp[p][j][1]);
+        }
+        pref = 0;
+        for(j = 1; j < sqrt_k; j++) {
+            upd(pref, dp[p][j][0]);
+            dp[l][j][1] = (count_lr[j] * 1LL * pref) % mod;
+        }
+    }
+    for(j = 1; j <= sqrt_k; j++) {
+        upd(ret, dp[l][j][0]);
+        upd(ret, dp[l][j][1]);
+    }
+    printf(""%d\n"", ret);
+    return 0;
+}
+
+ +

Tester's Solution

+ +
/*
+    Solution by sdya (Dmytro Soboliev)
+*/
+#include <iostream>
+#include <cstdio>
+#include <vector>
+#include <algorithm>
+#include <cstring>
+#include <cassert>
+
+using namespace std;
+
+const int P = 1000000007;
+const int maxN = 64000;
+
+vector < int > bounds, ways;
+int d[2][maxN], add[maxN];
+
+int buildBounds(int p) {
+  for (int i = 1; i * i <= p; ++i) {
+    ways.push_back(i);
+    bounds.push_back(p / i);
+  }
+
+  int m = bounds.size();
+  for (int i = 0; i < m; ++i) {
+    ways.push_back(bounds[m - 1 - i]);
+    bounds.push_back(ways[m - 1 - i]);
+  }
+
+  return m + m;
+}
+
+int main() {
+  int n, p;
+  cin >> n >> p;
+  assert(1 <= n && n <= 1e3);
+  assert(1 <= p && p <= 1e9);
+  int m = buildBounds(p);
+
+  int u = 0, v = 1;
+  memset(d[u], 0, sizeof(d[u]));
+  d[u][m - 1] = 1;
+  for (int i = 0; i < n; ++i, swap(u, v)) {
+    int covered = m - 1;
+    memset(add, 0, sizeof(add));
+    memset(d[v], 0, sizeof(d[v]));
+    for (int j = 0; j < m; ++j) {
+      if (d[u][j] == 0) {
+        continue;
+      }
+      while (covered >= 0 && bounds[covered] <= ways[j]) {
+        --covered;
+      }
+
+      add[covered + 1] += d[u][j];
+      if (add[covered + 1] >= P) {
+        add[covered + 1] -= P;
+      }
+
+      for (int k = covered; k >= 0; --k) {
+        int right = min(bounds[k], ways[j]);
+        int left = k == m - 1 ? 1 : bounds[k + 1] + 1;
+
+        if (left <= right) {
+          d[v][k] += (long long)(d[u][j]) * (long long)(right - left + 1) % (long long)(P);
+          if (d[v][k] >= P) {
+            d[v][k] -= P;
+          }
+        } else {
+          break;
+        }
+      }
+    }
+
+    for (int j = 1; j < m; ++j) {
+      add[j] += add[j - 1];
+      if (add[j] >= P) {
+        add[j] -= P;
+      }
+    }
+
+    for (int j = 0; j < m; ++j) {
+      int right = bounds[j];
+      int left = j == m - 1 ? 1 : bounds[j + 1] + 1;
+      d[v][j] += (long long)(add[j]) * (long long)(right - left + 1) % (long long)(P);
+      if (d[v][j] >= P) {
+        d[v][j] -= P;
+      }
+    }
+  }
+
+  long long res = 0;
+  for (int i = 0; i < m; ++i) {
+    res += d[u][i];
+  }
+
+  cout << res % P << endl;
+
+  return 0;
+}
+
",0.0,w1-p-sequences,2014-04-24T18:24:07,"{""contest_participation"":2214,""challenge_submissions"":260,""successful_submissions"":117}",2014-04-24T18:24:07,2016-07-23T15:27:56,setter,"###C++ +```cpp + +#include +#include +#include +using namespace std; + +#define maxn 1000 + 5 +#define max_sqrt_k 32000 +#define mod 1000000007 + +int dp[2][max_sqrt_k][2], n, k, sqrt_k, i, j, t, ret, pref, sum0, sum1, count_lr[max_sqrt_k], le, ri, l, p; + +void upd (int &a, int b) { + a += b; + if (a >= mod) a -= mod; +} + +int main (int argc, char * const argv[]) { + scanf(""%d %d"", &n, &k); + while (sqrt_k * sqrt_k < k) ++sqrt_k; + for(i = 1; i <= sqrt_k; i++) dp[1][i][0] = 1; + for(i = 1; i < sqrt_k; i++) { + le = k / (i + 1) + 1; + ri = k / i; + if (ri <= sqrt_k) continue; + le = max(le, sqrt_k + 1); + count_lr[i] = ri - le + 1; + } + for(i = 1; i < sqrt_k; i++) dp[1][i][1] = count_lr[i]; + l = 1; + for(i = 2; i <= n; i++) { + p = l; + l ^= 1; + sum0 = sum1 = 0; + for(j = 1; j <= sqrt_k; j++) { + upd(sum0, dp[p][j][0]); + upd(sum1, dp[p][j][1]); + } + t = sqrt_k; + for(j = 1; j <= sqrt_k; j++) { + while (j * t > k) upd(sum0, mod - dp[p][t--][0]); + dp[l][j][0] = sum1 + sum0; + if (dp[l][j][0] >= mod) dp[l][j][0] -= mod; + upd(sum1, mod - dp[p][j][1]); + } + pref = 0; + for(j = 1; j < sqrt_k; j++) { + upd(pref, dp[p][j][0]); + dp[l][j][1] = (count_lr[j] * 1LL * pref) % mod; + } + } + for(j = 1; j <= sqrt_k; j++) { + upd(ret, dp[l][j][0]); + upd(ret, dp[l][j][1]); + } + printf(""%d\n"", ret); + return 0; +} +``` +",not-set,2016-04-24T02:02:36,2016-07-23T15:24:00,C++ +52,2293,p-sequences,P-sequences," + + +We call a sequence of `N` natural numbers (*a*1, *a*2, ..., *a*N) a *P-sequence*, if the product of any two adjacent numbers in it is not greater than *P*. In other words, if a sequence (*a*1, *a*2, ..., *a*N) is a *P-sequence*, then *a*i * *a*i+1 ≤ `P` ∀ 1 ≤ i < N + +You are given `N` and `P`. Your task is to find the number of such *P-sequences* of `N` integers modulo 109+7. + +**Input Format** +The first line of input consists of `N` +The second line of the input consists of `P`. + +**Constraints** +2 ≤ N ≤ 103 +1 ≤ P ≤ 109 +1 ≤ ai + +**Output Format** +Output the number of *P-sequences* of `N` integers modulo 109+7. + +**Sample Input #00** + + 2 + 2 + +**Sample Output #00** + + 3 + +**Explanation #00** + +3 such sequences are {1,1},{1,2} and {2,1}",code,How many sequences of N elements are there if product of two adjacent elements is not greater than P,ai,2014-03-31T21:26:34,2022-08-31T08:14:51,"# +# Complete the 'pSequences' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER n +# 2. INTEGER p +# + +def pSequences(n, p): + # 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()) + + p = int(input().strip()) + + result = pSequences(n, p) + + fptr.write(str(result) + '\n') + + fptr.close() +","We call a sequence of `N` natural numbers (*a*1, *a*2, ..., *a*N) a *P-sequence*, if the product of any two adjacent numbers in it is not greater than *P*. In other words, if a sequence (*a*1, *a*2, ..., *a*N) is a *P-sequence*, then *a*i * *a*i+1 ≤ `P` ∀ 1 ≤ i < N + +You are given `N` and `P`. Your task is to find the number of such *P-sequences* of `N` integers modulo 109+7. +",0.550561798,"[""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 input consists of `N` +The second line of the input consists of `P`. +","Output the number of *P-sequences* of `N` integers modulo 109+7. +"," 2 + 2 +"," 3 +",Hard,P-Sequences - Week 1 Editorial,"

Difficulty level : Medium
+Required knowledge : Partial sums trick, DP
+Problem setter : Sergey Kulik
+Problem tester : Dmytro Soboliev

+ +

Approach

+ +

Consider a valid P-sequence of N integers: (a1, a2, ..., aN). If you take some i (1 <= i < N) and take a pair (ai, ai+1) from this sequence, at least one of the following statements will be true:

+ +
    +
  • ai is not greater than the square root (in future, to be short, sqrt) of P.
  • +
  • ai+1 is not greater than the square root of P.
  • +
+ +

And this fact gives a rise to the key idea of the solution. Let's have a DP F(N, R, t). The meaning of the DP state is: the number of P-sequences of N integer numbers, where:

+ +
    +
  • if t is false, then R is the N-th term of a P-sequence.
  • +
  • if t is true, then R is the maximal possible number that can be the N+1-th term of a P-sequence.
  • +
+ +

Basically, false value of t corresponds to the above case where ai isn't greater than sqrt(P) and true value of t corresponds to the case where ai is actually greater than sqrt(P), but ai+1 is not greater than sqrt(P).

+ +

We have O(N * sqrt(P)) states here, so we can calculate this DP in affordable time.

+ +

When we calculate the DP, we should take care of the initial DP values and about the DP transitions.

+ +

The initial DP values are the values of F(N, R, t) where N is equal to one. Here

+ +
    +
  • F(1, R, false) equals to one because R is the the only term of a P-sequence sequence here.

  • +
  • F(1, R, true) equals to the number of such integers K from the range [1; P] such that N divided by K equals to R. This number can be obtained by solving the corresponding equation, see the solution for the details.

  • +
+ +

When t (that means that ai+1 is not greater than sqrt(P)) is false you should take the sum of the following values in order to get F(N, R, t):

+ +
    +
  • the sum of F(N - 1, R', false), where R' for R' from 1 to sqrt(P). This corresponds to the case where the both ai and ai+1 are not greater than sqrt(P).

  • +
  • the sum of F(N - 1, R', true), where R' is greater or equal to R. This follows derives from the above DP state definition and corresponds to the case when ai is greater than sqrt(P) but ai+1 is smaller than sqrt(P).

  • +
+ +

When we have the true value of t, the transition is simpler. Here the value of F(N, R, t) equals to the sum of F(N - 1, R', t), where R' is not greater than R and then multiplied by the amount of such numbers K in the range [1; P] that P divided by K is R.

+ +

Here we're taking a sum of a multiple previously calculated DP states, but using, for example, the partial sums trick, we can do it in O(1).

+ +

Setter's solution

+ +
#include <iostream>
+#include <cstdio>
+#include <algorithm>
+using namespace std;
+
+#define maxn 1000 + 5
+#define max_sqrt_k 32000
+#define mod 1000000007
+
+int dp[2][max_sqrt_k][2], n, k, sqrt_k, i, j, t, ret, pref, sum0, sum1, count_lr[max_sqrt_k], le, ri, l, p;
+
+void upd (int &a, int b) {
+    a += b;
+    if (a >= mod) a -= mod;
+}
+
+int main (int argc, char * const argv[]) {
+    scanf(""%d %d"", &n, &k);
+    while (sqrt_k * sqrt_k < k) ++sqrt_k;
+    for(i = 1; i <= sqrt_k; i++) dp[1][i][0] = 1;
+    for(i = 1; i < sqrt_k; i++) {
+        le = k / (i + 1) + 1;
+        ri = k / i;
+        if (ri <= sqrt_k) continue;
+        le = max(le, sqrt_k + 1);
+        count_lr[i] = ri - le + 1;
+    }
+    for(i = 1; i < sqrt_k; i++) dp[1][i][1] = count_lr[i];
+    l = 1;
+    for(i = 2; i <= n; i++) {
+        p = l;
+        l ^= 1;
+        sum0 = sum1 = 0;
+        for(j = 1; j <= sqrt_k; j++) {
+            upd(sum0, dp[p][j][0]);
+            upd(sum1, dp[p][j][1]);
+        }
+        t = sqrt_k;
+        for(j = 1; j <= sqrt_k; j++) {
+            while (j * t > k) upd(sum0, mod - dp[p][t--][0]);
+            dp[l][j][0] = sum1 + sum0;
+            if (dp[l][j][0] >= mod) dp[l][j][0] -= mod;
+            upd(sum1, mod - dp[p][j][1]);
+        }
+        pref = 0;
+        for(j = 1; j < sqrt_k; j++) {
+            upd(pref, dp[p][j][0]);
+            dp[l][j][1] = (count_lr[j] * 1LL * pref) % mod;
+        }
+    }
+    for(j = 1; j <= sqrt_k; j++) {
+        upd(ret, dp[l][j][0]);
+        upd(ret, dp[l][j][1]);
+    }
+    printf(""%d\n"", ret);
+    return 0;
+}
+
+ +

Tester's Solution

+ +
/*
+    Solution by sdya (Dmytro Soboliev)
+*/
+#include <iostream>
+#include <cstdio>
+#include <vector>
+#include <algorithm>
+#include <cstring>
+#include <cassert>
+
+using namespace std;
+
+const int P = 1000000007;
+const int maxN = 64000;
+
+vector < int > bounds, ways;
+int d[2][maxN], add[maxN];
+
+int buildBounds(int p) {
+  for (int i = 1; i * i <= p; ++i) {
+    ways.push_back(i);
+    bounds.push_back(p / i);
+  }
+
+  int m = bounds.size();
+  for (int i = 0; i < m; ++i) {
+    ways.push_back(bounds[m - 1 - i]);
+    bounds.push_back(ways[m - 1 - i]);
+  }
+
+  return m + m;
+}
+
+int main() {
+  int n, p;
+  cin >> n >> p;
+  assert(1 <= n && n <= 1e3);
+  assert(1 <= p && p <= 1e9);
+  int m = buildBounds(p);
+
+  int u = 0, v = 1;
+  memset(d[u], 0, sizeof(d[u]));
+  d[u][m - 1] = 1;
+  for (int i = 0; i < n; ++i, swap(u, v)) {
+    int covered = m - 1;
+    memset(add, 0, sizeof(add));
+    memset(d[v], 0, sizeof(d[v]));
+    for (int j = 0; j < m; ++j) {
+      if (d[u][j] == 0) {
+        continue;
+      }
+      while (covered >= 0 && bounds[covered] <= ways[j]) {
+        --covered;
+      }
+
+      add[covered + 1] += d[u][j];
+      if (add[covered + 1] >= P) {
+        add[covered + 1] -= P;
+      }
+
+      for (int k = covered; k >= 0; --k) {
+        int right = min(bounds[k], ways[j]);
+        int left = k == m - 1 ? 1 : bounds[k + 1] + 1;
+
+        if (left <= right) {
+          d[v][k] += (long long)(d[u][j]) * (long long)(right - left + 1) % (long long)(P);
+          if (d[v][k] >= P) {
+            d[v][k] -= P;
+          }
+        } else {
+          break;
+        }
+      }
+    }
+
+    for (int j = 1; j < m; ++j) {
+      add[j] += add[j - 1];
+      if (add[j] >= P) {
+        add[j] -= P;
+      }
+    }
+
+    for (int j = 0; j < m; ++j) {
+      int right = bounds[j];
+      int left = j == m - 1 ? 1 : bounds[j + 1] + 1;
+      d[v][j] += (long long)(add[j]) * (long long)(right - left + 1) % (long long)(P);
+      if (d[v][j] >= P) {
+        d[v][j] -= P;
+      }
+    }
+  }
+
+  long long res = 0;
+  for (int i = 0; i < m; ++i) {
+    res += d[u][i];
+  }
+
+  cout << res % P << endl;
+
+  return 0;
+}
+
",0.0,w1-p-sequences,2014-04-24T18:24:07,"{""contest_participation"":2214,""challenge_submissions"":260,""successful_submissions"":117}",2014-04-24T18:24:07,2016-07-23T15:27:56,tester,"###C++ +```cpp + +/* + Solution by sdya (Dmytro Soboliev) +*/ +#include +#include +#include +#include +#include +#include + +using namespace std; + +const int P = 1000000007; +const int maxN = 64000; + +vector < int > bounds, ways; +int d[2][maxN], add[maxN]; + +int buildBounds(int p) { + for (int i = 1; i * i <= p; ++i) { + ways.push_back(i); + bounds.push_back(p / i); + } + + int m = bounds.size(); + for (int i = 0; i < m; ++i) { + ways.push_back(bounds[m - 1 - i]); + bounds.push_back(ways[m - 1 - i]); + } + + return m + m; +} + +int main() { + int n, p; + cin >> n >> p; + assert(1 <= n && n <= 1e3); + assert(1 <= p && p <= 1e9); + int m = buildBounds(p); + + int u = 0, v = 1; + memset(d[u], 0, sizeof(d[u])); + d[u][m - 1] = 1; + for (int i = 0; i < n; ++i, swap(u, v)) { + int covered = m - 1; + memset(add, 0, sizeof(add)); + memset(d[v], 0, sizeof(d[v])); + for (int j = 0; j < m; ++j) { + if (d[u][j] == 0) { + continue; + } + while (covered >= 0 && bounds[covered] <= ways[j]) { + --covered; + } + + add[covered + 1] += d[u][j]; + if (add[covered + 1] >= P) { + add[covered + 1] -= P; + } + + for (int k = covered; k >= 0; --k) { + int right = min(bounds[k], ways[j]); + int left = k == m - 1 ? 1 : bounds[k + 1] + 1; + + if (left <= right) { + d[v][k] += (long long)(d[u][j]) * (long long)(right - left + 1) % (long long)(P); + if (d[v][k] >= P) { + d[v][k] -= P; + } + } else { + break; + } + } + } + + for (int j = 1; j < m; ++j) { + add[j] += add[j - 1]; + if (add[j] >= P) { + add[j] -= P; + } + } + + for (int j = 0; j < m; ++j) { + int right = bounds[j]; + int left = j == m - 1 ? 1 : bounds[j + 1] + 1; + d[v][j] += (long long)(add[j]) * (long long)(right - left + 1) % (long long)(P); + if (d[v][j] >= P) { + d[v][j] -= P; + } + } + } + + long long res = 0; + for (int i = 0; i < m; ++i) { + res += d[u][i]; + } + + cout << res % P << endl; + + return 0; +} +``` +",not-set,2016-04-24T02:02:36,2016-07-23T15:27:56,C++ +53,2301,manasa-and-factorials,Manasa and Factorials," + + +Manasa was sulking her way through a boring class when suddenly her teacher singled her out and asked her a question. He gave her a number **n** and Manasa has to come up with the smallest number **m** which contains atleast **n** number of zeros at the end of **m!**. Help Manasa come out of the sticky situation. + +**Input Format** +The first line contains an integer _T_ i.e. the number of Test cases. +Next T lines will contain an integer n. + +**Output Format** +Print smallest such number m. + +**Constraints** +1 ≤ _T_ ≤ 100
+1 ≤ _n_ ≤ 1016 + +**Sample Input** + + 3 + 1 + 2 + 3 + + +**Sample Output** + + 5 + 10 + 15 + + +**Explanation** + +1. As 4! = 24 and 5! = 120, so minimum value of m will be 5. +2. As 9! = 362880 and 10! = 3628800, so minimum value of m will be 10. +3. As 14! = 87178291200 and 15! = 1307674368000, so minimum value of m will be 15.",code,Think about number of zeros in k!,ai,2014-04-04T20:18:51,2022-09-02T09:54:31,"# +# Complete the 'solve' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts LONG_INTEGER n as parameter. +# + +def solve(n): + # 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): + n = int(input().strip()) + + result = solve(n) + + fptr.write(str(result) + '\n') + + fptr.close() +"," + + +Manasa was sulking her way through a boring class when suddenly her teacher singled her out and asked her a question. He gave her a number **n** and Manasa has to come up with the smallest number **m** which contains atleast **n** number of zeros at the end of **m!**. Help Manasa come out of the sticky situation. + +**Input Format** +The first line contains an integer _T_ i.e. the number of Test cases. +Next T lines will contain an integer n. + +**Output Format** +Print smallest such number m. + +**Constraints** +1 ≤ _T_ ≤ 100
+1 ≤ _n_ ≤ 1016 + +**Sample Input** + + 3 + 1 + 2 + 3 + + +**Sample Output** + + 5 + 10 + 15 + + +**Explanation** + +1. As 4! = 24 and 5! = 120, so minimum value of m will be 5. +2. As 9! = 362880 and 10! = 3628800, so minimum value of m will be 10. +3. As 14! = 87178291200 and 15! = 1307674368000, so minimum value of m will be 15.",0.4872727272727272,"[""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,,,,,,"{""contest_participation"":1581,""challenge_submissions"":287,""successful_submissions"":188}",2014-04-29T17:15:38,2016-12-02T22:59:21,setter,"###C++ +```cpp +// Author Amit Pandey +#include + +using namespace std; + +bool check(long long int p, long long int n) +{ + long long int temp = p , outp =0, five = 5; + while(five < temp) + { + outp += temp/five; + five = five*5; + // cout<= n) + return true; + else + return false; +} + +int main() +{ + int t; + cin>>t; + while(t--) + { + long long int n; + cin>>n; + if(n==1) + { + cout<<""5""< +1 ≤ _n_ ≤ 1016 + +**Sample Input** + + 3 + 1 + 2 + 3 + + +**Sample Output** + + 5 + 10 + 15 + + +**Explanation** + +1. As 4! = 24 and 5! = 120, so minimum value of m will be 5. +2. As 9! = 362880 and 10! = 3628800, so minimum value of m will be 10. +3. As 14! = 87178291200 and 15! = 1307674368000, so minimum value of m will be 15.",code,Think about number of zeros in k!,ai,2014-04-04T20:18:51,2022-09-02T09:54:31,"# +# Complete the 'solve' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts LONG_INTEGER n as parameter. +# + +def solve(n): + # 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): + n = int(input().strip()) + + result = solve(n) + + fptr.write(str(result) + '\n') + + fptr.close() +"," + + +Manasa was sulking her way through a boring class when suddenly her teacher singled her out and asked her a question. He gave her a number **n** and Manasa has to come up with the smallest number **m** which contains atleast **n** number of zeros at the end of **m!**. Help Manasa come out of the sticky situation. + +**Input Format** +The first line contains an integer _T_ i.e. the number of Test cases. +Next T lines will contain an integer n. + +**Output Format** +Print smallest such number m. + +**Constraints** +1 ≤ _T_ ≤ 100
+1 ≤ _n_ ≤ 1016 + +**Sample Input** + + 3 + 1 + 2 + 3 + + +**Sample Output** + + 5 + 10 + 15 + + +**Explanation** + +1. As 4! = 24 and 5! = 120, so minimum value of m will be 5. +2. As 9! = 362880 and 10! = 3628800, so minimum value of m will be 10. +3. As 14! = 87178291200 and 15! = 1307674368000, so minimum value of m will be 15.",0.4872727272727272,"[""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,,,,,,"{""contest_participation"":1581,""challenge_submissions"":287,""successful_submissions"":188}",2014-04-29T17:15:38,2016-12-02T22:59:21,tester,"###Python 2 +```python +def pcount(p, n): + ''' the number of factors p of n! (where p is prime) ''' + if n < p: + return 0 + return n / p + pcount(p, n / p) + +def f(n): + ''' Least m such that m! has n trailing zeroes ''' + L, R = 0, 5*n + while R - L > 1: + M = L + R >> 1 + if pcount(5, M) < n: + L = M + else: + R = M + return R + +z = input() +assert 1 <= z <= 100 +for cas in xrange(z): + n = input() + assert 1 <= n <= 10**16 + print f(n) +``` +",not-set,2016-04-24T02:02:37,2016-07-23T17:34:26,Python +55,2298,courier-rank,Courier Rank,"CourierRank is a very famous and well established company in the market and well known for transporting products with minimum cost for their customers. Your friend chandu works at CourierRank and is facing a problem these days. You being an excellent programmer and his friend. He asks you to help him with the problem. + +Problem requires to deliver N couriers(Assume each courier to be identical) to N locations in the city with two kinds of delivery options: + +- A Big Truck: It can carry any number of boxes to any location in the city for cost L dollars. +- A Small Car: It costs R dollars for delivering 1 box to a location 1 unit away. + +For the sake of simplicity, Let us assume that: +1) The whole city is located on a single straight road. +2) The distance between consecutive cities is 1 unit. +3) All the couriers are placed exactly 1 unit distance before the first location. + +Help your friend chandu, Finding the minimum cost for delivering the couriers. + +**Input** +First line of input contains three integers N,L,R seperated by space, Where N is the number of Boxes, L and R are as described above. +Second line of input contains N integers seperated by space which are the locations where ith box needs to be couriered. + +**Output** +Output contains a single integer, which the minimum possible cost(in dollars) for delivering all the boxes to their respective locations. + +**Constraints** +1<=N<=100 +1<=L,R<=100000 +1<=location of box <= 10^6 + +**Sample Input** + + 5 82456 74095 + 761 685761 43 138742 8650 + +**Sample Output** + + 412280",code,,ai,2014-04-03T22:55:02,2016-09-09T09:42:08,,,,"CourierRank is a very famous and well established company in the market and well known for transporting products with minimum cost for their customers. Your friend chandu works at CourierRank and is facing a problem these days. You being an excellent programmer and his friend. He asks you to help him with the problem. + +Problem requires to deliver N couriers(Assume each courier to be identical) to N locations in the city with two kinds of delivery options: + +- A Big Truck: It can carry any number of boxes to any location in the city for cost L dollars. +- A Small Car: It costs R dollars for delivering 1 box to a location 1 unit away. + +For the sake of simplicity, Let us assume that: +1) The whole city is located on a single straight road. +2) The distance between consecutive cities is 1 unit. +3) All the couriers are placed exactly 1 unit distance before the first location. + +Help your friend chandu, Finding the minimum cost for delivering the couriers. + +**Input** +First line of input contains three integers N,L,R seperated by space, Where N is the number of Boxes, L and R are as described above. +Second line of input contains N integers seperated by space which are the locations where ith box needs to be couriered. + +**Output** +Output contains a single integer, which the minimum possible cost(in dollars) for delivering all the boxes to their respective locations. + +**Constraints** +1<=N<=100 +1<=L,R<=100000 +1<=location of box <= 10^6 + +**Sample Input** + + 5 82456 74095 + 761 685761 43 138742 8650 + +**Sample Output** + + 412280",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-05-01T07:27:59,2016-05-13T00:02:45,setter,"#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// STL +#define pb push_back +#define LL long long +#define ULL unsigned long long +#define L long +#define VCTP vector > +#define PII pair +#define PDD pair +#define F first +#define S second + + +// Useful constants +#define INF (int)1e9 +#define EPS 1e-9 + +// Useful hardware instructions +#define bitcount __builtin_popcount +#define gcd __gcd + +// Useful container manipulation / traversal macros +#define forall(i,a,b) for(int i=a;i (b) ? (a) : (b)) +#define miN(a,b) ( (a) < (b) ? (a) : (b)) +#define checkbit(n,b) ( (n >> b) & 1) +#define DREP(a) sort(all(a)); a.erase(unique(all(a)),a.end()) +#define INDEX(arr,ind) (lower_bound(all(arr),ind)-arr.begin()) + + + +#define st_clk double st=clock(); +#define end_clk double en=clock(); +#define show_time cout<<""\tTIME=""<<(en-st)/CLOCKS_PER_SEC< '9')) c = gc(); + if(c == '-') f = -1, c = gc(); + while(c >= '0' && c <= '9') + n = (n<<3) + (n<<1) + c - '0', c = gc(); + return n * f; +} + +/* +Problem can be solved using Dynamic programming. Solution is based on a tricky observation that optimal solution won't ever use truck to deliver +courier to a location where no courier is destined to be. +Reason: Let us say many couriers are taken by truck to position i and none of it was actually destined for there. let x be the couriers that should be moved +forward for their destined location and y be the couriers which should be moved backward for their destined location. +Case I: x > y, then we can use truck to deliver at location i+1 for more optimal result. +Case II: y > x, then we can use truck to deliver at location i-1 for more optimal result. +case III: x == y, then we can use truck to deliver at any of the two locations for more optimal result. +*/ + +long long dp[102][102]; + +int findcost(vector bb,int tc,int _lc){ + int n = bb.size(); + long long ans = 0; + long long lc = _lc; + for(int i=0;i boxes; + for(int i=0;i9+7_). + +**Input Format** +First line contains _T_, the number of test cases. +Each test case consists of _N_ and _M_ separated by a space. + +**Output Format** +For each test case, print the answer modulo (_109+7_). + +**Constraints** +1 ≤ T ≤ 200 +1 ≤ N,M ≤ 1000 + +**Sample Input** + + 2 + 1 1 + 2 3 + +**Sample Output** + + 1 + 6 + +**Explanation** +Test1: Out of all unique permutations ie. `01` and `10`, only second permutation satisfies. Hence, output is 1. +Test2: Out of all unique permutations ie. `00111 01011 01101 01110 10011 10101 10110 11001 11010 11100`, only `10011 10101 10110 11001 11010 11100` satisfy. Hence, output is 6.",code,Help Sherlock in counting permutations.,ai,2014-05-01T14:02:20,2022-09-02T09:54:12,"# +# 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() +","Watson asks Sherlock: +Given a string _S_ of _N_ `0's` and _M_ `1's`, how many unique permutations of this string start with `1`? + +Help Sherlock by printing the answer modulo (_109+7_). + +**Input Format** +First line contains _T_, the number of test cases. +Each test case consists of _N_ and _M_ separated by a space. + +**Output Format** +For each test case, print the answer modulo (_109+7_). + +**Constraints** +1 ≤ T ≤ 200 +1 ≤ N,M ≤ 1000 + +**Sample Input** + + 2 + 1 1 + 2 3 + +**Sample Output** + + 1 + 6 + +**Explanation** +Test1: Out of all unique permutations ie. `01` and `10`, only second permutation satisfies. Hence, output is 1. +Test2: Out of all unique permutations ie. `00111 01011 01101 01110 10011 10101 10110 11001 11010 11100`, only `10011 10101 10110 11001 11010 11100` satisfy. Hence, output is 6.",0.5980861244019139,"[""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,,,,,,"{""contest_participation"":922,""challenge_submissions"":417,""successful_submissions"":322}",2014-05-21T08:40:53,2016-12-02T15:01:16,setter,"###C++ +```cpp +//Language: C++ +//Author: darkshadows(Lalit Kundu) + +#include +#define assn(n,a,b) assert(n<=b && n>=a) +using namespace std; +typedef long long LL; +#define MOD 1000000007 +#define MAX 1000033 +LL mpow(LL a, LL n) +{ + LL ret=1; + LL b=a; + while(n) + { + if(n&1)ret=(ret*b)%MOD; + b=(b*b)%MOD; + n>>=1; + } + return (LL)ret; +} +LL fac[MAX],inv[MAX]; +void precalc() +{ + LL i; + fac[0]=1; + inv[0]=1; + fac[1]=1; + inv[1]=1; + for(i=2; i> t; + assn(t,1,200); + while(t--) + { + LL n,m,t=1ll,ans=1ll; + cin >> m >> n; + assn(n,1,1000); + assn(m,1,1000); + n--; + m+=n; + cout << choose(m,n) << endl; + } + return 0; +} +``` +",not-set,2016-04-24T02:02:39,2016-07-23T16:31:46,C++ +57,2475,sherlock-and-permutations,Sherlock and Permutations," + +Watson asks Sherlock: +Given a string _S_ of _N_ `0's` and _M_ `1's`, how many unique permutations of this string start with `1`? + +Help Sherlock by printing the answer modulo (_109+7_). + +**Input Format** +First line contains _T_, the number of test cases. +Each test case consists of _N_ and _M_ separated by a space. + +**Output Format** +For each test case, print the answer modulo (_109+7_). + +**Constraints** +1 ≤ T ≤ 200 +1 ≤ N,M ≤ 1000 + +**Sample Input** + + 2 + 1 1 + 2 3 + +**Sample Output** + + 1 + 6 + +**Explanation** +Test1: Out of all unique permutations ie. `01` and `10`, only second permutation satisfies. Hence, output is 1. +Test2: Out of all unique permutations ie. `00111 01011 01101 01110 10011 10101 10110 11001 11010 11100`, only `10011 10101 10110 11001 11010 11100` satisfy. Hence, output is 6.",code,Help Sherlock in counting permutations.,ai,2014-05-01T14:02:20,2022-09-02T09:54:12,"# +# 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() +","Watson asks Sherlock: +Given a string _S_ of _N_ `0's` and _M_ `1's`, how many unique permutations of this string start with `1`? + +Help Sherlock by printing the answer modulo (_109+7_). + +**Input Format** +First line contains _T_, the number of test cases. +Each test case consists of _N_ and _M_ separated by a space. + +**Output Format** +For each test case, print the answer modulo (_109+7_). + +**Constraints** +1 ≤ T ≤ 200 +1 ≤ N,M ≤ 1000 + +**Sample Input** + + 2 + 1 1 + 2 3 + +**Sample Output** + + 1 + 6 + +**Explanation** +Test1: Out of all unique permutations ie. `01` and `10`, only second permutation satisfies. Hence, output is 1. +Test2: Out of all unique permutations ie. `00111 01011 01101 01110 10011 10101 10110 11001 11010 11100`, only `10011 10101 10110 11001 11010 11100` satisfy. Hence, output is 6.",0.5980861244019139,"[""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,,,,,,"{""contest_participation"":922,""challenge_submissions"":417,""successful_submissions"":322}",2014-05-21T08:40:53,2016-12-02T15:01:16,tester,"###C++ +```cpp +//Language: C++ +//Author: xorfire(R Goutham) + +#include +#include +int mod = 1000000007, comb[2001][2001]; +int main() +{ + // Computing Binomial coefficients + for (int i = 0; i <= 2000; i++) + { + comb[i][0] = comb[i][i] = 1; + for (int j = 1; j < i; j++) + { + comb[i][j] = comb[i-1][j] + comb[i-1][j-1]; + if (comb[i][j] >= mod) comb[i][j] -= mod; + } + } + int t; scanf(""%d"", &t); + while (t--) + { + int n, m; scanf(""%d%d"", &n, &m); + assert(1 <= n and 1 <= m and n + m - 1 <= 2000); + printf(""%d\n"", comb[n + m - 1][n]); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:39,2016-07-23T16:32:55,C++ +58,2462,gcd-product,GCD Product,"[Russian](https://hr-filepicker.s3.amazonaws.com/w3/russian/2462-gcd-product.pdf)
+ + +This time your assignment is really simple. + +Calculate GCD(1, 1) * GCD(1, 2) * ... * GCD(1, M) * GCD(2, 1) * GCD(2, 2) * ... * GCD(2, M) * ... * GCD(N, 1) * GCD(N, 2) * ... * GCD(N, M). + +where GCD is defined as the [Greatest Common Divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). + +**Input Format** + +The first and only line contains two space separated integers *N* and *M*. + +**Output Format** + +Output the required product modulo 109+7. + +**Constraints** + +1 <= *N*, *M* <= 1.5 * 107 + +**Sample input:** + +
4 4
+ +**Sample output:** + +
96
+ +**Explanation** + +For the above testcase, N = 4, M = 4. So, + +GCD(1, 1) * GCD(1, 2) * ...... * GCD(4, 4) = 1 * 1 * 1 * 1 * 1 * 2 * 1 * 2 * 1 * 1 * 3 * 1 * 1 * 2 * 1 * 4 = 96. + +",code,Find the product of the Greatest Common Divisors for all the pairs inside a rectangle.,ai,2014-04-29T10:32:28,2022-09-02T09:54:44,"# +# 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') + + 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() +","This time your assignment is really simple. + +Calculate GCD(1, 1) * GCD(1, 2) * ... * GCD(1, M) * GCD(2, 1) * GCD(2, 2) * ... * GCD(2, M) * ... * GCD(N, 1) * GCD(N, 2) * ... * GCD(N, M). + +where GCD is defined as the [Greatest Common Divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). + +**Input Format** + +The first and only line contains two space separated integers *N* and *M*. + +**Output Format** + +Output the required product modulo 109+7. + +**Constraints** + +1 <= *N*, *M* <= 1.5 * 107 + +**Sample input:** + +
4 4
+ +**Sample output:** + +
96
+ +**Explanation** + +For the above testcase, N = 4, M = 4. So, + +GCD(1, 1) * GCD(1, 2) * ...... * GCD(4, 4) = 1 * 1 * 1 * 1 * 1 * 2 * 1 * 2 * 1 * 1 * 3 * 1 * 1 * 2 * 1 * 4 = 96. + +",0.4261363636363636,"[""c"",""clojure"",""cobol"",""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,,,,,,"{""contest_participation"":1475,""challenge_submissions"":236,""successful_submissions"":103}",2014-05-26T14:49:21,2016-12-08T09:25:32,setter,"###C++ +```cpp +#include +#include +using namespace std; + +#define maxn 15000000 + 5 +#define mod 1000000007 +#define tm Tm + +int n, m, i, j, p[maxn], dp[maxn], sf[maxn], sfn, g, tn, tm, ret, pref[maxn], l, c, p1, p2, r, carry; +long long sfm[maxn], t; + +int pw (int x, long long p) { + if (!p) return 1; + if (p == 1) return x; + int q = pw(x, p >> 1); + q = (1LL * q * q) % mod; + if (p & 1) q = (1LL * q * x) % mod; + return q; +} + +int main (int argc, char * const argv[]) { + scanf(""%d %d"", &n, &m); + if (n < m) swap(n, m); + for(i = 2; i <= n; i++) if (p[i] == 0) { + j = i; + while (j <= n) { + if (!p[j]) p[j] = i; + j += i; + } + } + for(i = 2; i <= n; i++) { + if (i == p[i]) dp[i] = -1; else + if (p[(i / p[i])] == p[i]) dp[i] = 0; else dp[i] = -1 * dp[i / p[i]]; + pref[i] = pref[i - 1] + dp[i]; + } + for(i = 1; i <= n; i++) if (dp[i] != 0) { + sf[++sfn] = i; + sfm[sfn] = dp[i]; + } + sf[sfn + 1] = m + 1; + ret = 1; + carry = 1, t = 1, tn = tm = -1; + for(g = 2; g <= m; g++) { + if (n / g != tn || m / g != tm) { + ret = (ret * 1LL * pw(carry, t)) % mod; + carry = 1LL; + } else { + carry = (carry * 1LL * g) % mod; + continue; + } + tn = n / g; + tm = m / g; + t = 1LL * tn * tm; + if (g <= 600000) { + l = 1; + while (l <= tm) { + ++c; + r = min(min(tn / (p1 = tn / l), tm / (p2 = tm / l)), tm); + t += p1 * 1LL * p2 * (pref[r] - pref[l - 1]); + l = r + 1; + } + } else for(i = 1; sf[i] <= tm; i++) t += sfm[i] * (tn / sf[i]) * (tm / sf[i]); + carry = (1LL * carry * g) % mod; + } + ret = (ret * 1LL * pw(carry, t)) % mod; + printf(""%d\n"", ret); + return 0; +} +``` +",not-set,2016-04-24T02:02:39,2016-07-23T18:25:31,C++ +59,2462,gcd-product,GCD Product,"[Russian](https://hr-filepicker.s3.amazonaws.com/w3/russian/2462-gcd-product.pdf)
+ + +This time your assignment is really simple. + +Calculate GCD(1, 1) * GCD(1, 2) * ... * GCD(1, M) * GCD(2, 1) * GCD(2, 2) * ... * GCD(2, M) * ... * GCD(N, 1) * GCD(N, 2) * ... * GCD(N, M). + +where GCD is defined as the [Greatest Common Divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). + +**Input Format** + +The first and only line contains two space separated integers *N* and *M*. + +**Output Format** + +Output the required product modulo 109+7. + +**Constraints** + +1 <= *N*, *M* <= 1.5 * 107 + +**Sample input:** + +
4 4
+ +**Sample output:** + +
96
+ +**Explanation** + +For the above testcase, N = 4, M = 4. So, + +GCD(1, 1) * GCD(1, 2) * ...... * GCD(4, 4) = 1 * 1 * 1 * 1 * 1 * 2 * 1 * 2 * 1 * 1 * 3 * 1 * 1 * 2 * 1 * 4 = 96. + +",code,Find the product of the Greatest Common Divisors for all the pairs inside a rectangle.,ai,2014-04-29T10:32:28,2022-09-02T09:54:44,"# +# 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') + + 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() +","This time your assignment is really simple. + +Calculate GCD(1, 1) * GCD(1, 2) * ... * GCD(1, M) * GCD(2, 1) * GCD(2, 2) * ... * GCD(2, M) * ... * GCD(N, 1) * GCD(N, 2) * ... * GCD(N, M). + +where GCD is defined as the [Greatest Common Divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). + +**Input Format** + +The first and only line contains two space separated integers *N* and *M*. + +**Output Format** + +Output the required product modulo 109+7. + +**Constraints** + +1 <= *N*, *M* <= 1.5 * 107 + +**Sample input:** + +
4 4
+ +**Sample output:** + +
96
+ +**Explanation** + +For the above testcase, N = 4, M = 4. So, + +GCD(1, 1) * GCD(1, 2) * ...... * GCD(4, 4) = 1 * 1 * 1 * 1 * 1 * 2 * 1 * 2 * 1 * 1 * 3 * 1 * 1 * 2 * 1 * 4 = 96. + +",0.4261363636363636,"[""c"",""clojure"",""cobol"",""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,,,,,,"{""contest_participation"":1475,""challenge_submissions"":236,""successful_submissions"":103}",2014-05-26T14:49:21,2016-12-08T09:25:32,tester,"###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 vector VI; +typedef vector VL; +typedef vector VPII; +#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 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 ostream& operator<<(ostream &o, pair t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;} +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;} +const int inf = 0x3f3f3f3f; +const long long linf = 0x3f3f3f3f3f3f3f3fLL; +const int mod = int(1e9) + 7; +const int N = 15111111; + +int n, m; + +int F[N]; + +inline LL exp(LL x, LL n, LL m = mod) { + LL r = 1; + while(n) { + if(n & 1) r = r * x % m; + x = x * x % m, n >>= 1; + } + return r; +} + +int main() { + cin >> n >> m; + if(n > m) swap(n, m); + + time_t t1 = clock(); + for(int i = 1; i < N; i++) F[i] = (LL)(n / i) * (m / i) % (mod - 1); + + for(int i = n; i >= 1; i--) + for(int j = i + i; j <= n; j += i) { + F[i] -= F[j]; + if(F[i] < 0) F[i] += mod - 1; + } + + int res = 1; + for(int i = 1; i <= n; i++) res = res * exp(i, F[i]) % mod; + cout << res << endl; + + /* + { + int br = 1; + for(int i = 1; i <= n; i++) + for(int j = 1; j <= m; j++) + br = (LL) br * __gcd(i, j) % mod; + cout << br << endl; + assert(br == res); + } + */ + + time_t t2 = clock(); + TM(t1, t2); + + return 0; +} +``` +",not-set,2016-04-24T02:02:39,2016-07-23T18:25:38,C++ +60,2560,palindrome-test,Palindrome Test,"Palindrome blablabla +Ecrire programme blabla langage blabla +Verifier chaine blabla. + +Entrée : +la chaine (String) +Sortie : +booléen",code,Vérifier que le mot est un palindrome,ai,2014-05-28T11:15:53,2016-09-09T09:43:55,,,,"Palindrome blablabla +Ecrire programme blabla langage blabla +Verifier chaine blabla. + +Entrée : +la chaine (String) +Sortie : +booléen",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-05-28T11:40:26,2016-05-13T00:02:19,setter,hello,not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,Unknown +61,2560,palindrome-test,Palindrome Test,"Palindrome blablabla +Ecrire programme blabla langage blabla +Verifier chaine blabla. + +Entrée : +la chaine (String) +Sortie : +booléen",code,Vérifier que le mot est un palindrome,ai,2014-05-28T11:15:53,2016-09-09T09:43:55,,,,"Palindrome blablabla +Ecrire programme blabla langage blabla +Verifier chaine blabla. + +Entrée : +la chaine (String) +Sortie : +booléen",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-05-28T11:40:26,2016-05-13T00:02:19,tester,Hello tester,not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,Unknown +62,2491,sherlock-and-minimax,Sherlock and MiniMax,"[Русский](https://hr-filepicker.s3.amazonaws.com/101may14/russian/2491-sherlock-and-minimax.pdf) \| +[中文](https://hr-filepicker.s3.amazonaws.com/101may14/chinese/2491-sherlock-and-minimax.pdf)
+Watson gives Sherlock an array _A1,A2...AN_. +He asks him to find an integer _M_ between _P_ and _Q_(both inclusive), such that, _min {|Ai-M|, 1 ≤ i ≤ N}_ is maximised. If there are multiple solutions, print the smallest one. + +**Input Format** +The first line contains _N_. The next line contains space separated _N_ integers, and denote the array _A_. The third line contains two space separated integers denoting _P_ and _Q_. + +**Output Format** +In one line, print the required answer. + +**Constraints** +1 ≤ N ≤ 102 +1 ≤ Ai ≤ 109 +1 ≤ P ≤ Q ≤ 109 + +**Sample Input** + + 3 + 5 8 14 + 4 9 + +**Sample Output** + + 4 + +**Explanation** +For M = 4,6,7, or 9, the result is 1. Since we have to output the smallest of the multiple solutions, we print 4.",code,"Watson gives Sherlock an array A1,A2...AN. Find an integer M + between P and Q(both inclusive), satistying a condition.",ai,2014-05-06T18:57:55,2022-08-31T08:14:38,"# +# Complete the 'sherlockAndMinimax' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER_ARRAY arr +# 2. INTEGER p +# 3. INTEGER q +# + +def sherlockAndMinimax(arr, p, q): + # 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()) + + arr = list(map(int, input().rstrip().split())) + + first_multiple_input = input().rstrip().split() + + p = int(first_multiple_input[0]) + + q = int(first_multiple_input[1]) + + result = sherlockAndMinimax(arr, p, q) + + fptr.write(str(result) + '\n') + + fptr.close() +","Watson gives Sherlock an array of integers. Given the endpoints of an integer range, for all $M$ in that inclusive range, determine the minimum( abs(arr[i]-M) for all $1 \le i \le |arr|$) ). Once that has been determined for all integers in the range, return the $M$ which generated the maximum of those values. If there are multiple $M$'s that result in that value, return the lowest one. + +For example, your array $arr = [3,5,7,9]$ and your range is from $p=6$ to $q=8$ inclusive. +``` +M |arr[1]-M| |arr[2]-M| |arr[3]-M| |arr[4]-M| Min +6 3 1 1 3 1 +7 4 2 0 2 0 +8 5 3 1 1 1 +``` +We look at the `Min` column and see the maximum of those three values is $1$. Two $M$'s result in that answer so we choose the lower value, $6$. + +**Function Description** + +Complete the *sherlockAndMinimax* function in the editor below. It should return an integer as described. + +sherlockAndMinimax has the following parameters: +- *arr*: an array of integers +- *p*: an integer that represents the lowest value of the range for $M$ +- *q*: an integer that represents the highest value of the range for $M$ ",0.5414364640883977,"[""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""]","The first line contains an integer $n$, the number of elements in $arr$. +The next line contains $n$ space-separated integers $arr[i]$. +The third line contains two space-separated integers $p$ and $q$, the inclusive endpoints for the range of $M$. +",Print the value of $M$ on a line.," 3 + 5 8 14 + 4 9 +"," 4 +",Hard,,,,,,"{""contest_participation"":1164,""challenge_submissions"":299,""successful_submissions"":128}",2014-05-30T22:31:21,2018-04-17T13:18:01,setter,"###C++ +```cpp +#include +using namespace std; +int n; +int arr[109]; +int A, B; +int answer; + +//returns the value to be maximised if M=x +int check( int x ) +{ + int ret = INT_MAX; + for( int i = 0; i < n; ++i ) + ret =min(ret, abs( x- arr[i] )); + return ret; +} + +// check is x is within limits and if check(x) is better store the answer +void limits( int x ) +{ + if( x < A || x > B ) return; + if(check(x) > check(answer)) answer = x; +} + +int main() +{ + scanf( ""%d"", &n ); + for( int i = 0; i < n; ++i ) scanf( ""%d"", &arr[i] ); + scanf( ""%d%d"", &A, &B ); + + answer = A; + + // check for A and B + limits( A ); + limits( B ); + + for( int i = 0; i < n; ++i ) + for( int j = i+1; j < n; ++j ) + { + // check for (A_i + A_j)/2 + limits( (arr[i]+arr[j])/2 ); + } + + printf( ""%d\n"",answer ); + + return 0; +} +``` +",not-set,2016-04-24T02:02:40,2016-07-23T14:21:41,C++ +63,2491,sherlock-and-minimax,Sherlock and MiniMax,"[Русский](https://hr-filepicker.s3.amazonaws.com/101may14/russian/2491-sherlock-and-minimax.pdf) \| +[中文](https://hr-filepicker.s3.amazonaws.com/101may14/chinese/2491-sherlock-and-minimax.pdf)
+Watson gives Sherlock an array _A1,A2...AN_. +He asks him to find an integer _M_ between _P_ and _Q_(both inclusive), such that, _min {|Ai-M|, 1 ≤ i ≤ N}_ is maximised. If there are multiple solutions, print the smallest one. + +**Input Format** +The first line contains _N_. The next line contains space separated _N_ integers, and denote the array _A_. The third line contains two space separated integers denoting _P_ and _Q_. + +**Output Format** +In one line, print the required answer. + +**Constraints** +1 ≤ N ≤ 102 +1 ≤ Ai ≤ 109 +1 ≤ P ≤ Q ≤ 109 + +**Sample Input** + + 3 + 5 8 14 + 4 9 + +**Sample Output** + + 4 + +**Explanation** +For M = 4,6,7, or 9, the result is 1. Since we have to output the smallest of the multiple solutions, we print 4.",code,"Watson gives Sherlock an array A1,A2...AN. Find an integer M + between P and Q(both inclusive), satistying a condition.",ai,2014-05-06T18:57:55,2022-08-31T08:14:38,"# +# Complete the 'sherlockAndMinimax' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER_ARRAY arr +# 2. INTEGER p +# 3. INTEGER q +# + +def sherlockAndMinimax(arr, p, q): + # 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()) + + arr = list(map(int, input().rstrip().split())) + + first_multiple_input = input().rstrip().split() + + p = int(first_multiple_input[0]) + + q = int(first_multiple_input[1]) + + result = sherlockAndMinimax(arr, p, q) + + fptr.write(str(result) + '\n') + + fptr.close() +","Watson gives Sherlock an array of integers. Given the endpoints of an integer range, for all $M$ in that inclusive range, determine the minimum( abs(arr[i]-M) for all $1 \le i \le |arr|$) ). Once that has been determined for all integers in the range, return the $M$ which generated the maximum of those values. If there are multiple $M$'s that result in that value, return the lowest one. + +For example, your array $arr = [3,5,7,9]$ and your range is from $p=6$ to $q=8$ inclusive. +``` +M |arr[1]-M| |arr[2]-M| |arr[3]-M| |arr[4]-M| Min +6 3 1 1 3 1 +7 4 2 0 2 0 +8 5 3 1 1 1 +``` +We look at the `Min` column and see the maximum of those three values is $1$. Two $M$'s result in that answer so we choose the lower value, $6$. + +**Function Description** + +Complete the *sherlockAndMinimax* function in the editor below. It should return an integer as described. + +sherlockAndMinimax has the following parameters: +- *arr*: an array of integers +- *p*: an integer that represents the lowest value of the range for $M$ +- *q*: an integer that represents the highest value of the range for $M$ ",0.5414364640883977,"[""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""]","The first line contains an integer $n$, the number of elements in $arr$. +The next line contains $n$ space-separated integers $arr[i]$. +The third line contains two space-separated integers $p$ and $q$, the inclusive endpoints for the range of $M$. +",Print the value of $M$ on a line.," 3 + 5 8 14 + 4 9 +"," 4 +",Hard,,,,,,"{""contest_participation"":1164,""challenge_submissions"":299,""successful_submissions"":128}",2014-05-30T22:31:21,2018-04-17T13:18:01,tester,"###C++ +```cpp +//C++ Code +Author Gerald +#ifdef ssu1 +#define _GLIBCXX_DEBUG +#endif +#undef NDEBUG + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define fore(i, l, r) for(int i = (l); i < (r); ++i) +#define forn(i, n) fore(i, 0, n) +#define fori(i, l, r) fore(i, l, (r) + 1) +#define sz(v) int((v).size()) +#define all(v) (v).begin(), (v).end() +#define pb push_back +#define mp make_pair +#define X first +#define Y second + +#if ( _WIN32 || __WIN32__ ) + #define LLD ""%I64d"" +#else + #define LLD ""%lld"" +#endif + +typedef long long li; +typedef long double ld; +typedef pair pt; + +template T abs(T a) { return a < 0 ? -a : a; } +template T sqr(T a) { return a*a; } + +const int INF = (int)1e9; +const ld EPS = 1e-9; +const ld PI = 3.1415926535897932384626433832795; + +int readInt(int l, int r){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int in range [%d, %d], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int in range [%d, %d], but found %d!"", l, r, x); + throw; + } + return x; +} + +int f(const vector& a, int m){ + int mn = (int)2e9; + forn(i, sz(a)){ + mn = min(mn, abs(a[i] - m)); + } + return mn; +} + +int main(){ +#ifdef ssu1 + assert(freopen(""input.txt"", ""rt"", stdin)); + //assert(freopen(""output.txt"", ""wt"", stdout)); +#endif + + int n, p, q; + n = readInt(1, 100); + vector a(n); + forn(i, n) + a[i] = readInt(1, 1000000000); + p = readInt(1, 1000000000); + q = readInt(1, 1000000000); + assert(p <= q); + + vector pat; + pat.pb(p); + pat.pb(q); + forn(i, n){ + forn(j, n){ + int x = (a[i] + a[j]) / 2; + fori(y, x - 1, x + 1){ + if(p <= y && y <= q) + pat.pb(y); + } + } + } + + sort(all(pat)); + + int curmx = -1, m = -1; + forn(i, sz(pat)){ + if(f(a, pat[i]) > curmx){ + curmx = f(a, pat[i]); + m = pat[i]; + } + } + printf(""%d\n"", m); + return 0; +} +```",not-set,2016-04-24T02:02:40,2016-07-23T14:24:58,C++ +64,2413,roy-and-alpha-beta-trees,Roy and alpha-beta trees,"[Russian](https://hr-filepicker.s3.amazonaws.com/w4/russian/2413-roy-and-alpha-beta-trees.pdf)
+ + +Roy has taken a liking to the [Binary Search Trees](https://en.wikipedia.org/wiki/Binary_search_tree)(*BST*). He is interested in knowing the number of ways an array *A* of *N* integers can be arranged to form a *BST*. Thus, he tries a few combinations, and notes down the numbers at the odd levels and the numbers at the even levels. + +You're given two values, *alpha* and *beta*. Can you calculate the sum of *Liking* of all possible *BST's* that can be formed from an array of *N* integers? *Liking* of each *BST* is defined as follows + + (sum of numbers on even levels * alpha) - (sum of numbers on odd levels * beta) + + +**Note** + ++ The root element is at level 0 ( Even ) ++ The elements smaller or equal to the parent element are present in the left subtree, elements greater than or equal to the parent element are present in the right subtree. Explained [here](https://www.hackerrank.com/contests/w4/challenges/roy-and-alpha-beta-trees/forum/questions/6070) + +If the answer is no less than 109 + 9, output the answer % 109 + 9. + +**Update** + +If the answer is less than 0, keep adding 109 + 9 until the value turns non negative. + +**Input Format** +The first line of input file contains an integer, *T*, denoting the number of test cases to follow. +Each testcase comprises of 3 lines. +The first line contains _N_, the number of integers. +The second line contains two space separated integers, _alpha_ and _beta_. +The third line contains space separated _N integers_, denoting the *ith* integer in array *A[i]*. + +**Output Format** +Output _T_ lines. Each line contains the answer to its respective test case. + +**Constraints** +1 ≤ *T* ≤ 10 +1 ≤ *N* ≤ 150 +1 ≤ *A[i]* ≤ 109 +1 ≤ *alpha,beta* ≤ 109 + +**Sample Input** + +
+4
+1
+1 1
+1
+2
+1 1
+1 2
+3
+1 1
+1 2 3
+5
+1 1
+1 2 3 4 5
+
+ +**Sample Output** + +
+1
+0
+6
+54
+
+ +**Explanation** + +There are 4 test cases in total. + ++ For the first test case, only 1 BST can be formed with `1` as the root node. Hence the *Liking* / sum is 1. ++ For the second test case, we get 2 BSTs of the form, the *Liking* of the first tree is 1 * 1 - 2 * 1 = -1 and 2 * 1 - 1 * 1 = 1, this sums to 0, hence the answer. + + +
+1                  2 
+ \                /
+  2              1
+
+ ++ For the third test case, we get 5 BSTs. The *Liking* of each of the BST from left to right are 2, -2, 4, 2, 0 which sums to 6 and hence the answer. + +
+1            2                 3          3      1
+ \          / \               /          /        \
+  2        1   3             1          2          3
+   \                          \        /          /
+    3                          2      1          2
+
+ ++ Similarly, for the 4th test case, the answer is 54. ",code,Can you calculate the sum of Liking of all possible BST's that can be formed from an array of N integers.,ai,2014-04-21T11:02:40,2022-09-02T10:00:36,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER alpha +# 2. INTEGER beta +# 3. INTEGER_ARRAY a +# + +def solve(alpha, beta, a): + # 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): + n = int(input().strip()) + + first_multiple_input = input().rstrip().split() + + alpha = int(first_multiple_input[0]) + + beta = int(first_multiple_input[1]) + + a = list(map(int, input().rstrip().split())) + + result = solve(alpha, beta, a) + + fptr.write(str(result) + '\n') + + fptr.close() +","Roy has taken a liking to the [Binary Search Trees](https://en.wikipedia.org/wiki/Binary_search_tree)(*BST*). He is interested in knowing the number of ways an array $A$ of $N$ integers can be arranged to form a *BST*. Thus, he tries a few combinations, and notes down the numbers at the odd levels and the numbers at the even levels. + +You're given two values, *alpha* and *beta*. Can you calculate the sum of *Liking* of all possible *BST's* that can be formed from an array of $N$ integers? *Liking* of each *BST* is defined as follows + + (sum of numbers on even levels * alpha) - (sum of numbers on odd levels * beta) + + +**Note** + ++ The root element is at level $0$ ( Even ) ++ The elements smaller or equal to the parent element are present in the left subtree, elements greater than or equal to the parent element are present in the right subtree. Explained [here](https://www.hackerrank.com/contests/w4/challenges/roy-and-alpha-beta-trees/forum/questions/6070) + +If the answer is no less than $10^9+9$, output the answer % $10^9+9$. + +(If the answer is less than $0$, keep adding $10^9+9$ until the value turns non negative.) + +**Input Format** +The first line of input file contains an integer, $T$, denoting the number of test cases to follow. +Each testcase comprises of $3$ lines. +The first line contains $N$, the number of integers. +The second line contains two space separated integers, _alpha_ and _beta_. +The third line contains space separated $N$ integers_, denoting the $i^{th}$ integer in array $A[i]$. + +**Output Format** +Output $T$ lines. Each line contains the answer to its respective test case. + +**Constraints** + +$1 \le T \le 10$ +$1 \le N \le 150$ +$1 \le A[i] \le 10^9$ +$1 \le alpha,beta \le 10^{9}$ + +**Sample Input** + +
+4
+1
+1 1
+1
+2
+1 1
+1 2
+3
+1 1
+1 2 3
+5
+1 1
+1 2 3 4 5
+
+ +**Sample Output** + +
+1
+0
+6
+54
+
+ +**Explanation** + +There are $4$ test cases in total. + ++ For the first test case, only $1$ BST can be formed with `1` as the root node. Hence the *Liking* / sum is $1$. + ++ For the second test case, we get 2 BSTs of the form, the *Liking* of the first tree is $1 * 1 - 2 * 1 = -1$ and $2 * 1 - 1 * 1 = 1$, this sums to $0$, hence the answer. + + +
+1                  2 
+ \                /
+  2              1
+
+ ++ For the third test case, we get $5$ BSTs. The *Liking* of each of the BST from left to right are $2, -2, 4, 2, 0$ which sums to $6$ and hence the answer. + +
+1            2                 3          3      1
+ \          / \               /          /        \
+  2        1   3             1          2          3
+   \                          \        /          /
+    3                          2      1          2
+
+ ++ Similarly, for the fourth test case, the answer is $54$. ",0.5784313725490197,"[""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,,,,,,"{""contest_participation"":1868,""challenge_submissions"":144,""successful_submissions"":109}",2014-06-01T21:08:38,2016-12-02T07:25:09,setter," + import java.io.*; + import java.util.Arrays; + import java.util.StringTokenizer; + + class ANKBST02_solver { + long go(int lo, int hi, int odd) { + if (lo > hi) { + return 0; + } + if (dp[lo][hi][odd] == -1) { + long ans = 0; + for (int root = lo; root <= hi; root++) { + //consider all BST in left subtree of root + ans += (go(lo, root - 1, 1 -odd) * cnt[hi - root - 1 + 1]) % MOD; + if (ans >= MOD) ans -= MOD; + if (ans < 0) ans += MOD; + //consider all BST in right subtree + ans += (go(root + 1, hi, 1 -odd) * cnt[root - 1 - lo + 1]) % MOD; + if (ans >= MOD) ans -= MOD; + if (ans < 0) ans += MOD; + //totTrees is total number of trees considered + long totTrees = (cnt[hi - root] * cnt[root - lo]) % MOD; + //remember to add the root as many times for each tree + ans += (totTrees * ((mul[odd] * a[root]) % MOD)) % MOD; + if(ans >= MOD) ans -= MOD; + if (ans < 0) ans += MOD; + } + dp[lo][hi][odd] = ans; + } + return dp[lo][hi][odd]; + } + + public void solve() throws IOException { + cnt = generateCatalan(205, MOD); + cnt[0] = 1; + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + PrintWriter pw = new PrintWriter(System.out); + int t = Integer.parseInt(br.readLine()); + + while (t --> 0) { + int n = Integer.parseInt(br.readLine()); + assert(n <= 200); + a = new long[n] ; + mul = new long[2]; + int i = 0; + for (StringTokenizer tokenizer = new StringTokenizer(br.readLine()); tokenizer.hasMoreTokens(); ) { + String s = tokenizer.nextToken(); + mul[i ++] = Integer.parseInt(s); + } + mul[1] = -mul[1]; + i = 0; + for (StringTokenizer tokenizer = new StringTokenizer(br.readLine()); tokenizer.hasMoreTokens(); ) { + String s = tokenizer.nextToken(); + a[i ++] = Integer.parseInt(s); + } + assert(i == n); + Arrays.sort(a); + dp = new long[n][n][2]; + for (int j = 0; j < n; j++) { + for (int k = 0; k < n; k++) { + for (int l = 0; l < 2; l++) { + dp[j][k][l] = -1; + } + } + } + pw.println(go(0, n - 1, 0)); + } + pw.close(); + } + + long[] a; + long[][][] dp; + long[] cnt; + long MOD = (int) (1e9 + 9); + long[] mul; + + public static long[] generateCatalan(int n, long module) { + long[] inv = generateReverse(n + 2, module); + long[] Catalan = new long[n]; + Catalan[1] = 1; + for (int i = 1; i < n - 1; i++) { + Catalan[i + 1] = (((2 * (2 * i + 1) * inv[i + 2]) % module) * Catalan[i]) % module; + } + return Catalan; + } + + public static long[] generateReverse(int upTo, long module) { + long[] result = new long[upTo]; + if (upTo > 1) + result[1] = 1; + for (int i = 2; i < upTo; i++) + result[i] = (module - module / i * result[((int) (module % i))] % module) % module; + return result; + } + } + + public class Solution { + public static void main(String[] args) throws IOException { + new ANKBST02_solver().solve(); + } + } +",not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,Python +65,2212,rooted-tree,Rooted Tree,"[Русский](https://hr-filepicker.s3.amazonaws.com/101may14/russian/2212-rooted_tree.pdf) \| +[中文](https://hr-filepicker.s3.amazonaws.com/101may14/chinese/2212-rooted_tree.pdf)
+You are given a rooted [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with _N_ nodes and the root of the tree, _R_, is also given. Each node of the tree contains a value, that is initially empty. You have to mantain the tree under two operations: + +1. Update Operation +2. Report Operation + +**Update Operation** +Each Update Operation begins with the character `U`. Character `U` is followed by 3 integers _T, V and K_. For every node which is the descendent of the node _T_, update it's value by adding _V + d\*K_, where _V_ and _K_ are the parameters of the query and _d_ is the distance of the node from _T_. Note that _V_ is added to node _T_. + +**Report Operation** +Each Report Operation begins with the character `Q`. Character `Q` is followed by 2 integers, _A_ and _B_. Output the sum of values of nodes in the path from _A_ to _B_ modulo _(109 + 7)_ + +**Input Format** +The first Line consists of 3 space separated integers, _N E R_, where _N_ is the number of nodes present, _E_ is the total number of queries (update + report), and _R_ is root of the tree. + +Each of the next _N-1_ lines contains 2 space separated integers, _X_ and _Y_ (_X_ and _Y_ are connected by an edge). + +Thereafter, _E_ lines follows: each line can represent either the Update Operation or the Report Operation.
+ +- _Update Operation_ is of the form : _U T V K_. +- _Report Operation_ is of the form : _Q A B_. + +**Output Format** +Output the answer for every given report operation. + +**Constraints** + +1 ≤ N, E ≤ 105 +1 ≤ E ≤ 105 +1 ≤ R, X, Y, T, A, B ≤ N +1 ≤ V, K ≤ 109 +X ≠ Y + +**Sample Input** + + 7 7 1 + 1 2 + 2 3 + 2 4 + 2 5 + 5 6 + 6 7 + U 5 10 2 + U 4 5 3 + Q 1 7 + U 6 7 4 + Q 2 7 + Q 1 4 + Q 2 4 + +**Sample Output** + + 36 + 54 + 5 + 5 + +**Explanation** + +- Values of Nodes after `U 5 10 2`: `[0 0 0 0 10 12 14]`. +- Values of Nodes after `U 4 5 3`: `[0 0 0 5 10 12 14]`. +- Sum of the Nodes from 1 to 7: 0 + 0 + 10 + 12 + 14 = 36. +- Values of Nodes after `U 6 7 4`: [0 0 0 5 10 19 25]. +- Sum of the Nodes from 2 to 7: 0 + 10 + 19 + 25 = 54. +- Sum of the Nodes from 1 to 4: 0 + 0 + 5 = 5. +- Sum of the Nodes from 2 to 4: 0 + 5 = 5.",code,Maintain the given tree under Update and Query operations.,ai,2014-03-23T14:11:05,2022-08-31T08:33:19,,,,"You are given a rooted [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with _N_ nodes and the root of the tree, _R_, is also given. Each node of the tree contains a value, that is initially empty. You have to mantain the tree under two operations: + +1. Update Operation +2. Report Operation + +**Update Operation** +Each Update Operation begins with the character `U`. Character `U` is followed by 3 integers _T, V and K_. For every node which is the descendent of the node _T_, update it's value by adding _V + d\*K_, where _V_ and _K_ are the parameters of the query and _d_ is the distance of the node from _T_. Note that _V_ is added to node _T_. + +**Report Operation** +Each Report Operation begins with the character `Q`. Character `Q` is followed by 2 integers, _A_ and _B_. Output the sum of values of nodes in the path from _A_ to _B_ modulo _(109 + 7)_ + +**Input Format** +The first Line consists of 3 space separated integers, _N E R_, where _N_ is the number of nodes present, _E_ is the total number of queries (update + report), and _R_ is root of the tree. + +Each of the next _N-1_ lines contains 2 space separated integers, _X_ and _Y_ (_X_ and _Y_ are connected by an edge). + +Thereafter, _E_ lines follows: each line can represent either the Update Operation or the Report Operation.
+ +- _Update Operation_ is of the form : _U T V K_. +- _Report Operation_ is of the form : _Q A B_. + +**Output Format** +Output the answer for every given report operation. + +**Constraints** + +1 ≤ N, E ≤ 105 +1 ≤ E ≤ 105 +1 ≤ R, X, Y, T, A, B ≤ N +1 ≤ V, K ≤ 109 +X ≠ Y + +**Sample Input** + + 7 7 1 + 1 2 + 2 3 + 2 4 + 2 5 + 5 6 + 6 7 + U 5 10 2 + U 4 5 3 + Q 1 7 + U 6 7 4 + Q 2 7 + Q 1 4 + Q 2 4 + +**Sample Output** + + 36 + 54 + 5 + 5 + +**Explanation** + +- Values of Nodes after `U 5 10 2`: `[0 0 0 0 10 12 14]`. +- Values of Nodes after `U 4 5 3`: `[0 0 0 5 10 12 14]`. +- Sum of the Nodes from 1 to 7: 0 + 0 + 10 + 12 + 14 = 36. +- Values of Nodes after `U 6 7 4`: [0 0 0 5 10 19 25]. +- Sum of the Nodes from 2 to 7: 0 + 10 + 19 + 25 = 54. +- Sum of the Nodes from 1 to 4: 0 + 0 + 5 = 5. +- Sum of the Nodes from 2 to 4: 0 + 5 = 5.",0.423728814,"[""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,,,,,,"{""contest_participation"":1164,""challenge_submissions"":30,""successful_submissions"":9}",2014-06-02T06:04:31,2016-12-01T20:38:59,setter," #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + using namespace std; + + #define mod 1000000007 + + typedef long long int ll; + + //Variables required for HL tree + int which[100001],size_sub[100001],parent[100001],depth[100001],seg_size,mapping[100001],counter,skip[100001],N,root,visit[100001],level; + bool hlson[100001]; + vector myvector[100001]; + const ll inv = 500000004; + + int power[25]; + void constant() + { + power[0]=1; + for(int i=1;i<=25;i++) power[i]=power[i-1]<<1; + } + int obtain(int x) + { + int l=0,y=x; + while(x!=0){ + l++; + x>>=1; + } + if(power[l-1]!=y) l++; + return l; + } + struct node{ + ll v,vx,d,dx,xxd; + node(ll a=0,ll b=0,ll c=0,ll e=0, ll f=0){ + v=a; + vx=b; + d=c; + dx=e; + xxd=f; + } + node operator + (const node &x)const{ + return node( (x.v+v)%mod , (x.vx+vx)%mod , (x.d+d)%mod, (x.dx+dx)%mod , (x.xxd+xxd)%mod ); + } + node operator % (int m) const{ + return node( v%m , vx%m , d%m , dx%m , xxd%m ); + } + }HL[1<<18],freq[100001]; + + /*********************************FOR FINDING LCA***********************************/ + int Root[100001][18],store[100001]; + void init() + { + store[0]=0;store[1]=0;store[2]=1; + int cmp=4; + for(int i=3;i<=100000;i++){ + if(cmp>i) store[i]=store[i-1]; + else{ + store[i]=store[i-1]+1; + cmp<<=1; + } + } + } + void process(int N) + { + memset(Root,-1,sizeof(Root)); + for(int i=1;i<=N;i++) Root[i][0]=parent[i]; + for(int i=1;(1<depth[q]) swap(p,q); + int steps=store[depth[q]]; + for(int i=steps;i>=0;i--) + if(depth[q]-(1<= depth[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]; + } + /*********************************FOR FINDING LCA***********************************/ + + + /*********************************HL Tree Coding Begins***************************/ + void dfs_pre(int root) + { + which[root]=-1; + skip[root]=root; //only purpose is to init it! + size_sub[root]=1; + for(vector::iterator it=myvector[root].begin();it!=myvector[root].end();it++){ + if(parent[root]==*it) continue; + parent[*it]=root; + depth[*it]=depth[root]+1; + dfs_pre(*it); + size_sub[root]+=size_sub[*it]; + } + for(vector::iterator it=myvector[root].begin();it!=myvector[root].end();it++){ + if(parent[root]==*it) continue; + if(size_sub[*it]>size_sub[root]/2){ + hlson[*it]=true; + which[root]=*it; + } + else{ + hlson[*it]=false; + } + } + } + void dfs_cal(int root) + { + int z; + for(vector::iterator it=myvector[root].begin();it!=myvector[root].end();it++){ + if(parent[root]==*it) continue; + if(hlson[*it]){ //heavy node detected + skip[*it]=skip[root]; + if(skip[root]==root){ + z=*it; + //construction of segment tree begins + while(z!=-1){ + mapping[z]=seg_size; + seg_size++; + z=which[z]; + } + } + } + dfs_cal(*it); + } + } + void seg_Update(int l) + { + int v; + while(l!=0){ + v=(l<<1); + HL[l]=(HL[v]+HL[v+1]); + l>>=1; + } + } + node seg_Query(int l,int r,int i,int j,int nod) + { + int v,mid; + if(jr) return node(); + if(l>=i && j>=r){ + return HL[nod]; + } + v=nod<<1; + mid=(l+r)>>1; + return seg_Query(l,mid,i,j,v)+seg_Query(mid+1,r,i,j,v+1); + } + node HL_Update(int x,node v) + { + int ind; + if(hlson[x]){ //Heavy Part + ind=mapping[x]+power[level-1]; + HL[ind]=(HL[ind]+v); + seg_Update(ind>>1); + } + } + node fun(ll x,ll v,ll d) + { + x=depth[x]; + return ( node( v,v*x,d,d*x,((x*x-x)%mod)*d )%mod ); + } + node HL_Query(int i,int j) //from i to j --> j is the ancestor + { + node r; + int end,st; + while(i!=j){ + if(hlson[i]){ + end=skip[i]; + st=i; + i=end; + end=which[i]; + if(depth[end]<=depth[j]){ + r=r+seg_Query(1,power[level-1],mapping[j]+1,mapping[st]+1,1); + return r; + } + else{ //carry on + r=r+seg_Query(1,power[level-1],mapping[end]+1,mapping[st]+1,1); + } + } + else{ + r=r+freq[i]; + i=parent[i]; + } + } + return ((r+freq[j])); + } + /*********************************HL Tree Coding Ends***************************/ + ll part1(node A,ll dep) + { + ll ret1 = ( A.v*(dep+1) - A.vx - A.dx*(dep) + A.xxd*(ll)inv )%mod; + ll ret2 = ( ( A.d*(dep*dep+dep) ) %mod )*(ll)inv ; + return (ret1+ret2)%mod; + } + ll part2(node A,ll a,ll y,ll z) //a-ances , y-left , z-right + { + ll cons = ( a*(y+z-(ll)2*a+(ll)1) + ((y-a)*(y-a+(ll)1))/(ll)2 + ((z-a)*(z-a+(ll)1))/(ll)2 )%mod; + return (( (A.v-A.dx)*(y+z-(ll)2*a+(ll)1) + A.d*(cons) ) %mod); + } + void solve() + { + node A,B,C,D; + char c; + int x,y,anc,Q; + ll s,b,nodes,expr,k,solution; + memset(freq,0,sizeof(freq)); + scanf(""%d%d%d"",&N,&Q,&root); + assert(N<=100000 && N>=1); + assert(Q<=100000 && Q>=1); + assert(root<=N && root>=1); + for(int i=1;i=1 && x<=N); + assert(y>=1 && y<=N); + assert(x!=y); + myvector[x].push_back(y); + myvector[y].push_back(x); + } + seg_size=0; + parent[root]=root; + depth[root]=0; + dfs_pre(root); //find heavy edges, parent, depth,which[] + process(N); + dfs_cal(root); //construct segment tree; + level=obtain(seg_size); + for(int i=0;i=1 && x<=N); + assert(s>=1 && s<=1000000000); + assert(k>=1 && k<=1000000000); + A=fun(x,s,k); + HL_Update(x,A); + freq[x]= (freq[x] + A) % mod; + } + else{ + scanf(""%d%d"",&x,&y); + assert(x>=1 && x<=N); + assert(y>=1 && y<=N); + anc=lca(x,y); + A=HL_Query(x,anc); + B=HL_Query(y,anc); + solution= part1(A,depth[x]) + part1 ( B, depth[y]) - freq[anc].v; + if(anc!=root){ + A = HL_Query(parent[anc],root); + solution = solution + part2(A,depth[anc],depth[x],depth[y]); + } + solution = solution % mod; + if(solution<0) solution+=mod; + printf(""%lld\n"",solution); + } + } + } + int main() + { + constant(); + init(); + solve(); + return 0; + } +",not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,C++ +66,2212,rooted-tree,Rooted Tree,"[Русский](https://hr-filepicker.s3.amazonaws.com/101may14/russian/2212-rooted_tree.pdf) \| +[中文](https://hr-filepicker.s3.amazonaws.com/101may14/chinese/2212-rooted_tree.pdf)
+You are given a rooted [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with _N_ nodes and the root of the tree, _R_, is also given. Each node of the tree contains a value, that is initially empty. You have to mantain the tree under two operations: + +1. Update Operation +2. Report Operation + +**Update Operation** +Each Update Operation begins with the character `U`. Character `U` is followed by 3 integers _T, V and K_. For every node which is the descendent of the node _T_, update it's value by adding _V + d\*K_, where _V_ and _K_ are the parameters of the query and _d_ is the distance of the node from _T_. Note that _V_ is added to node _T_. + +**Report Operation** +Each Report Operation begins with the character `Q`. Character `Q` is followed by 2 integers, _A_ and _B_. Output the sum of values of nodes in the path from _A_ to _B_ modulo _(109 + 7)_ + +**Input Format** +The first Line consists of 3 space separated integers, _N E R_, where _N_ is the number of nodes present, _E_ is the total number of queries (update + report), and _R_ is root of the tree. + +Each of the next _N-1_ lines contains 2 space separated integers, _X_ and _Y_ (_X_ and _Y_ are connected by an edge). + +Thereafter, _E_ lines follows: each line can represent either the Update Operation or the Report Operation.
+ +- _Update Operation_ is of the form : _U T V K_. +- _Report Operation_ is of the form : _Q A B_. + +**Output Format** +Output the answer for every given report operation. + +**Constraints** + +1 ≤ N, E ≤ 105 +1 ≤ E ≤ 105 +1 ≤ R, X, Y, T, A, B ≤ N +1 ≤ V, K ≤ 109 +X ≠ Y + +**Sample Input** + + 7 7 1 + 1 2 + 2 3 + 2 4 + 2 5 + 5 6 + 6 7 + U 5 10 2 + U 4 5 3 + Q 1 7 + U 6 7 4 + Q 2 7 + Q 1 4 + Q 2 4 + +**Sample Output** + + 36 + 54 + 5 + 5 + +**Explanation** + +- Values of Nodes after `U 5 10 2`: `[0 0 0 0 10 12 14]`. +- Values of Nodes after `U 4 5 3`: `[0 0 0 5 10 12 14]`. +- Sum of the Nodes from 1 to 7: 0 + 0 + 10 + 12 + 14 = 36. +- Values of Nodes after `U 6 7 4`: [0 0 0 5 10 19 25]. +- Sum of the Nodes from 2 to 7: 0 + 10 + 19 + 25 = 54. +- Sum of the Nodes from 1 to 4: 0 + 0 + 5 = 5. +- Sum of the Nodes from 2 to 4: 0 + 5 = 5.",code,Maintain the given tree under Update and Query operations.,ai,2014-03-23T14:11:05,2022-08-31T08:33:19,,,,"You are given a rooted [tree](http://en.wikipedia.org/wiki/Tree_(graph_theory)) with _N_ nodes and the root of the tree, _R_, is also given. Each node of the tree contains a value, that is initially empty. You have to mantain the tree under two operations: + +1. Update Operation +2. Report Operation + +**Update Operation** +Each Update Operation begins with the character `U`. Character `U` is followed by 3 integers _T, V and K_. For every node which is the descendent of the node _T_, update it's value by adding _V + d\*K_, where _V_ and _K_ are the parameters of the query and _d_ is the distance of the node from _T_. Note that _V_ is added to node _T_. + +**Report Operation** +Each Report Operation begins with the character `Q`. Character `Q` is followed by 2 integers, _A_ and _B_. Output the sum of values of nodes in the path from _A_ to _B_ modulo _(109 + 7)_ + +**Input Format** +The first Line consists of 3 space separated integers, _N E R_, where _N_ is the number of nodes present, _E_ is the total number of queries (update + report), and _R_ is root of the tree. + +Each of the next _N-1_ lines contains 2 space separated integers, _X_ and _Y_ (_X_ and _Y_ are connected by an edge). + +Thereafter, _E_ lines follows: each line can represent either the Update Operation or the Report Operation.
+ +- _Update Operation_ is of the form : _U T V K_. +- _Report Operation_ is of the form : _Q A B_. + +**Output Format** +Output the answer for every given report operation. + +**Constraints** + +1 ≤ N, E ≤ 105 +1 ≤ E ≤ 105 +1 ≤ R, X, Y, T, A, B ≤ N +1 ≤ V, K ≤ 109 +X ≠ Y + +**Sample Input** + + 7 7 1 + 1 2 + 2 3 + 2 4 + 2 5 + 5 6 + 6 7 + U 5 10 2 + U 4 5 3 + Q 1 7 + U 6 7 4 + Q 2 7 + Q 1 4 + Q 2 4 + +**Sample Output** + + 36 + 54 + 5 + 5 + +**Explanation** + +- Values of Nodes after `U 5 10 2`: `[0 0 0 0 10 12 14]`. +- Values of Nodes after `U 4 5 3`: `[0 0 0 5 10 12 14]`. +- Sum of the Nodes from 1 to 7: 0 + 0 + 10 + 12 + 14 = 36. +- Values of Nodes after `U 6 7 4`: [0 0 0 5 10 19 25]. +- Sum of the Nodes from 2 to 7: 0 + 10 + 19 + 25 = 54. +- Sum of the Nodes from 1 to 4: 0 + 0 + 5 = 5. +- Sum of the Nodes from 2 to 4: 0 + 5 = 5.",0.423728814,"[""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,,,,,,"{""contest_participation"":1164,""challenge_submissions"":30,""successful_submissions"":9}",2014-06-02T06:04:31,2016-12-01T20:38:59,tester," #ifdef ssu1 + #define _GLIBCXX_DEBUG + #endif + #undef NDEBUG + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + using namespace std; + + #define fore(i, l, r) for(int i = (l); i < (r); ++i) + #define forn(i, n) fore(i, 0, n) + #define fori(i, l, r) fore(i, l, (r) + 1) + #define sz(v) int((v).size()) + #define all(v) (v).begin(), (v).end() + #define pb push_back + #define mp make_pair + #define X first + #define Y second + + #if ( _WIN32 || __WIN32__ ) + #define LLD ""%I64d"" + #else + #define LLD ""%lld"" + #endif + + typedef long long li; + typedef long double ld; + typedef pair pt; + + template T abs(T a) { return a < 0 ? -a : a; } + template T sqr(T a) { return a*a; } + + const int INF = (int)1e9; + const ld EPS = 1e-9; + const ld PI = 3.1415926535897932384626433832795; + + int readInt(int l, int r){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int in range [%d, %d], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int in range [%d, %d], but found %d!"", l, r, x); + throw; + } + return x; + } + + const int NMAX = 300000; + const int LOG = 20; + const int mod = 1000000000 + 7; + + int n, q, root, used[NMAX]; + vector g[NMAX]; + int dep[NMAX], p[NMAX][LOG], lf[NMAX], rg[NMAX], mul[3][NMAX], timer = 0; + + void dfs(int v, int pv){ + used[v] = 1; + dep[v] = (v == pv ? 0 : dep[pv] + 1); + lf[v] = rg[v] = timer++; + + p[v][0] = pv; + fore(lev, 1, LOG){ + p[v][lev] = p[p[v][lev - 1]][lev - 1]; + } + + forn(i, sz(g[v])){ + int u = g[v][i]; + if(u == pv) + continue; + dfs(u, v); + rg[v] = rg[u]; + } + } + + int lca(int a, int b){ + if(dep[a] < dep[b]) + swap(a, b); + forn(i, LOG){ + if((dep[a] - dep[b]) & (1 << i)){ + a = p[a][i]; + } + } + for(int i = LOG - 1; i >= 0; --i){ + if(p[a][i] != p[b][i]){ + a = p[a][i]; + b = p[b][i]; + } + } + if(a != b) + a = p[a][0], b = p[b][0]; + assert(a == b); + return a; + } + + inline void norm(int& v){ + while(v < 0) + v += mod; + while(v >= mod) + v -= mod; + } + + int modpow(int a, int b){ + int ans = 1 % mod; + while(b){ + if(b & 1) + ans = (ans * li(a)) % mod; + a = (a * li(a)) % mod; + b >>= 1; + } + return ans; + } + + inline int rev(int a){ + return modpow(a, mod - 2); + } + + inline int doMod(li v){ + return (int)((v % mod + mod) % mod); + } + + void upd(int t[NMAX], int i, int v){ + for(; i < NMAX; i = (i | (i + 1))){ + t[i] += v; + norm(t[i]); + } + } + + int sum(int t[NMAX], int r){ + int ans = 0; + for(; r >= 0; r = (r & (r + 1)) - 1){ + ans += t[r]; + norm(ans); + } + return ans; + } + + int sum(int t[NMAX], int l, int r){ + int ans = sum(t, r) - sum(t, l - 1); + norm(ans); + return ans; + } + + int get(int a){ + int pw = 1, ans = 0; + forn(i, 3){ + ans = (ans + sum(mul[i], 0, lf[a]) * 1LL * pw) % mod; + pw = (pw * 1LL * dep[a]) % mod; + } + return ans; + } + + int dist(int a, int b){ + int mid = lca(a, b); + + int ans = get(a) + get(b) - 2 * get(mid); + norm(ans); + if(mid == root) + ans += get(mid); + else + ans += get(mid) - get(p[mid][0]); + norm(ans); + return ans; + } + + void rangeupd(int t[NMAX], int l, int r, int val){ + upd(t, l, val); + upd(t, r + 1, doMod(mod - val)); + } + + void doUpdQuery(int t, int V, int U){ + int L = lf[t], R = rg[t], x = V; + rangeupd(mul[0], L, R, doMod((1 - dep[t]) * li(x))); + rangeupd(mul[1], L, R, x); + x = U; + rangeupd(mul[0], L, R, doMod(-(1 - dep[t]) * 1LL * doMod(x * 1LL * dep[t]))); + rangeupd(mul[1], L, R, doMod(-x * 1LL * dep[t])); + + rangeupd(mul[1], L, R, doMod(-x * 1LL * dep[t] + x)); + rangeupd(mul[2], L, R, x); + x = doMod(-x * 1LL * rev(2)); + rangeupd(mul[0], L, R, doMod(((dep[t] * 1LL * dep[t] - dep[t]) % mod) * li(x))); + rangeupd(mul[1], L, R, doMod((-2 * dep[t] + 1) * li(x))); + rangeupd(mul[2], L, R, x); + } + + int main(){ + #ifdef ssu1 + assert(freopen(""input.txt"", ""rt"", stdin)); + //assert(freopen(""output.txt"", ""wt"", stdout)); + #endif + n = readInt(1, 100000); + q = readInt(1, 100000); + root = readInt(1, n) - 1; + + forn(i, n - 1){ + int a, b; + a = readInt(1, n) - 1; + b = readInt(1, n) - 1; + g[a].pb(b); + g[b].pb(a); + } + + dfs(root, root); + forn(v, n){ + assert(used[v]); + } + + forn(qi, q){ + char type; + assert(scanf("" %c "", &type) == 1); + assert(type == 'Q' || type == 'U'); + if(type == 'Q'){ + int a, b; + a = readInt(1, n) - 1; + b = readInt(1, n) - 1; + printf(""%d\n"", dist(a, b)); + }else{ + int t, v, k; + t = readInt(1, n) - 1; + v = readInt(1, 1000000000); + k = readInt(1, 1000000000); + doUpdQuery(t, v, k); + } + } + return 0; + }",not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,C++ +67,2523,easy-sum,Easy sum,"Little Kevin had never heard the word 'Infinitum'. So he asked his mentor to explain the word to him. His mentor knew that 'Infinitum' is a very large number. To show him how big [Infinitum](http://en.wikipedia.org/wiki/Ad_infinitum) can be, his mentor gave him a challenge: to sum the numbers from _1_ up to _N_. The sum started to get really large and was out of `long long int` range. And so the lesson was clear. + +Now his mentor introduced him to the concept of *mod* and asked him to retain only the remainder instead of the big number. And then, he gave him a formula to compute: + +$$\sum_{i=1}^{N} (i\%m)$$ + +**Input Format** +The first line contains _T_, the number of test cases. +_T_ lines follow, each containing 2 space separated integers _N m_ + +**Output Format** +Print the result on new line corresponding to each test case. + +**Constraint** +1 ≤ _T_ ≤ 1000 +1 ≤ _N_ ≤ 109 +1 ≤ _m_ ≤ 109 + +**Sample Input** + + 3 + 10 5 + 10 3 + 5 5 + +**Sample Output** + + 20 + 10 + 10 + +**Explanation** +Case 1: _N_ = 10 _m_ = 5, +1%5 + 2%5 + 3%5 + 4%5 + 5%5 + 6%5 + 7%5 + 8%5 + 9%5 + 10%5 = 20. +Similar explanation follows for Case 2 and 3. + + +",code,Find the mod sum,ai,2014-05-14T04:26:01,2022-09-02T09:55:04,"# +# 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() +","Little Kevin had never heard the word 'Infinitum'. So he asked his mentor to explain the word to him. His mentor knew that 'Infinitum' is a very large number. To show him how big [Infinitum](http://en.wikipedia.org/wiki/Ad_infinitum) can be, his mentor gave him a challenge: to sum the numbers from _1_ up to _N_. The sum started to get really large and was out of `long long int` range. And so the lesson was clear. + +Now his mentor introduced him to the concept of *mod* and asked him to retain only the remainder instead of the big number. And then, he gave him a formula to compute: + +$$\sum_{i=1}^{N} (i\%m)$$ + +**Input Format** +The first line contains _T_, the number of test cases. +_T_ lines follow, each containing 2 space separated integers _N m_ + +**Output Format** +Print the result on new line corresponding to each test case. + +**Constraint** +1 ≤ _T_ ≤ 1000 +1 ≤ _N_ ≤ 109 +1 ≤ _m_ ≤ 109 + +**Sample Input** + + 3 + 10 5 + 10 3 + 5 5 + +**Sample Output** + + 20 + 10 + 10 + +**Explanation** +Case 1: _N_ = 10 _m_ = 5, +1%5 + 2%5 + 3%5 + 4%5 + 5%5 + 6%5 + 7%5 + 8%5 + 9%5 + 10%5 = 20. +Similar explanation follows for Case 2 and 3. + + +",0.5975232198142415,"[""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,,,,,,"{""contest_participation"":2021,""challenge_submissions"":1071,""successful_submissions"":793}",2014-06-02T11:02:56,2016-12-07T10:25:14,setter,"###Python 2 +```python +for _ in range(input()): + N,M = [int(x) for x in raw_input().split()] + k = N%M + print (M-1)*(M)/2*(N/M) + k*(k+1)/2 +``` +",not-set,2016-04-24T02:02:40,2016-07-23T18:55:35,Python +68,2523,easy-sum,Easy sum,"Little Kevin had never heard the word 'Infinitum'. So he asked his mentor to explain the word to him. His mentor knew that 'Infinitum' is a very large number. To show him how big [Infinitum](http://en.wikipedia.org/wiki/Ad_infinitum) can be, his mentor gave him a challenge: to sum the numbers from _1_ up to _N_. The sum started to get really large and was out of `long long int` range. And so the lesson was clear. + +Now his mentor introduced him to the concept of *mod* and asked him to retain only the remainder instead of the big number. And then, he gave him a formula to compute: + +$$\sum_{i=1}^{N} (i\%m)$$ + +**Input Format** +The first line contains _T_, the number of test cases. +_T_ lines follow, each containing 2 space separated integers _N m_ + +**Output Format** +Print the result on new line corresponding to each test case. + +**Constraint** +1 ≤ _T_ ≤ 1000 +1 ≤ _N_ ≤ 109 +1 ≤ _m_ ≤ 109 + +**Sample Input** + + 3 + 10 5 + 10 3 + 5 5 + +**Sample Output** + + 20 + 10 + 10 + +**Explanation** +Case 1: _N_ = 10 _m_ = 5, +1%5 + 2%5 + 3%5 + 4%5 + 5%5 + 6%5 + 7%5 + 8%5 + 9%5 + 10%5 = 20. +Similar explanation follows for Case 2 and 3. + + +",code,Find the mod sum,ai,2014-05-14T04:26:01,2022-09-02T09:55:04,"# +# 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() +","Little Kevin had never heard the word 'Infinitum'. So he asked his mentor to explain the word to him. His mentor knew that 'Infinitum' is a very large number. To show him how big [Infinitum](http://en.wikipedia.org/wiki/Ad_infinitum) can be, his mentor gave him a challenge: to sum the numbers from _1_ up to _N_. The sum started to get really large and was out of `long long int` range. And so the lesson was clear. + +Now his mentor introduced him to the concept of *mod* and asked him to retain only the remainder instead of the big number. And then, he gave him a formula to compute: + +$$\sum_{i=1}^{N} (i\%m)$$ + +**Input Format** +The first line contains _T_, the number of test cases. +_T_ lines follow, each containing 2 space separated integers _N m_ + +**Output Format** +Print the result on new line corresponding to each test case. + +**Constraint** +1 ≤ _T_ ≤ 1000 +1 ≤ _N_ ≤ 109 +1 ≤ _m_ ≤ 109 + +**Sample Input** + + 3 + 10 5 + 10 3 + 5 5 + +**Sample Output** + + 20 + 10 + 10 + +**Explanation** +Case 1: _N_ = 10 _m_ = 5, +1%5 + 2%5 + 3%5 + 4%5 + 5%5 + 6%5 + 7%5 + 8%5 + 9%5 + 10%5 = 20. +Similar explanation follows for Case 2 and 3. + + +",0.5975232198142415,"[""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,,,,,,"{""contest_participation"":2021,""challenge_submissions"":1071,""successful_submissions"":793}",2014-06-02T11:02:56,2016-12-07T10:25:14,tester,"###Python 2 +```python +for c in xrange(input()):print(lambda N,m:N/m*m*(m-1)/2+(N%m*2+1)**2/8)(*map(int,raw_input().split())) +``` +",not-set,2016-04-24T02:02:40,2016-07-23T18:56:00,Python +69,1636,crush,Array Manipulation,"[Russian](https://hr-filepicker.s3.amazonaws.com/w4/russian/1636-crush.pdf)
+ + +Devendra is on cloud nine after seeing his crush smiling at him in class. At that very moment his professor singles him out and asks him a question. Devendra's mind is all too fuzzy with his crush and her smile to concentrate on anything else. Help him solve the problem :
+ +You are given a list of size N, initialized with zeroes. You have to perform M queries on the list and output the maximum of final values of all the N elements in the list. For every query, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both inclusive). + +**Input Format** +First line will contain two integers _N_ and _M_ separated by a single space.
+Next M lines will contain three integers _a_, _b_ and _k_ separated by a single space.
+Numbers in list are numbered from _1_ to _N_. + +**Output Format** +A single line containing *maximum value in the final list.* + +**Constraints** +3 ≤ *N* ≤ 107 +1 ≤ *M* ≤ 2 \* 105 +1 ≤ *a* ≤ *b* ≤ N +0 ≤ *k* ≤ 109 + +**Sample Input #00** + + 5 3 + 1 2 100 + 2 5 100 + 3 4 100 + + +**Sample Output #00** + + 200 + +**Explanation** + +After first update list will be `100 100 0 0 0`.
+After second update list will be `100 200 100 100 100`.
+After third update list will be `100 200 200 200 100`.
+So the required answer will be 200. + +**Note** + +The initial testcases are easy and naive solutions might pass. Only efficient solutions can pass the additional testcases. ",code,Perform m operations on an array and print the maximum of the values.,ai,2014-01-09T11:29:47,2022-09-02T09:59:47,"# +# Complete the 'arrayManipulation' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts following parameters: +# 1. INTEGER n +# 2. 2D_INTEGER_ARRAY queries +# + +def arrayManipulation(n, queries): + # 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() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + queries = [] + + for _ in range(m): + queries.append(list(map(int, input().rstrip().split()))) + + result = arrayManipulation(n, queries) + + fptr.write(str(result) + '\n') + + fptr.close() +","Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. + +**Example** +$n = 10$ +$queries = [[1, 5, 3], [4, 8, 7], [6, 9, 1]$ + +Queries are interpreted as follows: +``` + a b k + 1 5 3 + 4 8 7 + 6 9 1 +``` +Add the values of $k$ between the indices $a$ and $b$ inclusive: +``` +index-> 1 2 3 4 5 6 7 8 9 10 + [0,0,0, 0, 0,0,0,0,0, 0] + [3,3,3, 3, 3,0,0,0,0, 0] + [3,3,3,10,10,7,7,7,0, 0] + [3,3,3,10,10,8,8,8,1, 0] +``` + +The largest value is $10$ after all operations are performed. + +**Function Description** + +Complete the function *arrayManipulation* in the editor below. + +arrayManipulation has the following parameters: + +- *int n* - the number of elements in the array +- *int queries[q][3]* - a two dimensional array of queries where each *queries[i]* contains three integers, *a*, *b*, and *k*. + +**Returns** + +- *int* - the maximum value in the resultant array ",0.5048025613660619,"[""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""]","The first line contains two space-separated integers $n$ and $m$, the size of the array and the number of operations. +Each of the next $m$ lines contains three space-separated integers $a$, $b$ and $k$, the left index, right index and summand. ", ," 5 3 + 1 2 100 + 2 5 100 + 3 4 100 +"," 200 +",Hard,,,,,,"{""contest_participation"":1783,""challenge_submissions"":658,""successful_submissions"":361}",2014-06-03T07:16:46,2020-09-08T16:59:12,setter,"```cpp +#include + +using namespace std; +long a[400009]; + +int main() { + + int n; + int m; + cin >> n >> m; + vector < pair < int, int > > v; + + for(int a0 = 0; a0 < m; a0++) { + + int a; + int b; + int k; + cin >> a >> b >> k; + + //storing the query + //this will add k in the prefix sum for index >= a + v.push_back(make_pair(a, k)); + + //adding -1*k will remove k from the prefix sum for index > b + v.push_back(make_pair(b+1, -1 * k)); + } + + long mx = 0, sum = 0; + + sort(v.begin(), v.end()); + + for(int i=0 ; i<2*m; i++) { + + sum += v[i].second; + mx = max(mx, sum); + + } + + cout< + + +Devendra is on cloud nine after seeing his crush smiling at him in class. At that very moment his professor singles him out and asks him a question. Devendra's mind is all too fuzzy with his crush and her smile to concentrate on anything else. Help him solve the problem :
+ +You are given a list of size N, initialized with zeroes. You have to perform M queries on the list and output the maximum of final values of all the N elements in the list. For every query, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both inclusive). + +**Input Format** +First line will contain two integers _N_ and _M_ separated by a single space.
+Next M lines will contain three integers _a_, _b_ and _k_ separated by a single space.
+Numbers in list are numbered from _1_ to _N_. + +**Output Format** +A single line containing *maximum value in the final list.* + +**Constraints** +3 ≤ *N* ≤ 107 +1 ≤ *M* ≤ 2 \* 105 +1 ≤ *a* ≤ *b* ≤ N +0 ≤ *k* ≤ 109 + +**Sample Input #00** + + 5 3 + 1 2 100 + 2 5 100 + 3 4 100 + + +**Sample Output #00** + + 200 + +**Explanation** + +After first update list will be `100 100 0 0 0`.
+After second update list will be `100 200 100 100 100`.
+After third update list will be `100 200 200 200 100`.
+So the required answer will be 200. + +**Note** + +The initial testcases are easy and naive solutions might pass. Only efficient solutions can pass the additional testcases. ",code,Perform m operations on an array and print the maximum of the values.,ai,2014-01-09T11:29:47,2022-09-02T09:59:47,"# +# Complete the 'arrayManipulation' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts following parameters: +# 1. INTEGER n +# 2. 2D_INTEGER_ARRAY queries +# + +def arrayManipulation(n, queries): + # 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() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + queries = [] + + for _ in range(m): + queries.append(list(map(int, input().rstrip().split()))) + + result = arrayManipulation(n, queries) + + fptr.write(str(result) + '\n') + + fptr.close() +","Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. + +**Example** +$n = 10$ +$queries = [[1, 5, 3], [4, 8, 7], [6, 9, 1]$ + +Queries are interpreted as follows: +``` + a b k + 1 5 3 + 4 8 7 + 6 9 1 +``` +Add the values of $k$ between the indices $a$ and $b$ inclusive: +``` +index-> 1 2 3 4 5 6 7 8 9 10 + [0,0,0, 0, 0,0,0,0,0, 0] + [3,3,3, 3, 3,0,0,0,0, 0] + [3,3,3,10,10,7,7,7,0, 0] + [3,3,3,10,10,8,8,8,1, 0] +``` + +The largest value is $10$ after all operations are performed. + +**Function Description** + +Complete the function *arrayManipulation* in the editor below. + +arrayManipulation has the following parameters: + +- *int n* - the number of elements in the array +- *int queries[q][3]* - a two dimensional array of queries where each *queries[i]* contains three integers, *a*, *b*, and *k*. + +**Returns** + +- *int* - the maximum value in the resultant array ",0.5048025613660619,"[""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""]","The first line contains two space-separated integers $n$ and $m$, the size of the array and the number of operations. +Each of the next $m$ lines contains three space-separated integers $a$, $b$ and $k$, the left index, right index and summand. ", ," 5 3 + 1 2 100 + 2 5 100 + 3 4 100 +"," 200 +",Hard,,,,,,"{""contest_participation"":1783,""challenge_submissions"":658,""successful_submissions"":361}",2014-06-03T07:16:46,2020-09-08T16:59:12,tester,"```python +def arrayManipulation(n, queries): + arr = [0] * (n+1) + # add the value at first index + # subtract the value at last index + 1 + for q in queries: + start, end, amt = q + arr[start-1] += amt + arr[end] -= amt + + # max value and running sum + mv = -1 + running = 0 + for a in arr: + running += a + if running > mv: + mv = running + + return mv +```",not-set,2016-04-24T02:02:40,2020-09-08T16:59:12,Python +71,472,print,Difficult Printer,"There are N printers and you have M papers to print. But every paper has a diffculty value (indicated by d[i]), and every printer has an ability value (indicated by a[j]). The printer j can print the paper i, iff a[j] >= d[i]. + +It takes one second for a printer to print a paper (if it's possible to print that is). Your task is to calculate the minimal seconds (indicated by T) for the printers to print all the papers. + +**Input format:** + +N M
+a[0] a[1] ... a[n-1]
+d[0] d[1] ... d[m-1]
+ +**Output format:** + +T + +**Constraints:** + +0 < N, M, a[i], d[i] < 100000 +Every testcase assures that the answer is finite. + +**Sample Input:** + +3 5
+7 4 6
+1 3 4 6 1
+ +**Sample Output:** + +2 + +**Explanation:** + +One possibility. + +The printer with ability 7 prints the pages of difficulty 1 first and then difficulty 3 (takes 2s)
+The printer with ability 4 prints the pages of difficulty 1 first and then difficulty 4 (takes 2s)
+The printer with ability 6 prints the pages of difficulty 6
+ +The maximum amount of pages a printer had was 2, so the answer is 2.",code,,ai,2013-03-11T17:19:00,2016-09-09T09:29:21,,,,"There are N printers and you have M papers to print. But every paper has a diffculty value (indicated by d[i]), and every printer has an ability value (indicated by a[j]). The printer j can print the paper i, iff a[j] >= d[i]. + +It takes one second for a printer to print a paper (if it's possible to print that is). Your task is to calculate the minimal seconds (indicated by T) for the printers to print all the papers. + +**Input format:** + +N M
+a[0] a[1] ... a[n-1]
+d[0] d[1] ... d[m-1]
+ +**Output format:** + +T + +**Constraints:** + +0 < N, M, a[i], d[i] < 100000 +Every testcase assures that the answer is finite. + +**Sample Input:** + +3 5
+7 4 6
+1 3 4 6 1
+ +**Sample Output:** + +2 + +**Explanation:** + +One possibility. + +The printer with ability 7 prints the pages of difficulty 1 first and then difficulty 3 (takes 2s)
+The printer with ability 4 prints the pages of difficulty 1 first and then difficulty 4 (takes 2s)
+The printer with ability 6 prints the pages of difficulty 6
+ +The maximum amount of pages a printer had was 2, so the answer is 2.",0.5920000000000001,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-06-03T14:05:30,2017-04-13T02:32:24,tester," #include + using namespace std; + + + int nPrinters, nPapers; + vector a, d; + + bool canSolveWithin(int maxTime) { + int printerIdx = 0, paperIdx = 0; + while(printerIdx < nPrinters && paperIdx < nPapers) { + int curTime = 0; + while(paperIdx < nPapers && curTime < maxTime && d[paperIdx] <= a[printerIdx]) { + paperIdx++; + curTime++; + } + printerIdx++; + } + + return paperIdx == nPapers; + } + + int main() + { + cin >> nPrinters >> nPapers; + int tmp; + + for(int i = 0; i < (int)nPrinters; ++i) { + cin >> tmp; + a.push_back(tmp); + } + for(int i = 0; i < (int)nPapers; ++i) { + cin >> tmp; + d.push_back(tmp); + } + sort(a.begin(), a.end()); + reverse(a.begin(), a.end()); + sort(d.begin(), d.end()); + reverse(d.begin(), d.end()); + assert(a[0] >= d[0]); + + int minTime = 1, maxTime = 1e5; + + while(minTime < maxTime) { + int midTime = (minTime + maxTime) / 2; + if(canSolveWithin(midTime)) + maxTime = midTime; + else + minTime = midTime+1; + } + cout << minTime << ""\n""; + + + return 0; + } +",not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,C++ +72,2572,gifts,Gifts,"In order to transform her student into the perfect knight, Shaina has given to Koga the best possible gifts for a saint: a bunch of scrolls that contains all ancient techniques discovered by older saints. + +Shaina said: + + > Listen carefully Koga, here you have all the attack techniques from all the Athena's Saints - Bronze, Silver and Gold Saints - before you. It is your duty to master them all. + +Koga said: + + > Great! Can I learn them in any order I want to? + +Shaina said: + + > No my young saint, certain order must be respected, but you can always switch amongst Bronze, Silver and Gold as you wish. Within each type, only outer techniques will make you powerful enough to learn and master inner techniques. If you see the scrolls of a some type as a list, you could never learn from the i-th, if neither (i + 1)-th or (i - 1)-th scroll has been mastered yet. You need at least one of them. In other words, from each type + perspective, learning the techniques is some sort of travel from the outside to inside. + +Koga said: + + > I understand Shaina. Is there anything else I should know? + +Shaina said: + + > Actually, there is one more thing: every time you learn a technique, no matter what is its type, you should use one of these stones, respecting the order they + currently have; the stone will increase the power you got from the just learned technique. Basically, the stone multiplies the power of the technique. + +Koga said: + + > Wait a minute, that means some learning order will get the largest possible overall power. How will I know which technique to learn after each one? + +Shaina said: + + > Look up inside you Koga and you will find the answer. + +Koga is somewhat crazy, but within himself he is a wise saint and should be able to solve the riddle. But could you? + +**Input Format** +Input begins with a line containing 3 (B, S, G) integers separated by a single white space, denoting we have B, S, and G bronze, silver and gold scrolls respectively. B + S + G lines follow each one with some integer saying the power of some technique: first B belong to bronze's, next S belong to silver's and last G belong to gold's. Scrolls for each type are arranged in the same order these integers are given in the input. The input ends with B + S + G lines, having each one a single integer describing the multiplication power of some stone. The input order matches the one in which Koga will receive the stones. + +**Output Format** +Output just one line with a single integer: the largest possible sum you can get from learning the techniques with the restrictions mentioned above. **Remember that you must pick the outer techniques from each type first and yes, don't forget to properly use the stones :)** + +**Constraints** + +* 1 <= B, S, G <= 20 +* All input numbers are positive. +* The output will always fit in **32 bits signed integer**. + +**Sample Input:** + + 2 2 2 + 4 + 1 + 2 + 3 + 5 + 6 + 1 + 2 + 3 + 4 + 5 + 6 + +**Sample Output:** + + 91 + +**Sample Input:** + + 4 4 4 + 10 + 1 + 10 + 9 + 10 + 1 + 10 + 9 + 10 + 1 + 10 + 9 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + +**Sample Output:** + + 648 + +**Explanation** + +In the first test case, we have 4, 1 for bronze, 2, 3 for silver and 5, 6 for gold. On the other hand, stones multipliers are 1, 2, 3, 4, 5, 6. The best possible way to learn the techniques (i.e. the one achieving the largest possible result) is: + +* B2 S1 S2 B1 G1 G2 = 1x1 + 2x2 + 3x3 + 4x4 + 5x5 + 6x6 = 91 + +*Note: For a complete list with all possible ways and their results, click [here](http://pastebin.com/e860K0XZ)* +",code,"From these gifts, what's the best you can do?",ai,2014-06-03T18:11:32,2019-07-02T13:58:34,,,,"Shaina has given to her student, Koga, a bunch of scrolls, some instructions to remember while learning the techniques described in the scrolls, and some stones that will multiply the power of the techniques. The instructions are as follows: + +1. He has to master all the Bronze, Silver, and Gold Saints techniques. + +2. He cannot learn them in just any random order, but can switch among Bronze, Silver, and Gold. Within each type, only outer techniques will make him powerful enough to learn and master inner techniques. That is, if he sees the scrolls of some type as a list, you could never learn from the $i^{th}$, if neither $(i + 1)^{th}$ nor $(i - 1)^{th}$ scroll has been mastered yet. + +3. And lastly, every time he learns a technique, whichever type it is, he has to use one of these stones, respecting the order they currently have. + +You have to help him figure out the specific learning order that will get Koga the largest possible overall power. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]","Input begins with a line containing three integers, $B$, $S$, and $G$, separated by a single white space, denoting we have $B$, $S$, and $G$ bronze, silver, and gold scrolls, respectively. $B + S + G$ lines follow, each one with some integer saying the power of some technique: first $B$ belong to bronze's, next $S$ belong to silver's and last $G$ belong to gold's. Scrolls for each type are arranged in the same order these integers are given in the input. The input ends with $B + S + G$ lines, each having a single integer describing the multiplication power of some stone. The input order matches the one in which Koga will receive the stones. + +**Constraints** + +$1 \le B, S, G \le 10$ + +$1 \le B_i, S_i, G_i \le 10^5$ + +$1 \le i^{th} stone \le 300$ + +All input numbers are positive.","Output just one line with a single integer: the largest possible sum you can get from learning the techniques with the restrictions mentioned above. **Remember that you must pick the outer techniques from each type first and, yes, don't forget to properly use the stones :)** + +The output will always fit in a **32-bit signed integer**."," 2 2 2 + 4 + 1 + 2 + 3 + 5 + 6 + 1 + 2 + 3 + 4 + 5 + 6 ", 91,Hard,,,,,,,2014-06-03T20:56:00,2017-02-12T04:14:52,setter," //============================================================================ + // Name : GIFTS.cpp + // Author : Shaka + // Version : + // Copyright : Your copyright notice + // Description : Hello World in C++, Ansi-style + //============================================================================ + + #include + #include + using namespace std; + const int MAXN = 21; + int dp[MAXN][MAXN][MAXN][MAXN][MAXN][MAXN]; + int A[MAXN], B[MAXN], C[MAXN]; + int weight[MAXN * 3]; + int N, M, L; + int solve(int a, int b, int c, int d, int e, int f) { + if (a > b && c > d && e > f) return 0; //no more scrolls to learn + if (!dp[a][b][c][d][e][f]) { //all values are positive, so 0 means unvisited state in the dp + int &rx = dp[a][b][c][d][e][f], tmp; + int wx = weight[(N - 1 + a - b) + (M - 1 + c - d) + (L - 1 + e - f)]; + //possible transitions in bronze techniques + if (a <= b) { + tmp = wx * A[a] + solve(a + 1, b, c, d, e, f); + if (tmp > rx) rx = tmp; + } + if (a < b) { + tmp = wx * A[b] + solve(a, b - 1, c, d, e, f); + if (tmp > rx) rx = tmp; + } + + //possible transitions in silver techniques + if (c <= d) { + tmp = wx * B[c] + solve(a, b, c + 1, d, e, f); + if (tmp > rx) rx = tmp; + } + if (c < d) { + tmp = wx * B[d] + solve(a, b, c, d - 1, e, f); + if (tmp > rx) rx = tmp; + } + + //possible transitions in gold techniques + if (e <= f) { + tmp = wx * C[e] + solve(a, b, c, d, e + 1, f); + if (tmp > rx) rx = tmp; + } + if (e < f) { + tmp = wx * C[f] + solve(a, b, c, d, e, f - 1); + if (tmp > rx) rx = tmp; + } + } + return dp[a][b][c][d][e][f]; + } + + int main() { + register int i; + scanf(""%d%d%d"", &N, &M, &L); + for (i = 0; i < N; ++i) scanf(""%d"", A + i); + for (i = 0; i < M; ++i) scanf(""%d"", B + i); + for (i = 0; i < L; ++i) scanf(""%d"", C + i); + for (i = 0; i < N + M + L; ++i) scanf(""%d"", weight + i); + printf(""%d\n"", solve(0, N - 1, 0, M - 1, 0, L - 1)); + return 0; + }",not-set,2016-04-24T02:02:40,2016-04-24T02:02:40,C++ +73,2561,dance-class,Dancing in Pairs,"Bob is a dance teacher and he started dance classes recently. He observes a strange attendance pattern among his students. Initially, there are no students. On day *i*, a new student starts attending the class. The student stops attending the class, if and only if he has attended the class for _i_ consecutive days. +Also, the student resumes attending the class, if and only if he has not attended the class for _i_ consecutive days. + +We denote the student who starts coming on day *i* as student *i*. +To mark attendance, `o` denotes present and `x` denotes absent. + +For example, the schedule for student 1 from day 1 is as follows: +`oxoxoxoxoxoxoxoxoxox...` + +The schedule for the student 3 from day 1 is as follows: + +`xxoooxxxoooxxxoooxxx...` +(Student 3 starts attending the class from day 3, and stops attending from day 6, and then starts attending from day 9, and so on. ) + +The schedule for the student 5 from day 1 is as follows. +`xxxxoooooxxxxxoooooxxxxx...` + +Bob wants his students to dance in pairs. However, if the number of students coming on day _i_ is odd, then there will be someone who can't find a partner. So Bob wants to know if the number of students coming on day i is even or odd. We denote the number of students coming on day _i_ as _N(i)_. Please find out whether _N(i)_ is even or odd. + + +**Input format** + +The first line contains an integer, _T_, which denotes the number of test cases. +For each test case, there is an integer _i_ + +**Output Format** +For each test case, if _N(i)_ is even, then print `even`. +If _N(i)_ is odd, then print one line `odd`. + +**Constraints** +1 ≤ *T* ≤ 100 +1 ≤ *i* ≤ 1018 + +**Sample Input** + + 4 + 1 + 2 + 3 + 4 + +**Sample Output** + + odd + odd + odd + even + +**Explanation** +The number of students coming on day 1 is 1: only student #1 attends the class. So N(1)=1 and it is odd. +The number of students coming on day 2 is 1: student #2, so n(2)=1 and it is odd. +The number of students coming on day 3 is 3: student #1, student #2, and student #3. So N(3)=3 and it is odd. +The number of students coming on day 4 is 2: student #3 and student #4. So N(4)=2 and it is even. ",code,Find out if they can dance in pairs?,ai,2014-05-29T07:35:20,2022-09-02T09:54:27,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING. +# The function accepts LONG_INTEGER i as parameter. +# + +def solve(i): + # 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): + i = int(input().strip()) + + result = solve(i) + + fptr.write(result + '\n') + + fptr.close() +","Bob is a dance teacher and he started dance classes recently. He observes a strange attendance pattern among his students. Initially, there are no students. On day *i*, a new student starts attending the class. The student stops attending the class, if and only if he has attended the class for _i_ consecutive days. +Also, the student resumes attending the class, if and only if he has not attended the class for _i_ consecutive days. + +We denote the student who starts coming on day *i* as student *i*. +To mark attendance, `o` denotes present and `x` denotes absent. + +For example, the schedule for student 1 from day 1 is as follows: +`oxoxoxoxoxoxoxoxoxox...` + +The schedule for the student 3 from day 1 is as follows: + +`xxoooxxxoooxxxoooxxx...` +(Student 3 starts attending the class from day 3, and stops attending from day 6, and then starts attending from day 9, and so on. ) + +The schedule for the student 5 from day 1 is as follows. +`xxxxoooooxxxxxoooooxxxxx...` + +Bob wants his students to dance in pairs. However, if the number of students coming on day _i_ is odd, then there will be someone who can't find a partner. So Bob wants to know if the number of students coming on day i is even or odd. We denote the number of students coming on day _i_ as _N(i)_. Please find out whether _N(i)_ is even or odd. + + +**Input format** + +The first line contains an integer, _T_, which denotes the number of test cases. +For each test case, there is an integer _i_ + +**Output Format** +For each test case, if _N(i)_ is even, then print `even`. +If _N(i)_ is odd, then print one line `odd`. + +**Constraints** +1 ≤ *T* ≤ 100 +1 ≤ *i* ≤ 1018 + +**Sample Input** + + 4 + 1 + 2 + 3 + 4 + +**Sample Output** + + odd + odd + odd + even + +**Explanation** +The number of students coming on day 1 is 1: only student #1 attends the class. So N(1)=1 and it is odd. +The number of students coming on day 2 is 1: student #2, so n(2)=1 and it is odd. +The number of students coming on day 3 is 3: student #1, student #2, and student #3. So N(3)=3 and it is odd. +The number of students coming on day 4 is 2: student #3 and student #4. So N(4)=2 and it is even. ",0.5806451612903226,"[""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,,,,,,"{""contest_participation"":2021,""challenge_submissions"":338,""successful_submissions"":195}",2014-06-09T09:29:38,2016-12-03T09:20:56,setter,"###Python 2 +```python +import fileinput +n=0 +for line in fileinput.input(): + t=int(line) + if n>0: + p=1 + q=10**9+1 + while q-p>=2: + mi=(p+q)/2 + if mi**2>t: + q=mi + else: + p=mi + ans=p + if ans%2==1: + print 'odd' + else: + print 'even' + else: + n=int(line) +``` +",not-set,2016-04-24T02:02:41,2016-07-23T17:55:14,Python +74,2561,dance-class,Dancing in Pairs,"Bob is a dance teacher and he started dance classes recently. He observes a strange attendance pattern among his students. Initially, there are no students. On day *i*, a new student starts attending the class. The student stops attending the class, if and only if he has attended the class for _i_ consecutive days. +Also, the student resumes attending the class, if and only if he has not attended the class for _i_ consecutive days. + +We denote the student who starts coming on day *i* as student *i*. +To mark attendance, `o` denotes present and `x` denotes absent. + +For example, the schedule for student 1 from day 1 is as follows: +`oxoxoxoxoxoxoxoxoxox...` + +The schedule for the student 3 from day 1 is as follows: + +`xxoooxxxoooxxxoooxxx...` +(Student 3 starts attending the class from day 3, and stops attending from day 6, and then starts attending from day 9, and so on. ) + +The schedule for the student 5 from day 1 is as follows. +`xxxxoooooxxxxxoooooxxxxx...` + +Bob wants his students to dance in pairs. However, if the number of students coming on day _i_ is odd, then there will be someone who can't find a partner. So Bob wants to know if the number of students coming on day i is even or odd. We denote the number of students coming on day _i_ as _N(i)_. Please find out whether _N(i)_ is even or odd. + + +**Input format** + +The first line contains an integer, _T_, which denotes the number of test cases. +For each test case, there is an integer _i_ + +**Output Format** +For each test case, if _N(i)_ is even, then print `even`. +If _N(i)_ is odd, then print one line `odd`. + +**Constraints** +1 ≤ *T* ≤ 100 +1 ≤ *i* ≤ 1018 + +**Sample Input** + + 4 + 1 + 2 + 3 + 4 + +**Sample Output** + + odd + odd + odd + even + +**Explanation** +The number of students coming on day 1 is 1: only student #1 attends the class. So N(1)=1 and it is odd. +The number of students coming on day 2 is 1: student #2, so n(2)=1 and it is odd. +The number of students coming on day 3 is 3: student #1, student #2, and student #3. So N(3)=3 and it is odd. +The number of students coming on day 4 is 2: student #3 and student #4. So N(4)=2 and it is even. ",code,Find out if they can dance in pairs?,ai,2014-05-29T07:35:20,2022-09-02T09:54:27,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING. +# The function accepts LONG_INTEGER i as parameter. +# + +def solve(i): + # 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): + i = int(input().strip()) + + result = solve(i) + + fptr.write(result + '\n') + + fptr.close() +","Bob is a dance teacher and he started dance classes recently. He observes a strange attendance pattern among his students. Initially, there are no students. On day *i*, a new student starts attending the class. The student stops attending the class, if and only if he has attended the class for _i_ consecutive days. +Also, the student resumes attending the class, if and only if he has not attended the class for _i_ consecutive days. + +We denote the student who starts coming on day *i* as student *i*. +To mark attendance, `o` denotes present and `x` denotes absent. + +For example, the schedule for student 1 from day 1 is as follows: +`oxoxoxoxoxoxoxoxoxox...` + +The schedule for the student 3 from day 1 is as follows: + +`xxoooxxxoooxxxoooxxx...` +(Student 3 starts attending the class from day 3, and stops attending from day 6, and then starts attending from day 9, and so on. ) + +The schedule for the student 5 from day 1 is as follows. +`xxxxoooooxxxxxoooooxxxxx...` + +Bob wants his students to dance in pairs. However, if the number of students coming on day _i_ is odd, then there will be someone who can't find a partner. So Bob wants to know if the number of students coming on day i is even or odd. We denote the number of students coming on day _i_ as _N(i)_. Please find out whether _N(i)_ is even or odd. + + +**Input format** + +The first line contains an integer, _T_, which denotes the number of test cases. +For each test case, there is an integer _i_ + +**Output Format** +For each test case, if _N(i)_ is even, then print `even`. +If _N(i)_ is odd, then print one line `odd`. + +**Constraints** +1 ≤ *T* ≤ 100 +1 ≤ *i* ≤ 1018 + +**Sample Input** + + 4 + 1 + 2 + 3 + 4 + +**Sample Output** + + odd + odd + odd + even + +**Explanation** +The number of students coming on day 1 is 1: only student #1 attends the class. So N(1)=1 and it is odd. +The number of students coming on day 2 is 1: student #2, so n(2)=1 and it is odd. +The number of students coming on day 3 is 3: student #1, student #2, and student #3. So N(3)=3 and it is odd. +The number of students coming on day 4 is 2: student #3 and student #4. So N(4)=2 and it is even. ",0.5806451612903226,"[""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,,,,,,"{""contest_participation"":2021,""challenge_submissions"":338,""successful_submissions"":195}",2014-06-09T09:29:38,2016-12-03T09:20:56,tester,"###Python 2 +```python +from decimal import Decimal as D +for cas in range(input()):print[""even"",""odd""][int(D(input()).sqrt())&1] +``` +",not-set,2016-04-24T02:02:41,2016-07-23T17:55:35,Python +75,2339,permutation-problem,Permutation Problem,"How many n-digit numbers (without leading zeros) are there such that no digit occurs more than k times? + +As the count of such n-digit numbers can be very large, print the answer mod (109+7) + +**Input Format** + +The first line contains an integer, _T_ , the number of test cases. This is followed by _T_ lines each containing 2 space separated integers, _n_ _k_ + + +**Constraints** + +_T_ ≤ 100000 +1 ≤ _n_ ≤ 1000 +1 ≤ _k_ ≤ 109 + +**Sample Input** + + 2 + 2 3 + 2 1 + +**Sample Output** + + 90 + 81 + +**Explanation** +Case 1: A number can appear three times. So we have 9 (all except 0) numbers for first digit and 10 numbers for the second digit. +Case 2: A number can appear only once. So we have 9 choices for the first digit and 9(all except the first one) for the second digit. + +",code,Find the number of n digit numbers,ai,2014-04-10T09:15:12,2022-09-02T09:54:56,"# +# Complete the 'solve' function below. +# +# The function is expected to return an 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() +","How many n-digit numbers (without leading zeros) are there such that no digit occurs more than k times? + +As the count of such n-digit numbers can be very large, print the answer mod (109+7) + +**Input Format** + +The first line contains an integer, _T_ , the number of test cases. This is followed by _T_ lines each containing 2 space separated integers, _n_ and _k_ + + +**Constraints** + +_T_ ≤ 100000 +1 ≤ _n_ ≤ 1000 +1 ≤ _k_ ≤ 109 + +**Sample Input** + + 2 + 2 3 + 2 1 + +**Sample Output** + + 90 + 81 + +**Explanation** +Case 1: A number can appear three times. So we have 9 (all except 0) numbers for first digit and 10 numbers for the second digit. +Case 2: A number can appear only once. So we have 9 choices for the first digit and 9(all except the first one) for the second digit. + +",0.4693877551020408,"[""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,,,,,,"{""contest_participation"":2021,""challenge_submissions"":165,""successful_submissions"":54}",2014-06-09T09:30:00,2016-12-06T19:43:26,tester,"###C++ +```cpp +#include +#include +#define mod 1000000007 +#define min(a,b) ((a)<(b)?(a):(b)) +#define LIM 1000 +#define ull unsigned long long +#define _9_10 300000003 // (9/10'ths mod 10^9+7) + +ull fac[LIM+1]; +ull ifc[LIM+1]; +ull **F[11]; + +int main() { + // precalculate factorials and inverse factorials + fac[0] = ifc[0] = fac[1] = ifc[1] = 1; + for (int i = 2; i <= LIM; i++) { // put the inverses in ifc + ifc[i] = (mod - mod/i) * ifc[mod%i] % mod; + } + for (int i = 2; i <= LIM; i++) { // precalculate fac and ifc + fac[i] = fac[i-1] * i % mod; + ifc[i] = ifc[i-1] * ifc[i] % mod; + } + + // precalculate F[d][n][k] = f_d(n,k) + // around 10^2/2 * 600^2/2 < 10000000 operations + for (int d = 0; d <= 10; d++) { + F[d] = (ull**)malloc((LIM+1)*sizeof(ull*)); + for (int n = 0; n <= LIM; n++) { + F[d][n] = (ull*)calloc(n+1, sizeof(ull)); + for (int k = 0; k <= n; k++) { + if (n == 0) { + F[d][n][k] = 1; + } else if (k == 0 or d == 0) { + F[d][n][k] = 0; + } else { + ull s = 0; + ull pw = 1; + int nn = n; + int nk = k-1; + for (int e = 0; e <= d; e++) { + if (e*k > n) break; + s += fac[d] * ifc[e] % mod * ifc[d-e] % mod * fac[n] % mod * ifc[nn] % mod * pw % mod * F[d-e][nn][min(nn,nk)]; + pw = pw * ifc[k] % mod; + nn -= k; + } + F[d][n][k] = s % mod; + } + } + } + } + + + + ull **f = F[10]; + int z; + scanf(""%d"", &z); + for (int cas = 1; cas <= z; cas++) { + int n, k; + scanf(""%d%d"", &n, &k); + ull ans = f[n][min(n, k)] * _9_10 % mod; // 1/10'ths of the numbers start with zero + printf(""%llu\n"", ans); + } +} +``` +",not-set,2016-04-24T02:02:41,2016-07-23T18:38:08,C++ +76,2557,kundu-and-tree,Kundu and Tree,"Kundu is true tree lover. Tree is a connected graph having _N_ vertices and _N-1_ edges. Today when he got a tree, he colored each edge with one of either red(`r`) or black(`b`) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex _a_ to _b_, vertex _b_ to _c_ and vertex _c_ to _a_ . Note that (a,b,c), (b,a,c) and all such permutations will be considered as the same triplet. + +If the answer is greater than 109 + 7, print the answer modulo (%) 109 + 7. + +**Input Format** +The first line contains an integer _N_, i.e., the number of vertices in tree. +The next _N-1_ lines represent edges: 2 space separated integers denoting an edge followed by a color of the edge. A color of an edge is denoted by a small letter of English alphabet, and it can be either red(`r`) or black(`b`). + +**Output Format** +Print a single number i.e. the number of triplets. + +**Constraints** +1 ≤ _N_ ≤ 105
+A node is numbered between 1 to *N*. + +**Sample Input** + + 5 + 1 2 b + 2 3 r + 3 4 r + 4 5 b + + +**Sample Output** + + 4 + +**Explanation** + +Given tree is something like this.
+![img1](https://hr-filepicker.s3.amazonaws.com/kundu-and-trees.jpg) + +(2,3,4) is one such triplet because on all paths i.e 2 to 3, 3 to 4 and 2 to 4 there is atleast one edge having red color.
+(2,3,5), (1,3,4) and (1,3,5) are other such triplets. +Note that (1,2,3) is NOT a triplet, because the path from 1 to 2 does not have an edge with red color.",code,"Find the number of triplets (a,b,c) such that atleast one edge is colored red on all the three paths.",ai,2014-05-28T05:49:51,2022-08-31T08:33:12,,,,"Kundu is true tree lover. Tree is a connected graph having _N_ vertices and _N-1_ edges. Today when he got a tree, he colored each edge with one of either red(`r`) or black(`b`) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex _a_ to _b_, vertex _b_ to _c_ and vertex _c_ to _a_ . Note that (a,b,c), (b,a,c) and all such permutations will be considered as the same triplet. + +If the answer is greater than 109 + 7, print the answer modulo (%) 109 + 7. + +**Input Format** +The first line contains an integer _N_, i.e., the number of vertices in tree. +The next _N-1_ lines represent edges: 2 space separated integers denoting an edge followed by a color of the edge. A color of an edge is denoted by a small letter of English alphabet, and it can be either red(`r`) or black(`b`). + +**Output Format** +Print a single number i.e. the number of triplets. + +**Constraints** +1 ≤ _N_ ≤ 105
+A node is numbered between 1 to *N*. + +**Sample Input** + + 5 + 1 2 b + 2 3 r + 3 4 r + 4 5 b + + +**Sample Output** + + 4 + +**Explanation** + +Given tree is something like this.
+![image](https://s3.amazonaws.com/hr-assets/0/1526563539-7ce683027b-kundu-and-trees.jpg) + +(2,3,4) is one such triplet because on all paths i.e 2 to 3, 3 to 4 and 2 to 4 there is atleast one edge having red color.
+(2,3,5), (1,3,4) and (1,3,5) are other such triplets. +Note that (1,2,3) is NOT a triplet, because the path from 1 to 2 does not have an edge with red color.",0.4658385093167702,"[""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,,,,,,"{""contest_participation"":3,""challenge_submissions"":0,""successful_submissions"":0}",2014-06-12T12:50:12,2016-12-02T11:13:36,setter," #include + + using namespace std; + + #define MOD 1000000007 + #define s(a) scanf(""%d"",&a); + + vector edges[100009]; + long long int visited[100009]; + long long int count1[100009]; + long long int B[100009],C[100009],D[100009]; + + void dfs(int x, int temp) + { + if(visited[x] == 0) + visited[x] = temp; + for(int i = 0 ; i< edges[x].size() ; i++) + { + if(visited[edges[x][i]] == 0) + dfs(edges[x][i],temp); + } + return; + } + + int main() + { + int n,i,a,b; + char c; + s(n); + for(i=0 ; i< n -1 ; i++) + { + s(a); + s(b); + cin>>c; + if( c != 'r') + { + edges[a].push_back(b); + edges[b].push_back(a); + } + } + int temp = 1; + for(i=1 ; i<=n ; i++) + { + if(visited[i] == 0) + { + dfs(i,temp); + temp++; + } + } + for(i=1 ; i<= n ; i++) + count1[visited[i]]++; + long long int sum = 0; + B[n-1] = count1[n]; + for(i=n-2;i>=0;i--) B[i] = (B[i+1] + count1[i+1])%MOD; + for(i=1;i=1;i--) D[i] = (D[i+1] + C[i])%MOD; + + for(i=0;i9 + 7, print the answer modulo (%) 109 + 7. + +**Input Format** +The first line contains an integer _N_, i.e., the number of vertices in tree. +The next _N-1_ lines represent edges: 2 space separated integers denoting an edge followed by a color of the edge. A color of an edge is denoted by a small letter of English alphabet, and it can be either red(`r`) or black(`b`). + +**Output Format** +Print a single number i.e. the number of triplets. + +**Constraints** +1 ≤ _N_ ≤ 105
+A node is numbered between 1 to *N*. + +**Sample Input** + + 5 + 1 2 b + 2 3 r + 3 4 r + 4 5 b + + +**Sample Output** + + 4 + +**Explanation** + +Given tree is something like this.
+![img1](https://hr-filepicker.s3.amazonaws.com/kundu-and-trees.jpg) + +(2,3,4) is one such triplet because on all paths i.e 2 to 3, 3 to 4 and 2 to 4 there is atleast one edge having red color.
+(2,3,5), (1,3,4) and (1,3,5) are other such triplets. +Note that (1,2,3) is NOT a triplet, because the path from 1 to 2 does not have an edge with red color.",code,"Find the number of triplets (a,b,c) such that atleast one edge is colored red on all the three paths.",ai,2014-05-28T05:49:51,2022-08-31T08:33:12,,,,"Kundu is true tree lover. Tree is a connected graph having _N_ vertices and _N-1_ edges. Today when he got a tree, he colored each edge with one of either red(`r`) or black(`b`) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex _a_ to _b_, vertex _b_ to _c_ and vertex _c_ to _a_ . Note that (a,b,c), (b,a,c) and all such permutations will be considered as the same triplet. + +If the answer is greater than 109 + 7, print the answer modulo (%) 109 + 7. + +**Input Format** +The first line contains an integer _N_, i.e., the number of vertices in tree. +The next _N-1_ lines represent edges: 2 space separated integers denoting an edge followed by a color of the edge. A color of an edge is denoted by a small letter of English alphabet, and it can be either red(`r`) or black(`b`). + +**Output Format** +Print a single number i.e. the number of triplets. + +**Constraints** +1 ≤ _N_ ≤ 105
+A node is numbered between 1 to *N*. + +**Sample Input** + + 5 + 1 2 b + 2 3 r + 3 4 r + 4 5 b + + +**Sample Output** + + 4 + +**Explanation** + +Given tree is something like this.
+![image](https://s3.amazonaws.com/hr-assets/0/1526563539-7ce683027b-kundu-and-trees.jpg) + +(2,3,4) is one such triplet because on all paths i.e 2 to 3, 3 to 4 and 2 to 4 there is atleast one edge having red color.
+(2,3,5), (1,3,4) and (1,3,5) are other such triplets. +Note that (1,2,3) is NOT a triplet, because the path from 1 to 2 does not have an edge with red color.",0.4658385093167702,"[""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,,,,,,"{""contest_participation"":3,""challenge_submissions"":0,""successful_submissions"":0}",2014-06-12T12:50:12,2016-12-02T11:13:36,tester," // When I wrote this, only God and I understood what I was doing + // Now, God only knows + + #include + using namespace std; + #define assn(n,a,b) assert(n<=b && n>=a) + #define pb push_back + typedef vector VI; + typedef long long LL; + #define MOD 1000000007 + LL mpow(LL a, LL n) + {LL ret=1;LL b=a;while(n) {if(n&1) + ret=(ret*b)%MOD;b=(b*b)%MOD;n>>=1;} + return (LL)ret;} + VI ar[100005]={}; + int flag[100005]={}; + int bfs(int node) + { + queue < int > myq; + myq.push(node); + flag[node]=1; + int p,cnt=0; + while(!myq.empty()) + { + p=myq.front(); + cnt++; + myq.pop(); + for(int i=0; i> n; + assn(n,1,100000); + for(i=1; i> u >> v >> s; + u--,v--; + if(s[0]!='r')ar[u].pb(v),ar[v].pb(u); + } + for(i=0; i$5$ +For each _a x_ or _r x_, $x$ will always be a signed integer (which will fit in 32 bits). + +**Sample Input:** + + 7 + r 1 + a 1 + a 2 + a 1 + r 1 + r 2 + r 1 + +**Sample Output:** + + Wrong! + 1 + 1.5 + 1 + 1.5 + 1 + Wrong! + +**Note:** As evident from the last line of the input, if after remove operation the list becomes empty, you have to print *Wrong!*. ",0.418013857,"[""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,,,,,,,2014-06-16T10:15:13,2016-12-01T23:14:40,setter," #include + #include + #include + #include + + using namespace std; + + multiset s1,s2; //0<=|s1|-|s2|<=1 + char s[55]; + + void gao() { + int a,b; + bool f1,f2; + if (s1.empty()) { + puts(""Wrong!""); + return; + } + if (s1.size()==s2.size()) { + a=*s1.rbegin(); + b=*s2.begin(); + f1=a%2; + f2=b%2; + if (f1==f2) { + printf(""%.0lf\n"",(a*1.+b)/2.); + } + else { + printf(""%.1lf\n"",(a*1.+b)/2.); + } + } + else { + printf(""%d\n"",*s1.rbegin()); + } + } + + void gao1(int x) { //add x + if (s1.empty()) { + s1.insert(x); + } + else if (s1.size()==s2.size()) { + s2.insert(x); + s1.insert(*s2.begin()); + s2.erase(s2.begin()); + } + else { + s1.insert(x); + s2.insert(*s1.rbegin()); + s1.erase(s1.find(*s1.rbegin())); + } + gao(); + + } + + void gao2(int x) { + multiset::iterator t1=s1.find(x),t2=s2.find(x); + if ((t1==s1.end()) && (t2==s2.end())) { + puts(""Wrong!""); + return; + } + if (s1.size()==s2.size()) { + if (t2!=s2.end()) { + s2.erase(t2); + } + else { + s1.erase(t1); + s1.insert(*s2.begin()); + s2.erase(s2.begin()); + } + } + else if (t1!=s1.end()) { + s1.erase(t1); + } + else { + s2.erase(t2); + s2.insert(*s1.rbegin()); + s1.erase(s1.find(*s1.rbegin())); + } + gao(); + } + + int main() { + int i,x; + + /*s1.clear(); + s2.clear();*/ + for (scanf(""%d"",&i);i;--i) { + scanf(""%s%d"",s,&x); + if (s[0]=='a') { + gao1(x); + } + else { + gao2(x); + } + } + return 0; + + } + +",not-set,2016-04-24T02:02:41,2016-04-24T02:02:41,C++ +79,104,median,Median Updates,"The median of *M* numbers is defined as the middle number after sorting them in order, if *M* is odd. Or it is the average of the middle 2 numbers (again after sorting), if *M* is even. You have an empty number list at first. Then you can add in or remove some number from the list. For each add or remove operation, output the median of numbers in the list. + + +**Example :** +For a set of *M = 5* numbers *{9, 2, 8, 4, 1}* the median is the third number in sorted set *{1, 2, 4, 8, 9}* which is *4*. Similarly, for a set of *M = 4*, *{5, 2, 10, 4}*, the median is the average of second and the third element in the sorted set *{2, 4, 5, 10}* which is *(4+5)/2 = 4.5*.   + +**Input:** +The first line is an integer *N* that indicates the number of operations. Each of the next *N* lines is either *a x* or *r x* . *a x* indicates that x is added to the set, and *r x* indicates that x is removed from the set. + +**Output:** +For each operation: If the operation is _add_ output the median after adding *x* in a single line. If the operation is _remove_ and the number *x* is not in the list, output *Wrong!* in a single line. If the operation is _remove_ and the number *x* is in the list, output the median after deleting *x* in a single line. (If the result is an integer DO NOT output decimal point. And if the result is a real number , DO NOT output trailing 0s.) + +**Note** +If your median is 3.0, print only 3. And if your median is 3.50, print only 3.5. Whenever you need to print the median and the list is empty, print *Wrong!* + +**Constraints:** +0 < *N* <= 100,000 +For each *a x* or *r x*, *x* will always be an integer which will fit in 32 bit signed integer. + +**Sample Input:** + + 7 + r 1 + a 1 + a 2 + a 1 + r 1 + r 2 + r 1 + +**Sample Output:** + + Wrong! + 1 + 1.5 + 1 + 1.5 + 1 + Wrong! + +**Note:** As evident from the last line of the input, if after remove operation the list becomes empty, you have to print *Wrong!*. ",code,Return the median after each number is added to a list.,algorithm,2013-01-04T20:28:56,2022-08-31T08:33:08,"#!/bin/python +def median(a,x): + + +N = int(input()) +s = [] +x = [] +for i in range(0, N): + tmp = input().strip().split(' ') + a, b = [xx for xx in tmp] + s.append(a) + x.append(int(b)) +median(s,x) +",,,"The median of $M$ numbers is defined as the middle number after sorting them in order if $M$ is odd. Or it is the average of the middle two numbers if $M$ is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. + +**Example:** +For a set of $M = 5$ numbers ${9, 2, 8, 4, 1}$ the median is the third number in the sorted set ${1, 2, 4, 8, 9}$, which is $4$. Similarly, for a set of $M = 4$ numbers, ${5, 2, 10, 4}$, the median is the average of the second and the third element in the sorted set ${2, 4, 5, 10}$, which is $(4+5)/2 = 4.5$.   + +**Input:** +The first line is an integer, $N$, that indicates the number of operations. Each of the next $N$ lines is either _a x_ or _r x_. _a x_ indicates that $x$ is added to the set, and _r x_ indicates that $x$ is removed from the set. + +**Output:** +For each operation: If the operation is _add_, output the median after adding $x$ in a single line. If the operation is _remove_ and the number $x$ is not in the list, output *Wrong!* in a single line. If the operation is _remove_ and the number $x$ is in the list, output the median after deleting $x$ in a single line. (If the result is an integer DO NOT output decimal point. And if the result is a real number, DO NOT output trailing 0s.) + +**Note** +If your median is 3.0, print only 3. And if your median is 3.50, print only 3.5. Whenever you need to print the median and the list is empty, print *Wrong!* + +**Constraints:** +$0 \lt N \le 10$$5$ +For each _a x_ or _r x_, $x$ will always be a signed integer (which will fit in 32 bits). + +**Sample Input:** + + 7 + r 1 + a 1 + a 2 + a 1 + r 1 + r 2 + r 1 + +**Sample Output:** + + Wrong! + 1 + 1.5 + 1 + 1.5 + 1 + Wrong! + +**Note:** As evident from the last line of the input, if after remove operation the list becomes empty, you have to print *Wrong!*. ",0.418013857,"[""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,,,,,,,2014-06-16T10:15:13,2016-12-01T23:14:40,tester," + #include + #include + #include + + using namespace std; + using namespace __gnu_pbds; + + typedef pair< int , int > pii; + + int main() { + int t; + cin>>t; + char c; + int n; + int insert_counter = 0; + tree < pii , null_type , less , rb_tree_tag , tree_order_statistics_node_update > T; + + for (int i = 0;i>c>>n; + if (c == 'r') { + auto it = T.find_by_order( T.order_of_key( {n,-1} ) ); + if( it == T.end() || it->first != n ) { + cout<<""Wrong!""<first<first; + long long int t2 = T.find_by_order(T.size()/2 -1)->first; + long long int temp = t1 + t2; + if (temp == -1) cout<<""-""; + cout<y) return 1; + ans = pow(A[x],find(x+1,y)) + return ans + } + +Note : pow(a,b) = *ab*. + +**Input Format** +The first line of the input contains an integer *N*. +The next line contains *N* space separated non-negative integers(whole numbers less than or equal to 9). +The line after that contains a positive integer, *Q* , the denotes the number of queries to follow. +*Q* lines follow, each line contains two positive integer *x* and *y* separated by a single space. + +**Output Format** +For each query, display 'Even' if the value returned is Even, otherwise display 'Odd'. + +**Constraints** +2 ≤ *N* ≤ 105 +2 ≤ *Q* ≤ 105 +1 ≤ *x,y* ≤ *N* +*x* ≤ *y* + +Array is 1-indexed. + +*No 2 consecutive entries in the array will be zero.* + +**Sample Input** + + 3 + 3 2 7 + 2 + 1 2 + 2 3 + +**Sample Output** + + Odd + Even + +**Explanation** + +find(1,2) = 9, which is Odd +find(2,3) = 128, which is even ",code,Is the number odd or even?,ai,2014-06-08T11:37:31,2022-09-02T09:54:12,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING_ARRAY. +# The function accepts following parameters: +# 1. INTEGER_ARRAY arr +# 2. 2D_INTEGER_ARRAY queries +# + +def solve(arr, queries): + # 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())) + + q = int(input().strip()) + + queries = [] + + for _ in range(q): + queries.append(list(map(int, input().rstrip().split()))) + + result = solve(arr, queries) + + fptr.write('\n'.join(result)) + fptr.write('\n') + + fptr.close() +","You are given an array *A* of size *N*. You are also given an integer *Q*. Can you figure out the answer to each of the *Q* queries? + +Each query contains 2 integers x and y, and you need to find whether the value find(x,y) is Odd or Even: + + find(int x,int y) + { + if(x>y) return 1; + ans = pow(A[x],find(x+1,y)) + return ans + } + +Note : pow(a,b) = *ab*. + +**Input Format** +The first line of the input contains an integer *N*. +The next line contains *N* space separated non-negative integers(whole numbers less than or equal to 9). +The line after that contains a positive integer, *Q* , the denotes the number of queries to follow. +*Q* lines follow, each line contains two positive integer *x* and *y* separated by a single space. + +**Output Format** +For each query, display 'Even' if the value returned is Even, otherwise display 'Odd'. + +**Constraints** +2 ≤ *N* ≤ 105 +2 ≤ *Q* ≤ 105 +1 ≤ *x,y* ≤ *N* +*x* ≤ *y* + +Array is 1-indexed. + +*No 2 consecutive entries in the array will be zero.* + +**Sample Input** + + 3 + 3 2 7 + 2 + 1 2 + 2 3 + +**Sample Output** + + Odd + Even + +**Explanation** + +find(1,2) = 9, which is Odd +find(2,3) = 128, which is even ",0.5514705882352942,"[""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,,,,,,"{""contest_participation"":2182,""challenge_submissions"":916,""successful_submissions"":579}",2014-06-18T06:05:31,2016-12-05T12:34:41,setter,"###C++ +```cpp +#include +#include +#define MaxN 100000 +int A[MaxN+1]; +int main() +{ + int N,Q,x,y,last=1,flip; + scanf(""%d"",&N); + for(int i=1;i<=N;i++){ + scanf(""%d"",&A[i]); + assert(0 <= A[i] && A[i]<=9); + assert(!(last==0 && last==A[i])); + last=A[i]; + } + scanf(""%d"",&Q); + while(Q--){ + scanf(""%d %d"",&x,&y); + assert(x<=y && y<=N && x>=1); + if(x!=y && A[x+1]==0) flip=1; + else flip=0; + if(flip) printf(""Odd\n""); + else if(A[x]&1) printf(""Odd\n""); + else printf(""Even\n""); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:42,2016-07-23T16:31:21,C++ +81,2581,even-odd-query,Even Odd Query,"You are given an array *A* of size *N*. You are also given an integer *Q*. Can you figure out the answer to each of the *Q* queries? + +Each query contains 2 integers x and y, and you need to find whether the value find(x,y) is Odd or Even: + + find(int x,int y) + { + if(x>y) return 1; + ans = pow(A[x],find(x+1,y)) + return ans + } + +Note : pow(a,b) = *ab*. + +**Input Format** +The first line of the input contains an integer *N*. +The next line contains *N* space separated non-negative integers(whole numbers less than or equal to 9). +The line after that contains a positive integer, *Q* , the denotes the number of queries to follow. +*Q* lines follow, each line contains two positive integer *x* and *y* separated by a single space. + +**Output Format** +For each query, display 'Even' if the value returned is Even, otherwise display 'Odd'. + +**Constraints** +2 ≤ *N* ≤ 105 +2 ≤ *Q* ≤ 105 +1 ≤ *x,y* ≤ *N* +*x* ≤ *y* + +Array is 1-indexed. + +*No 2 consecutive entries in the array will be zero.* + +**Sample Input** + + 3 + 3 2 7 + 2 + 1 2 + 2 3 + +**Sample Output** + + Odd + Even + +**Explanation** + +find(1,2) = 9, which is Odd +find(2,3) = 128, which is even ",code,Is the number odd or even?,ai,2014-06-08T11:37:31,2022-09-02T09:54:12,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING_ARRAY. +# The function accepts following parameters: +# 1. INTEGER_ARRAY arr +# 2. 2D_INTEGER_ARRAY queries +# + +def solve(arr, queries): + # 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())) + + q = int(input().strip()) + + queries = [] + + for _ in range(q): + queries.append(list(map(int, input().rstrip().split()))) + + result = solve(arr, queries) + + fptr.write('\n'.join(result)) + fptr.write('\n') + + fptr.close() +","You are given an array *A* of size *N*. You are also given an integer *Q*. Can you figure out the answer to each of the *Q* queries? + +Each query contains 2 integers x and y, and you need to find whether the value find(x,y) is Odd or Even: + + find(int x,int y) + { + if(x>y) return 1; + ans = pow(A[x],find(x+1,y)) + return ans + } + +Note : pow(a,b) = *ab*. + +**Input Format** +The first line of the input contains an integer *N*. +The next line contains *N* space separated non-negative integers(whole numbers less than or equal to 9). +The line after that contains a positive integer, *Q* , the denotes the number of queries to follow. +*Q* lines follow, each line contains two positive integer *x* and *y* separated by a single space. + +**Output Format** +For each query, display 'Even' if the value returned is Even, otherwise display 'Odd'. + +**Constraints** +2 ≤ *N* ≤ 105 +2 ≤ *Q* ≤ 105 +1 ≤ *x,y* ≤ *N* +*x* ≤ *y* + +Array is 1-indexed. + +*No 2 consecutive entries in the array will be zero.* + +**Sample Input** + + 3 + 3 2 7 + 2 + 1 2 + 2 3 + +**Sample Output** + + Odd + Even + +**Explanation** + +find(1,2) = 9, which is Odd +find(2,3) = 128, which is even ",0.5514705882352942,"[""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,,,,,,"{""contest_participation"":2182,""challenge_submissions"":916,""successful_submissions"":579}",2014-06-18T06:05:31,2016-12-05T12:34:41,tester,"###C++ +```cpp +#include +using namespace std; +int A[100008], N; +int find(int x, int y){ + if(A[x]%2) return 1; + if(x == y) return 0; + if(A[x+1] == 0) return 1; + return 0; +} +int main(){ + int x,y,Q; + cin >> N; + for(int i = 1; i <= N; i++) cin >> A[i]; + cin >> Q; + while(Q--){ + cin >> x >> y; + if(find(x,y)) cout << ""Odd"" << endl; + else cout << ""Even"" << endl; + } + return 0; +} +``` +",not-set,2016-04-24T02:02:42,2016-07-23T16:31:28,C++ +82,3092,reverse-trip-to-jerusalem,Reverse Trip to Jerusalem,"You and your $N-1$ friends recently got tired of playing Trip to Jerusalem (i.e. Musical Chairs). In order to make things interesting again, you decide to invent a new game. And you call it *Reverse Trip to Jerusalem*. + +Here's how it works. Instead of arranging the chairs in a circle, the $N$ friends (including you) arrange yourselves in a circle. Then exactly one person in the circle holds the chair. + +For the first round, all $N$ of you will be in the circle. The music starts and plays for $C_1$ seconds. Every second, the person holding the chair shall pass it to the person to his left. The person who receives the chair when the music ends is OUT and he/she is not included in the circle in the subsequent rounds. The person to his left then receives the chair. And that's where the chair starts for the second round. + +For the $i^\text{th}$ round, $N-i+1$ players remain and the person holding the chair is the person to the left of the most recently outed person. The music starts and plays for $C_i$ seconds. The procedure for passing the chair is the same as the first round. The player who receives the chair when the music ends is OUT. + +The person who remains after $N-1$ rounds is the winner. + +Of course, you want to win this. It is your dream and you believe that you will survive. The person who initially holds the chair in the first round is Todd. You wish to know where to position yourself in order to win the game. + +**Input Format** +The input consists of two lines. +The first line contains a single integer $N$. +The second line contains $N-1$ integers, the $C_i$'s, each separated by single spaces. + +**Output Format** +Output a single line describing the winning position. If the winning position is the $P^\text{th}$ position to the left of Todd, then output the integer $P$ (Note that $0 < P < N$). However, if the winning position is Todd's position, print `YOU MUST BE TODD`. + +**Constraints** +$1 \le N \le 2\cdot 10^5$ +$1 \le C_i \le 2\cdot 10^5$ + +**Sample Input 1** + + 5 + 1 2 2 4 + +**Sample Output 1** + + 2 + +**Sample Input 2** + + 2 + 1 + +**Sample Output 2** + + YOU MUST BE TODD + +**Explanation** +In the first case, let $P_1$, $P_2$, $P_3$ and $P_4$ be the four persons to Todd's left, in that order. The first round begins with Todd passing the chair to $P_1$, which subsequently outs him (since the music is only 1 second long). The second round starts with $P_2$ holding the chair. The music ends when $P_4$ receives the chair, thus forcing him out of the game. The third round starts with Todd again and stops at $P_3$. The fourth round starts with Todd and ends with Todd and so $P_2$ survives. + +In the second case, Todd passes the chair to the other person, the 1-second music stops and that person is out of the game. Hence, the only way to win the game is to become Todd. + +",code,Winning in Trip to Jerusalem is so two thousand and late. Winning Reverse Trip to Jerusalem is what matters.,ai,2014-06-19T02:26:40,2018-03-13T12:03:35,,,,"You and your $N-1$ friends recently got tired of playing Trip to Jerusalem (i.e. Musical Chairs). In order to make things interesting again, you decide to invent a new game. And you call it *Reverse Trip to Jerusalem*. + +Here's how it works. Instead of arranging the chairs in a circle, the $N$ friends (including you) arrange yourselves in a circle. Then exactly one person in the circle holds the chair. + +For the first round, all $N$ of you will be in the circle. The music starts and plays for $C_1$ seconds. Every second, the person holding the chair shall pass it to the person to his left. The person who receives the chair when the music ends is OUT and he/she is not included in the circle in the subsequent rounds. The person to his left then receives the chair. And that's where the chair starts for the second round. + +For the $i^\text{th}$ round, $N-i+1$ players remain and the person holding the chair is the person to the left of the most recently outed person. The music starts and plays for $C_i$ seconds. The procedure for passing the chair is the same as the first round. The player who receives the chair when the music ends is OUT. + +The person who remains after $N-1$ rounds is the winner. + +Of course, you want to win this. It is your dream and you believe that you will survive. The person who initially holds the chair in the first round is Todd. You wish to know where to position yourself in order to win the game. + +**Input Format** +The input consists of two lines. +The first line contains a single integer $N$. +The second line contains $N-1$ integers, the $C_i$'s, each separated by single spaces. + +**Output Format** +Output a single line describing the winning position. If the winning position is the $P^\text{th}$ position to the left of Todd, then output the integer $P$ (Note that $0 < P < N$). However, if the winning position is Todd's position, print `YOU MUST BE TODD`. + +**Constraints** +$1 \le N \le 2\cdot 10^5$ +$1 \le C_i \le 2\cdot 10^5$ + +*Note:* The time limit is half of the usual time limit. + +**Sample Input 1** + + 5 + 1 2 2 4 + +**Sample Output 1** + + 2 + +**Sample Input 2** + + 2 + 1 + +**Sample Output 2** + + YOU MUST BE TODD + +**Explanation** +In the first case, let $P_1$, $P_2$, $P_3$ and $P_4$ be the four persons to Todd's left, in that order. The first round begins with Todd passing the chair to $P_1$, which subsequently outs him (since the music is only 1 second long). The second round starts with $P_2$ holding the chair. The music ends when $P_4$ receives the chair, thus forcing him out of the game. The third round starts with Todd again and stops at $P_3$. The fourth round starts with Todd and ends with Todd and so $P_2$ survives. + +In the second case, Todd passes the chair to the other person, the 1-second music stops and that person is out of the game. Hence, the only way to win the game is to become Todd. + +",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,"{""contest_participation"":83,""challenge_submissions"":12,""successful_submissions"":4}",2014-06-21T10:01:03,2018-02-06T18:33:47,setter,"```cpp +#include +#include + +struct tree { + int count; // how many are alive at this tree + int l; // leftmost index + tree *parent; + tree *left; + tree *right; +}; + +int n; +tree *root; +tree *curr; + +tree *leftmost() { + // find the leftmost alive leaf + tree *t = root; + while (t->left) { + if (t->left->count) { + // there are alive leaves on the left. go there + t = t->left; + } else { + t = t->right; + } + } + return t; +} + +tree *create(int l, int r) { + // create a tree on range [l,r) + tree *t = (tree*)malloc(sizeof(tree)); + t->count = r - l; + t->l = l; + t->parent = 0; + t->left = 0; + t->right = 0; + if (r - l > 1) { + int m = l + r >> 1; + t->left = create(l, m); + t->right = create(m, r); + t->left->parent = t; + t->right->parent = t; + } + return t; +} +void init() { + root = create(0, n); + curr = leftmost();// start at person 0 +} + +int count_right(tree *t) { + // how many alive leaves are to the right of leaf t? + int ct = 0; + while (t->parent) { + tree *p = t->parent; + if (p->left == t) { + ct += p->right->count; + } + t = p; + } + return ct; +} +void forward(int k) { + // assumes k < root->count + int ct = count_right(curr); + if (k > ct) { + // wrap around + k -= ct + 1; + curr = leftmost(); + } + if (k) { + // go up + while (curr->parent) { + tree *p = curr->parent; + if (p->left == curr) { + if (k <= p->right->count) { + curr = p->right; + break; + } else { + k -= p->right->count; + } + } + curr = p; + } + // go down + while (curr->left) { + if (k <= curr->left->count) { + curr = curr->left; + } else { + k -= curr->left->count; + curr = curr->right; + } + } + } +} + +void eliminate() { + // eliminate curr + curr->count = 0; + for (tree *p = curr->parent; p; p = p->parent) { + p->count--; + } + // find next alive leaf + forward(1); +} + +int main() { + scanf(""%d"",&n); + init(); + for (int i = 0; i < n - 1; ++i) { + int C; + scanf(""%d"", &C); + forward(C % (n-i)); // move to C'th person + eliminate(); // eliminate + } + + if (curr->l == 0) { + printf(""YOU MUST BE TODD\n""); + } else { + printf(""%d\n"", curr->l); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:42,2018-02-06T17:55:02,C++ +83,3092,reverse-trip-to-jerusalem,Reverse Trip to Jerusalem,"You and your $N-1$ friends recently got tired of playing Trip to Jerusalem (i.e. Musical Chairs). In order to make things interesting again, you decide to invent a new game. And you call it *Reverse Trip to Jerusalem*. + +Here's how it works. Instead of arranging the chairs in a circle, the $N$ friends (including you) arrange yourselves in a circle. Then exactly one person in the circle holds the chair. + +For the first round, all $N$ of you will be in the circle. The music starts and plays for $C_1$ seconds. Every second, the person holding the chair shall pass it to the person to his left. The person who receives the chair when the music ends is OUT and he/she is not included in the circle in the subsequent rounds. The person to his left then receives the chair. And that's where the chair starts for the second round. + +For the $i^\text{th}$ round, $N-i+1$ players remain and the person holding the chair is the person to the left of the most recently outed person. The music starts and plays for $C_i$ seconds. The procedure for passing the chair is the same as the first round. The player who receives the chair when the music ends is OUT. + +The person who remains after $N-1$ rounds is the winner. + +Of course, you want to win this. It is your dream and you believe that you will survive. The person who initially holds the chair in the first round is Todd. You wish to know where to position yourself in order to win the game. + +**Input Format** +The input consists of two lines. +The first line contains a single integer $N$. +The second line contains $N-1$ integers, the $C_i$'s, each separated by single spaces. + +**Output Format** +Output a single line describing the winning position. If the winning position is the $P^\text{th}$ position to the left of Todd, then output the integer $P$ (Note that $0 < P < N$). However, if the winning position is Todd's position, print `YOU MUST BE TODD`. + +**Constraints** +$1 \le N \le 2\cdot 10^5$ +$1 \le C_i \le 2\cdot 10^5$ + +**Sample Input 1** + + 5 + 1 2 2 4 + +**Sample Output 1** + + 2 + +**Sample Input 2** + + 2 + 1 + +**Sample Output 2** + + YOU MUST BE TODD + +**Explanation** +In the first case, let $P_1$, $P_2$, $P_3$ and $P_4$ be the four persons to Todd's left, in that order. The first round begins with Todd passing the chair to $P_1$, which subsequently outs him (since the music is only 1 second long). The second round starts with $P_2$ holding the chair. The music ends when $P_4$ receives the chair, thus forcing him out of the game. The third round starts with Todd again and stops at $P_3$. The fourth round starts with Todd and ends with Todd and so $P_2$ survives. + +In the second case, Todd passes the chair to the other person, the 1-second music stops and that person is out of the game. Hence, the only way to win the game is to become Todd. + +",code,Winning in Trip to Jerusalem is so two thousand and late. Winning Reverse Trip to Jerusalem is what matters.,ai,2014-06-19T02:26:40,2018-03-13T12:03:35,,,,"You and your $N-1$ friends recently got tired of playing Trip to Jerusalem (i.e. Musical Chairs). In order to make things interesting again, you decide to invent a new game. And you call it *Reverse Trip to Jerusalem*. + +Here's how it works. Instead of arranging the chairs in a circle, the $N$ friends (including you) arrange yourselves in a circle. Then exactly one person in the circle holds the chair. + +For the first round, all $N$ of you will be in the circle. The music starts and plays for $C_1$ seconds. Every second, the person holding the chair shall pass it to the person to his left. The person who receives the chair when the music ends is OUT and he/she is not included in the circle in the subsequent rounds. The person to his left then receives the chair. And that's where the chair starts for the second round. + +For the $i^\text{th}$ round, $N-i+1$ players remain and the person holding the chair is the person to the left of the most recently outed person. The music starts and plays for $C_i$ seconds. The procedure for passing the chair is the same as the first round. The player who receives the chair when the music ends is OUT. + +The person who remains after $N-1$ rounds is the winner. + +Of course, you want to win this. It is your dream and you believe that you will survive. The person who initially holds the chair in the first round is Todd. You wish to know where to position yourself in order to win the game. + +**Input Format** +The input consists of two lines. +The first line contains a single integer $N$. +The second line contains $N-1$ integers, the $C_i$'s, each separated by single spaces. + +**Output Format** +Output a single line describing the winning position. If the winning position is the $P^\text{th}$ position to the left of Todd, then output the integer $P$ (Note that $0 < P < N$). However, if the winning position is Todd's position, print `YOU MUST BE TODD`. + +**Constraints** +$1 \le N \le 2\cdot 10^5$ +$1 \le C_i \le 2\cdot 10^5$ + +*Note:* The time limit is half of the usual time limit. + +**Sample Input 1** + + 5 + 1 2 2 4 + +**Sample Output 1** + + 2 + +**Sample Input 2** + + 2 + 1 + +**Sample Output 2** + + YOU MUST BE TODD + +**Explanation** +In the first case, let $P_1$, $P_2$, $P_3$ and $P_4$ be the four persons to Todd's left, in that order. The first round begins with Todd passing the chair to $P_1$, which subsequently outs him (since the music is only 1 second long). The second round starts with $P_2$ holding the chair. The music ends when $P_4$ receives the chair, thus forcing him out of the game. The third round starts with Todd again and stops at $P_3$. The fourth round starts with Todd and ends with Todd and so $P_2$ survives. + +In the second case, Todd passes the chair to the other person, the 1-second music stops and that person is out of the game. Hence, the only way to win the game is to become Todd. + +",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,"{""contest_participation"":83,""challenge_submissions"":12,""successful_submissions"":4}",2014-06-21T10:01:03,2018-02-06T18:33:47,tester,"```cpp +#include +#include +#include +#include +#include + +using namespace std; + +int f[200010]; + + +int main() { +int n; + scanf(""%d"",&n); + for (int i = 0; i + 1 < n; ++i) { + scanf(""%d"",f + i); + + } + int x = 0; + for (int i = 2; i <= n; ++i) { + x = (x + f[n - i] + 1) % i; + } + + if (x == 0) { + puts(""YOU MUST BE TODD""); + } + else { + printf(""%d\n"",x); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:42,2018-02-06T17:55:02,C++ +84,2579,messy-medians,Messy Medians,"Robin is stuck doing a terminally boring data entry job. She has to enter a lot of numeric observations manually and report running medians after each step to her project lead. The task is sufficiently mind-numbing for her to make a lot of entry errors. Fortunately, she has a keen eye and often notices her mistakes. On the other hand, sometimes she makes mistakes while spotting - or correcting - previous mistakes, and so on. +
+Your task is to implement a program that will help Robin finish this boring job as soon as possible. The program will accept user input and report a running median for all the observations entered so far. It should also be capable of rolling back to any previous state (including those that were previously rolled back on their own). + +**Input Format** + +First line contains an integer,*T*, the total number of lines to follow. +
+Each of the following *T* lines contains either: + +1. a positive integer *N* that will contribute in calculation of the current running median; + +2. or a request to roll back to a previous state, which is represented by a negative number between -1 and -*M*, where *M* is the total number of queries executed so far. -1 requests a return to the immediately preceding state (which actually results in no state change), while -*M* requests a return to the state after entering the very first number. + +**Output Format** + +Output *T* integers, representing current running medians after performing operations on corresponding lines in the input. + +**Constraints** + +1 ≤ _T_ ≤ 105 +1 ≤ _N_ ≤ 109 +1 ≤ _M_ ≤ number of queries executed so far. + +**Notes** + +* You will never be asked to roll back to a non-existent state, or a state for which the running median is not well-defined. In particular, the first line after *T* will always be a positive number. + +* You should print out the median after executing each query, including rollbacks. + +* For collections with even number of elements we report the smaller of the two candidate medians. + + + +**Sample Input** + + 10 + 1 + 5 + -2 + 3 + 2 + 5 + 4 + -7 + 2 + -3 + +**Sample Output** + + 1 + 1 + 1 + 1 + 2 + 2 + 3 + 1 + 1 + 3 + +**Explanation** + +(This represents the collection of the numbers tracked after each step, with median in bold.) + +Step 1: 1 -> [**1**] + +Step 2: 5 -> [**1**, 5] + +Step 3: request a return to state after step (3 - 2) = 1 -> [**1**] + +Step 4: 3 -> [**1**, 3] + +Step 5: 2 -> [1, **2**, 3] + +Step 6: 5 -> [1, **2**, 3, 5] + +Step 7: 4 -> [1, 2, **3**, 4, 5] + +Step 8: request a return to state after step (8 - 7) = 1 -> [**1**] + +Step 9: 2 -> [**1**, 2] + +Step 10: request a return to state after step (10 - 3) = 7 -> [1, 2, **3**, 4, 5] + +--- + +**Tested by:** [Abhiranjan Kumar](/abhiranjan) +",code,(Add|Remove|getMedian),ai,2014-06-05T17:02:31,2016-09-01T16:22:55,,,,"Robin is stuck doing a terminally boring data entry job. She has to enter a lot of numeric observations manually and report running medians after each step to her project lead. The task is sufficiently mind-numbing for her to make a lot of entry errors. Fortunately, she has a keen eye and often notices her mistakes. On the other hand, sometimes she makes mistakes while spotting - or correcting - previous mistakes, and so on. +
+Your task is to implement a program that will help Robin finish this boring job as soon as possible. The program will accept user input and report a running median for all the observations entered so far. It should also be capable of rolling back to any previous state (including those that were previously rolled back on their own). + +**Input Format** + +First line contains an integer,*T*, the total number of lines to follow. +
+Each of the following *T* lines contains either: + +1. a positive integer *N* that will contribute in calculation of the current running median; + +2. or a request to roll back to a previous state, which is represented by a negative number between -1 and -*M*, where *M* is the total number of queries executed so far. -1 requests a return to the immediately preceding state (which actually results in no state change), while -*M* requests a return to the state after entering the very first number. + +**Output Format** + +Output *T* integers, representing current running medians after performing operations on corresponding lines in the input. + +**Constraints** + +1 ≤ _T_ ≤ 105 +1 ≤ _N_ ≤ 109 +1 ≤ _M_ ≤ number of queries executed so far. + +**Notes** + +* You will never be asked to roll back to a non-existent state, or a state for which the running median is not well-defined. In particular, the first line after *T* will always be a positive number. + +* You should print out the median after executing each query, including rollbacks. + +* For collections with even number of elements we report the smaller of the two candidate medians. + + + +**Sample Input** + + 10 + 1 + 5 + -2 + 3 + 2 + 5 + 4 + -7 + 2 + -3 + +**Sample Output** + + 1 + 1 + 1 + 1 + 2 + 2 + 3 + 1 + 1 + 3 + +**Explanation** + +(This represents the collection of the numbers tracked after each step, with median in bold.) + +Step 1: 1 -> [**1**] + +Step 2: 5 -> [**1**, 5] + +Step 3: request a return to state after step (3 - 2) = 1 -> [**1**] + +Step 4: 3 -> [**1**, 3] + +Step 5: 2 -> [1, **2**, 3] + +Step 6: 5 -> [1, **2**, 3, 5] + +Step 7: 4 -> [1, 2, **3**, 4, 5] + +Step 8: request a return to state after step (8 - 7) = 1 -> [**1**] + +Step 9: 2 -> [**1**, 2] + +Step 10: request a return to state after step (10 - 3) = 7 -> [1, 2, **3**, 4, 5] + +--- + +**Tested by:** [Abhiranjan Kumar](/abhiranjan) +",0.574468085,"[""haskell"",""clojure"",""scala"",""erlang"",""sbcl"",""ocaml"",""fsharp"",""racket"",""elixir""]",,,,,Hard,,,,,,,2014-06-23T20:20:45,2016-12-07T10:52:12,setter," object Solution { + class BinomHeap[T](lt: (T, T) => Boolean) { + def min(a: Option[T], b: Option[T]): Option[T] = + (a, b) match { + case (None, None) => None + case (None, _) => b + case (_, None) => a + case (Some(a), Some(b)) => + if (lt(a, b)) + Some(a) + else + Some(b) + } + + case class Node(val rank: Int, val x: T, val ts: List[Node]) { + val size = 1 << rank + + override def toString = + ""Tree ("" ++ rank.toString ++ ""): "" ++ x.toString ++ "" ["" ++ ((ts map (_.toString)) mkString "", "") ++ ""]"" + + def link(other: Node) = { + require(rank == other.rank) + + if (lt(x, other.x)) + new Node(rank + 1, x, other :: ts) + else + new Node(rank + 1, other.x, this :: other.ts) + } + } + + class Heap(xxmin: => Option[T], val size: Int, val ts: List[Node]) { + lazy val xmin: Option[T] = xxmin + + override def toString = + ""Heap:\n"" ++ ((ts map (x => ""\t"" ++ x.toString)) mkString ""\n"") ++ ""\n"" + + def isEmpty = size == 0 + + def insert(x: T): Heap = + insTree(new Node(0, x, Nil)) + + def merge(other: Heap) = + new Heap(min(xmin, other.xmin), size + other.size, mergeAux(other).ts) + + def deleteMin = { + val (t @ Node(_, x, ts1), h2) = removeMinTree + mkHeap(t.size - 1, ts1.reverse) merge h2 + } + + private def mkHeap(sz: Int, ts: List[Node]): Heap = + new Heap((new Heap(None, sz, ts)).findMin, sz, ts) + + private def findMin = { + val (t, _) = removeMinTree + Some(t.x) + } + + @annotation.tailrec + private def insTree(t: Node): Heap = + ts match { + case Nil => new Heap(Some(t.x), size + t.size, List(t)) + case t0 :: ts0 => + if (t.rank < t0.rank) + new Heap(min(Some(t.x), xmin), size + t.size, t :: ts) + else { + require(t.rank == t0.rank) + mkHeap(size - t0.size, ts0) insTree (t link t0) + } + } + + private def mergeAux(other: Heap): Heap = + (ts, other.ts) match { + case (_, Nil) => this + case (Nil, _) => other + case (t1 :: ts1, t2 :: ts2) => + if (t1.rank < t2.rank) + mkHeap(size + other.size, t1 :: (mkHeap(size - t1.size, ts1) mergeAux other).ts) + else if (t2.rank < t1.rank) + mkHeap(size + other.size, t2 :: (mergeAux(mkHeap(other.size - t2.size, ts2))).ts) + else + (mkHeap(size - t1.size, ts1) mergeAux mkHeap(size - t2.size, ts2)) insTree (t1 link t2) + } + + private def removeMinTree: (Node, Heap) = { + ts match { + case List(t) => (t, new Heap(None, 0, Nil)) + case t :: ts => { + val (t0, h0) = mkHeap(size - t.size, ts).removeMinTree + if (lt(t.x, t0.x)) + (t, mkHeap(size - t.size, ts)) + else + (t0, mkHeap(t.size + h0.size, t :: h0.ts)) + } + case _ => (ts.head, this) + } + } + } + + def empty: Heap = new Heap(None, 0, Nil) + } + + class RunningMedian(val l: BinomHeap[Int]#Heap, val r: BinomHeap[Int]#Heap) { + require(l.size == r.size || l.size == r.size + 1) + + def med = l.xmin + + def add(x: Int) = { + if (l.size == 0 || x <= l.xmin.get) { + val nl = l insert x + if (nl.size == r.size + 2) { + val x0 = nl.xmin + val nl0 = nl.deleteMin + new RunningMedian(nl0, r insert x0.get) + } + else + new RunningMedian(nl, r) + } + else { + val nr = r insert x + if (nr.size > l.size) { + val x0 = nr.xmin + val nr0 = nr.deleteMin + new RunningMedian(l insert x0.get, nr0) + } + else + new RunningMedian(l, nr) + } + } + } + + @annotation.tailrec + def loop(n: Int, lim: Int, rm: RunningMedian, store: collection.immutable.Vector[RunningMedian]): Unit = { + if (n > lim) + () + else { + val x = readLine.toInt + if (x > 0) { + val rm0 = rm add x + println(rm0.med.get) + loop(n + 1, lim, rm0, store :+ rm0) + } + else { + val rm0 = store(n + x - 1) + println(rm0.med.get) + loop(n + 1, lim, rm0, store :+ rm0) + } + } + } + + def main(args: Array[String]) = { + val rm = new RunningMedian(new BinomHeap[Int](_ > _).empty, new BinomHeap[Int](_ < _).empty) + val n = readLine.toInt + loop(1, n, rm, collection.immutable.Vector()) + } + } +",not-set,2016-04-24T02:02:43,2016-04-24T02:02:43,Python +85,2579,messy-medians,Messy Medians,"Robin is stuck doing a terminally boring data entry job. She has to enter a lot of numeric observations manually and report running medians after each step to her project lead. The task is sufficiently mind-numbing for her to make a lot of entry errors. Fortunately, she has a keen eye and often notices her mistakes. On the other hand, sometimes she makes mistakes while spotting - or correcting - previous mistakes, and so on. +
+Your task is to implement a program that will help Robin finish this boring job as soon as possible. The program will accept user input and report a running median for all the observations entered so far. It should also be capable of rolling back to any previous state (including those that were previously rolled back on their own). + +**Input Format** + +First line contains an integer,*T*, the total number of lines to follow. +
+Each of the following *T* lines contains either: + +1. a positive integer *N* that will contribute in calculation of the current running median; + +2. or a request to roll back to a previous state, which is represented by a negative number between -1 and -*M*, where *M* is the total number of queries executed so far. -1 requests a return to the immediately preceding state (which actually results in no state change), while -*M* requests a return to the state after entering the very first number. + +**Output Format** + +Output *T* integers, representing current running medians after performing operations on corresponding lines in the input. + +**Constraints** + +1 ≤ _T_ ≤ 105 +1 ≤ _N_ ≤ 109 +1 ≤ _M_ ≤ number of queries executed so far. + +**Notes** + +* You will never be asked to roll back to a non-existent state, or a state for which the running median is not well-defined. In particular, the first line after *T* will always be a positive number. + +* You should print out the median after executing each query, including rollbacks. + +* For collections with even number of elements we report the smaller of the two candidate medians. + + + +**Sample Input** + + 10 + 1 + 5 + -2 + 3 + 2 + 5 + 4 + -7 + 2 + -3 + +**Sample Output** + + 1 + 1 + 1 + 1 + 2 + 2 + 3 + 1 + 1 + 3 + +**Explanation** + +(This represents the collection of the numbers tracked after each step, with median in bold.) + +Step 1: 1 -> [**1**] + +Step 2: 5 -> [**1**, 5] + +Step 3: request a return to state after step (3 - 2) = 1 -> [**1**] + +Step 4: 3 -> [**1**, 3] + +Step 5: 2 -> [1, **2**, 3] + +Step 6: 5 -> [1, **2**, 3, 5] + +Step 7: 4 -> [1, 2, **3**, 4, 5] + +Step 8: request a return to state after step (8 - 7) = 1 -> [**1**] + +Step 9: 2 -> [**1**, 2] + +Step 10: request a return to state after step (10 - 3) = 7 -> [1, 2, **3**, 4, 5] + +--- + +**Tested by:** [Abhiranjan Kumar](/abhiranjan) +",code,(Add|Remove|getMedian),ai,2014-06-05T17:02:31,2016-09-01T16:22:55,,,,"Robin is stuck doing a terminally boring data entry job. She has to enter a lot of numeric observations manually and report running medians after each step to her project lead. The task is sufficiently mind-numbing for her to make a lot of entry errors. Fortunately, she has a keen eye and often notices her mistakes. On the other hand, sometimes she makes mistakes while spotting - or correcting - previous mistakes, and so on. +
+Your task is to implement a program that will help Robin finish this boring job as soon as possible. The program will accept user input and report a running median for all the observations entered so far. It should also be capable of rolling back to any previous state (including those that were previously rolled back on their own). + +**Input Format** + +First line contains an integer,*T*, the total number of lines to follow. +
+Each of the following *T* lines contains either: + +1. a positive integer *N* that will contribute in calculation of the current running median; + +2. or a request to roll back to a previous state, which is represented by a negative number between -1 and -*M*, where *M* is the total number of queries executed so far. -1 requests a return to the immediately preceding state (which actually results in no state change), while -*M* requests a return to the state after entering the very first number. + +**Output Format** + +Output *T* integers, representing current running medians after performing operations on corresponding lines in the input. + +**Constraints** + +1 ≤ _T_ ≤ 105 +1 ≤ _N_ ≤ 109 +1 ≤ _M_ ≤ number of queries executed so far. + +**Notes** + +* You will never be asked to roll back to a non-existent state, or a state for which the running median is not well-defined. In particular, the first line after *T* will always be a positive number. + +* You should print out the median after executing each query, including rollbacks. + +* For collections with even number of elements we report the smaller of the two candidate medians. + + + +**Sample Input** + + 10 + 1 + 5 + -2 + 3 + 2 + 5 + 4 + -7 + 2 + -3 + +**Sample Output** + + 1 + 1 + 1 + 1 + 2 + 2 + 3 + 1 + 1 + 3 + +**Explanation** + +(This represents the collection of the numbers tracked after each step, with median in bold.) + +Step 1: 1 -> [**1**] + +Step 2: 5 -> [**1**, 5] + +Step 3: request a return to state after step (3 - 2) = 1 -> [**1**] + +Step 4: 3 -> [**1**, 3] + +Step 5: 2 -> [1, **2**, 3] + +Step 6: 5 -> [1, **2**, 3, 5] + +Step 7: 4 -> [1, 2, **3**, 4, 5] + +Step 8: request a return to state after step (8 - 7) = 1 -> [**1**] + +Step 9: 2 -> [**1**, 2] + +Step 10: request a return to state after step (10 - 3) = 7 -> [1, 2, **3**, 4, 5] + +--- + +**Tested by:** [Abhiranjan Kumar](/abhiranjan) +",0.574468085,"[""haskell"",""clojure"",""scala"",""erlang"",""sbcl"",""ocaml"",""fsharp"",""racket"",""elixir""]",,,,,Hard,,,,,,,2014-06-23T20:20:45,2016-12-07T10:52:12,tester,"**Approach #1** + + module Main where + import Data.List + import Data.Char + import qualified Data.Vector as V + import qualified Data.Map as Map + import Text.Printf + + data SegmentTree = Leaf { + count :: Int + , index :: Int + } + | Node { + count :: Int + , leftIdx :: Int + , rightIdx :: Int + , leftTree :: SegmentTree + , rightTree :: SegmentTree + } + + + initialiseTree :: Int -> SegmentTree + initialiseTree = createNode 1 + where + createNode l r + | l == r = Leaf 0 l + | otherwise = Node 0 l r (createNode l mid) (createNode (mid+1) r) + where + mid = (l+r) `div` 2 + + insertNode :: Int -> SegmentTree -> SegmentTree + insertNode val lf@(Leaf cnt idx) = if idx == val then lf{count = cnt+1} else lf + insertNode val nd@(Node cnt lIdx rIdx lTree rTree) + | lIdx <= val && val <= rIdx = nd {count = cnt+1, leftTree = insertNode val lTree, rightTree = insertNode val rTree} + | otherwise = nd + + getElements :: Int -> SegmentTree -> Int + getElements val (Leaf cnt idx) = if idx <= val then cnt else 0 + getElements val (Node cnt lIdx rIdx lTree rTree) + | lIdx > val = 0 + | rIdx < val = cnt + | otherwise = getElements val lTree + getElements val rTree + + getMedian :: SegmentTree -> Int + getMedian root = binarySearch (leftIdx root) (rightIdx root) + where + cnt = (count root + 1)`div`2 + binarySearch l r + | l == r = l + | getElements mid root >= cnt = binarySearch l mid + | otherwise = binarySearch (mid+1) r + where mid = (l+r+0) `div` 2 + + main :: IO () + main = getContents >>= mapM_ print. solve. map read. words + + solve (n:arr) + | n /= length arr = error $ ""length arr = "" ++ show (length arr) + | any (\x -> x == 0 || x > 10^9) arr = error $ ""arr = "" ++ show arr + | otherwise = map getIdx [ getMedian (trees V.! i) |i <- [1..len]] + where + ans = [ (indAns i, trees V.! i) | i <- [1..len]] + indAns i = getIdx $ getMedian (trees V.! i) + root = initialiseTree. length $ sarr + vArr = V.fromList arr + trees = V.fromList $ root : [ let v = vArr V.! (i - 1) in + if v > 0 then + insertNode (getRIdx v) (trees V.! (i-1)) + else trees V.! (i+v) + | i <- [1..len] + ] + sarr = map head. group. dropWhile (<= 0). sort $ arr + len = length arr + idx, revIdx :: Map.Map Int Int + revIdx = Map.fromList. zip sarr $ [1..] + idx = Map.fromList. zip [(1::Int)..] $ sarr + getRIdx key = Map.findWithDefault (-1) key revIdx + getIdx key = Map.findWithDefault (-1) key idx + +--- + +**Approach #2** + + import qualified Data.Vector as V + import qualified Data.MultiSet as MultiSet + import Text.Printf -- printf ""%0.6f"" (1.0) + + data MSet a = MSet { + mSet :: MultiSet.MultiSet a + , size :: Int + }-- deriving (Show) + + instance Show a => Show (MSet a) where + show (MSet st sz) = printf ""%d: %s"" sz (show.MultiSet.toList $ st) + + emptyMSet :: MSet a + emptyMSet = MSet MultiSet.empty 0 + + insertIntoMSet, deleteFromMSet :: (Show a, Ord a) => a -> MSet a -> MSet a + insertIntoMSet x (MSet st sz) = MSet (MultiSet.insert x st) (sz+1) + deleteFromMSet x (MSet st sz) + | MultiSet.member x st = MSet (MultiSet.delete x st) (sz-1) + | otherwise = error $ printf ""member %s not found in set = %s\n"" (show x) (show st) + + data Container a = Container { + firstSet :: MSet a + , secondSet :: MSet a + }-- deriving (Show) + + instance Show a => Show (Container a) where + show (Container fSet sSet) = printf ""{%-25s %-25s}"" (show fSet) (show sSet) + + emptyContainer :: Container Int + emptyContainer = Container emptyMSet emptyMSet + + addToContainer :: (Show a, Ord a) => a -> Container a -> Container a + addToContainer x cont + | sz1 + sz2 == 0 = cont { firstSet = insertIntoMSet x fSet } + | sz2 == 0 && x >= mx1 = cont { secondSet = insertIntoMSet x sSet } + | sz2 == 0 && x < mx1 = cont { firstSet = insertIntoMSet x (deleteFromMSet mx1 fSet), + secondSet = insertIntoMSet mx1 sSet } + | sz1 == sz2 && x <= mn2 = cont { firstSet = insertIntoMSet x fSet } + | sz1 == sz2 && x > mn2 = cont { firstSet = insertIntoMSet mn2 fSet, + secondSet = insertIntoMSet x (deleteFromMSet mn2 sSet) } + | sz1 == sz2+1 && x >= mx1 = cont { secondSet = insertIntoMSet x sSet} + | sz1 == sz2+1 && x < mx1 = cont { firstSet = insertIntoMSet x (deleteFromMSet mx1 fSet), + secondSet = insertIntoMSet mx1 sSet} + | otherwise = error $ printf ""Error\nfirstSet = %s\nsecondSet = %s\nmx1 = %s, mn2 = %s, x = %s"" (show fSet) (show sSet) (show mx1) (show mn2) (show x) + where + sz1 = size. firstSet $ cont + sz2 = size. secondSet $ cont + fSet = firstSet cont + sSet = secondSet cont + mx1 = MultiSet.findMax. mSet $ fSet + mn2 = MultiSet.findMin. mSet $ sSet + + getMedian :: (Show a, Ord a) => Container a -> a + getMedian = MultiSet.findMax. mSet. firstSet + + main :: IO () + main = getContents >>= mapM_ (print. getMedian). tail. V.toList. validate. map read. lines + + validate (n:a) + | n /= len = error $ printf ""n = %d, len = %d\n"" n len + | any (\x -> x > 10^9|| x < -n) a = error $ printf ""a = %s\n"" (show a) + | otherwise = containers + where + len = length a + vArr = V.fromList a + containers1 = scanl (flip addToContainer) emptyContainer a + containers = V.fromList $ emptyContainer : [getContainer i | i <- [1..n]] + getContainer idx + | val >= 0 = addToContainer val (containers V.! (idx-1)) + | val < 0 = containers V.! (idx + val) + where + val = vArr V.! (idx-1) + + + +",not-set,2016-04-24T02:02:43,2016-04-24T02:02:43,Python +86,3129,world-peace,World Peace,"The Artifact of World Peace was obtained by the evil Pharaoh. He smashed it into pieces and hid them inside a temple. The temple has a very elaborate and confusing floor plan. It contained different rooms. Each room has a trap. Moreover, to go from one room to another, you must pass by a corridor and each of these also has a trap. The Pharaoh suddenly realized he was low on budget because the college tuition fee of his children suddenly increased. Unprepared to sacrifice the future of his children, he decided to not push through with the traps inside the rooms BUT retain the traps in the corridors. Don't be fooled though, it is still very difficult to infiltrate this temple. + +You decide that you want to get the pieces of this Sacred Artifact of _World Peace_, put these together to recreate the Artifact of _World Peace_ and then finally obtain millions of dollars by selling it on eBay. + +You list down all the known rooms of this temple. Each corridor has a trap and a certain skill level is required to clear this trap. Furthermore, to secure all pieces of the artifact, you realize that you just need to form the safest routes between pairs of rooms. + +To summarize, the temple has $R$ known rooms and $C$ corridors. Each corridor connects two rooms and has its corresponding trap. Each trap has a certain _skill level_ $s$ required in order to clear it. If your skill level is below this $s$, you fail the trap and subsequently die a slow, horrible and painful death. After planning, you realize you just have to travel between $P$ pairs of rooms. For each pair of rooms $A$ and $B$, you must select the safest corridors (i.e. the path which requires the lowest skill level) to travel from room $A$ to room $B$. Given these information, you must find out the minimum skill level you must have in order to survive travelling through the corridors which connect each of these pairs of rooms. + +**Input Format** +The first line of input contains two integers, the number of rooms $R$ in the temple and the number of corridors $C$ in the temple. The rooms are numbered from $1$ to $R$. + +The next $C$ lines each contain three integers: $A$, $B$ and $s$ in that order. This tells us that to survive the corridor connecting room $A$ and room $B$, your skill level must be $s$ or higher. + +The next line contains a single integer, $P$. This indicates how many pairs of rooms you must plan a route for. + +The next $P$ lines each contain two integers, $A$ and $B$. This tells us that you must plan the safest route between rooms $A$ and $B$. + +**Output Format** +Output a single line containing a single integer, $S$, the minimum skill level you must have in order to travel between each of the $P$ pairs of rooms. + +If it is impossible to travel between one of the $P$ pairs of rooms, output `MISSION IMPOSSIBLE`. + +**Constraints** +$1 \le R \le 10^5$ +$1 \le C \le 10^5$ +$1 \le P \le 10^5$ +$1 \le A, B \le R$ +$A \ne B$ +$1 \le s \le 10^6$ + +**Sample Input 1** + + 8 12 + 1 2 1 + 1 4 2 + 2 3 5 + 2 4 4 + 3 4 2 + 5 2 11 + 5 2 10 + 5 6 1 + 6 8 3 + 7 6 2 + 8 7 3 + 5 8 4 + 2 + 1 3 + 5 8 + +**Sample Output 1** + + 3 + +**Sample Input 2** + + 3 1 + 1 3 100 + 1 + 1 2 + +**Sample Output 2** + + MISSION IMPOSSIBLE + +**Explanation** +The first case corresponds to the following floor plan: +![image](https://hr-challenge-images.s3.amazonaws.com/3129/3129.png) + + +The safest path to travel from room $1$ to room $3$ is going from room $1$ to room $4$ then room $4$ to room $3$. The minimum skill level to safely traverse the corridors connecting these rooms is $2$. The safest path to travel from room $5$ to room $8$ is going from room $5$ to room $6$, then room $7$ and finally room $8$ (or if you're feeling less adventurous, you could skip going to room $7$ and travel from $5$ to $6$ to $8$ instead). The minimum skill level to safely traverse these corridors is $3$. Thus to travel between all $P = 2$ pairs of rooms, one must have a minimum skill level of $3$. + +For the second case, there is no way to get from room $1$ to room $2$ regardless of your skill level. How did they get the pieces there? It shall remain a mystery. +",code,How skillful must you be to retrieve The Artifact of World Peace?,ai,2014-06-22T19:04:22,2018-02-06T18:26:45,,,,"The Artifact of World Peace was obtained by the evil Pharaoh. He smashed it into pieces and hid them inside a temple. The temple has a very elaborate and confusing floor plan. It contained different rooms. Each room has a trap. Moreover, to go from one room to another, you must pass by a corridor and each of these also has a trap. The Pharaoh suddenly realized he was low on budget because the college tuition fee of his children suddenly increased. Unprepared to sacrifice the future of his children, he decided to not push through with the traps inside the rooms BUT retain the traps in the corridors. Don't be fooled though, it is still very difficult to infiltrate this temple. + +You decide that you want to get the pieces of this Sacred Artifact of _World Peace_, put these together to recreate the Artifact of _World Peace_ and then finally obtain millions of dollars by selling it on eBay. + +You list down all the known rooms of this temple. Each corridor has a trap and a certain skill level is required to clear this trap. Furthermore, to secure all pieces of the artifact, you realize that you just need to form the safest routes between pairs of rooms. + +To summarize, the temple has $R$ known rooms and $C$ corridors. Each corridor connects two rooms and has its corresponding trap. Each trap has a certain _skill level_ $s$ required in order to clear it. If your skill level is below this $s$, you fail the trap and subsequently die a slow, horrible and painful death. After planning, you realize you just have to travel between $P$ pairs of rooms. For each pair of rooms $A$ and $B$, you must select the safest corridors (i.e. the path which requires the lowest skill level) to travel from room $A$ to room $B$. Given these information, you must find out the minimum skill level you must have in order to survive travelling through the corridors which connect each of these pairs of rooms. + +**Input Format** +The first line of input contains two integers, the number of rooms $R$ in the temple and the number of corridors $C$ in the temple. The rooms are numbered from $1$ to $R$. + +The next $C$ lines each contain three integers: $A$, $B$ and $s$ in that order. This tells us that to survive the corridor connecting room $A$ and room $B$, your skill level must be $s$ or higher. + +The next line contains a single integer, $P$. This indicates how many pairs of rooms you must plan a route for. + +The next $P$ lines each contain two integers, $A$ and $B$. This tells us that you must plan the safest route between rooms $A$ and $B$. + +**Output Format** +Output a single line containing a single integer, $S$, the minimum skill level you must have in order to travel between each of the $P$ pairs of rooms. + +If it is impossible to travel between one of the $P$ pairs of rooms, output `MISSION IMPOSSIBLE`. + +**Constraints** +$1 \le R \le 10^5$ +$1 \le C \le 10^5$ +$1 \le P \le 10^5$ +$1 \le A, B \le R$ +$A \ne B$ +$1 \le s \le 10^6$ + +**Sample Input 1** + + 8 12 + 1 2 1 + 1 4 2 + 2 3 5 + 2 4 4 + 3 4 2 + 5 2 11 + 5 2 10 + 5 6 1 + 6 8 3 + 7 6 2 + 8 7 3 + 5 8 4 + 2 + 1 3 + 5 8 + +**Sample Output 1** + + 3 + +**Sample Input 2** + + 3 1 + 1 3 100 + 1 + 1 2 + +**Sample Output 2** + + MISSION IMPOSSIBLE + +**Explanation** +The first case corresponds to the following floor plan: +![image](https://hr-challenge-images.s3.amazonaws.com/3129/3129.png) + + +The safest path to travel from room $1$ to room $3$ is going from room $1$ to room $4$ then room $4$ to room $3$. The minimum skill level to safely traverse the corridors connecting these rooms is $2$. The safest path to travel from room $5$ to room $8$ is going from room $5$ to room $6$, then room $7$ and finally room $8$ (or if you're feeling less adventurous, you could skip going to room $7$ and travel from $5$ to $6$ to $8$ instead). The minimum skill level to safely traverse these corridors is $3$. Thus to travel between all $P = 2$ pairs of rooms, one must have a minimum skill level of $3$. + +For the second case, there is no way to get from room $1$ to room $2$ regardless of your skill level. How did they get the pieces there? It shall remain a mystery. +",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-24T05:03:25,2018-02-06T18:32:10,setter,"```cpp +#include + +struct edge { + int a, b, s; +}; + +int ea[111111]; +int eb[111111]; +int es[111111]; +int pa[111111]; +int pb[111111]; +int ps[111111]; +int r, c, p; + +int find(int n) { + return ps[n] < 0 ? n : ps[n] = find(ps[n]); +} + +int kaya(int cost) { + for (int i = 0; i < r; i++) ps[i] = -1; + + for (int i = 0; i < c; i++) { + if (es[i] > cost) continue; + int fa = find(ea[i]); + int fb = find(eb[i]); + if (fa != fb) { + if (ps[fa] == ps[fb]) ps[fb]--; + if (ps[fa] > ps[fb]) { + ps[fa] = fb; + } else { + ps[fb] = fa; + } + } + } + + for (int i = 0; i < p; i++) { + if (find(pa[i]) != find(pb[i])) return 0; + } + return 1; +} + +int main() { + scanf(""%d%d"", &r, &c); + for( int i = 0; i < c; i++) { + int a, b, s; + scanf(""%d%d%d"", &a, &b, &s); + ea[i] = --a; + eb[i] = --b; + es[i] = s; + } + + scanf(""%d"", &p); + for (int i = 0; i < p; i++) { + int a, b; + scanf(""%d%d"", &a, &b); + pa[i] = --a; + pb[i] = --b; + } + + int L = -1; + int R = 1000001; + + if (!kaya(R)) { + printf(""MISSION IMPOSSIBLE\n""); + } else { + while (R - L > 1) { + int M = L + R >> 1; + (kaya(M) ? R : L) = M; + } + printf(""%d\n"", R); + } +} +``` +",not-set,2016-04-24T02:02:43,2018-02-06T18:26:46,C++ +87,3129,world-peace,World Peace,"The Artifact of World Peace was obtained by the evil Pharaoh. He smashed it into pieces and hid them inside a temple. The temple has a very elaborate and confusing floor plan. It contained different rooms. Each room has a trap. Moreover, to go from one room to another, you must pass by a corridor and each of these also has a trap. The Pharaoh suddenly realized he was low on budget because the college tuition fee of his children suddenly increased. Unprepared to sacrifice the future of his children, he decided to not push through with the traps inside the rooms BUT retain the traps in the corridors. Don't be fooled though, it is still very difficult to infiltrate this temple. + +You decide that you want to get the pieces of this Sacred Artifact of _World Peace_, put these together to recreate the Artifact of _World Peace_ and then finally obtain millions of dollars by selling it on eBay. + +You list down all the known rooms of this temple. Each corridor has a trap and a certain skill level is required to clear this trap. Furthermore, to secure all pieces of the artifact, you realize that you just need to form the safest routes between pairs of rooms. + +To summarize, the temple has $R$ known rooms and $C$ corridors. Each corridor connects two rooms and has its corresponding trap. Each trap has a certain _skill level_ $s$ required in order to clear it. If your skill level is below this $s$, you fail the trap and subsequently die a slow, horrible and painful death. After planning, you realize you just have to travel between $P$ pairs of rooms. For each pair of rooms $A$ and $B$, you must select the safest corridors (i.e. the path which requires the lowest skill level) to travel from room $A$ to room $B$. Given these information, you must find out the minimum skill level you must have in order to survive travelling through the corridors which connect each of these pairs of rooms. + +**Input Format** +The first line of input contains two integers, the number of rooms $R$ in the temple and the number of corridors $C$ in the temple. The rooms are numbered from $1$ to $R$. + +The next $C$ lines each contain three integers: $A$, $B$ and $s$ in that order. This tells us that to survive the corridor connecting room $A$ and room $B$, your skill level must be $s$ or higher. + +The next line contains a single integer, $P$. This indicates how many pairs of rooms you must plan a route for. + +The next $P$ lines each contain two integers, $A$ and $B$. This tells us that you must plan the safest route between rooms $A$ and $B$. + +**Output Format** +Output a single line containing a single integer, $S$, the minimum skill level you must have in order to travel between each of the $P$ pairs of rooms. + +If it is impossible to travel between one of the $P$ pairs of rooms, output `MISSION IMPOSSIBLE`. + +**Constraints** +$1 \le R \le 10^5$ +$1 \le C \le 10^5$ +$1 \le P \le 10^5$ +$1 \le A, B \le R$ +$A \ne B$ +$1 \le s \le 10^6$ + +**Sample Input 1** + + 8 12 + 1 2 1 + 1 4 2 + 2 3 5 + 2 4 4 + 3 4 2 + 5 2 11 + 5 2 10 + 5 6 1 + 6 8 3 + 7 6 2 + 8 7 3 + 5 8 4 + 2 + 1 3 + 5 8 + +**Sample Output 1** + + 3 + +**Sample Input 2** + + 3 1 + 1 3 100 + 1 + 1 2 + +**Sample Output 2** + + MISSION IMPOSSIBLE + +**Explanation** +The first case corresponds to the following floor plan: +![image](https://hr-challenge-images.s3.amazonaws.com/3129/3129.png) + + +The safest path to travel from room $1$ to room $3$ is going from room $1$ to room $4$ then room $4$ to room $3$. The minimum skill level to safely traverse the corridors connecting these rooms is $2$. The safest path to travel from room $5$ to room $8$ is going from room $5$ to room $6$, then room $7$ and finally room $8$ (or if you're feeling less adventurous, you could skip going to room $7$ and travel from $5$ to $6$ to $8$ instead). The minimum skill level to safely traverse these corridors is $3$. Thus to travel between all $P = 2$ pairs of rooms, one must have a minimum skill level of $3$. + +For the second case, there is no way to get from room $1$ to room $2$ regardless of your skill level. How did they get the pieces there? It shall remain a mystery. +",code,How skillful must you be to retrieve The Artifact of World Peace?,ai,2014-06-22T19:04:22,2018-02-06T18:26:45,,,,"The Artifact of World Peace was obtained by the evil Pharaoh. He smashed it into pieces and hid them inside a temple. The temple has a very elaborate and confusing floor plan. It contained different rooms. Each room has a trap. Moreover, to go from one room to another, you must pass by a corridor and each of these also has a trap. The Pharaoh suddenly realized he was low on budget because the college tuition fee of his children suddenly increased. Unprepared to sacrifice the future of his children, he decided to not push through with the traps inside the rooms BUT retain the traps in the corridors. Don't be fooled though, it is still very difficult to infiltrate this temple. + +You decide that you want to get the pieces of this Sacred Artifact of _World Peace_, put these together to recreate the Artifact of _World Peace_ and then finally obtain millions of dollars by selling it on eBay. + +You list down all the known rooms of this temple. Each corridor has a trap and a certain skill level is required to clear this trap. Furthermore, to secure all pieces of the artifact, you realize that you just need to form the safest routes between pairs of rooms. + +To summarize, the temple has $R$ known rooms and $C$ corridors. Each corridor connects two rooms and has its corresponding trap. Each trap has a certain _skill level_ $s$ required in order to clear it. If your skill level is below this $s$, you fail the trap and subsequently die a slow, horrible and painful death. After planning, you realize you just have to travel between $P$ pairs of rooms. For each pair of rooms $A$ and $B$, you must select the safest corridors (i.e. the path which requires the lowest skill level) to travel from room $A$ to room $B$. Given these information, you must find out the minimum skill level you must have in order to survive travelling through the corridors which connect each of these pairs of rooms. + +**Input Format** +The first line of input contains two integers, the number of rooms $R$ in the temple and the number of corridors $C$ in the temple. The rooms are numbered from $1$ to $R$. + +The next $C$ lines each contain three integers: $A$, $B$ and $s$ in that order. This tells us that to survive the corridor connecting room $A$ and room $B$, your skill level must be $s$ or higher. + +The next line contains a single integer, $P$. This indicates how many pairs of rooms you must plan a route for. + +The next $P$ lines each contain two integers, $A$ and $B$. This tells us that you must plan the safest route between rooms $A$ and $B$. + +**Output Format** +Output a single line containing a single integer, $S$, the minimum skill level you must have in order to travel between each of the $P$ pairs of rooms. + +If it is impossible to travel between one of the $P$ pairs of rooms, output `MISSION IMPOSSIBLE`. + +**Constraints** +$1 \le R \le 10^5$ +$1 \le C \le 10^5$ +$1 \le P \le 10^5$ +$1 \le A, B \le R$ +$A \ne B$ +$1 \le s \le 10^6$ + +**Sample Input 1** + + 8 12 + 1 2 1 + 1 4 2 + 2 3 5 + 2 4 4 + 3 4 2 + 5 2 11 + 5 2 10 + 5 6 1 + 6 8 3 + 7 6 2 + 8 7 3 + 5 8 4 + 2 + 1 3 + 5 8 + +**Sample Output 1** + + 3 + +**Sample Input 2** + + 3 1 + 1 3 100 + 1 + 1 2 + +**Sample Output 2** + + MISSION IMPOSSIBLE + +**Explanation** +The first case corresponds to the following floor plan: +![image](https://hr-challenge-images.s3.amazonaws.com/3129/3129.png) + + +The safest path to travel from room $1$ to room $3$ is going from room $1$ to room $4$ then room $4$ to room $3$. The minimum skill level to safely traverse the corridors connecting these rooms is $2$. The safest path to travel from room $5$ to room $8$ is going from room $5$ to room $6$, then room $7$ and finally room $8$ (or if you're feeling less adventurous, you could skip going to room $7$ and travel from $5$ to $6$ to $8$ instead). The minimum skill level to safely traverse these corridors is $3$. Thus to travel between all $P = 2$ pairs of rooms, one must have a minimum skill level of $3$. + +For the second case, there is no way to get from room $1$ to room $2$ regardless of your skill level. How did they get the pieces there? It shall remain a mystery. +",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-24T05:03:25,2018-02-06T18:32:10,tester,"```cpp +#include +#include +#include +#include + +using namespace std; + +const int N = 100005; +int f[N],num[N]; +struct node { + int x,y,s; +}; + +node a[N]; +pair b[N]; + +int getf(int x) { + return (f[x] == x)?x:(f[x] = getf(f[x])); +} + +void make(int x,int y) { + x = getf(x); + y = getf(y); + if (x == y) { + return; + } + if (num[x] < num[y]) { + f[x] = y; + num[y] += num[x]; + } + else { + f[y] = x; + num[x] += num[y]; + } +} + +bool check(int m,int n,int p,int v) { + for (int i = 0; i < n; ++i) { + num[f[i] = i] = 1; + } + for (int i = 0; i < m; ++i) { + if (a[i].s <= v) { + make(a[i].x,a[i].y); + } + } + for (int i = 0; i < p; ++i) { + if (getf(b[i].first) != getf(b[i].second)) { + return false; + } + } + return true; +} + +int main() { +int n,m; + scanf(""%d%d"",&n,&m); + assert((n >= 1) && (n <= 100000)); + assert((m >= 1) && (m <= 100000)); + int left = 2000000, right = 0; + for (int i = 0; i < m; ++i) { + scanf(""%d%d%d"",&a[i].x,&a[i].y,&a[i].s); + assert((a[i].x >= 1) && (a[i].x <= n)); + assert((a[i].y >= 1) && (a[i].y <= n) && (a[i].x != a[i].y)); + assert((a[i].s >= 1) && (a[i].s <= 1000000)); + --a[i].x; + --a[i].y; + left = min(left, a[i].s); + right = max(right, a[i].s); + } + int p; + scanf(""%d"",&p); + assert((p >= 1) && (p <= 100000)); + for (int i = 0; i < p; ++i) { + scanf(""%d%d"",&b[i].first,&b[i].second); + assert((b[i].first >= 1) && (b[i].first <= n)); + assert((b[i].second >= 1) && (b[i].second <= n) && (b[i].first != b[i].second)); + --b[i].first; + --b[i].second; + } + int answer = -1; + while (left <= right) { + int mid =(left + right) >> 1; + if (check(m,n,p,mid)) { + answer = mid; + right = mid - 1; + } + else { + left = mid + 1; + } + } + if (answer >= 0) { + printf(""%d\n"",answer); + } + else { + puts(""MISSION IMPOSSIBLE""); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:43,2018-02-06T18:26:46,C++ +88,3152,uppals-ego,Uppal's Ego,"Ramu is very good at maths. He always tries to play with different kinds of numbers. This time he has discovered a new type of numbers and has named them **KMH** numbers. According to him, a number **N** is a **KMH** number, if **the sum of its prime divisors is a power of 2** i.e **_(2, 4, 8, ...and so on)._** +**Example:** +**1. 15= 3 X 5** +prime divisors 3,5 +sum = 3 + 5 = 8 +**2. 3025 = 52 X 112** +prime divisors 5,11 +sum = 5 + 11 = 16 + +So **15**, **3025** are some **KMH numbers**. + +Uppal is Ramu’s roommate and Ramu challenges him to do a task related to **KMH** numbers. Uppal will be given 2 integers **A,B** and asked to tell **the number of integers between A and B (inclusive) whose ""Sum of digits"" is a KMH number**. Uppal takes every lose to his ego . So he has asked your help so that he can answer all queries asked by Ramu. Help Uppal so that his ego doesn't get hurt. + +**Example** +**44** +sum of digits : 4 + 4 = 8 +8 = 23 +sum of prime divisors = 2. +So **44** is a number whose sum of digits is a **KMH** number. + +###**INPUT FORMAT** +First line contains number of test cases **T**. +Next **T** lines will contain two integers **A** and **B** separated by a space. + +###**OUTPUT FORMAT** +Output should contain **T** lines, each conatining answer to Ramu's query explained above. + +###**CONSTRAINTS:** +Number of test cases **T**, **1 ≤ T ≤ 100** +**1 ≤ A ≤ B ≤ 1015** + +###**SAMPLE INPUT** +2 +1 10 +40 50 + +###**SAMPLE OUTPUT** +3 +2 + +###**EXPLANATION** +In the first test case **2**, **4** and **8** are the numbers between **1** and **10**. +In the second test case **40** and **44** are the numbers between **40** and **50**.",code,Help Uppal so that his ego doesn't get hurt.,ai,2014-06-24T08:08:53,2016-09-09T09:47:13,,,,"Ramu is very good at maths. He always tries to play with different kinds of numbers. This time he has discovered a new type of numbers and has named them **KMH** numbers. According to him, a number **N** is a **KMH** number, if **the sum of its prime divisors is a power of 2** i.e **_(2, 4, 8, ...and so on)._** +**Example:** +**1. 15= 3 X 5** +prime divisors 3,5 +sum = 3 + 5 = 8 +**2. 3025 = 52 X 112** +prime divisors 5,11 +sum = 5 + 11 = 16 + +So **15**, **3025** are some **KMH numbers**. + +Uppal is Ramu’s roommate and Ramu challenges him to do a task related to **KMH** numbers. Uppal will be given 2 integers **A,B** and asked to tell **the number of integers between A and B (inclusive) whose ""Sum of digits"" is a KMH number**. Uppal takes every lose to his ego . So he has asked your help so that he can answer all queries asked by Ramu. Help Uppal so that his ego doesn't get hurt. + +**Example** +**44** +sum of digits : 4 + 4 = 8 +8 = 23 +sum of prime divisors = 2. +So **44** is a number whose sum of digits is a **KMH** number. + +###**INPUT FORMAT** +First line contains number of test cases **T**. +Next **T** lines will contain two integers **A** and **B** separated by a space. + +###**OUTPUT FORMAT** +Output should contain **T** lines, each conatining answer to Ramu's query explained above. + +###**CONSTRAINTS:** +Number of test cases **T**, **1 ≤ T ≤ 100** +**1 ≤ A ≤ B ≤ 1015** + +###**SAMPLE INPUT** +2 +1 10 +40 50 + +###**SAMPLE OUTPUT** +3 +2 + +###**EXPLANATION** +In the first test case **2**, **4** and **8** are the numbers between **1** and **10**. +In the second test case **40** and **44** are the numbers between **40** and **50**.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""erlang"",""brainfuck"",""javascript"",""go"",""d"",""ocaml"",""pascal"",""sbcl"",""python3"",""groovy"",""objectivec"",""fsharp"",""cobol"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""whitespace"",""tsql"",""cpp14""]",,,,,Hard,,,,,,,2014-06-24T08:24:54,2017-11-21T15:46:55,setter," #include + #include + #define LL long long int + #define rep(i,x,n) for(i=x;i=0)ans+=dp[bits-1][kmh[k]-x-j]; + } + } + x+=(str[i]-48); + } + return ans; + } + + int main() + { + LL i,j,k,n,t,a,b; + + //compute KMH numbers + LL d[136]={0}; + for(i=2;i<136;i++) + { + if(!d[i]) + { + for(j=i;j<136;j+=i) + d[j]+=i; + } + } + for(i=2;i<136;i++)if((d[i]&(d[i]-1))==0)kmh[p++]=i; + + //dp to compute number of integers of x bits with s sum as dp[x][s] + rep(i,0,10)dp[1][i]=1; + dp[0][0]=1; + rep(i,2,16) //bits + { + rep(j,0,136) //sum + { + rep(k,0,10) //setting MSB as k + { + if(j-k>=0) + dp[i][j]+=dp[i-1][j-k]; + } + } + } + + cin>>t; + while(t--) + { + cin>>a>>b; + cout< + #include + #define ll long long + + int lower[211111]; + int upper[211111]; + char cmd[111]; + int xs[211111]; + int ys[211111]; + int *adj[211111]; + int adc[211111]; + int deg[211111]; + int que[211111]; + int main() { + int n, m; + scanf(""%d%d"", &n, &m); + for (int i = 0; i < n; i++) { + lower[i] = 0; + upper[i] = 2111111111; + adc[i] = deg[i] = 0; + } + int c = 0; + for (int i = 0; i < m; i++) { + int x, y; + scanf(""%s%d%d"", cmd, &x, &y); + x--; + if (*cmd == 'A' or *cmd == 'B') y--; + if (*cmd == 'B') { + *cmd = 'A'; + x ^= y, y ^= x, x ^= y; + } + if (*cmd == 'A') { + xs[c] = x; + ys[c] = y; + c++; + adc[y]++; + } else if (*cmd == 'C') { + if (lower[x] < y) lower[x] = y; + } else if (*cmd == 'D') { + if (upper[x] > y) upper[x] = y; + } else { + //assert(0);// shouldn't happen + } + } + for (int i = 0; i < n; i++) { + adj[i] = (int*)malloc(adc[i] * sizeof(int)); + adc[i] = 0; + } + for (int i = 0; i < c; i++) { + int x = xs[i]; + int y = ys[i]; + adj[y][adc[y]++] = x; + deg[x]++; + } + int q = 0; + for (int i = 0; i < n; i++) { + if (!deg[i]) que[q++] = i; + } + int succ = 1; + for (int f = 0; f < q; f++) { + int i = que[f]; + if (!(succ = ++lower[i] < upper[i])) break; + for (int nb = 0; nb < adc[i]; nb++) { + int j = adj[i][nb]; + if (lower[j] < lower[i]) lower[j] = lower[i]; + if (!--deg[j]) que[q++] = j; + } + } + succ &= q == n; + if (succ) { + for (int i = 0; i < n; i++) { + printf(""%d\n"", lower[i]); + } + } else { + printf(""IMPOSSIBLE\n""); + } + } +",not-set,2016-04-24T02:02:44,2016-04-24T02:02:44,C++ +90,3098,big-balls,Big Balls,"In the jackpot round of a game show, Big Balls, you are given $N$ jackpot balls, each having an integer weight (in grams). Within the time alloted, you may put two balls on opposite sides of a scale in order to determine which ball is heavier. To help you with your task, the host added some extra balls (different from the $N$ jackpot balls) and reveals to you how heavy each of them are (in grams). + +At the end of the allotted time, you must guess the weight of each of the $N$ balls. Take note that each of your guesses must be a positive integer. The only catch is that if the sum of your guesses exceeds the actual sum of the weights, you go home with nothing. Knowing this, you reckon that guessing too high at any point is too risky (it would cost you everything), you decide to guess the weight of each ball such that the sum of the weights of your guesses is minimized. + +**Input Format** +The first line of input will contain two positive integers, $N$ and $M$, separated by a space. +The next $M$ lines describe the comparisons you were able to do during the time alloted. +With each comparison you gain one of the following information: + +* Type A: Ball $X$ is heavier than Ball $Y$. +* Type B: Ball $X$ is lighter than Ball $Y$. +* Type C: Ball $X$ is heavier than the ball weighing $W$ grams. +* Type D: Ball $X$ is lighter than the ball weighing $W$ grams. + +The $M$ lines will each contain a letter from $A$ to $D$ representing the statement it describes and two integers. If the statement is of type $A$ or $B$, the two integers will be $X$ and $Y$ (in that order), describing which two balls were compared. If the statement is of type $C$ or $D$, the two integers will be $X$ and $W$ (in that order), giving an upper/lower bound for the weight of ball $X$. + +**Output Format** +If it is impossible to make a logical conclusion (i.e. there are contradictions with the statements given), output a single line containing the word `IMPOSSIBLE`. + +Otherwise, output $N$ lines, each containing a single integer. The $i^\text{th}$ line should contain your guess (based on the strategy described above) for the weight of Ball $i$. + +It is guaranteed that the answer is unique. Note that balls may have the same weights. + +**Constraints** +$1 \le N \le 2\cdot 10^5$ +$1 \le M \le 2\cdot 10^5$ +$1 \le X \le N$ +$1 \le Y \le N$ +$X \ne Y$ +$1 \le W \le 10^9$ + +**Sample Input 1** + + 1 1 + D 1 1 + +**Sample Output 1** + + IMPOSSIBLE + +**Sample Input 2** + + 5 6 + A 2 1 + B 1 2 + C 3 4 + D 4 12 + B 5 4 + C 1 1 + +**Sample Output 2** + + 2 + 3 + 5 + 2 + 1 + +**Explanation** +The first case deals with $N = 1$ ball and exactly $M = 1$ statement stating that Ball $1$ is lighter than the ball weighing $1$ gram. Hence its weight must be less than $1$ gram. There is no positive integer less than $1$ and so this setup is impossible. + +The second case deals with $N = 5$ balls and $M = 6$ statements which translate as follows: + +* Ball 2 is heavier than Ball 1. +* Ball 1 is lighter than Ball 2. +* Ball 3 is heavier than the ball weighing 4 grams. +* Ball 4 is lighter than the ball weighing 12 grams. +* Ball 5 is lighter than Ball 4. +* Ball 1 is heavier than the ball weighing 1 gram. + +Since the only lower bound for Ball 1 is the fact that it is heavier than $1$ gram, we should guess $2$ for Ball 1. We shouldn't guess any higher since we might go over the sum. Now, since Ball 2 is heavier than Ball 1, we should guess $3$ for that. And so on. +",code,Guess the weights of the balls from comparisons.,ai,2014-06-19T03:48:36,2016-09-09T09:46:50,,,,"In the jackpot round of a game show, Big Balls, you are given $N$ jackpot balls, each having an integer weight (in grams). Within the time alloted, you may put two balls on opposite sides of a scale in order to determine which ball is heavier. To help you with your task, the host added some extra balls (different from the $N$ jackpot balls) and reveals to you how heavy each of them are (in grams). + +At the end of the allotted time, you must guess the weight of each of the $N$ balls. Take note that each of your guesses must be a positive integer. The only catch is that if the sum of your guesses exceeds the actual sum of the weights, you go home with nothing. Knowing this, you reckon that guessing too high at any point is too risky (it would cost you everything), you decide to guess the weight of each ball such that the sum of the weights of your guesses is minimized. + +**Input Format** +The first line of input will contain two positive integers, $N$ and $M$, separated by a space. +The next $M$ lines describe the comparisons you were able to do during the time alloted. +With each comparison you gain one of the following information: + +* Type A: Ball $X$ is heavier than Ball $Y$. +* Type B: Ball $X$ is lighter than Ball $Y$. +* Type C: Ball $X$ is heavier than the ball weighing $W$ grams. +* Type D: Ball $X$ is lighter than the ball weighing $W$ grams. + +The $M$ lines will each contain a letter from $A$ to $D$ representing the statement it describes and two integers. If the statement is of type $A$ or $B$, the two integers will be $X$ and $Y$ (in that order), describing which two balls were compared. If the statement is of type $C$ or $D$, the two integers will be $X$ and $W$ (in that order), giving an upper/lower bound for the weight of ball $X$. + +**Output Format** +If it is impossible to make a logical conclusion (i.e. there are contradictions with the statements given), output a single line containing the word `IMPOSSIBLE`. + +Otherwise, output $N$ lines, each containing a single integer. The $i^\text{th}$ line should contain your guess (based on the strategy described above) for the weight of Ball $i$. + +It is guaranteed that the answer is unique. Note that balls may have the same weights. + +**Constraints** +$1 \le N \le 2\cdot 10^5$ +$1 \le M \le 2\cdot 10^5$ +$1 \le X \le N$ +$1 \le Y \le N$ +$X \ne Y$ +$1 \le W \le 10^9$ + +**Sample Input 1** + + 1 1 + D 1 1 + +**Sample Output 1** + + IMPOSSIBLE + +**Sample Input 2** + + 5 6 + A 2 1 + B 1 2 + C 3 4 + D 4 12 + B 5 4 + C 1 1 + +**Sample Output 2** + + 2 + 3 + 5 + 2 + 1 + +**Explanation** +The first case deals with $N = 1$ ball and exactly $M = 1$ statement stating that Ball $1$ is lighter than the ball weighing $1$ gram. Hence its weight must be less than $1$ gram. There is no positive integer less than $1$ and so this setup is impossible. + +The second case deals with $N = 5$ balls and $M = 6$ statements which translate as follows: + +* Ball 2 is heavier than Ball 1. +* Ball 1 is lighter than Ball 2. +* Ball 3 is heavier than the ball weighing 4 grams. +* Ball 4 is lighter than the ball weighing 12 grams. +* Ball 5 is lighter than Ball 4. +* Ball 1 is heavier than the ball weighing 1 gram. + +Since the only lower bound for Ball 1 is the fact that it is heavier than $1$ gram, we should guess $2$ for Ball 1. We shouldn't guess any higher since we might go over the sum. Now, since Ball 2 is heavier than Ball 1, we should guess $3$ for that. And so on. +",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-24T19:18:31,2017-03-17T05:18:04,tester," #include + #include + #include + #include + #include + #include + + using namespace std; + + const int N = 200002; + + set con[N]; + int ind[N],L[N],G[N],a[N]; + char s[5]; + queue q; + + bool run(int n) { + int m = 0; + for (int i = 0; i < n; ++i) { + if (L[i] - 1 < G[i] + 1) { + return false; + + } + //printf(""%d %d %d\n"",i,L[i],G[i]); + if (ind[i] == 0) { + q.push(i); + } + } + + while (!q.empty()) { + int x = q.front(); + q.pop(); + ++m; + a[x] = G[x] + 1; + //printf(""a[%d] = %d\n"",x,a[x]); + for (set::iterator t = con[x].begin(); t != con[x].end(); ++t) { + G[*t] = max(a[x], G[*t]); + if (L[*t] - 1 < G[*t] + 1) { + //puts(""haha""); + return false; + } + if (--ind[*t] == 0) { + q.push(*t); + } + } + } + //printf(""m = %d\n"",m); + return (m == n); + } + + int main() { + int n,m; + + scanf(""%d%d"",&n,&m); + assert((n >= 1) && (n <= 200000)); + assert((m >= 1) && (m <= 200000)); + for (int i = 0; i < n; ++i) { + L[i] = 2000000000; + G[i] = 0; + } + for (int i = 0; i < m; ++i) { + int x,y; + scanf(""%s%d%d"",s,&x,&y); + assert((strcmp(s,""A"") == 0) || (strcmp(s,""B"") == 0) || (strcmp(s,""C"") == 0) || (strcmp(s,""D"") == 0)); + --x; + switch(s[0]) { + case 'A': + --y; + assert((x >= 0) && (x < n)); + assert((y >= 0) && (y < n) && (y != x)); + if (con[y].find(x) == con[y].end()) { + con[y].insert(x); + ++ind[x]; + } + break; + case 'B': + --y; + assert((x >= 0) && (x < n)); + assert((y >= 0) && (y < n) && (y != x)); + if (con[x].find(y) == con[x].end()) { + con[x].insert(y); + ++ind[y]; + } + break; + case 'C': + assert((y >= 1) && (y <= 1000000000)); + G[x] = max(G[x], y); + break; + case 'D': + assert((y >= 1) && (y <= 1000000000)); + L[x] = min(L[x], y); + break; + } + } + if (run(n)) { + for (int i = 0; i < n; ++i) { + printf(""%d\n"",a[i]); + } + + } + else { + puts(""IMPOSSIBLE""); + } + + return 0; + }",not-set,2016-04-24T02:02:44,2016-04-24T02:02:44,C++ +91,3153,testing-iii,Testing III,"There are $w$ watermelons. Print YES if it can be divided into two parts, each weighing an even number. Print NO otherwise. + +This is identical to the Watermelon challenge on Codeforces.",code,This problem is easy.,ai,2014-06-24T19:35:49,2016-09-09T09:47:13,,,,"There are $w$ watermelons. Print YES if it can be divided into two parts, each weighing an even number. Print NO otherwise. + +This is identical to the Watermelon challenge on Codeforces.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-06-24T19:39:59,2016-05-13T00:01:39,tester,"#include + +int main(void) { + int n; + scanf(""%d"", &n); + puts((n >= 4 && n % 2 == 0) ? ""YES"" : ""NO""); + return 0; +}",not-set,2016-04-24T02:02:44,2016-04-24T02:02:44,C++ +92,3051,connecting-points,Connecting points,"John has his own 3-dimensional space. He currently has $N$ distinct points that belong to this space. + +Today John is connecting the points with each other. In each step, he chooses two points and connects them together by drawing a curved line between them. After that he always puts single point somewhere on the curved line. Note that this point initially has 2 connections, and it can be further connected by curve lines with others. Also note that multiple curved-lines can be drawn between each pair of points. +
+There is one condition: each point which currently has strictly less than $K$ connections can be used for making new connections again. +
+John wants to maximize total number of drawn curve lines. Help him and calculate how many curve lines can John draw. Note that a pair of point can be connected multiple times with different curved lines. + +PS: Refer to the explanation/image given below for more clarity. + +**Input Format** +The first line contains a single integer $T$, representing the number of test cases to follow. Each of the following $T$ lines (or testcases) contains two integers separated by single space: $N$ - the number of points in three-dimensional space, $K$ - number of maximum connections that can be made for the present testcase. + +**Output Format** +For each of the test case, print the count of drawn curve lines, or $-1$ if John will never end connecting the points. + + +**Constraints** +$1 \le T \le 50$ +$1 \le N \le 10^9$ +$0 \le K \le 10$ + +**Sample Input:** + + 5 + 7 0 + 47 1 + 2 2 + 2 3 + 3 10 + +**Sample Output:** + + 0 + 23 + 2 + 5 + -1 + +**Explanation** +*Sample Case #00:* Points are not allowed to be connected at all, so no curved-line can be drawn. +*Sample Case #01:* Since only one line can be drawn out of a point, at most 23 pair of points can be joined via curves. +*Sample Case #02:* John connects both points twice. It yields four points two initial and two appended. All points are connected twice. +*Sample Case #03:* Following picture illustrates the process of connecting the points. Orange points with three edges no longer can be connected. +![connecting-points.gif](https://hr-challenge-images.s3.amazonaws.com/3051/connecting-points.gif) +
+*Sample Case #04:* John will never stop adding points. + +--- +**Tested by** [Shang-En Huang](https://www.hackerrank.com/tmt514)",code,How many curve lines will be drawn?,ai,2014-06-16T18:38:48,2019-07-02T13:58:38,,,,"John has his own 3-dimensional space. He currently has $N$ distinct points that belong to this space. + +Today John is connecting the points with each other. In each step, he chooses two points and connects them together by drawing a curved line between them. After that he always puts single point somewhere on the curved line. Note that this point initially has 2 connections, and it can be further connected by curve lines with others. Also note that multiple curved-lines can be drawn between each pair of points. +
+There is one condition: each point which currently has strictly less than $K$ connections can be used for making new connections again. +
+John wants to maximize total number of drawn curve lines. Help him and calculate how many curve lines can John draw. Note that a pair of point can be connected multiple times with different curved lines. + +PS: Refer to the explanation/image given below for more clarity. + +**Input Format** +The first line contains a single integer $T$, representing the number of test cases to follow. Each of the following $T$ lines (or testcases) contains two integers separated by single space: $N$ - the number of points in three-dimensional space, $K$ - number of maximum connections that can be made for the present testcase. + +**Output Format** +For each of the test case, print the count of drawn curve lines, or $-1$ if John will never end connecting the points. + + +**Constraints** +$1 \le T \le 50$ +$1 \le N \le 10^9$ +$0 \le K \le 10$ + +**Sample Input:** + + 5 + 7 0 + 47 1 + 2 2 + 2 3 + 3 10 + +**Sample Output:** + + 0 + 23 + 2 + 5 + -1 + +**Explanation** +*Sample Case #00:* Points are not allowed to be connected at all, so no curved-line can be drawn. +*Sample Case #01:* Since only one line can be drawn out of a point, at most 23 pair of points can be joined via curves. +*Sample Case #02:* John connects both points twice. It yields four points two initial and two appended. All points are connected twice. +*Sample Case #03:* Following picture illustrates the process of connecting the points. Orange points with three edges no longer can be connected. +![connecting-points.gif](https://hr-challenge-images.s3.amazonaws.com/3051/connecting-points.gif) +
+*Sample Case #04:* John will never stop adding points. + +--- +**Tested by** [Shang-En Huang](https://www.hackerrank.com/tmt514)",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-06-24T21:08:10,2016-05-13T00:01:37,setter," + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + using namespace std; + + typedef pair PII; + typedef vector VI; + + #define FOR(i, a, b) for(int i = (a); i < (b); ++i) + #define RFOR(i, a, b) for(int i = (a) - 1; i >= (b); --i) + #define CLEAR(a, b) memset(a, b, sizeof(a)) + #define ALL(a) (a).begin(),(a).end() + #define PB push_back + #define MP make_pair + #define MOD 1000000007 + #define INF 1000000007 + #define y1 agaga + #define ll long long + #define ull unsigned long long + + vector V; + int n,k; + + int f(int n, int k) + { + if (n == 1 || k == 0) return 0; + if (k == 1) return n / 2; + if (k == 2) return n; + if (k >= 4) return -1; + return -2; + } + + int main() + { + //freopen(""input.txt"", ""r"", stdin); + //freopen(""output.txt"", ""w"", stdout); + + int t; + cin >> t; + + while (t--) + { + + cin >> n >> k; + + if (f(n,k)!=-2) + { + cout << f(n,k) << endl; + continue; + } + + + cout << (ll)(n)*3-1<< endl; + + } + + + return 0; + }",not-set,2016-04-24T02:02:44,2016-04-24T02:02:44,C++ +93,3051,connecting-points,Connecting points,"John has his own 3-dimensional space. He currently has $N$ distinct points that belong to this space. + +Today John is connecting the points with each other. In each step, he chooses two points and connects them together by drawing a curved line between them. After that he always puts single point somewhere on the curved line. Note that this point initially has 2 connections, and it can be further connected by curve lines with others. Also note that multiple curved-lines can be drawn between each pair of points. +
+There is one condition: each point which currently has strictly less than $K$ connections can be used for making new connections again. +
+John wants to maximize total number of drawn curve lines. Help him and calculate how many curve lines can John draw. Note that a pair of point can be connected multiple times with different curved lines. + +PS: Refer to the explanation/image given below for more clarity. + +**Input Format** +The first line contains a single integer $T$, representing the number of test cases to follow. Each of the following $T$ lines (or testcases) contains two integers separated by single space: $N$ - the number of points in three-dimensional space, $K$ - number of maximum connections that can be made for the present testcase. + +**Output Format** +For each of the test case, print the count of drawn curve lines, or $-1$ if John will never end connecting the points. + + +**Constraints** +$1 \le T \le 50$ +$1 \le N \le 10^9$ +$0 \le K \le 10$ + +**Sample Input:** + + 5 + 7 0 + 47 1 + 2 2 + 2 3 + 3 10 + +**Sample Output:** + + 0 + 23 + 2 + 5 + -1 + +**Explanation** +*Sample Case #00:* Points are not allowed to be connected at all, so no curved-line can be drawn. +*Sample Case #01:* Since only one line can be drawn out of a point, at most 23 pair of points can be joined via curves. +*Sample Case #02:* John connects both points twice. It yields four points two initial and two appended. All points are connected twice. +*Sample Case #03:* Following picture illustrates the process of connecting the points. Orange points with three edges no longer can be connected. +![connecting-points.gif](https://hr-challenge-images.s3.amazonaws.com/3051/connecting-points.gif) +
+*Sample Case #04:* John will never stop adding points. + +--- +**Tested by** [Shang-En Huang](https://www.hackerrank.com/tmt514)",code,How many curve lines will be drawn?,ai,2014-06-16T18:38:48,2019-07-02T13:58:38,,,,"John has his own 3-dimensional space. He currently has $N$ distinct points that belong to this space. + +Today John is connecting the points with each other. In each step, he chooses two points and connects them together by drawing a curved line between them. After that he always puts single point somewhere on the curved line. Note that this point initially has 2 connections, and it can be further connected by curve lines with others. Also note that multiple curved-lines can be drawn between each pair of points. +
+There is one condition: each point which currently has strictly less than $K$ connections can be used for making new connections again. +
+John wants to maximize total number of drawn curve lines. Help him and calculate how many curve lines can John draw. Note that a pair of point can be connected multiple times with different curved lines. + +PS: Refer to the explanation/image given below for more clarity. + +**Input Format** +The first line contains a single integer $T$, representing the number of test cases to follow. Each of the following $T$ lines (or testcases) contains two integers separated by single space: $N$ - the number of points in three-dimensional space, $K$ - number of maximum connections that can be made for the present testcase. + +**Output Format** +For each of the test case, print the count of drawn curve lines, or $-1$ if John will never end connecting the points. + + +**Constraints** +$1 \le T \le 50$ +$1 \le N \le 10^9$ +$0 \le K \le 10$ + +**Sample Input:** + + 5 + 7 0 + 47 1 + 2 2 + 2 3 + 3 10 + +**Sample Output:** + + 0 + 23 + 2 + 5 + -1 + +**Explanation** +*Sample Case #00:* Points are not allowed to be connected at all, so no curved-line can be drawn. +*Sample Case #01:* Since only one line can be drawn out of a point, at most 23 pair of points can be joined via curves. +*Sample Case #02:* John connects both points twice. It yields four points two initial and two appended. All points are connected twice. +*Sample Case #03:* Following picture illustrates the process of connecting the points. Orange points with three edges no longer can be connected. +![connecting-points.gif](https://hr-challenge-images.s3.amazonaws.com/3051/connecting-points.gif) +
+*Sample Case #04:* John will never stop adding points. + +--- +**Tested by** [Shang-En Huang](https://www.hackerrank.com/tmt514)",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-06-24T21:08:10,2016-05-13T00:01:37,tester," #include + #include + #include + #include + #include + #include + #define SZ(x) ((int)(x).size()) + #define FOR(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it) + using namespace std; + typedef long long LL; + + void solve() { + int n, k; + scanf(""%d%d"", &n, &k); + if(k == 0) { + printf(""0\n""); + } else if(k == 1) { + printf(""%d\n"", n/2); + } else if(k == 2) { + printf(""%d\n"", n==1? 0: n); + } else if(k == 3) { + printf(""%lld\n"", n==1? 0LL: n + (2LL*n-1)); + } else + puts(""-1""); + } + + int main(void) { + int T; + scanf(""%d"", &T); + while(T--) solve(); + return 0; + } +",not-set,2016-04-24T02:02:44,2016-04-24T02:02:44,C++ +94,3097,skwishinese,Skwishinese ,"The language Skwishinese has its own elegant, albeit complicated, measure for the beauty of a word. + +Before we can start describing how to measure it, we must first define a subsequence. Discovered by and named after the famous Skwishinese doctor, Aaron J. Subsequence, a _subsequence_ of a word is another word that can be formed by removing one or more (possibly none) of the letters of that word. For example, `loooo` is a subsequence of `troolooloo`, but `trooooll` and `banana` are not. + +Moreover, the _reverse_ of a word is obtained simply by reversing the order of the letters. For example, the reverse of `troolooloo` is `oolooloort`. We denote the reverse of $U$ by $U^R$. + +Let $U$ be a Skwishinese word. We can form a nonsensical word, $UU^R$, by _concatenating_ $U$ and its reverse. For example, if $U$ is `loooo`, then $UU^R$ will be `looooooool`. + +Now, the _beauty_ of a Skwishinese word $V$ is the length of the shortest word $U$ that is a subsequence of $V$ and such that $V$ is a subsequence of $UU^R$ (the concatenation of $U$ and its reverse). + +For example, the beauty of the word `troolooloo` is 6, because 6 is the length of the shortest word $U$ satisfying the above conditions (in this case, $U$ is `troolo`). + +**Input Format** +The input consists of exactly two lines. + +The first line contains $N$, a positive integer giving the length of the word $V$. + +The second line contains $V$ a word in Skwishinese. It is a string consisting only of lowercase letters from the English alphabet. + +**Output Format** +Output the beauty of the Skwishinese word $V$. + +**Constraints** +$1 \le N \le 400$ +$V$ consists only of lowercase letters + +**Sample Input** + + 6 + oleleo + +**Sample Output** + + 4 + +**Explanation** +One such possible $U$ is `oele` (because `oele` is a subsequence of `oleleo`, and `oleleo` is a subsequence of $UU^R$ = `oeleeleo`). Another is `olel`. + +It can be shown that this is the shortest possible, so the answer is 4.",code,Determine how beautiful a Skwishinese word is.,ai,2014-06-19T03:42:29,2018-02-06T18:45:19,,,,"The language Skwishinese has its own elegant, albeit complicated, measure for the beauty of a word. + +Before we can start describing how to measure it, we must first define a subsequence. Discovered by and named after the famous Skwishinese doctor, Aaron J. Subsequence, a _subsequence_ of a word is another word that can be formed by removing one or more (possibly none) of the letters of that word. For example, `loooo` is a subsequence of `troolooloo`, but `trooooll` and `banana` are not. + +Moreover, the _reverse_ of a word is obtained simply by reversing the order of the letters. For example, the reverse of `troolooloo` is `oolooloort`. We denote the reverse of $U$ by $U^R$. + +Let $U$ be a Skwishinese word. We can form a nonsensical word, $UU^R$, by _concatenating_ $U$ and its reverse. For example, if $U$ is `loooo`, then $UU^R$ will be `looooooool`. + +Now, the _beauty_ of a Skwishinese word $V$ is the length of the shortest word $U$ that is a subsequence of $V$ and such that $V$ is a subsequence of $UU^R$ (the concatenation of $U$ and its reverse). + +For example, the beauty of the word `troolooloo` is 6, because 6 is the length of the shortest word $U$ satisfying the above conditions (in this case, $U$ is `troolo`). + +**Input Format** +The input consists of exactly two lines. + +The first line contains $N$, a positive integer giving the length of the word $V$. + +The second line contains $V$ a word in Skwishinese. It is a string consisting only of lowercase letters from the English alphabet. + +**Output Format** +Output the beauty of the Skwishinese word $V$. + +**Constraints** +$1 \le N \le 400$ +$V$ consists only of lowercase letters + +**Sample Input** + + 6 + oleleo + +**Sample Output** + + 4 + +**Explanation** +One such possible $U$ is `oele` (because `oele` is a subsequence of `oleleo`, and `oleleo` is a subsequence of $UU^R$ = `oeleeleo`). Another is `olel`. + +It can be shown that this is the shortest possible, so the answer is 4.",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-25T11:28:33,2018-02-06T18:45:22,setter,"```cpp +#include +#define infinity 111111111 +int min(int a, int b) { + return a < b ? a : b; +} + +char V[411]; +int F[411][411][411]; +int main() { + int N; + scanf(""%d%s"", &N, V); + for (int i = N; i >= 0; i--) { + // try on ones and zeroes + for (int j = 0; j < N; j++) { + for (int k = j ? j - 1 : 0; k < N; k++) { + if (j > k) {// empty strjng + F[i][j][k] = 0; + } else if (i >= N) { + F[i][j][k] = infinity; + } else { + int X; + if (V[i] != V[j] and V[i] != V[k]) { + X = 1 + F[i+1][j][k]; + } else if (V[i] != V[j] and V[i] == V[k]) { + X = 1 + F[i+1][j][k-1]; + } else if (V[i] == V[j] and V[i] != V[k]) { + X = 1 + F[i+1][j+1][k]; + } else if (V[i] == V[j] and V[i] == V[k]) { + X = 1 + F[i+1][j+1][k-1]; + } + F[i][j][k] = min(F[i+1][j][k], X); + } + } + } + } + printf(""%d\n"", F[0][0][N-1]); +} +``` +",not-set,2016-04-24T02:02:44,2018-02-06T18:45:22,C++ +95,3097,skwishinese,Skwishinese ,"The language Skwishinese has its own elegant, albeit complicated, measure for the beauty of a word. + +Before we can start describing how to measure it, we must first define a subsequence. Discovered by and named after the famous Skwishinese doctor, Aaron J. Subsequence, a _subsequence_ of a word is another word that can be formed by removing one or more (possibly none) of the letters of that word. For example, `loooo` is a subsequence of `troolooloo`, but `trooooll` and `banana` are not. + +Moreover, the _reverse_ of a word is obtained simply by reversing the order of the letters. For example, the reverse of `troolooloo` is `oolooloort`. We denote the reverse of $U$ by $U^R$. + +Let $U$ be a Skwishinese word. We can form a nonsensical word, $UU^R$, by _concatenating_ $U$ and its reverse. For example, if $U$ is `loooo`, then $UU^R$ will be `looooooool`. + +Now, the _beauty_ of a Skwishinese word $V$ is the length of the shortest word $U$ that is a subsequence of $V$ and such that $V$ is a subsequence of $UU^R$ (the concatenation of $U$ and its reverse). + +For example, the beauty of the word `troolooloo` is 6, because 6 is the length of the shortest word $U$ satisfying the above conditions (in this case, $U$ is `troolo`). + +**Input Format** +The input consists of exactly two lines. + +The first line contains $N$, a positive integer giving the length of the word $V$. + +The second line contains $V$ a word in Skwishinese. It is a string consisting only of lowercase letters from the English alphabet. + +**Output Format** +Output the beauty of the Skwishinese word $V$. + +**Constraints** +$1 \le N \le 400$ +$V$ consists only of lowercase letters + +**Sample Input** + + 6 + oleleo + +**Sample Output** + + 4 + +**Explanation** +One such possible $U$ is `oele` (because `oele` is a subsequence of `oleleo`, and `oleleo` is a subsequence of $UU^R$ = `oeleeleo`). Another is `olel`. + +It can be shown that this is the shortest possible, so the answer is 4.",code,Determine how beautiful a Skwishinese word is.,ai,2014-06-19T03:42:29,2018-02-06T18:45:19,,,,"The language Skwishinese has its own elegant, albeit complicated, measure for the beauty of a word. + +Before we can start describing how to measure it, we must first define a subsequence. Discovered by and named after the famous Skwishinese doctor, Aaron J. Subsequence, a _subsequence_ of a word is another word that can be formed by removing one or more (possibly none) of the letters of that word. For example, `loooo` is a subsequence of `troolooloo`, but `trooooll` and `banana` are not. + +Moreover, the _reverse_ of a word is obtained simply by reversing the order of the letters. For example, the reverse of `troolooloo` is `oolooloort`. We denote the reverse of $U$ by $U^R$. + +Let $U$ be a Skwishinese word. We can form a nonsensical word, $UU^R$, by _concatenating_ $U$ and its reverse. For example, if $U$ is `loooo`, then $UU^R$ will be `looooooool`. + +Now, the _beauty_ of a Skwishinese word $V$ is the length of the shortest word $U$ that is a subsequence of $V$ and such that $V$ is a subsequence of $UU^R$ (the concatenation of $U$ and its reverse). + +For example, the beauty of the word `troolooloo` is 6, because 6 is the length of the shortest word $U$ satisfying the above conditions (in this case, $U$ is `troolo`). + +**Input Format** +The input consists of exactly two lines. + +The first line contains $N$, a positive integer giving the length of the word $V$. + +The second line contains $V$ a word in Skwishinese. It is a string consisting only of lowercase letters from the English alphabet. + +**Output Format** +Output the beauty of the Skwishinese word $V$. + +**Constraints** +$1 \le N \le 400$ +$V$ consists only of lowercase letters + +**Sample Input** + + 6 + oleleo + +**Sample Output** + + 4 + +**Explanation** +One such possible $U$ is `oele` (because `oele` is a subsequence of `oleleo`, and `oleleo` is a subsequence of $UU^R$ = `oeleeleo`). Another is `olel`. + +It can be shown that this is the shortest possible, so the answer is 4.",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-25T11:28:33,2018-02-06T18:45:22,tester,"```cpp +#include +#include +#include +#include +#include + +using namespace std; + +char s[402]; +int dp[2][402][402]; + +void better(int &x,int y) { + if ((x < 0) || (x > y)) { + x = y; + } +} + +int main() { + memset(dp,0xff,sizeof(dp)); + dp[0][0][0] = 0; + int n; + scanf(""%d%s"",&n,s); + assert((n >= 1) && (n <= 400)); + assert(strlen(s) == n); + int answer = n, last = 0; + for (int i = 1; i <= n; ++i) { + assert(islower(s[i - 1])); + int now = i & 1; + memcpy(dp[now], dp[last],sizeof(dp[0])); + for (int j = 0; j < i; ++j) { + for (int k = 0; (k < i) && (j + k < n); ++k) { + if (dp[last][j][k] >= 0) { + int jj = (s[i - 1] == s[j])?(j + 1):j; + int kk = (s[i - 1] == s[n - k - 1])?(k + 1):k; + better(dp[now][jj][kk], dp[last][j][k] + 1); + if (jj + kk >= n) { + answer = min(answer, dp[now][jj][kk]); + } + } + } + } + last = now;; + } + + printf(""%d\n"",answer); + return 0; +} +``` +",not-set,2016-04-24T02:02:44,2018-02-06T18:45:22,C++ +96,3164,net-admin,Network administration,"Like every IT company, the Uplink Corporation has its own network. But, unlike the rest of the companies around the world, Uplink's network is subject to very specific restrictions: + +* Any pair of servers within the network should be directly connected by at most 1 link. +* Each link is controlled by some specific network administrator. +* No server has more than 2 links connected to it, that are controlled by the same administrator. +* For easier management, links controlled by some administrator cannot be redundant (this is, removing any link will disconnect some two previously connected servers) + +Notice that 2 connected servers might not have any direct link between them. Furthermore, in order to keep the network in a secured status, Uplink directives periodically try to perform some modifications over the network to mislead hackers. The problem is, having such a huge network, they need a software to efficiently simulate the network status after any of such modifications. You have been assigned to write the core section of that software. + +Operations performed by the directives are: + +* Change the administrator assigned to some particular link. +* Place some number of security devices along a particular link. + +Also, given a network administrator, they would like to know how many devices are in the path created by links controlled by that administrator (if any) between 2 servers. + +**Input Format** +Input begins with a line containing 4 integers $S, L, A, T$ separated by a single whitespace, denoting the number of servers, links, network administrators and transformations, respectively. $L$ lines follow each one with 3 integers $x, y~(x \lt y)$ and $a_i~(1 \le a_i \le A)$, saying that there is a link between server $x$ and server $y$, and that link is controlled by administrator $a_i$. Initially, network topology fulfills the restrictions described above and there is no security device along any link. Remaining $T$ lines in the input follow one the next formats: + +* $1$ $A$ $B$ $a_i$ + +meaning that link between server $A$ and server $B$ $(A \lt B)$ is requested to be assigned to administrator $a_i$ + +* $2$ $A$ $B$ $x$ + +meaning that the number of security devices along the link between server $A$ and server $B$ $(A \lt B)$ will be fixed to $x$, removing any existing devices on this link before the operation. The involved link will always exist. + +* $3$ $A$ $B$ $a_i$ + +meaning that directives want to know the number of security devices placed along the path between server $A$ and server $B$, just considering links controlled by administrator $a_i$. + +**Output Format** +For each network transformation in the form $1$ $A$ $B$ $a_i$ you should output: + +* ""Wrong link"" if there is no direct link between server $A$ and server $B$. +* ""Already controlled link"" if the requested link does exist, but it is already controlled by administrator $a_i$. +* ""Server overload"" if administrator $a_i$ already controls 2 links connected to one of the involved servers. +* ""Network redundancy"" if the requested assignment creates no new connection considering just the links controlled by $a_i$. +* ""Assignment done"" if none of the above conditions holds. In this case, link directly connecting $A$ with $B$ is assigned to $a_i$. + + +For each network transformation in the form $3$ $A$ $B$ $a_i$ you should output: + +* ""No connection"" if there is no path between the requested servers considering just the links controlled by $a_i$. +* ""$D$ security devices placed"" where **D** is the number of security devices placed so far on the existing connection between the requested servers considering just the links controlled by $a_i$. + +**Constraints** + +$1 \le S \le 10^5$ +$1 \le L \le 5 \times 10^5$ +$1 \le A \le 10^2$ +$1 \le T \le 5 \times 10^5$ +$1 \le x \le 2000$ + +**Sample Input:** + + 4 5 3 15 + 1 2 1 + 2 3 1 + 3 4 2 + 1 4 2 + 1 3 3 + 2 3 4 49 + 1 1 2 3 + 2 1 4 64 + 3 1 4 2 + 1 1 2 3 + 3 4 2 3 + 3 1 3 3 + 1 1 4 3 + 3 3 4 2 + 3 2 4 1 + 2 1 4 13 + 2 1 3 21 + 2 2 3 24 + 1 2 3 3 + 1 2 4 3 + +**Sample Output:** + + Assignment done + 64 security devices placed + Already controlled link + No connection + 0 security devices placed + Server overload + 49 security devices placed + No connection + Network redundancy + Wrong link +",code,"Given a network administrator, find out how many devices are in the path created by links controlled by that administrator (if any) between 2 servers.",ai,2014-06-25T22:32:13,2022-09-02T10:00:41,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING_ARRAY. +# The function accepts following parameters: +# 1. INTEGER s +# 2. INTEGER a +# 3. 2D_INTEGER_ARRAY links +# 4. 2D_INTEGER_ARRAY queries +# + +def solve(s, a, links, queries): + # 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() + + s = int(first_multiple_input[0]) + + l = int(first_multiple_input[1]) + + a = int(first_multiple_input[2]) + + t = int(first_multiple_input[3]) + + links = [] + + for _ in range(l): + links.append(list(map(int, input().rstrip().split()))) + + queries = [] + + for _ in range(t): + queries.append(list(map(int, input().rstrip().split()))) + + result = solve(s, a, links, queries) + + fptr.write('\n'.join(result)) + fptr.write('\n') + + fptr.close() +","Time Limits C:5, Cpp:5, C#:6, Java:8, Php:18, Ruby:20, Python:20, Perl:18, Haskell:10, Scala:14, Javascript:20, Pascal:5 + +Like every IT company, the Uplink Corporation has its own network. But, unlike the rest of the companies around the world, Uplink's network is subject to very specific restrictions: + +* Any pair of servers within the network should be directly connected by at most 1 link. +* Each link is controlled by some specific network administrator. +* No server has more than 2 links connected to it, that are controlled by the same administrator. +* For easier management, links controlled by some administrator cannot be redundant (this is, removing any link will disconnect some two previously connected servers) + +Notice that 2 connected servers might not have any direct link between them. Furthermore, in order to keep the network in a secured status, Uplink directives periodically try to perform some modifications over the network to mislead hackers. The problem is, having such a huge network, they need a software to efficiently simulate the network status after any of such modifications. You have been assigned to write the core section of that software. + +Operations performed by the directives are: + +* Change the administrator assigned to some particular link. +* Place some number of security devices along a particular link. + +Also, given a network administrator, they would like to know how many devices are in the path created by links controlled by that administrator (if any) between 2 servers. + +**Input Format** +Input begins with a line containing 4 integers $S, L, A, T$ separated by a single whitespace, denoting the number of servers, links, network administrators and transformations, respectively. $L$ lines follow each one with 3 integers $x, y~(x \lt y)$ and $a_i~(1 \le a_i \le A)$, saying that there is a link between server $x$ and server $y$, and that link is controlled by administrator $a_i$. Initially, network topology fulfills the restrictions described above and there is no security device along any link. Remaining $T$ lines in the input follow one the next formats: + +* $1$ $A$ $B$ $a_i$ + +meaning that link between server $A$ and server $B$ $(A \lt B)$ is requested to be assigned to administrator $a_i$ + +* $2$ $A$ $B$ $x$ + +meaning that the number of security devices along the link between server $A$ and server $B$ $(A \lt B)$ will be fixed to $x$, removing any existing devices on this link before the operation. The involved link will always exist. + +* $3$ $A$ $B$ $a_i$ + +meaning that directives want to know the number of security devices placed along the path between server $A$ and server $B$, just considering links controlled by administrator $a_i$. + +**Output Format** +For each network transformation in the form $1$ $A$ $B$ $a_i$ you should output: + +* ""Wrong link"" if there is no direct link between server $A$ and server $B$. +* ""Already controlled link"" if the requested link does exist, but it is already controlled by administrator $a_i$. +* ""Server overload"" if administrator $a_i$ already controls 2 links connected to one of the involved servers. +* ""Network redundancy"" if the requested assignment creates no new connection considering just the links controlled by $a_i$. +* ""Assignment done"" if none of the above conditions holds. In this case, link directly connecting $A$ with $B$ is assigned to $a_i$. + + +For each network transformation in the form $3$ $A$ $B$ $a_i$ you should output: + +* ""No connection"" if there is no path between the requested servers considering just the links controlled by $a_i$. +* ""$D$ security devices placed"" where **D** is the number of security devices placed so far on the existing connection between the requested servers considering just the links controlled by $a_i$. + +**Constraints** + +$1 \le S \le 10^5$ +$1 \le L \le 5 \times 10^5$ +$1 \le A \le 10^2$ +$1 \le T \le 5 \times 10^5$ +$1 \le x \le 2000$ + +**Sample Input:** + + 4 5 3 15 + 1 2 1 + 2 3 1 + 3 4 2 + 1 4 2 + 1 3 3 + 2 3 4 49 + 1 1 2 3 + 2 1 4 64 + 3 1 4 2 + 1 1 2 3 + 3 4 2 3 + 3 1 3 3 + 1 1 4 3 + 3 3 4 2 + 3 2 4 1 + 2 1 4 13 + 2 1 3 21 + 2 2 3 24 + 1 2 3 3 + 1 2 4 3 + +**Sample Output:** + + Assignment done + 64 security devices placed + Already controlled link + No connection + 0 security devices placed + Server overload + 49 security devices placed + No connection + Network redundancy + Wrong link +",0.4166666666666667,"[""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,,,,,,,2014-06-25T22:32:35,2016-12-03T07:57:19,setter," //============================================================================ + // Name : NETADMIN.cpp + // Author : Shaka + // Version : + // Copyright : Your copyright notice + // Description : Hello World in C++, Ansi-style + //============================================================================ + + #include + #include + #include + using namespace std; + const int MAXSERVER = 8000, MAXADMIN = 100, MAXLINK = 1e5; + struct node { + node *prx, *lft, *rgt; + bool rev; + int sum, fx, size; + node() { + clear(); + } + + void clear() { + lft = rgt = prx = NULL; + rev = 0; + sum = fx = 0; + size = 1; + } + + bool is_root() { + return !prx || (prx->lft != this && prx->rgt != this); + } + }; + + struct lnk { + node *a, *b; + lnk() { + clear(); + } + node *get() { + if (a) return a; + else if (b) return b; + return NULL; + } + node *get_diff(node* x) { + if (a == x) return b; + else if (b == x) return a; + return get(); + } + void add(node *x) { + if (!a) a = x; + else if (!b) b = x; + } + + void del(node* x) { + if (a == x) a = NULL; + else if (b == x) b = NULL; + } + void clear() { + a = b = NULL; + } + int count() { + return (a != NULL) + (b != NULL); + } + }; + typedef pair pii; + typedef pair pin; + + + static void clean_reverse(node *px) { + if (px->rev) { + px->rev = 0; + swap(px->lft, px->rgt); + if (px->lft) + px->lft->rev ^= 1; + if (px->rgt) + px->rgt->rev ^= 1; + } + } + + static void fix_size_and_sum(node *px) { + int lsize = px->lft ? px->lft->size : 0; + int rsize = px->rgt ? px->rgt->size : 0; + px->size = lsize + rsize + 1; + + int lsum = px->lft ? px->lft->sum : 0; + int rsum = px->rgt ? px->rgt->sum : 0; + px->sum = lsum + rsum + px->fx; + } + + void zig(node *p) { + node *q = p->prx, *r = q->prx; + if ((q->lft = p->rgt)) q->lft->prx = q; + p->rgt = q, q->prx = p; + if (((p->prx = r))) { + if (r->lft == q) r->lft = p; + if (r->rgt == q) r->rgt = p; + } + } + + void zag(node *p) { + node *q = p->prx, *r = q->prx; + if ((q->rgt = p->lft)) q->rgt->prx = q; + p->lft = q, q->prx = p; + if (((p->prx = r))) { + if (r->lft == q) r->lft = p; + if (r->rgt == q) r->rgt = p; + } + } + lnk table[MAXSERVER][MAXADMIN]; + map ehash; + + static void splay(node *px) { + struct node *f, *gf; + while (!px->is_root()) { + f = px->prx; + gf = f->prx; + if (!gf) { + clean_reverse(f); + clean_reverse(px); + if (f->lft == px) zig(px); + else zag(px); + fix_size_and_sum(f); + fix_size_and_sum(px); + } else { + clean_reverse(gf); + clean_reverse(f); + clean_reverse(px); + if (gf->lft == f) + if (f->lft == px) zig(f), zig(px); + else zag(px), zig(px); + else if (f->lft == px) zig(px), zag(px); + else zag(f), zag(px); + fix_size_and_sum(gf); + fix_size_and_sum(f); + fix_size_and_sum(px); + } + } + clean_reverse(px); + } + static void make_last (node *x) { + splay(x); + if (x->rgt) x->rev ^= 1; + } + + static void make_first (node *x) { + splay(x); + if (x->lft) x->rev ^= 1; + } + + static void add_edge(int a, int b, int i, node *px) { + node *l, *r; + l = table[a][i].get(); + if (l) make_last(l); + + r = table[b][i].get(); + if (r) make_first(r); + + px->lft = l; + if (l) l->prx = px; + + px->rgt = r; + if (r) r->prx = px; + + px->rev = 0; + px->prx = NULL; + + fix_size_and_sum(px); + + table[a][i].add(px); + table[b][i].add(px); + } + + static void del_edge(int a, int b, int x, node *px) { + splay(px); + if (px->lft) px->lft->prx = NULL; + if (px->rgt) px->rgt->prx = NULL; + table[a][x].del(px); + table[b][x].del(px); + px->lft = NULL; + px->rgt = NULL; + px->prx = NULL; + fix_size_and_sum(px); + } + + static bool connected(int a, int b, int x) { + node *pa = table[a][x].get(), *pb = table[b][x].get(); + if (pa != pb) { + splay(pa), splay(pb); + return pa->prx != NULL; + } + return true; + } + + int xrank(node* px) { + splay(px); + return px->lft ? px->lft->size : 0; + } + + node* frx[MAXLINK]; + int main() { + register int N, M, C, T, i, j, a, b, x, cmd; + scanf(""%d%d%d%d"", &N, &M, &C, &T); + for (i = 0; i < M; ++i) + frx[i] = new node(); + ehash.clear(); + pii key; + for (i = 0; i < M; ++i) { + scanf(""%d%d%d"", &a, &b, &j); + --a, --b, --j; + key = make_pair(a, b); + node *ptx = frx[i]; + ehash[key] = make_pair(j + 1, ptx); + add_edge(a, b, j, ptx); + } + node *px, *qx, *tx, *ux; + int rpx, rqx, rtx, rux; + while (T--) { + scanf(""%d%d%d%d"", &cmd, &a, &b, &i); + --a, --b; + if (cmd == 1) { + --i; + key = make_pair(a, b); + pin& data = ehash[key]; + x = data.first; + if (!x) { //not found in edges storage + printf(""Wrong link\n""); + continue; + } + --x; + if (x == i) { //this cable is already controlled by this admin + printf(""Already controlled link\n""); + continue; + } + if (table[a][i].count() == 2 || table[b][i].count() == 2) { //at least one of the serves has 2 cables related the new admin + printf(""Server overload\n""); + continue; + } + if (table[a][i].count() > 0 && table[b][i].count() > 0 && connected(a, b, i)) { //it is possible to get from one of them to the other + printf(""Network redundancy\n""); + continue; + } + px = data.second; //get the proper node (i.e. the node for edge a <-> b) + + del_edge(a, b, x, px); + + add_edge(a, b, i, px); + + data.first = i + 1; //update the company owning this cable + + printf(""Assignment done\n""); + } else if(cmd == 2) { + key = make_pair(a, b); + + pin& data = ehash[key]; + + px = data.second; + + splay(px); + + px->fx = i; + + fix_size_and_sum(px); + } else { + --i; + if (a > b) swap(a, b); + key = make_pair(a, b); + pin& data = ehash[key]; + if (data.second && data.first == i + 1) { + printf(""%d security devices placed\n"", data.second->fx); + continue; + } + lnk al = table[a][i], bl = table[b][i]; + if (al.count() > 0 && bl.count() > 0 && connected(a, b, i)) { + if (al.count() == 1 && bl.count() == 1) { //happy case :) + px = al.get(); + make_first(px); + x = px->sum; + } else if (al.count() + bl.count() == 3) { //one is extreme, we need to find the next one + if (al.count() > 1) swap(al, bl); + + px = al.get(); + make_first(px); + x = px->sum; + + qx = bl.a, tx = bl.b; + if (xrank(qx) > xrank(tx)) swap(qx, tx); + + splay(qx); + x -= qx->rgt->sum; + } else { //hard case, invoking creativity :) + px = al.a, qx = al.b, tx = bl.a, ux = bl.b; + rpx = xrank(px), rqx = xrank(qx), rtx = xrank(tx), rux = xrank(ux); + if (rpx > rqx) swap(px, qx), swap(rpx, rqx); + if (rtx > rux) swap(tx, ux), swap(rtx, rux); + + if (rpx > rtx) swap(px, tx), swap(rpx, rtx), swap(qx, ux), swap(rqx, rux); + /** + * At this point: + * a is to the left and b to the right + * px is the lowest a's edge and qx is the highest a's edge + * tx is the lowest b's edge and ux is the highest b's edge + * */ + + splay(qx); + x = qx->fx + qx->rgt->sum; + + splay(tx); + x -= tx->rgt->sum; + } + printf(""%d security devices placed\n"", x); + } else printf(""No connection\n""); + } + } + return 0; + } +",not-set,2016-04-24T02:02:44,2016-04-24T02:02:44,C++ +97,2565,xor-love,XOR love,"Devendra loves the XOR operation very much which is denoted by $\wedge$ sign in most of the programming languages. He has a list $A$ of $N$ numbers and he wants to know the answers of $M$ queries. Each query will be denoted by three numbers i.e. $K,P,R$ . + +For query $K,P \text{ and } R$, he has to print the value of the $KPRsum$ which can be described as given below. As the value of the $KPRsum$ can be large. So, print it modulus $(10^9 + 7)$. + +$$ KPRsum = \sum_{i=P}^{R-1} \sum_{j=i+1}^{R} (K \oplus (A[i] \oplus A[j]) )$$ + +**Input Format** +The first line contains an integer $N$, i.e., the number of the elements in the list. List is numbered from $1$ to $N$. +Next line will contain $N$ space seperated integers. +Third line will contain a number $M$ i.e. number of queries followed by $M$ lines each containing integers $K,P \& R$. + +**Output Format** +Print $M$ lines, $i^{th}$ line will be answer of $i^{th}$ query. **Answer will be 0 in case of P=R.** + +**Constraints** +$1 \le N \le 10^5$ +$1 \le A[i] \le 10^6$ +$1 \le M \le 10^5$ +$0 \le K \le 10^6$ +$1 \le P \le R \le N$ + +**Sample Input** + + 3 + 1 2 3 + 2 + 1 1 3 + 2 1 3 + + +**Sample Output** + + 5 + 4 + +**Explanation** + +For first query, it will will be $$(1 \oplus( 1 \oplus 2) ) + (1 \oplus( 1 \oplus 3) ) + (1 \oplus( 2 \oplus 3) ) = 5 $$",code,Reply to query related to XOR.,ai,2014-05-30T20:35:04,2022-09-02T09:55:10,,,,"Devendra loves the XOR operation very much which is denoted by $\wedge$ sign in most of the programming languages. He has a list $A$ of $N$ numbers and he wants to know the answers of $M$ queries. Each query will be denoted by three numbers i.e. $K,P,R$ . + +For query $K,P \text{ and } R$, he has to print the value of the $KPRsum$ which can be described as given below. As the value of the $KPRsum$ can be large. So, print it modulus $(10^9 + 7)$. + +$$ KPRsum = \sum_{i=P}^{R-1} \sum_{j=i+1}^{R} (K \oplus (A[i] \oplus A[j]) )$$ + +**Input Format** +The first line contains an integer $N$, i.e., the number of the elements in the list. List is numbered from $1$ to $N$. +Next line will contain $N$ space seperated integers. +Third line will contain a number $M$ i.e. number of queries followed by $M$ lines each containing integers $K,P \& R$. + +**Output Format** +Print $M$ lines, $i^{th}$ line will be answer of $i^{th}$ query. **Answer will be 0 in case of P=R.** + +**Constraints** +$1 \le N \le 10^5$ +$1 \le A[i] \le 10^6$ +$1 \le M \le 10^5$ +$0 \le K \le 10^6$ +$1 \le P \le R \le N$ + +**Sample Input** + + 3 + 1 2 3 + 2 + 1 1 3 + 2 1 3 + + +**Sample Output** + + 5 + 4 + +**Explanation** + +For first query, it will will be $$(1 \oplus( 1 \oplus 2) ) + (1 \oplus( 1 \oplus 3) ) + (1 \oplus( 2 \oplus 3) ) = 5 $$",0.4769230769230769,"[""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,,,,,,,2014-06-26T10:13:36,2016-12-06T09:46:26,setter,"###C++ +```cpp +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; +typedef long long int ll; +int A[100001][31]; +int main() +{ + ll answer=0,ones,zeros,o,z; + int N,x,pow[31],y,k,M; + pow[0]=1; + for(int i=1;i<31;i++) pow[i]=pow[i-1]<<1; + scanf(""%d"",&N); + assert(N<=100000 && N>=1); + for(int i=0;i<31;i++) A[0][i]=0; + for(int i=1;i<=N;i++) + { + scanf(""%d"",&x); + assert(x<=1000000 && x>=1); + for(int j=0;j<31;j++) A[i][j] = A[i-1][j]+((x&pow[j])?1:0); + } + scanf(""%d"",&M); + assert(M<=10000); + while(M--) + { + answer=0; + scanf(""%d"",&k); + assert(k>=1 && k<=1000000); + x=0; + y=N; + for(int i=0;i<31;i++){ + o=A[y][i]-A[x][i]; + z = (y-x) - o; + ones = z*o; + zeros = (z*(z-1) + o*(o-1))/2; + if((k&pow[i])==0) + answer = (answer + (ll)pow[i]*ones); + else + answer = (answer + (ll)pow[i]*zeros); + } + printf(""%lld\n"",answer%(1000000007)); + + } + return 0; + } +``` +",not-set,2016-04-24T02:02:45,2016-07-23T18:58:34,C++ +98,2565,xor-love,XOR love,"Devendra loves the XOR operation very much which is denoted by $\wedge$ sign in most of the programming languages. He has a list $A$ of $N$ numbers and he wants to know the answers of $M$ queries. Each query will be denoted by three numbers i.e. $K,P,R$ . + +For query $K,P \text{ and } R$, he has to print the value of the $KPRsum$ which can be described as given below. As the value of the $KPRsum$ can be large. So, print it modulus $(10^9 + 7)$. + +$$ KPRsum = \sum_{i=P}^{R-1} \sum_{j=i+1}^{R} (K \oplus (A[i] \oplus A[j]) )$$ + +**Input Format** +The first line contains an integer $N$, i.e., the number of the elements in the list. List is numbered from $1$ to $N$. +Next line will contain $N$ space seperated integers. +Third line will contain a number $M$ i.e. number of queries followed by $M$ lines each containing integers $K,P \& R$. + +**Output Format** +Print $M$ lines, $i^{th}$ line will be answer of $i^{th}$ query. **Answer will be 0 in case of P=R.** + +**Constraints** +$1 \le N \le 10^5$ +$1 \le A[i] \le 10^6$ +$1 \le M \le 10^5$ +$0 \le K \le 10^6$ +$1 \le P \le R \le N$ + +**Sample Input** + + 3 + 1 2 3 + 2 + 1 1 3 + 2 1 3 + + +**Sample Output** + + 5 + 4 + +**Explanation** + +For first query, it will will be $$(1 \oplus( 1 \oplus 2) ) + (1 \oplus( 1 \oplus 3) ) + (1 \oplus( 2 \oplus 3) ) = 5 $$",code,Reply to query related to XOR.,ai,2014-05-30T20:35:04,2022-09-02T09:55:10,,,,"Devendra loves the XOR operation very much which is denoted by $\wedge$ sign in most of the programming languages. He has a list $A$ of $N$ numbers and he wants to know the answers of $M$ queries. Each query will be denoted by three numbers i.e. $K,P,R$ . + +For query $K,P \text{ and } R$, he has to print the value of the $KPRsum$ which can be described as given below. As the value of the $KPRsum$ can be large. So, print it modulus $(10^9 + 7)$. + +$$ KPRsum = \sum_{i=P}^{R-1} \sum_{j=i+1}^{R} (K \oplus (A[i] \oplus A[j]) )$$ + +**Input Format** +The first line contains an integer $N$, i.e., the number of the elements in the list. List is numbered from $1$ to $N$. +Next line will contain $N$ space seperated integers. +Third line will contain a number $M$ i.e. number of queries followed by $M$ lines each containing integers $K,P \& R$. + +**Output Format** +Print $M$ lines, $i^{th}$ line will be answer of $i^{th}$ query. **Answer will be 0 in case of P=R.** + +**Constraints** +$1 \le N \le 10^5$ +$1 \le A[i] \le 10^6$ +$1 \le M \le 10^5$ +$0 \le K \le 10^6$ +$1 \le P \le R \le N$ + +**Sample Input** + + 3 + 1 2 3 + 2 + 1 1 3 + 2 1 3 + + +**Sample Output** + + 5 + 4 + +**Explanation** + +For first query, it will will be $$(1 \oplus( 1 \oplus 2) ) + (1 \oplus( 1 \oplus 3) ) + (1 \oplus( 2 \oplus 3) ) = 5 $$",0.4769230769230769,"[""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,,,,,,,2014-06-26T10:13:36,2016-12-06T09:46:26,tester,"###C++ +```cpp +#ifdef ssu1 +#define _GLIBCXX_DEBUG +#endif +#undef NDEBUG + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define fore(i, l, r) for(int i = (l); i < (r); ++i) +#define forn(i, n) fore(i, 0, n) +#define fori(i, l, r) fore(i, l, (r) + 1) +#define sz(v) int((v).size()) +#define all(v) (v).begin(), (v).end() +#define pb push_back +#define mp make_pair +#define X first +#define Y second + +typedef long long li; +typedef long double ld; +typedef pair pt; + +template T abs(T a) { return a < 0 ? -a : a; } +template T sqr(T a) { return a*a; } + +const int INF = (int)1e9; +const ld EPS = 1e-9; +const ld PI = 3.1415926535897932384626433832795; + +/* + + This is just to check correctness of input + +*/ +int readInt(int l, int r){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int in range [%d, %d], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int in range [%d, %d], but found %d!"", l, r, x); + throw; + } + return x; +} +int readInt(int l, int r, string name){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int %s in range [%d, %d], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int %s in range [%d, %d], but found %d!"", name.c_str(), l, r, x); + throw; + } + return x; +} +li readLong(li l, li r){ + li x; + if(scanf(""%lld"", &x) != 1){ + fprintf(stderr, ""Expected long long in range [%lld, %lld], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected long long in range [%lld, %lld], but found %lld!"", l, r, x); + throw; + } + return x; +} +li readLong(li l, li r, string name){ + li x; + if(scanf(""%lld"", &x) != 1){ + fprintf(stderr, ""Expected long long %s in range [%lld, %lld], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected long long %s in range [%lld, %lld], but found %lld!"", name.c_str(), l, r, x); + throw; + } + return x; +} +const ld __EPS__ = 1e-15; +ld readDouble(double l, double r){ + double x; + if(scanf(""%lf"", &x) != 1){ + fprintf(stderr, ""Expected double in range [%lf, %lf], but haven't found!"", l, r); + throw; + } + if(!(l <= x + __EPS__ && x <= r + __EPS__)){ + fprintf(stderr, ""Expected double in range [%lf, %lf], but found %lf!"", l, r, x); + throw; + } + return x; +} +ld readDouble(double l, double r, string name){ + double x; + if(scanf(""%lf"", &x) != 1){ + fprintf(stderr, ""Expected double %s in range [%lf, %lf], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x + __EPS__ && x <= r + __EPS__)){ + fprintf(stderr, ""Expected double %s in range [%lf, %lf], but found %lf!"", name.c_str(), l, r, x); + throw; + } + return x; +} + +const int LOG = 22; +const int NMAX = 100000; +const int VMAX = 1000000; + +int bit(int v, int i){ + return (v >> i) & 1; +} + +int z[LOG][NMAX], o[LOG][NMAX], n; + +void upd(int t[NMAX], int i, int di){ + for(; i < n; i = (i | (i + 1))) + t[i] += di; +} + +int sum(int t[NMAX], int r){ + int ans = 0; + for(; r >= 0; r = (r & (r + 1)) - 1) + ans += t[r]; + return ans; +} + +int sum(int t[NMAX], int l, int r){ + return sum(t, r) - sum(t, l - 1); +} + +int main(){ +#ifdef ssu1 + assert(freopen(""input.txt"", ""rt"", stdin)); + //assert(freopen(""output.txt"", ""wt"", stdout)); +#endif + n = readInt(1, NMAX, ""n""); + forn(i, n){ + int cur = readInt(1, VMAX, ""a[i]""); + forn(j, LOG){ + if(bit(cur, j)) + upd(o[j], i, 1); + else + upd(z[j], i, 1); + } + } + int m = readInt(1, 100000, ""m""); + forn(mi, m){ + int K, l, r; + K = readInt(0, VMAX); + l = readInt(1, n) - 1; + r = readInt(1, n) - 1; + assert(l <= r); + + li ans = 0; + forn(i, LOG){ + int cnt[2]; + cnt[0] = sum(o[i], l, r); + cnt[1] = sum(z[i], l, r); +// if(i == 0) +// cerr << cnt[0] << "" "" << cnt[1] << endl; + + forn(b1, 2){ + forn(b2, b1 + 1){ + int result = b1 ^ b2 ^ bit(K, i); + if(result == 0) + continue; + li ways = 0; + if(b1 == b2) + ways = (cnt[b1] * 1LL * (cnt[b1] - 1)) / 2; + else + ways = cnt[b1] * 1LL * cnt[b2]; + ans += ways * (1LL << i); + } + } + } + + printf(""%lld\n"", ans % (int(1e9) + 7)); + } + + return 0; +} +``` +",not-set,2016-04-24T02:02:45,2016-07-23T18:58:47,C++ +99,3166,dcbus,Dassu And Business,"Dassu is very disturbed since the brutal murdur of her pet mosquito. As such, she is unable to concentrate on her studies. +So, she decided to step into business.
+ + She had learnt that she had to deal with **2 type of people - Dealers and Customers**. +There are **N dealers** and **M customers**. Also, there are **P types of products**. + +Dealer i provides each item at cost **CPi** and has **Aij** units of j-th item. +Customer i buys each item at **SPi** and requires at the most **Bij** units of j-th item.
+(If a dealer has X items of some type, it is **not necessary** that you purchase all X items. You can purchase any number of items between **0 to X(both inclusive)** . Similiary, if a customer can buy X products of a type, it is **not necessary** to give him exact X products. Rather you can give him any number of items from **0 to X(both inclusive)** to him, **depending upon your profit** .) + +Now she has **R rupees** initially. + She knows that **dealers come in early morning** so as to sell their items as soon as possible. + She also knows that the **customers come in at night** after their office. +

So what is the **maximum profit that she can make today?** Assume dealers gives no loan. +

+###INPUT FORMAT + + The **First Line** of Input will have 4 Integers - **N, M, P** & **R**.
+ The **next line** will have **N** integers, the rate of every dealer (CPi is the rate at which i-th dealer provides all the products).
+ The **next line** will have **M** integers, the Selling Price for every customer(SPi is the rate at which i-th customer buys all the products).
+ The **next N lines** will have **P integers each**. It will represent the matrix **A[][]**.
+ The **next M lines** will have **P integers each**. It will represent the matrix **B[][]**.
+ +###OUTPUT FORMAT + +Output a **Single Integer** corresponding to the **maximum profit** Miss Dassu can make today. + +###CONSTRAINTS + +1<= N,M,P,R <=1000
+0<= Aij, Bij, CPi, SPi <= 1000
+The Sum of all Aij will not exceed 1000
+The Sum of all Bij will not exceed 1000
+ +###EXAMPLE + +**INPUT :** +

+3 2 2 3
+1 2 3
+4 5
+1 2
+1 3
+2 3
+0 2
+3 1
+

+**OUTPUT :** +

+11

+**EXPLANATION** +

Dassu has 3 rupees in the begining. She can buy 1 item1 and 2 item2 from dealer1. The cost will be 1 rupees each, i.e. 3 rupees. She can sell 1 item1 and 1 item2 to customer2 at 5 rupees each, and 1 item2 to customer1 at 4 rupees. So she sells them for 14 rupees, making a profit of 11.",code,Help Dassu make the maximum out of the day.,ai,2014-06-26T10:16:14,2016-09-09T09:47:21,,,,"Dassu is very disturbed since the brutal murdur of her pet mosquito. As such, she is unable to concentrate on her studies. +So, she decided to step into business.
+ + She had learnt that she had to deal with **2 type of people - Dealers and Customers**. +There are **N dealers** and **M customers**. Also, there are **P types of products**. + +Dealer i provides each item at cost **CPi** and has **Aij** units of j-th item. +Customer i buys each item at **SPi** and requires at the most **Bij** units of j-th item.
+(If a dealer has X items of some type, it is **not necessary** that you purchase all X items. You can purchase any number of items between **0 to X(both inclusive)** . Similiary, if a customer can buy X products of a type, it is **not necessary** to give him exact X products. Rather you can give him any number of items from **0 to X(both inclusive)** to him, **depending upon your profit** .) + +Now she has **R rupees** initially. + She knows that **dealers come in early morning** so as to sell their items as soon as possible. + She also knows that the **customers come in at night** after their office. +

So what is the **maximum profit that she can make today?** Assume dealers gives no loan. +

+###INPUT FORMAT + + The **First Line** of Input will have 4 Integers - **N, M, P** & **R**.
+ The **next line** will have **N** integers, the rate of every dealer (CPi is the rate at which i-th dealer provides all the products).
+ The **next line** will have **M** integers, the Selling Price for every customer(SPi is the rate at which i-th customer buys all the products).
+ The **next N lines** will have **P integers each**. It will represent the matrix **A[][]**.
+ The **next M lines** will have **P integers each**. It will represent the matrix **B[][]**.
+ +###OUTPUT FORMAT + +Output a **Single Integer** corresponding to the **maximum profit** Miss Dassu can make today. + +###CONSTRAINTS + +1<= N,M,P,R <=1000
+0<= Aij, Bij, CPi, SPi <= 1000
+The Sum of all Aij will not exceed 1000
+The Sum of all Bij will not exceed 1000
+ +###EXAMPLE + +**INPUT :** +

+3 2 2 3
+1 2 3
+4 5
+1 2
+1 3
+2 3
+0 2
+3 1
+

+**OUTPUT :** +

+11

+**EXPLANATION** +

Dassu has 3 rupees in the begining. She can buy 1 item1 and 2 item2 from dealer1. The cost will be 1 rupees each, i.e. 3 rupees. She can sell 1 item1 and 1 item2 to customer2 at 5 rupees each, and 1 item2 to customer1 at 4 rupees. So she sells them for 14 rupees, making a profit of 11.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""erlang"",""brainfuck"",""javascript"",""go"",""d"",""ocaml"",""pascal"",""sbcl"",""python3"",""groovy"",""objectivec"",""fsharp"",""cobol"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""whitespace"",""tsql"",""cpp14""]",,,,,Hard,,,,,,,2014-06-27T05:17:03,2018-08-14T21:11:55,setter,

[CODE](http://ideone.com/z3TwMM),not-set,2016-04-24T02:02:45,2016-04-24T02:02:45,Unknown +100,3167,prime-not-prime,Prime Not-Prime,"Jigar is trying to solve a math problem and prove to Aghaye Mojri that he is good at math, But it seems this problem is too tough to be solved on paper, So he asks you to calculte the SUM of |p-x| for all prime numbers *p* in range [1, n] and all non prime integers *x* in range [1, n]. As the answer can be very large, print the answer mod (109+9). + +__Input Format__
+The first line contains an integer __T__, the number of test cases. +This is followed by __T__ lines each containing 1 integer __n__. + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 600000 + +__Sample Input__
+
+2
+2
+5
+
+ +__Sample Output__
+
+1
+11
+
+ +__Explanation__
+ +The primes in the range [1, 2] ( both included ) are just [2] and the non primes in the range [1, 2] ( both included ) are just [1]. So, + +we get + + |2 - 1| = 1 + +The primes in the range [1, 5] are [2, 3, 5] and the non-primes are [1, 4]. So, + +we get + + |2-1|+|2-4|+ |3-1|+|3-4| + |5-1|+|5-4| = 1+2 + 2+1 + 4+1 = 11 +",code,Can you figure out the sum of differences of every prime with every composite number within a range?,ai,2014-06-27T07:09:16,2016-09-09T09:47:21,,,,"Jigar is trying to solve a math problem and prove to Aghaye Mojri that he is good at math, But it seems this problem is too tough to be solved on paper, So he asks you to calculte the SUM of |p-x| for all prime numbers *p* in range [1, n] and all non prime integers *x* in range [1, n]. As the answer can be very large, print the answer mod (109+9). + +__Input Format__
+The first line contains an integer __T__, the number of test cases. +This is followed by __T__ lines each containing 1 integer __n__. + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 600000 + +__Sample Input__
+
+2
+2
+5
+
+ +__Sample Output__
+
+1
+11
+
+ +__Explanation__
+ +The primes in the range [1, 2] ( both included ) are just [2] and the non primes in the range [1, 2] ( both included ) are just [1]. So, + +we get + + |2 - 1| = 1 + +The primes in the range [1, 5] are [2, 3, 5] and the non-primes are [1, 4]. So, + +we get + + |2-1|+|2-4|+ |3-1|+|3-4| + |5-1|+|5-4| = 1+2 + 2+1 + 4+1 = 11 +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""visualbasic"",""java8"",""cpp14""]",,,,,Hard,,,,,,,2014-06-27T07:12:06,2016-12-03T04:02:42,setter," #include + #include + #include + #include + using namespace std; + + typedef long long ll; + const ll MOD = 1000000009; + const ll N = 600000+10; + bool mark[N]; + + int main() + { + memset(mark, 0, sizeof mark); + mark[0] = mark[1] = true; + for(ll i = 2; i*i < N; i ++) + if(mark[i] == false) // i is prime + for(ll j = i*i; j < N; j += i) + mark[j] = true; + + ll test, n; + ll allPrime; + ll leftPrime, leftNotPrime; + ll rightPrime, rightNotPrime; + + cin >> test; + while(test --) + { + cin >> n; + allPrime = 0; + for(ll i = 1; i <= n; i ++) + if(mark[i] == false) + allPrime ++; + + leftPrime = 0; + leftNotPrime = 1; + rightPrime = allPrime; + rightNotPrime = n-allPrime-1; + + ll i = 1; + long long res = 0; + while(i < n) + { + res = (res + leftPrime*rightNotPrime) % MOD; + res = (res + leftNotPrime*rightPrime) % MOD; + if(mark[i+1] == false) // i+1 is prime + { + leftPrime ++; + rightPrime --; + } + else + { + leftNotPrime ++; + rightNotPrime --; + } + i ++; + } + cout << res << endl; + } + + return 0; + }",not-set,2016-04-24T02:02:45,2016-04-24T02:02:45,C++ +101,3167,prime-not-prime,Prime Not-Prime,"Jigar is trying to solve a math problem and prove to Aghaye Mojri that he is good at math, But it seems this problem is too tough to be solved on paper, So he asks you to calculte the SUM of |p-x| for all prime numbers *p* in range [1, n] and all non prime integers *x* in range [1, n]. As the answer can be very large, print the answer mod (109+9). + +__Input Format__
+The first line contains an integer __T__, the number of test cases. +This is followed by __T__ lines each containing 1 integer __n__. + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 600000 + +__Sample Input__
+
+2
+2
+5
+
+ +__Sample Output__
+
+1
+11
+
+ +__Explanation__
+ +The primes in the range [1, 2] ( both included ) are just [2] and the non primes in the range [1, 2] ( both included ) are just [1]. So, + +we get + + |2 - 1| = 1 + +The primes in the range [1, 5] are [2, 3, 5] and the non-primes are [1, 4]. So, + +we get + + |2-1|+|2-4|+ |3-1|+|3-4| + |5-1|+|5-4| = 1+2 + 2+1 + 4+1 = 11 +",code,Can you figure out the sum of differences of every prime with every composite number within a range?,ai,2014-06-27T07:09:16,2016-09-09T09:47:21,,,,"Jigar is trying to solve a math problem and prove to Aghaye Mojri that he is good at math, But it seems this problem is too tough to be solved on paper, So he asks you to calculte the SUM of |p-x| for all prime numbers *p* in range [1, n] and all non prime integers *x* in range [1, n]. As the answer can be very large, print the answer mod (109+9). + +__Input Format__
+The first line contains an integer __T__, the number of test cases. +This is followed by __T__ lines each containing 1 integer __n__. + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 600000 + +__Sample Input__
+
+2
+2
+5
+
+ +__Sample Output__
+
+1
+11
+
+ +__Explanation__
+ +The primes in the range [1, 2] ( both included ) are just [2] and the non primes in the range [1, 2] ( both included ) are just [1]. So, + +we get + + |2 - 1| = 1 + +The primes in the range [1, 5] are [2, 3, 5] and the non-primes are [1, 4]. So, + +we get + + |2-1|+|2-4|+ |3-1|+|3-4| + |5-1|+|5-4| = 1+2 + 2+1 + 4+1 = 11 +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""visualbasic"",""java8"",""cpp14""]",,,,,Hard,,,,,,,2014-06-27T07:12:06,2016-12-03T04:02:42,tester," #include + + using namespace std; + + vector prime; + vector minFactor; + vector isp; + vector non_prime; + vector dp; + vector sum_prime; + vector sum_non_prime; + + #define MAX 6e5 + #define MOD 1000000009 + + void generatePrime(int n = MAX) { + isp.resize(n + 1, 1), isp[0] = isp[1] = 0; + minFactor.resize(n + 1); + for(int i = 1; i <= n; i++) minFactor[i] = i; + for(int i = 2; i <= n; i++) { + if(!isp[i]) continue; + prime.push_back(i); + for(int j = i + i; j <= n; j += i) { + isp[j] = 0; + if(minFactor[j] == j) minFactor[j] = i; + } + } + } + + void generateNonPrime(int n = MAX) + { + int iter = 1; + for(auto i = prime.begin(); i != prime.end(); i++) + { + while(iter < *i) + { + non_prime.push_back(iter); + iter += 1; + } + iter = *i + 1; + } + for(int i = prime.back()+1; i <= 10; i++) + non_prime.push_back(i); + } + + void setSumPrimeNonPrime() + { + sum_prime.push_back(prime[0]); + int temp; + for(int i = 1; i < (int)prime.size(); i++) + { + temp = sum_prime[i-1] + prime[i]; + if(temp >= MOD) + temp -= MOD; + sum_prime.push_back(temp); + } + + sum_non_prime.push_back(non_prime[0]); + for(int i = 1; i < (int)non_prime.size(); i++) + { + temp = sum_non_prime[i-1] + non_prime[i]; + if(temp >= MOD) + temp -= MOD; + sum_non_prime.push_back(temp); + } + } + + int main() + { + int t, x, iter = 1, sum = 0; + int sum_prime_iter = 1, sum_non_prime_iter = 0; + + cin >> t; + assert(1 <= t && t <= 20); + generatePrime(); + generateNonPrime(); + setSumPrimeNonPrime(); + + auto prime_iter = prime.begin(); + prime_iter++; + + dp.push_back(0); + dp.push_back(0); + dp.push_back(1); + for(int i = 3; i <= MAX; i++) + { + sum = dp[i-1]; + if(i == *prime_iter) // If it's a prime + { + int a = (int)(((long long)i * (long long)(sum_non_prime_iter+1)) % MOD); + int b = sum_non_prime[sum_non_prime_iter]; + int temp = a - b; + + if(temp < 0) + temp += MOD; + + sum += temp; + + } else // If it's a non-prime + { + int a = (int)(((long long)i * (long long)(sum_prime_iter+1)) % MOD); + int b = sum_prime[sum_prime_iter]; + int temp = a - b; + + if(temp < 0) + temp += MOD; + + sum += temp; + + } + + if(sum >= MOD) + sum -= MOD; + + dp.push_back(sum); + + if(i+1 != *(++prime_iter)) + { + prime_iter--; + sum_non_prime_iter += 1; + } else + sum_prime_iter += 1; + } + + while(t--) + { + cin >> x; + assert(1 <= x && x <= 2e6); + cout << dp[x] << endl; + } + + return 0; + }",not-set,2016-04-24T02:02:45,2016-04-24T02:02:45,C++ +102,2590,boleyn-salary,Boleyn Salary," +Boleyn Su runs a company called Acme. There are _N_ employees in the company, and each one of them is represented by a unique employee id whose range lies in _[1, N]_. Being the head of company, Boleyn's employee id is _1_. +
+Each employee, except Boleyn, has exactly one direct superior. This means that the hierarchial structure of the company is like a tree, where + +1. Boleyn, employee id 1, represents the root node. +2. Each pair of employee is directly or indirectly connected to one another. +3. There is no cycle. + +Let's represent the salary by the array _s = {s[1], s[2], s[3]..., s[N]}_, where _s[i]_ is the salary of the _ith_ employee. Salary structure in the company is non-uniform. Even a subordinate may get a higher salary than her superior. Some of the employees in Acme are curious about who gets the _kth_ lowest salary *among her subordinates*. Help them in solving their query. + +**Note** + +1. _1st_ lowest salary is equivalent to lowest salary, _2nd_ lowest means lowest salary which is greater that _1st_ lowest salary, and so on. +2. Salary of each employee is different. +3. It is not necessary that the people who are placed higher on hierarchy will have a greater salary than their subordinates. + +**Input Format** +The first line contains two space separated integers, _N Q_, where _N_ is the number of employees in Acme, and _Q_ is the number of queries. +Then follows _N-1_ lines. Each of these lines contain two space separated integers, _u p_, where _p_ is the superior of _u_. _u_ and _p_ are employees id. +In the next line there are _N_ space separated integers, _s[1] s[2] ... s[n]_, where _s[i]_, _i ∈ [1..N]_, is the salary of _ith_ employee. +Then, _Q_ queries follow. Each query contains two space separated integers, _v k_. See output format for it's definition. + +**Output format** +For the first query, print the id of employee who has the _kth_ lowest salary among the subordinates of _v_. +For the subsequent queries, we need to find the _kth_ lowest salary of the subordinates of _v+d_, where _d_ is the answer of previous query. + +**Constraints** +1 ≤ _N_ ≤ 3*104 +1 ≤ _Q_ ≤ 3*104 +1 ≤ _s[i]_ ≤ 109, _i_ ∈ _[1..N]_ +_s[i]_ ≠ s[j], 1 ≤ i < j ≤ _N_ +1 ≤ _u, p_ ≤ _N_, _u_ ≠ _p_ +_-N_ ≤ _d_ ≤ _N_ +For _1st_ query, 1 ≤ _v_ ≤ _N_ +For later queries, 1 ≤ _v+d_ ≤ _N_ +For each query, 1 ≤ _K_ ≤ Number_of_subordinates + +**Sample Input** + + 8 7 + 2 1 + 3 2 + 4 2 + 7 4 + 8 4 + 5 1 + 6 5 + 70 40 60 80 10 20 30 50 + 2 1 + -6 5 + -4 1 + -5 3 + 2 1 + -5 4 + 2 2 + +**Sample Output** + + 7 + 8 + 7 + 3 + 6 + 2 + 8 + +**Explanation** +Tree structure will be + + 1(70) + / \ + / \ + 2(40) 5(10) + / \ \ + / \ \ + 3(60) 4(80) 6(20) + / \ + / \ + 7(30) 8(50) + + +*Query #1* `Node = 2`, `k = 1`: Subordinates, in increasing order of salary, are _(7, 30), (8, 50), (3, 60), (4, 80)_. So employee _7_ has the _1st_ lowest salary among the subordinates of _2_. +*Query #2* `Node = -6+7 = 1`, `k = 5`: Subordinates are _(5, 10), (6, 20), (7, 30), (2, 40), (8, 50), (3, 60), (4, 80)_ . _8th_ employee has the _5th_ lowest salary among the subordinate of _1_. +*Query #3* `Node = -4+8 = 4`, `k = 1`: Subordinates are _(7, 30), (8, 50)_ . Similarly 7 is the answer of this query. +*Query #4* `Node = -5+7 = 2`, `k = 3`: Subordinates are _(7, 30), (8, 50), (3, 60), (4, 80)_. Similarly 3 is the answer for this query. +*Query #5* `Node = 2+3 = 5`, `k = 1`: Subordinates are _(6, 20)_. _6th_ employee has the most, and only, lowest salary. +*Query #6* `Node = -5+6 = 1`, `k = 4`: Subordinates are _(5, 10), (6, 20), (7, 30), (2, 40), (8, 50), (3, 60), (4, 80)_. 2 is answer of this query. +*Query #7* `Node = 2+2 = 4`, `k = 2`: Subordinates are _(7, 30), (8, 50)_. Employee _8_ has the second lowest salaries among the subordinates of 4. + +--- +**Tested by:** [scturtle](/scturtle) +",code,K'th lowest salary.,ai,2014-06-10T10:02:53,2016-09-01T16:24:34,,,," +Boleyn Su runs a company called Acme. There are _N_ employees in the company, and each one of them is represented by a unique employee id whose range lies in _[1, N]_. Being the head of company, Boleyn's employee id is _1_. +
+Each employee, except Boleyn, has exactly one direct superior. This means that the hierarchial structure of the company is like a tree, where + +1. Boleyn, employee id 1, represents the root node. +2. Each pair of employee is directly or indirectly connected to one another. +3. There is no cycle. + +Let's represent the salary by the array _s = {s[1], s[2], s[3]..., s[N]}_, where _s[i]_ is the salary of the _ith_ employee. Salary structure in the company is non-uniform. Even a subordinate may get a higher salary than her superior. Some of the employees in Acme are curious about who gets the _kth_ lowest salary *among her subordinates*. Help them in solving their query. + +**Note** + +1. _1st_ lowest salary is equivalent to lowest salary, _2nd_ lowest means lowest salary which is greater that _1st_ lowest salary, and so on. +2. Salary of each employee is different. +3. It is not necessary that the people who are placed higher on hierarchy will have a greater salary than their subordinates. + +**Input Format** +The first line contains two space separated integers, _N Q_, where _N_ is the number of employees in Acme, and _Q_ is the number of queries. +Then follows _N-1_ lines. Each of these lines contain two space separated integers, _u p_, where _p_ is the superior of _u_. _u_ and _p_ are employees id. +In the next line there are _N_ space separated integers, _s[1] s[2] ... s[n]_, where _s[i]_, _i ∈ [1..N]_, is the salary of _ith_ employee. +Then, _Q_ queries follow. Each query contains two space separated integers, _v k_. See output format for it's definition. + +**Output format** +For the first query, print the id of employee who has the _kth_ lowest salary among the subordinates of _v_. +For the subsequent queries, we need to find the _kth_ lowest salary of the subordinates of _v+d_, where _d_ is the answer of previous query. + +**Constraints** +1 ≤ _N_ ≤ 3*104 +1 ≤ _Q_ ≤ 3*104 +1 ≤ _s[i]_ ≤ 109, _i_ ∈ _[1..N]_ +_s[i]_ ≠ s[j], 1 ≤ i < j ≤ _N_ +1 ≤ _u, p_ ≤ _N_, _u_ ≠ _p_ +_-N_ ≤ _d_ ≤ _N_ +For _1st_ query, 1 ≤ _v_ ≤ _N_ +For later queries, 1 ≤ _v+d_ ≤ _N_ +For each query, 1 ≤ _K_ ≤ Number_of_subordinates + +**Sample Input** + + 8 7 + 2 1 + 3 2 + 4 2 + 7 4 + 8 4 + 5 1 + 6 5 + 70 40 60 80 10 20 30 50 + 2 1 + -6 5 + -4 1 + -5 3 + 2 1 + -5 4 + 2 2 + +**Sample Output** + + 7 + 8 + 7 + 3 + 6 + 2 + 8 + +**Explanation** +Tree structure will be + + 1(70) + / \ + / \ + 2(40) 5(10) + / \ \ + / \ \ + 3(60) 4(80) 6(20) + / \ + / \ + 7(30) 8(50) + + +*Query #1* `Node = 2`, `k = 1`: Subordinates, in increasing order of salary, are _(7, 30), (8, 50), (3, 60), (4, 80)_. So employee _7_ has the _1st_ lowest salary among the subordinates of _2_. +*Query #2* `Node = -6+7 = 1`, `k = 5`: Subordinates are _(5, 10), (6, 20), (7, 30), (2, 40), (8, 50), (3, 60), (4, 80)_ . _8th_ employee has the _5th_ lowest salary among the subordinate of _1_. +*Query #3* `Node = -4+8 = 4`, `k = 1`: Subordinates are _(7, 30), (8, 50)_ . Similarly 7 is the answer of this query. +*Query #4* `Node = -5+7 = 2`, `k = 3`: Subordinates are _(7, 30), (8, 50), (3, 60), (4, 80)_. Similarly 3 is the answer for this query. +*Query #5* `Node = 2+3 = 5`, `k = 1`: Subordinates are _(6, 20)_. _6th_ employee has the most, and only, lowest salary. +*Query #6* `Node = -5+6 = 1`, `k = 4`: Subordinates are _(5, 10), (6, 20), (7, 30), (2, 40), (8, 50), (3, 60), (4, 80)_. 2 is answer of this query. +*Query #7* `Node = 2+2 = 4`, `k = 2`: Subordinates are _(7, 30), (8, 50)_. Employee _8_ has the second lowest salaries among the subordinates of 4. + +--- +**Tested by:** [scturtle](/scturtle) +",0.5769230769230769,"[""haskell"",""clojure"",""scala"",""erlang"",""sbcl"",""ocaml"",""fsharp"",""racket"",""elixir""]",,,,,Hard,,,,,,,2014-06-27T11:05:34,2016-05-13T00:01:25,tester," import Control.Monad + import Data.List hiding (insert) + import Data.Graph + import Data.Ord (comparing) + import qualified Data.Array as A + import qualified Data.IntMap as M + + ---- naive AVL BEGIN ---- + + data AVL a = Null | Branch a (AVL a) (AVL a) Int Int -- height size + deriving Show + + height Null = 0 + height (Branch _ _ _ h _) = h + + size Null = 0 + size (Branch _ _ _ _ s) = s + + insert :: (Ord a) => AVL a -> a -> AVL a + insert Null val = Branch val Null Null 1 1 + insert (Branch this lt rt h s) val = + if val < this then balance $ Branch this (insert lt val) rt h (s+1) + else balance $ Branch this lt (insert rt val) h (s+1) + + rol :: AVL a -> AVL a + rol (Branch this lt (Branch val rlt rrt _ _) _ s) = Branch val (Branch this lt rlt (1 + max (height lt) (height rlt)) + (1 + size lt + size rlt)) + rrt + (1 + max (1 + max (height lt) (height rlt)) (height rrt)) s + + ror :: AVL a -> AVL a + ror (Branch this (Branch val llt lrt _ _) rt _ s) = Branch val llt + (Branch this lrt rt (1 + max (height lrt) (height rt)) + (1 + size lrt + size rt)) + (1 + max (height llt) (1 + max (height lrt) (height rt))) s + + balance :: AVL a -> AVL a + balance self@(Branch this lt rt h s) + | height lt - height rt > 1 = case lt of Null -> ror self + (Branch _ llt lrt _ _) -> let lt' = if height llt < height lrt then rol lt else lt + in ror (Branch this lt' rt h s) + | height lt - height rt < -1 = case rt of Null -> rol self + (Branch _ rlt rrt _ _) -> let rt' = if height rlt > height rrt then ror rt else rt + in rol (Branch this lt rt' h s) + | otherwise = Branch this lt rt (1 + max (height lt) (height rt)) s + + select :: AVL a -> Int -> a + select Null k = error ""null"" + select (Branch this lt rt s _) k + | rank == k = this + | rank > k = select lt k + | otherwise = select rt (k - rank) + where rank = size lt + 1 + + ---- naive AVL END ---- + + walk Null = [] + walk (Branch this lt rt _ _) = this : walk lt ++ walk rt + + merge ta tb + | size ta >= size tb = foldl insert ta (walk tb) + | otherwise = merge tb ta + + build :: A.Array Int Int -> Graph -> M.IntMap (AVL (Int, Int)) -> Int -> M.IntMap (AVL (Int, Int)) + build sal g m u = let vs = g A.! u + ut = foldl1 merge $ (foldl insert Null [(sal A.! v, v) | v <- vs]) : [m M.! v | v <- vs] + in M.insert u ut m + + toTwo [] = [] + toTwo (x:y:rs) = (y,x):toTwo rs + + main = do inputs <- getContents >>= return . map (read :: String -> Int) . words + let (n:m:rest) = inputs + (edges,rest') = splitAt (2*(n-1)) rest + edges' = toTwo edges + (salaries, rest'') = splitAt n rest' + queries = toTwo rest'' + + graph = buildG (1, n) edges' + salaries' = A.listArray (1, n) salaries + + build' = build salaries' graph + topOrder = reverse $ topSort graph + trees = M.toAscList $ foldl build' M.empty topOrder + vecs = A.array (1, n) trees + results = tail $ scanl (\n (k, u) -> snd $ select (vecs A.! (n+u)) k) 0 queries + + mapM_ print results +",not-set,2016-04-24T02:02:45,2016-04-24T02:02:45,Python +103,2500,gordons-beverage,Gordon's Beverage,"Mr Gordon likes making beverages. +Mr Gordon is very rich, so he has farm in space. +His farm has sizes *W\*H\*D*. It is divided into sections wich are cubes of size 1*1*1. +There are *N* fields of different fruit trees. +Each field of trees is located in a big cube of size 4*4*4, with top-left-front corner at *(X$_f$,Y$_f$,Z$_f$)*. + +Mr Gordon wonders how many lines of different fruit trees cube with top-left-front corner at *(X$_1$,Y$_1$,Z$_1$)* and bottom-right-back corner at *(X$_2$,Y$_2$,Z$_2$)* contains completely. + +Help him with that. + +####__Input format__ +The first line contains the number of fruit trees lines *N*. +Next *N* lines contains 3 integers each: *X$_{f_i}$,Y$_{f_i}$,Z$_{f_i}$*, coordinates of fruit field's top-left-front corner. +Next line contains number of mr Gordon requests *M*. +Next *M* lines contains 6 integers each: *X$_{1_i}$,Y$_{1_i}$,Z$_{1_i}$,X$_{2_i}$,Y$_{2_i}$,Z$_{2_i}$*, coordinates of two opposite corners of big cube, Mr Gordon request. + +####__Output format__ +*M* lines. +I-th line contains one integer, answer for i-th request. + +####__Constraints__ +1 <= *N*, *M* <= 100000 +0 <= *|X|, |Y|, |Z|* <= 100 +*X$_{1_i}$*<*X$_{2_i}$* +*Y$_{1_i}$*<*Y$_{2_i}$* +*Z$_{1_i}$*<*Z$_{2_i}$* + +####__Input__ + 7 + 4 4 4 + 7 7 7 + 4 7 4 + 7 4 7 + 7 7 4 + 4 4 7 + -4 -4 -4 + 4 + -8 -8 -8 8 8 8 + 0 0 0 7 7 5 + 3 7 3 10 10 10 + 3 2 0 8 8 6 + +####__Output__ + 7 + 3 + 0 + 1",code,Help Gordon to make a beverage.,ai,2014-05-10T02:21:09,2019-07-02T13:58:31,,,,"Mr Gordon likes making beverages. +Mr Gordon is very rich, so he has a farm in space. +His farm is divided into sections wich are cubes of size 1*1*1. +There are *N* fields of different fruit trees. +Each field of trees is located in a big cube of size 4*4*4, with bottom-right-back corner at *(X$_f$,Y$_f$,Z$_f$)*.
+Mr Gordon wonders how many different fruit trees are completely contained in the big cube with top-left-front corner at *(X$_1$,Y$_1$,Z$_1$)* and bottom-right-back corner at *(X$_2$,Y$_2$,Z$_2$)* . + +Help him with that. + +**Input format** +The first line contains the number of fruit trees, *N*. +Next *N* lines contain 3 integers each: *X$_{f_i}$,Y$_{f_i}$,Z$_{f_i}$*, coordinates of fruit field's bottom-right-back corner. +Next line contains number of Mr Gordon requests *M*. +Next *M* lines contains 6 integers each: *X$_{1_i}$,Y$_{1_i}$,Z$_{1_i}$,X$_{2_i}$,Y$_{2_i}$,Z$_{2_i}$*, coordinates of two opposite corners of big cube. + +**Output Format** +You have to print *M* lines where the +I-th line contains one integer, answer for the I-th request. + +**Constraints** +$1 \le N, M \le 10^5$ +$0 \le |X|, |Y|, |Z| \le 100$ +$X_{1_i} < X_{2_i}$ +$Y_{1_i} < Y_{2_i}$ +$Z_{1_i} < Z_{2_i}$ + +**Sample Input** + + 7 + 4 4 4 + 7 7 7 + 4 7 4 + 7 4 7 + 7 7 4 + 4 4 7 + -4 -4 -4 + 4 + -8 -8 -8 8 8 8 + 0 0 0 7 7 5 + 3 7 3 10 10 10 + 3 2 0 8 8 6 + +**Sample Output** + + 7 + 3 + 0 + 1 + +**Explanation** +Here are the top-left-front and bottom-right-back coordinates of all the fruit fields: + + 1. (0, 0, 0) (4, 4, 4) + 2. (3, 3, 3) (7, 7, 7) + 3. (0, 3, 0) (4, 7, 4) + 4. (3, 0, 3) (7, 4, 7) + 5. (3, 3, 0) (7, 7, 4) + 6. (0, 0, 3) (4, 4, 7) + 7. (-8, -8, -8) (-4, -4, -4) + +- For query (-8, -8, -8) (8, 8, 8), all fruit fields are inside it. + +- For query (0, 0, 0) (7, 7, 5), the 1st, 3rd, 5th fruit fields are inside it. + +- For query (3, 7, 3) (10, 10, 10), no field is inside it, because every top-left-front vertex is outside of the query cube. + +- For query (3, 2, 0) (8, 8, 6), the 5th fruit field is inside it. + + ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-27T20:02:46,2016-12-22T00:39:56,setter," #include + using namespace std; + + //N is an array size, choosen such way, that we can store values in indexes starting from 1. + //For values [-100, 100] we'd like to store them as [1, 201]. + //We are leaving 0'th index unused just not to write 'if'`s when initializing. + const int N = 202; + //K is an offset that we'll add to our indexes. + //In our case we need -100 to become 1, so that's 101. + const int K = 101; + + //The value, stored at a[x][y][z] is the number of fields with bottom-right-back corner in a cube with top-left-front corner at (0,0,0) and bottom-right-back corner at(x,y,z). + int a[N][N][N]; + + int main() + { + freopen(""input.txt"",""r"",stdin); + freopen(""output.txt"",""w"",stdout); + int n,m; + scanf(""%d"", &n); + for (;n; --n) + { + int x,y,z; + scanf(""%d%d%d"", &x, &y, &z); + a[x+K][y+K][z+K]++; + + } + //initialization + + for (int i = 1; i < N; ++i) + { + for (int j = 1; j < N; ++j) + { + for (int k = 1; k < N; ++k) + { + //Here we just use the formula we have got from the inclusion-exclusion principle. + a[i][j][k] += a[i-1][j][k] + a[i][j-1][k] + a[i][j][k-1] + - a[i-1][j-1][k] - a[i-1][j][k-1] - a[i][j-1][k-1] + + a[i-1][j-1][k-1]; + } + } + } + + scanf(""%d"", &m); + for (;m; --m) + { + int x1, y1, z1, x2, y2, z2; + scanf(""%d%d%d%d%d%d"", &x1, &y1, &z1, &x2, &y2, &z2); + //Here we are adding our offset to all indexes. + x1 += K, y1 += K, z1 += K, x2 += K, y2 += K, z2 += K; + //Instead of calculating the number of fields of size 4x4x4 which must fit in a cube [(x1,y1,z1),(x2,y2,z2)] + //we just calculate the number of bottom-right-back corners in a cube [(x1+3,y1+3,z1+3),(x2,y2,z2)]. + x1+=3,y1+=3,z1+=3; + + int res = 0; + + if (x1 +using namespace std; + +long long cross_product(long long ax, long long ay, + long long bx, long long by, + long long cx, long long cy) +{ + return (bx - ax) * (cy - ay) - (by - ay) * (cx - ax); +} + +bool inside(long long ax, long long ay, + long long bx, long long by, + long long cx, long long cy) +{ + return (min(ax,bx)<=cx && cx<=max(ax,bx) && + min(ay,by)<=cy && cy<=max(ay,by)); +} + +bool intersect (long long ax, long long ay, + long long bx, long long by, + long long cx, long long cy, + long long dx, long long dy) +{ + long long abc=cross_product(ax, ay, bx, by, cx, cy); + long long abd=cross_product(ax, ay, bx, by, dx, dy); + long long cda=cross_product(cx, cy, dx, dy, ax, ay); + long long cdb=cross_product(cx, cy, dx, dy, bx, by); + + if (((abc>0 && abd<0)||(abc<0 && abd>0)) && + ((cda>0 && cdb<0)||(cda<0 && cdb>0))) + return true; + + if (abc == 0 && inside(ax, ay, bx, by, cx, cy))return true; + if (abd == 0 && inside(ax, ay, bx, by, dx, dy))return true; + if (cda == 0 && inside(cx, cy, dx, dy, ax, ay))return true; + if (cdb == 0 && inside(cx, cy, dx, dy, bx, by))return true; + + return false; +} + +void solve() +{ + long long x, y, ax, ay, bx, by; + cin >> ax >> ay >> bx >> by >> x >> y; + cout << (intersect(0, 0, x, y, ax, ay, bx, by)?""NO\n"":""YES\n""); +} + +int main() +{ + int t; + cin >> t; + for (;t;--t) + { + solve(); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:45,2016-07-23T19:07:56,C++ +105,2535,dynamic-summation,Dynamic Summation,"Given a tree of _N_ nodes, where each node is uniquely numbered in between _[1, N]_. Each node also has a value which is initially 0. You need to perform following two operations in the tree. + +1. Update Operation +2. Report Operation + +**Update Operation** + + U r t a b + +Adds ab + (a+1)b + (b+1)a to all nodes in the subtree rooted at `t`, considering that tree is rooted at `r` (see explanation for more details). + +**Report Operation** + + R r t m + +Output the sum of all nodes in the subtree rooted at `t`, considering that tree is rooted at `r`. Output the sum modulo `m` (see explanation for more details). + +**Input Format** + +First line contains _N_, number of nodes in the tree. +Next _N-1_ lines contain two space separated integers _x_ and _y_ which denote that there is an edge between node _x_ and node _y_. +Next line contains _Q_, number of queries to follow. +Next _Q_ lines follow, each line will be either a report operation or an update operation. + +**Output Format** + +For each report query output the answer in a separate line. + +**Constraints** + +1 ≤ _N_ ≤ 100000 +1 ≤ _Q_ ≤ 100000 +1 ≤ _m_ ≤ 101 +1 ≤ _r, t, x, y_ ≤ _N_ +_x_ ≠ _y_ +1 ≤ _a, b_ ≤ 1018 + +**Notes** + +1. There will be at most one edge between a pair of nodes. +2. There will be no loop. +2. Tree will be completely connected. + +**Sample Input** + + 4 + 1 2 + 2 3 + 3 4 + 4 + U 3 2 2 2 + U 2 3 2 2 + R 1 2 8 + R 4 3 9 + +**Sample Output** + + 2 + 3 + +**Explanation** + +Initially Values in each node : [0,0,0,0] +The first query is `U 3 2 2 2`. Here, tree is rooted at 3. It looks like + + 3(0) + / \ + / \ + 2(0) 4(0) + | + | + 1(0) + +For the sub tree rooted at 2 ( nodes 2 and 1 ), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After first update operation, nodes 1, 2, 3, and 4 will have values 22, 22, 0 and 0 respectively. + + 3(0) + / \ + / \ + 2(22) 4(0) + | + | + 1(22) + +The second query is `U 2 3 2 2`. Here, tree is rooted at 2. It looks like + + 2(22) + / \ + / \ + 1(22) 3(0) + | + | + 4(0) + +For the sub tree rooted at 3 (nodes 3 and 4), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After second update operation, nodes 1, 2, 3, and 4 each have values 22,22,22,22 respectively. + + 2(22) + / \ + / \ + 1(22) 3(22) + | + | + 4(22) + + +The first report query is `R 1 2 8` asks for the sum modulo 8 of the subtree rooted at 2, when the tree is rooted at 1. The tree looks like + + 1(22) + \ + \ + 2*(22) + | + | + 3*(22) + | + | + 4*(22) + +The sum of the values of nodes 2, 3 and 4 are + + (22 + 22 + 22) % 8 = 2 + +The second report query is `R 4 3 9` asks for the sum modulo 9 of the subtree rooted at 3 when the tree is rooted at 4. The tree looks like + + 4(22) + \ + \ + 3*(22) + | + | + 2*(22) + | + | + 1*(22) + +The sum of the values of nodes 3, 2 and 1 are + + (22 + 22 + 22) % 9 = 3 + +**Time Limits:** +C, C++: 4s | Java and other JVM based languages: 10s | Python, Python3 = 45s | Other interpreted Language: 30s | C#, Haskell: 10s | Rest: 3 times of [default](https://www.hackerrank.com/environment). +",code,"Given a tree, perform two kinds of queries. Add a given value to all nodes in a subtree and print the sum of all the values in a given subtree",ai,2014-05-17T19:05:11,2022-08-31T08:33:19,,,,"Given a tree of _N_ nodes, where each node is uniquely numbered in between _[1, N]_. Each node also has a value which is initially 0. You need to perform following two operations in the tree. + +1. Update Operation +2. Report Operation + +**Update Operation** + + U r t a b + +Adds ab + (a+1)b + (b+1)a to all nodes in the subtree rooted at `t`, considering that tree is rooted at `r` (see explanation for more details). + +**Report Operation** + + R r t m + +Output the sum of all nodes in the subtree rooted at `t`, considering that tree is rooted at `r`. Output the sum modulo `m` (see explanation for more details). + +**Input Format** + +First line contains _N_, number of nodes in the tree. +Next _N-1_ lines contain two space separated integers _x_ and _y_ which denote that there is an edge between node _x_ and node _y_. +Next line contains _Q_, number of queries to follow. +Next _Q_ lines follow, each line will be either a report operation or an update operation. + +**Output Format** + +For each report query output the answer in a separate line. + +**Constraints** + +1 ≤ _N_ ≤ 100000 +1 ≤ _Q_ ≤ 100000 +1 ≤ _m_ ≤ 101 +1 ≤ _r, t, x, y_ ≤ _N_ +_x_ ≠ _y_ +1 ≤ _a, b_ ≤ 1018 + +**Notes** + +1. There will be at most one edge between a pair of nodes. +2. There will be no loop. +2. Tree will be completely connected. + +**Sample Input** + + 4 + 1 2 + 2 3 + 3 4 + 4 + U 3 2 2 2 + U 2 3 2 2 + R 1 2 8 + R 4 3 9 + +**Sample Output** + + 2 + 3 + +**Explanation** + +Initially Values in each node : [0,0,0,0] +The first query is `U 3 2 2 2`. Here, tree is rooted at 3. It looks like + + 3(0) + / \ + / \ + 2(0) 4(0) + | + | + 1(0) + +For the sub tree rooted at 2 ( nodes 2 and 1 ), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After first update operation, nodes 1, 2, 3, and 4 will have values 22, 22, 0 and 0 respectively. + + 3(0) + / \ + / \ + 2(22) 4(0) + | + | + 1(22) + +The second query is `U 2 3 2 2`. Here, tree is rooted at 2. It looks like + + 2(22) + / \ + / \ + 1(22) 3(0) + | + | + 4(0) + +For the sub tree rooted at 3 (nodes 3 and 4), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After second update operation, nodes 1, 2, 3, and 4 each have values 22,22,22,22 respectively. + + 2(22) + / \ + / \ + 1(22) 3(22) + | + | + 4(22) + + +The first report query is `R 1 2 8` asks for the sum modulo 8 of the subtree rooted at 2, when the tree is rooted at 1. The tree looks like + + 1(22) + \ + \ + 2*(22) + | + | + 3*(22) + | + | + 4*(22) + +The sum of the values of nodes 2, 3 and 4 are + + (22 + 22 + 22) % 8 = 2 + +The second report query is `R 4 3 9` asks for the sum modulo 9 of the subtree rooted at 3 when the tree is rooted at 4. The tree looks like + + 4(22) + \ + \ + 3*(22) + | + | + 2*(22) + | + | + 1*(22) + +The sum of the values of nodes 3, 2 and 1 are + + (22 + 22 + 22) % 9 = 3 + +**Time Limits:** +C, C++: 4s | Java and other JVM based languages: 10s | Python, Python3 = 45s | Other interpreted Language: 30s | C#, Haskell: 10s | Rest: 3 times of [default](https://www.hackerrank.com/environment). +",0.4787234042553192,"[""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,,,,,,,2014-06-28T17:37:26,2016-12-02T06:26:04,setter," #include + #include + #include + #include + #include + using namespace std; + #define MaxVal 100004 + #define FOR(i,n) for(int i=0;i<(n);i++) + typedef long long int ll; + ll invcons[5][5]; + int mod[10],num[200]; + ll UPPER = (ll)1000000000*(ll)1000000000; + struct bit{ + int a[10]; + bit operator + (const bit &x) const{ + bit y; + FOR(i,10){ + y.a[i] = (x.a[i] + a[i] ); + if( y.a[i] >=mod[i]) y.a[i]-=mod[i]; + } + return y; + } + }tree[MaxVal]; + ll binpow(ll a,ll g,int m) + { + a = a%m ; + ll ans=1; + while(g){ + if(g&1) ans = (ans*a)%m; + a = (a*a)%m; + g>>=1; + } + return ans; + } + bit read(int index) + { + bit answer; + FOR(i,10) answer.a[i]=0; + while(index!=0){ + answer = answer + tree[index]; + index = index - (index&(-index)); + } + return answer; + } + void update ( bit val , int index ) + { + while ( indexy) return; + bit sending,rsending; + FOR(i,10){ + if( !(i & 1)){ + sending.a[i] = binpow ( a,g , mod[i] ); + sending.a[i] = sending.a[i] + binpow ( g +1, a,mod[i]); + if ( sending.a[i] >= mod[i] ) sending.a[i] -= mod[i]; + sending.a[i] = sending.a[i] + binpow ( a+1 , g,mod[i]); + if ( sending.a[i] >= mod[i] ) sending.a[i] -= mod[i]; + rsending.a[i]= mod[i] - sending.a[i]; + } + else{ + sending.a[i] = ((ll)sending.a[i-1]*(ll)x)%mod[i]; + rsending.a[i] =((ll)rsending.a[i-1]*(ll)(y+1))%mod[i]; + } + } + update(sending,x); + update(rsending,y+1); + } + bit QUERY(int x,int y) + { + bit ans1,ans2 ; + ans2 = read(y); + if(x==1){ + for(int i=0;i<10;i+=2){ + ans2.a[i] =((ll) ans2.a[i] * (ll)(y+1) ) %mod[i]; + } + return ans2; + } + ans1 = read(x-1); + FOR(i,10){ + if( !(i&1) ) ans2.a[i] = ((ll)ans2.a[i]*(ll)(y+1) - (ll)ans1.a[i]*(ll)(x) )%mod[i] ; + else ans2.a[i] = ans2.a[i] - ans1.a[i]; + if(ans2.a[i] < 0 ) ans2.a[i] += mod[i]; + } + return ans2; + } + void constant() + { + mod[0]=mod[1]= 64*81*25*49*11*13; + mod[2]=mod[3]= 17*19*23*29*31*37; + mod[4]=mod[5]= 43*47*53*59*79; + mod[6]=mod[7]= 61*67*71*73*41; + mod[8]=mod[9]= 83*89*97*101; + num[17]=num[19]=num[23]=num[29]=num[31]=num[37]=2; + num[43]=num[47]=num[53]=num[59]=num[79]=4; + num[61]=num[67]=num[71]=num[73]=num[41]=6; + num[83]=num[89]=num[97]=num[101]=8; + } + + /*******************************Graph Part************************************/ + int start[MaxVal],ending[MaxVal],Root[MaxVal][18],parent[MaxVal],depth[MaxVal],store[MaxVal],which,counter; + int N,x,y; + vector graph[MaxVal]; + void init() + { + store[0]=0;store[1]=0;store[2]=1; + int cmp=4; + for(int i=3;i<=100000;i++){ + if(cmp>i) store[i]=store[i-1]; + else{ + store[i]=store[i-1]+1; + cmp<<=1; + } + } + } + void process(int N) + { + memset(Root,-1,sizeof(Root)); + for(int i=1;i<=N;i++) Root[i][0]=parent[i]; + for(int i=1;(1<=0;i--) + if(depth[p]-(1<= depth[q]+1) + p=Root[p][i]; + if(parent[p]!=q) return 1; + which = p; + return 0; + } + void dfs(int r) + { + counter++; + start[r]=counter; + for(vector::iterator it=graph[r].begin();it!=graph[r].end();it++){ + if(parent[r]==*it) continue; + parent[*it]=r; + depth[*it]=depth[r]+1; + dfs(*it); + } + ending[r]=counter; + } + /*******************************graph part endings*************************************/ + + /**************************************CRT Begins*********************************/ + ll inverse(ll a,ll b) //b>a + { + ll Remainder,p0=0,p1=1,pcurr=1,q,m=b; + while(a!=0) + { + Remainder=b%a; + q=b/a; + if(Remainder!=0) + { + pcurr=p0-(p1*q)%m; + if(pcurr<0) + pcurr+=m; + p0=p1; + p1=pcurr; + } + b=a; + a=Remainder; + } + return pcurr; + } + ll CRT(int rem0,int mod0,int rem1,int mod1,int rm) //t is the number of pairs of rem and mod + { + ll ans = rem0,m = mod[2*mod0],m1=mod[2*mod1]; + + ll a = invcons[mod0][mod1]%rm; + ll b = invcons[mod1][mod0]%rm; + ans = (((ans * m1)%rm) *b + ((rem1 * m)%rm) * a) % rm; + return ans; + } + /**************************************CRT ending **********************************/ + int a[] = {2,3,5,7}; + void calculate(bit ans,int m) + { + int s=1; + for(int i=0;i<4;i++){ + while(m%a[i]==0){ + m/=a[i]; + s*=a[i]; + } + if(m<=13){ + s=s*m; + m=1; + break; + } + } + if(m==1){ + //only mod[0] in action + int p = ans.a[0] - ans.a[1]; + if( p < 0 ) p+= mod[0]; + printf(""%d\n"",p%(m*s)); + } + else if (s==1){ + //num[m] + int p = ans.a[num[m]] - ans.a[num[m]+1]; + if( p < 0 ) p+= mod[num[m]]; + printf(""%d\n"",p%(m*s)); + } + else{ + //apply crt + int rem0,rem1; + rem0 = ans.a[0] - ans.a[1]; + rem1 = ans.a[num[m]] - ans.a[num[m]+1]; + if(rem0 <0) rem0+=mod[0]; + if(rem1<0) rem1+=mod[num[m]]; + printf(""%lld\n"",CRT(rem0,0,rem1,num[m]/2,s*m)); + } + } + int main() + { + constant(); + for(int i=0;i<5;i++) for(int j=0;j<5;j++) if(i!=j) invcons[i][j]=inverse(mod[2*i],mod[2*j]); + counter=0; + char c; + int curr,sub,Q,cc; + ll g,g1,a; + bit ans; + scanf(""%d"",&N); + assert(N>=2 && N<=100000); + FOR(i,N-1){ + scanf(""%d%d"",&x,&y); + assert(x>=1 && x<=N); + assert(y>=1 && y<=N); + graph[x].push_back(y); + graph[y].push_back(x); + } + init(); + parent[1]=1; + depth[1]=0; + dfs(1); + process(N); + scanf(""%d"",&Q); + assert(Q>=1 && Q<=100000); + FOR(i,Q){ + scanf("" %c%d%d%lld"",&c,&curr,&sub,&a); + assert(c=='U' || c=='R'); + assert(curr>=1 && curr<=N); + assert(sub>=1 && sub<=N); + cc=lca(curr,sub); + if(c=='U'){ + scanf(""%lld"",&g); + assert(a>=1 && a<=UPPER); + assert(g>=1 && g<=UPPER); + if (curr == sub){ + UPDATE ( a, g, 1, N ); + } + else if(cc) UPDATE ( a, g, start[sub],ending[sub] ); + else{ + UPDATE( a, g, 1, start[which]-1); + UPDATE( a, g, ending[which]+1, N); + } + } + else{ + assert(a>=1 && a<=101); + if(a==1){ + printf(""0\n""); + continue; + } + if ( curr == sub){ + ans=QUERY(1,N); + } + else if(cc){ + ans=QUERY(start[sub],ending[sub]); + } + else{ + ans = QUERY (1, start[which]-1); + ans = ans + QUERY (ending[which]+1, N); + } + calculate(ans,a); + } + } + return 0; + }",not-set,2016-04-24T02:02:45,2016-04-24T02:02:45,C++ +106,2535,dynamic-summation,Dynamic Summation,"Given a tree of _N_ nodes, where each node is uniquely numbered in between _[1, N]_. Each node also has a value which is initially 0. You need to perform following two operations in the tree. + +1. Update Operation +2. Report Operation + +**Update Operation** + + U r t a b + +Adds ab + (a+1)b + (b+1)a to all nodes in the subtree rooted at `t`, considering that tree is rooted at `r` (see explanation for more details). + +**Report Operation** + + R r t m + +Output the sum of all nodes in the subtree rooted at `t`, considering that tree is rooted at `r`. Output the sum modulo `m` (see explanation for more details). + +**Input Format** + +First line contains _N_, number of nodes in the tree. +Next _N-1_ lines contain two space separated integers _x_ and _y_ which denote that there is an edge between node _x_ and node _y_. +Next line contains _Q_, number of queries to follow. +Next _Q_ lines follow, each line will be either a report operation or an update operation. + +**Output Format** + +For each report query output the answer in a separate line. + +**Constraints** + +1 ≤ _N_ ≤ 100000 +1 ≤ _Q_ ≤ 100000 +1 ≤ _m_ ≤ 101 +1 ≤ _r, t, x, y_ ≤ _N_ +_x_ ≠ _y_ +1 ≤ _a, b_ ≤ 1018 + +**Notes** + +1. There will be at most one edge between a pair of nodes. +2. There will be no loop. +2. Tree will be completely connected. + +**Sample Input** + + 4 + 1 2 + 2 3 + 3 4 + 4 + U 3 2 2 2 + U 2 3 2 2 + R 1 2 8 + R 4 3 9 + +**Sample Output** + + 2 + 3 + +**Explanation** + +Initially Values in each node : [0,0,0,0] +The first query is `U 3 2 2 2`. Here, tree is rooted at 3. It looks like + + 3(0) + / \ + / \ + 2(0) 4(0) + | + | + 1(0) + +For the sub tree rooted at 2 ( nodes 2 and 1 ), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After first update operation, nodes 1, 2, 3, and 4 will have values 22, 22, 0 and 0 respectively. + + 3(0) + / \ + / \ + 2(22) 4(0) + | + | + 1(22) + +The second query is `U 2 3 2 2`. Here, tree is rooted at 2. It looks like + + 2(22) + / \ + / \ + 1(22) 3(0) + | + | + 4(0) + +For the sub tree rooted at 3 (nodes 3 and 4), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After second update operation, nodes 1, 2, 3, and 4 each have values 22,22,22,22 respectively. + + 2(22) + / \ + / \ + 1(22) 3(22) + | + | + 4(22) + + +The first report query is `R 1 2 8` asks for the sum modulo 8 of the subtree rooted at 2, when the tree is rooted at 1. The tree looks like + + 1(22) + \ + \ + 2*(22) + | + | + 3*(22) + | + | + 4*(22) + +The sum of the values of nodes 2, 3 and 4 are + + (22 + 22 + 22) % 8 = 2 + +The second report query is `R 4 3 9` asks for the sum modulo 9 of the subtree rooted at 3 when the tree is rooted at 4. The tree looks like + + 4(22) + \ + \ + 3*(22) + | + | + 2*(22) + | + | + 1*(22) + +The sum of the values of nodes 3, 2 and 1 are + + (22 + 22 + 22) % 9 = 3 + +**Time Limits:** +C, C++: 4s | Java and other JVM based languages: 10s | Python, Python3 = 45s | Other interpreted Language: 30s | C#, Haskell: 10s | Rest: 3 times of [default](https://www.hackerrank.com/environment). +",code,"Given a tree, perform two kinds of queries. Add a given value to all nodes in a subtree and print the sum of all the values in a given subtree",ai,2014-05-17T19:05:11,2022-08-31T08:33:19,,,,"Given a tree of _N_ nodes, where each node is uniquely numbered in between _[1, N]_. Each node also has a value which is initially 0. You need to perform following two operations in the tree. + +1. Update Operation +2. Report Operation + +**Update Operation** + + U r t a b + +Adds ab + (a+1)b + (b+1)a to all nodes in the subtree rooted at `t`, considering that tree is rooted at `r` (see explanation for more details). + +**Report Operation** + + R r t m + +Output the sum of all nodes in the subtree rooted at `t`, considering that tree is rooted at `r`. Output the sum modulo `m` (see explanation for more details). + +**Input Format** + +First line contains _N_, number of nodes in the tree. +Next _N-1_ lines contain two space separated integers _x_ and _y_ which denote that there is an edge between node _x_ and node _y_. +Next line contains _Q_, number of queries to follow. +Next _Q_ lines follow, each line will be either a report operation or an update operation. + +**Output Format** + +For each report query output the answer in a separate line. + +**Constraints** + +1 ≤ _N_ ≤ 100000 +1 ≤ _Q_ ≤ 100000 +1 ≤ _m_ ≤ 101 +1 ≤ _r, t, x, y_ ≤ _N_ +_x_ ≠ _y_ +1 ≤ _a, b_ ≤ 1018 + +**Notes** + +1. There will be at most one edge between a pair of nodes. +2. There will be no loop. +2. Tree will be completely connected. + +**Sample Input** + + 4 + 1 2 + 2 3 + 3 4 + 4 + U 3 2 2 2 + U 2 3 2 2 + R 1 2 8 + R 4 3 9 + +**Sample Output** + + 2 + 3 + +**Explanation** + +Initially Values in each node : [0,0,0,0] +The first query is `U 3 2 2 2`. Here, tree is rooted at 3. It looks like + + 3(0) + / \ + / \ + 2(0) 4(0) + | + | + 1(0) + +For the sub tree rooted at 2 ( nodes 2 and 1 ), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After first update operation, nodes 1, 2, 3, and 4 will have values 22, 22, 0 and 0 respectively. + + 3(0) + / \ + / \ + 2(22) 4(0) + | + | + 1(22) + +The second query is `U 2 3 2 2`. Here, tree is rooted at 2. It looks like + + 2(22) + / \ + / \ + 1(22) 3(0) + | + | + 4(0) + +For the sub tree rooted at 3 (nodes 3 and 4), we add ab + (a+1)b + (b+1)a = 22 + 32 + 32 = 22. After second update operation, nodes 1, 2, 3, and 4 each have values 22,22,22,22 respectively. + + 2(22) + / \ + / \ + 1(22) 3(22) + | + | + 4(22) + + +The first report query is `R 1 2 8` asks for the sum modulo 8 of the subtree rooted at 2, when the tree is rooted at 1. The tree looks like + + 1(22) + \ + \ + 2*(22) + | + | + 3*(22) + | + | + 4*(22) + +The sum of the values of nodes 2, 3 and 4 are + + (22 + 22 + 22) % 8 = 2 + +The second report query is `R 4 3 9` asks for the sum modulo 9 of the subtree rooted at 3 when the tree is rooted at 4. The tree looks like + + 4(22) + \ + \ + 3*(22) + | + | + 2*(22) + | + | + 1*(22) + +The sum of the values of nodes 3, 2 and 1 are + + (22 + 22 + 22) % 9 = 3 + +**Time Limits:** +C, C++: 4s | Java and other JVM based languages: 10s | Python, Python3 = 45s | Other interpreted Language: 30s | C#, Haskell: 10s | Rest: 3 times of [default](https://www.hackerrank.com/environment). +",0.4787234042553192,"[""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,,,,,,,2014-06-28T17:37:26,2016-12-02T06:26:04,tester," #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 vector VI; + typedef vector VL; + typedef vector VPII; + #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 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 ostream& operator<<(ostream &o, pair t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;} + template void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? ""\n"" : ""\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;} + const int inf = 0x3f3f3f3f; + const long long linf = 0x3f3f3f3f3f3f3f3fLL; + const int mod = int(1e9) + 7; + const int N = 111111; + + template + struct segment_tree { + + static const int maxn = 4 * 111111; + T a[maxn], sum[maxn], lazy[maxn]; + int s[maxn], e[maxn]; + int n; + int md; + + #define ls (x << 1) + #define rs (x << 1 | 1) + + void init(T* v, int n, int m) { + this->n = n; + for(int i = 1; i <= n; i++) a[i] = v[i]; + md = m; + build(1, n, 1); + } + + void Up(int x) { + sum[x] = sum[ls] + sum[rs]; + if(sum[x] >= md) sum[x] -= md; + } + + void Down(int x) { + if(lazy[x] == 0) return; + lazy[ls] += lazy[x]; + lazy[rs] += lazy[x]; + sum[ls] = (sum[ls] + (LL) lazy[x] * (e[ls] - s[ls] + 1)) % md; + sum[rs] = (sum[rs] + (LL) lazy[x] * (e[rs] - s[rs] + 1)) % md; + + if(lazy[ls] >= md) lazy[ls] -= md; + if(lazy[rs] >= md) lazy[rs] -= md; + lazy[x] = 0; + } + + void build(int l, int r, int x) { + s[x] = l, e[x] = r; + lazy[x] = 0; + if(l == r) { + sum[x] = a[l]; + return; + } + int m = (l + r) / 2; + build(l, m, ls); + build(m + 1, r, rs); + Up(x); + } + + void modify(int L, int R, T c, int l, int r, int x) { + if(L <= l && r <= R) { + lazy[x] += c; + if(lazy[x] >= md) lazy[x] -= md; + sum[x] = (sum[x] + (LL)(r - l + 1) * c) % md; + return; + } + Down(x); + int m = (l + r) / 2; + if(L <= m) modify(L, R, c, l, m, ls); + if(R > m) modify(L, R, c, m + 1, r, rs); + Up(x); + } + + T getsum(int L, int R, int l, int r, int x) { + if(L <= l && r <= R) return sum[x] % md; + Down(x); + T res = 0; + int m = (l + r) / 2; + if(L <= m) { + res += getsum(L, R, l, m, ls); + if(res >= md) res -= md; + } + if(R > m) { + res += getsum(L, R, m + 1, r, rs); + if(res >= md) res -= md; + } + return res; + } + + inline void add(int L, int R, T c) {return modify(L, R, c, 1, n, 1);} + T getsum(int L, int R) {return getsum(L, R, 1, n, 1);} + }; + + segment_tree sgt[5]; + typedef long long int ll; + ll binpow(ll a,ll g,int m) + { + a = a%m; + ll ans=1; + while(g){ + if(g&1) ans = ((ll)ans*(ll)a)%m; + a = ((ll)a*(ll)a)%m; + g>>=1; + } + return ans; + } + int n, Q; + + vector g[N]; + + int father[N]; + int depth[N]; + int s[N]; + int e[N]; + int cnt; + + void dfs(int u, int dep, int par) { + father[u] = par; + s[u] = ++cnt; + depth[u] = dep; + for(auto v : g[u]) { + if(v == par) continue; + dfs(v, dep + 1, u); + } + e[u] = cnt; + } + + int p[N][21]; + void lca_init() { + for(int i = 1; i <= n; i++) p[i][0] = father[i]; + for(int j = 1; 1 << j < n; j++) + for(int i = 1; i <= n; i++) + if(p[i][j - 1] != -1) p[i][j] = p[p[i][j - 1]][j - 1]; + } + + int lca_up(int u, int m) { + for(int i = 0; i <= 20; i++) if(m & (1 << i)) u = p[u][i]; + return u; + } + + int lca(int a, int b) { + if(depth[a] < depth[b]) swap(a, b); + a = lca_up(a, depth[a] - depth[b]); + if(a == b) return a; + for(int i = 20; i >= 0; i--) if(p[a][i] != p[b][i]) a = p[a][i], b = p[b][i]; + return father[a]; + } + + int exp(int x, int n, int m) { + LL r = 1; + while(n) { + if(n & 1) r = r * x % m; + x = (LL) x * x % m, n >>= 1; + } + return r % m; + } + + int md[5] = {64 * 81 * 25 * 49 * 11 * 13, + 17 * 19 * 23 * 29 * 31 * 37, + 43 * 47 * 53 * 59 * 79, + 61 * 67 * 71 * 73 * 41, + 83 * 89 * 97 * 101 + }; + + int ex[102][102][5]; + int gg[102][5]; + + int extended_euclid(int a, int b, int &x, int &y) { + if(b == 0) {x = 1; y = 0; return a;} + int d = extended_euclid(b, a % b, y, x); + y -= a / b * x; + return d; + } + + int CRT(int w[], int b[], int len) { + int ret = 0, n = 1, x, y; + for(int i = 0; i < len; i++) n *= w[i]; + for(int i = 0; i < len; i++) { + int m = n / w[i] ; + int d = extended_euclid(w[i], m, x, y); + ret = (ret + y * m * b[i]) % n; + } + return (n + ret % n) % n; + } + + int main() { + /*for(int i = 1; i <= 101; i++) + for(int j = 1; j <= 101; j++) + for(int k = 0; k < 5; k++) + ex[i][j][k] = exp(i, j, md[k]);*/ + for(int i = 1; i <= 101; i++) + for(int k = 0; k < 5; k++) + gg[i][k] = __gcd(i, md[k]); + scanf(""%d"",&n); + //assert(1 <= n && n <= 100000); + for(int i = 1; i < n; i++) { + int u, v; + scanf(""%d%d"",&u,&v); + // assert(1 <= u && u <= n); + // assert(1 <= v && u <= n); + g[u].pb(v); + g[v].pb(u); + } + + int d[N] = {}; + for(int i = 0; i < 5; i++) sgt[i].init(d, n, md[i]); + + dfs(1, 0, 0); + + // Is a tree? + //for(int i = 1; i <= n; i++) if(father[i] == 0) assert(i == 1); + + lca_init(); + scanf(""%d"",&Q); + //assert(1 <= Q && Q <= 100000); + + vector ans; + for(int q = 1; q <= Q; q++) { + char op; + int root, sub, m; + ll a,b; + scanf("" %c%d%d"",&op,&root,&sub); + pair A(-1, -1), B(-1, -1); + // linearize + if(lca(root, sub) != sub) { + A = mp(s[sub], e[sub]); + } else if(root == sub) { + A = mp(1, n); + } else { + A = mp(1, n); + int x = depth[root] - depth[sub] - 1; + int u = lca_up(root, x); + B = mp(s[u], e[u]); + } + if(op == 'U') { + scanf(""%lld%lld"",&a,&b); + for(int i = 0; i < 5; i++) { + //int x = ex[a][b][i]; + int x = binpow(a,b,md[i]); + x = x+binpow(b+1,a,md[i]); + if ( x>md[i] ) x-= md[i]; + x = x+binpow(a+1,b,md[i]); + if ( x>md[i] ) x-= md[i]; + sgt[i].add(A.x, A.y, x); + if(B.x != -1) sgt[i].add(B.x, B.y, md[i] - x); + } + } else if(op == 'R') { + scanf(""%d"",&m); + if(m == 1) {ans.pb(0); continue;} + int res = 0; + int mm[5], rm1[5], rm2[5], c = 0; + for(int i = 0; i < 5; i++) { + int g = gg[m][i]; + if(g == 1) continue; + mm[c] = g; + rm1[c] = sgt[i].getsum(A.x, A.y) % g; + if(B.x != -1) rm2[c] = sgt[i].getsum(B.x, B.y) % g; + c++; + } + res = CRT(mm, rm1, c); + if(B.x != -1) res -= CRT(mm, rm2, c); + res = (res % m + m) % m; + ans.pb(res); + } else { + assert(0); + } + } + PV(ALL(ans)); + return 0; + } + +",not-set,2016-04-24T02:02:46,2016-04-24T02:02:46,C++ +107,2141,minimum-average-waiting-time,Minimum Average Waiting Time,"Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. + +Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza, he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=3, Tieu can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9. + +Help Tieu achieve the minimum average waiting time. For the sake of simplicity, just find the integer part of the minimum average waiting time. + +**Input Format** + +* The first line contains an integer N, which is the number of customers. +* In the next N lines, the ith line contains two space separated numbers Ti and Li. Ti is the time when ith customer order a pizza, and Li is the time required to cook that pizza. + +**Output Format** + +* Display the integer part of the minimum average waiting time. + +**Constraints** + +* 1 ≤ N ≤ 105 +* 0 ≤ Ti ≤ 109 +* 1 ≤ Li ≤ 109 + +**Note** + +* The waiting time is calculated as the difference between the time a customer orders pizza (the time at which they enter the shop) and the time she is served. + +* Cook does not know about the future orders. + +**Sample Input #00** + + 3 + 0 3 + 1 9 + 2 6 + +**Sample Output #00** + + 9 + +**Sample Input #01** + + 3 + 0 3 + 1 9 + 2 5 + +**Sample Output #01** + + 8 + +**Explanation #01** + +Let's call the person ordering at time = 0 as *A*, time = 1 as *B* and time = 2 as *C*. By delivering pizza for *A*, *C* and *B* we get the minimum average wait time to be + + (3 + 6 + 16)/3 = 25/3 = 8.33 + +the integer part is `8` and hence the answer. ",code,Calculate the minimum average wait time of a person to receive his/her pizza?,ai,2014-03-15T14:31:33,2022-09-02T10:00:23,"# +# Complete the 'minimumAverage' function below. +# +# The function is expected to return an INTEGER. +# The function accepts 2D_INTEGER_ARRAY customers as parameter. +# + +def minimumAverage(customers): + # 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()) + + customers = [] + + for _ in range(n): + customers.append(list(map(int, input().rstrip().split()))) + + result = minimumAverage(customers) + + fptr.write(str(result) + '\n') + + fptr.close() +","Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. + +Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza, he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=3, Tieu can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9. + +Help Tieu achieve the minimum average waiting time. For the sake of simplicity, just find the integer part of the minimum average waiting time. + +**Input Format** + +* The first line contains an integer N, which is the number of customers. +* In the next N lines, the ith line contains two space separated numbers Ti and Li. Ti is the time when ith customer order a pizza, and Li is the time required to cook that pizza. + +- The $i^{th}$ customer is not the customer arriving at the $i^{th}$ arrival time. + +**Output Format** + +* Display the integer part of the minimum average waiting time. + +**Constraints** + +* 1 ≤ N ≤ 105 +* 0 ≤ Ti ≤ 109 +* 1 ≤ Li ≤ 109 + +**Note** + +* The waiting time is calculated as the difference between the time a customer orders pizza (the time at which they enter the shop) and the time she is served. + +* Cook does not know about the future orders. + +**Sample Input #00** + + 3 + 0 3 + 1 9 + 2 6 + +**Sample Output #00** + + 9 + +**Sample Input #01** + + 3 + 0 3 + 1 9 + 2 5 + +**Sample Output #01** + + 8 + +**Explanation #01** + +Let's call the person ordering at time = 0 as *A*, time = 1 as *B* and time = 2 as *C*. By delivering pizza for *A*, *C* and *B* we get the minimum average wait time to be + + (3 + 6 + 16)/3 = 25/3 = 8.33 + +the integer part is `8` and hence the answer. ",0.4182692307692308,"[""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,,,,,,,2014-06-30T16:02:37,2016-12-02T02:59:41,setter," /* + Solution: pick the order that takes shortest time to cook. + */ + #include + #include + #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 order[maxn]; + multiset > available_order; + + bool getChar(char& c) { + return (scanf(""%c"", &c) == 1); + } + + void nextInt(long long& u, char endline, int l, int r) { + int sign = 1; + long long sum = 0; + char c; + assert(getChar(c)); + if (c == '-') sign = -1; + else { + assert('0' <= c && c <= '9'); + sum = (c - '0'); + } + + int cnt = 0; + + for (int i = 1; i <= 15; i++) { + assert(getChar(c)); + if (c == endline) break; + assert('0' <= c && c <= '9'); + sum = sum * 10 + (c - '0'); + cnt ++; + assert(cnt <= 15); + } + + sum = sign * sum; + assert (l <= sum && sum <= r); + u = sum; + } + + void nextInt(int& u, char endline, int l, int r) { + long long tmp; + nextInt(tmp, endline, l, r); + u = tmp; + } + + int main() { + //freopen(""a.in"", ""rb"", stdin); freopen(""a.out"", ""wb"", stdout); + nextInt(n, '\n', 1, 1e5); + for (int i = 0; i < n; i++) { + nextInt(order[i].first, ' ', 0, 1e9); + nextInt(order[i].second, '\n', 1, 1e9); + } + + //sort the orders in the increaseing order of the submit time. + sort(order, order + n); + + //we maintain the available_order set, which stores the submitted order in the increasing order of the time to cook + int pos = 0;//pos is the next order to be considered to be push in available_order + long long current_time = order[0].first; + //the total waiting time may be out of 64bit integer range so we maintain two values average and mod so that total waiting time = average * n + mod. + long long average = 0, mod = 0; + + for (int i = 0; i < n; i++) { + //push all submitted orders into available_order + while (pos < n && order[pos].first <= current_time) { + //note that in available_order, the order is stored in the increasing order of time to cook + available_order.insert(make_pair(order[pos].second, order[pos].first)); + pos++; + } + + //take out the order that has a shortest time to cook + pair item = *available_order.begin(); + + available_order.erase(available_order.begin()); + + //update current_time, average and mod + current_time += item.first; + //this is the waiting_time of the current order + long long waiting_time = current_time - item.second; + + mod += waiting_time % n; + average += waiting_time / n; + + if (mod >= n) { + average += mod / n; + mod %= n; + } + } + + cout << average << endl; + char __c; + assert(!getChar(__c)); + return 0; + }",not-set,2016-04-24T02:02:46,2016-04-24T02:02:46,C++ +108,2141,minimum-average-waiting-time,Minimum Average Waiting Time,"Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. + +Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza, he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=3, Tieu can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9. + +Help Tieu achieve the minimum average waiting time. For the sake of simplicity, just find the integer part of the minimum average waiting time. + +**Input Format** + +* The first line contains an integer N, which is the number of customers. +* In the next N lines, the ith line contains two space separated numbers Ti and Li. Ti is the time when ith customer order a pizza, and Li is the time required to cook that pizza. + +**Output Format** + +* Display the integer part of the minimum average waiting time. + +**Constraints** + +* 1 ≤ N ≤ 105 +* 0 ≤ Ti ≤ 109 +* 1 ≤ Li ≤ 109 + +**Note** + +* The waiting time is calculated as the difference between the time a customer orders pizza (the time at which they enter the shop) and the time she is served. + +* Cook does not know about the future orders. + +**Sample Input #00** + + 3 + 0 3 + 1 9 + 2 6 + +**Sample Output #00** + + 9 + +**Sample Input #01** + + 3 + 0 3 + 1 9 + 2 5 + +**Sample Output #01** + + 8 + +**Explanation #01** + +Let's call the person ordering at time = 0 as *A*, time = 1 as *B* and time = 2 as *C*. By delivering pizza for *A*, *C* and *B* we get the minimum average wait time to be + + (3 + 6 + 16)/3 = 25/3 = 8.33 + +the integer part is `8` and hence the answer. ",code,Calculate the minimum average wait time of a person to receive his/her pizza?,ai,2014-03-15T14:31:33,2022-09-02T10:00:23,"# +# Complete the 'minimumAverage' function below. +# +# The function is expected to return an INTEGER. +# The function accepts 2D_INTEGER_ARRAY customers as parameter. +# + +def minimumAverage(customers): + # 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()) + + customers = [] + + for _ in range(n): + customers.append(list(map(int, input().rstrip().split()))) + + result = minimumAverage(customers) + + fptr.write(str(result) + '\n') + + fptr.close() +","Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. + +Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza, he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=3, Tieu can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9. + +Help Tieu achieve the minimum average waiting time. For the sake of simplicity, just find the integer part of the minimum average waiting time. + +**Input Format** + +* The first line contains an integer N, which is the number of customers. +* In the next N lines, the ith line contains two space separated numbers Ti and Li. Ti is the time when ith customer order a pizza, and Li is the time required to cook that pizza. + +- The $i^{th}$ customer is not the customer arriving at the $i^{th}$ arrival time. + +**Output Format** + +* Display the integer part of the minimum average waiting time. + +**Constraints** + +* 1 ≤ N ≤ 105 +* 0 ≤ Ti ≤ 109 +* 1 ≤ Li ≤ 109 + +**Note** + +* The waiting time is calculated as the difference between the time a customer orders pizza (the time at which they enter the shop) and the time she is served. + +* Cook does not know about the future orders. + +**Sample Input #00** + + 3 + 0 3 + 1 9 + 2 6 + +**Sample Output #00** + + 9 + +**Sample Input #01** + + 3 + 0 3 + 1 9 + 2 5 + +**Sample Output #01** + + 8 + +**Explanation #01** + +Let's call the person ordering at time = 0 as *A*, time = 1 as *B* and time = 2 as *C*. By delivering pizza for *A*, *C* and *B* we get the minimum average wait time to be + + (3 + 6 + 16)/3 = 25/3 = 8.33 + +the integer part is `8` and hence the answer. ",0.4182692307692308,"[""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,,,,,,,2014-06-30T16:02:37,2016-12-02T02:59:41,tester," #include + #define assn(n,a,b) assert(n>=a && n<=b) + #define F first + #define S second + #define mp make_pair + using namespace std; + int main() + { + int n,i; + vector < pair < int, int > > ar; + long long cur=0,ans=0; + cin >> n; + ar.resize(n); + assn(n,1,1e5); + for(i=0; i> ar[i].F >> ar[i].S; + assn(ar[i].F, 0, 1e9); + assn(ar[i].S, 1, 1e9); + } + + sort(ar.begin(),ar.end()); + priority_queue< pair < int, int > , vector< pair < int, int> >, greater< pair < int, int > > > mheap; + i=1; + mheap.push(mp(ar[0].S,ar[0].F)); + cur=ar[0].F; + while(!mheap.empty() || i p = mheap.top(); + mheap.pop(); + cur+=(long long)(p.F); + // printf(""cur:%d cook-time:%d coming-time:%d\n"",cur,p.F,p.S); + ans+=(long long)(cur)-(long long)(p.S); + } + cout << ans/n << endl; + return 0; + } +",not-set,2016-04-24T02:02:46,2016-04-24T02:02:46,C++ +109,3090,all-for-9-9-for-all,All for Nine and Nine for All,"Everyone's favorite noontime show, _Lunchtime Surprise_, launched a new game recently. They called it: _All for Nine and Nine for All_. There would be $N$ boxes, each containing a single digit from `0` to `9`, lined up and the team of nine contestants would have to decide which boxes to open. After opening the boxes, we can read the resulting number from left to right. If this number is positive and can be divided evenly by 9, then they either win that amount of money (in pesos) or 99999 pesos, whichever is lower. However, if the resulting number has leading zeros (i.e. reading the number from left to right results in `00144`), it is considered an invalid number. Hence, the contetants lose in that case. + +After a few episodes, they realized that winning was relatively easy. The researchers needed to revise the rules. In their proposed set of rules, contestants must choose a set of _consecutive boxes_ instead of any set of boxes. All the other original rules apply. + +Now, the researchers needed some kind of report that shows that there are less ways to win using their proposed rules, as compared to the original. They shall give examples of box arrangements and show how many ways one can win using the original set of rules, and how many ways to win using their proposed rules. + +**Input Format** +The first line contains a single integer, which is $N$. +The second line contains a string of length $N$, consisting of digits `0`-`9`, describing a box arrangement. + +**Output Format** +Output exactly two lines. +The first line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the original set of rules. +The second line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the proposed set of rules. + + +**Constraints** +$1 \le N \le 10^6$ + +**Sample Input** + + 5 + 33931 + +**Sample Output** + + 3 + 2 + +**Explanation** +For the original set of rules, there are three ways. + +1. The contestants can open boxes $1$, $2$ and $4$. Reading it from left to right, our contestants go home with 333 pesos! + +2. The contestants can open box $3$ only. Reading it from left to right, our contestants go home with 9 pesos! + +3. The contestants can open boxes $1$, $2$, $3$ and $4$. Reading it from left to right, our contestants go home with 3393 pesos! + +For the second method, there are two ways. These two ways are the cases illustrated as #2 and #3 above.",code,How many ways can you win in this new Lunchtime Surprise game?,ai,2014-06-19T02:14:04,2018-07-05T02:44:52,,,," + +Everyone's favorite noontime show, _Lunchtime Surprise_, launched a new game recently. They called it: _All for Nine and Nine for All_. There would be $N$ boxes, each containing a single digit from `0` to `9`, lined up and the team of nine contestants would have to decide which boxes to open. After opening the boxes, we can read the resulting number from left to right. If this number is positive and can be divided evenly by 9, then they either win that amount of money (in pesos) or 99999 pesos, whichever is lower. However, if the resulting number has leading zeros (e.g. reading the number from left to right results in `00144`), it is considered an invalid number. Hence, the contetants lose in that case. + +After a few episodes, they realized that winning was relatively easy. The researchers needed to revise the rules. In their proposed set of rules, contestants must choose a set of _consecutive boxes_ instead of any set of boxes. All the other original rules apply. + +Now, the researchers needed some kind of report that shows that there are less ways to win using their proposed rules, as compared to the original. They shall give examples of box arrangements and show how many ways one can win using the original set of rules, and how many ways to win using their proposed rules. + +**Input Format** +The first line contains a single integer, which is $N$. +The second line contains a string of length $N$, consisting of digits `0`-`9`, describing a box arrangement. + +**Output Format** +Output exactly two lines. +The first line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the original set of rules. +The second line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the proposed set of rules. + + +**Constraints** +$1 \le N \le 10^6$ + +**Sample Input** + + 5 + 33931 + +**Sample Output** + + 3 + 2 + +**Explanation** +For the original set of rules, there are three ways. + +1. The contestants can open boxes $1$, $2$ and $4$. Reading it from left to right, our contestants go home with 333 pesos! + +2. The contestants can open box $3$ only. Reading it from left to right, our contestants go home with 9 pesos! + +3. The contestants can open boxes $1$, $2$, $3$ and $4$. Reading it from left to right, our contestants go home with 3393 pesos! + +For the second method, there are two ways. These two ways are the cases illustrated as #2 and #3 above.",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-30T17:14:35,2016-12-13T12:55:58,setter," #include + #include + #define ll long long + #define mod 1000000000 + #define alok(n,t) ((t*)malloc((n)*sizeof(t))) + + char S[1111111]; + int *F = alok(9, int); + int *G = alok(9, int); + int *H = alok(9, int); + int *nF = alok(9, int); + int *nG = alok(9, int); + int *nH = alok(9, int); + + int main() { + int N; + scanf(""%d%s"", &N, S); + for (int i = 0; i < N; i++) S[i] -= '0'; + ll ans1 = 0, ans2 = 0; + for (int i = N; i >= 0; i--) { + for (int m = 0; m < 9; m++) { + if (i == N) { + nF[m] = 0; + nG[m] = 0; + nH[m] = 0; + } else { + nF[m] = (F[(m-S[i]+9)%9] + (S[i] % 9 == m)) % mod; + nG[m] = (H[(m-S[i]+9)%9] + (S[i] % 9 == m)) % mod; + nH[m] = (nG[m] + H[m]) % mod; + } + } + int *t; + t = nF; nF = F; F = t; + t = nG; nG = G; G = t; + t = nH; nH = H; H = t; + if (S[i] != 0) { + ans1 = (ans1 + G[0]) % mod; + ans2 = (ans2 + F[0]) % mod; + } + } + printf(""%lld\n%lld\n"", ans1, ans2); + } +",not-set,2016-04-24T02:02:46,2016-04-24T02:02:46,C++ +110,3090,all-for-9-9-for-all,All for Nine and Nine for All,"Everyone's favorite noontime show, _Lunchtime Surprise_, launched a new game recently. They called it: _All for Nine and Nine for All_. There would be $N$ boxes, each containing a single digit from `0` to `9`, lined up and the team of nine contestants would have to decide which boxes to open. After opening the boxes, we can read the resulting number from left to right. If this number is positive and can be divided evenly by 9, then they either win that amount of money (in pesos) or 99999 pesos, whichever is lower. However, if the resulting number has leading zeros (i.e. reading the number from left to right results in `00144`), it is considered an invalid number. Hence, the contetants lose in that case. + +After a few episodes, they realized that winning was relatively easy. The researchers needed to revise the rules. In their proposed set of rules, contestants must choose a set of _consecutive boxes_ instead of any set of boxes. All the other original rules apply. + +Now, the researchers needed some kind of report that shows that there are less ways to win using their proposed rules, as compared to the original. They shall give examples of box arrangements and show how many ways one can win using the original set of rules, and how many ways to win using their proposed rules. + +**Input Format** +The first line contains a single integer, which is $N$. +The second line contains a string of length $N$, consisting of digits `0`-`9`, describing a box arrangement. + +**Output Format** +Output exactly two lines. +The first line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the original set of rules. +The second line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the proposed set of rules. + + +**Constraints** +$1 \le N \le 10^6$ + +**Sample Input** + + 5 + 33931 + +**Sample Output** + + 3 + 2 + +**Explanation** +For the original set of rules, there are three ways. + +1. The contestants can open boxes $1$, $2$ and $4$. Reading it from left to right, our contestants go home with 333 pesos! + +2. The contestants can open box $3$ only. Reading it from left to right, our contestants go home with 9 pesos! + +3. The contestants can open boxes $1$, $2$, $3$ and $4$. Reading it from left to right, our contestants go home with 3393 pesos! + +For the second method, there are two ways. These two ways are the cases illustrated as #2 and #3 above.",code,How many ways can you win in this new Lunchtime Surprise game?,ai,2014-06-19T02:14:04,2018-07-05T02:44:52,,,," + +Everyone's favorite noontime show, _Lunchtime Surprise_, launched a new game recently. They called it: _All for Nine and Nine for All_. There would be $N$ boxes, each containing a single digit from `0` to `9`, lined up and the team of nine contestants would have to decide which boxes to open. After opening the boxes, we can read the resulting number from left to right. If this number is positive and can be divided evenly by 9, then they either win that amount of money (in pesos) or 99999 pesos, whichever is lower. However, if the resulting number has leading zeros (e.g. reading the number from left to right results in `00144`), it is considered an invalid number. Hence, the contetants lose in that case. + +After a few episodes, they realized that winning was relatively easy. The researchers needed to revise the rules. In their proposed set of rules, contestants must choose a set of _consecutive boxes_ instead of any set of boxes. All the other original rules apply. + +Now, the researchers needed some kind of report that shows that there are less ways to win using their proposed rules, as compared to the original. They shall give examples of box arrangements and show how many ways one can win using the original set of rules, and how many ways to win using their proposed rules. + +**Input Format** +The first line contains a single integer, which is $N$. +The second line contains a string of length $N$, consisting of digits `0`-`9`, describing a box arrangement. + +**Output Format** +Output exactly two lines. +The first line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the original set of rules. +The second line should contain an integer indicating the number of ways (modulo $10^9$) one can win using the proposed set of rules. + + +**Constraints** +$1 \le N \le 10^6$ + +**Sample Input** + + 5 + 33931 + +**Sample Output** + + 3 + 2 + +**Explanation** +For the original set of rules, there are three ways. + +1. The contestants can open boxes $1$, $2$ and $4$. Reading it from left to right, our contestants go home with 333 pesos! + +2. The contestants can open box $3$ only. Reading it from left to right, our contestants go home with 9 pesos! + +3. The contestants can open boxes $1$, $2$, $3$ and $4$. Reading it from left to right, our contestants go home with 3393 pesos! + +For the second method, there are two ways. These two ways are the cases illustrated as #2 and #3 above.",0.5,"[""c"",""cpp"",""java"",""python3"",""python"",""cpp14""]", , , , ,Hard,,,,,,,2014-06-30T17:14:35,2016-12-13T12:55:58,tester," #include + #include + #include + #include + #include + + using namespace std; + + const int M = 1000000000; + char s[1000006]; + int dp[2][9]; + + void ad(int &x,int y) { + if ((x += y) >= M) { + x -= M; + } + } + + int f(int x) { + return (x >= 9)?(x - 9):x; + } + + int main() { + int n; + scanf(""%d%s"",&n,s); + assert((n > 0) && (n <= 1000000)); + assert(strlen(s) == n); + int last = 0; + for (int i = 0; i < n; ++i) { + assert(isdigit(s[i])); + + int now = last ^ 1; + memcpy(dp[now],dp[last],sizeof(dp[0])); + for (int j = 0; j < 9; ++j) { + ad(dp[now][f(j + s[i] - '0')], dp[last][j]); + } + if (s[i] != '0') { + ad(dp[now][f(s[i] - '0')], 1); + } + + last ^= 1; + + } + printf(""%d\n"",dp[last][0]); + memset(dp[0],0,sizeof(dp[0])); + last = 0; + int answer = 0; + for (int i = 0; i < n; ++i) { + assert(isdigit(s[i])); + int now = last ^ 1; + memset(dp[now],0,sizeof(dp[0])); + for (int j = 0; j < 9; ++j) { + ad(dp[now][f(j + s[i] - '0')], dp[last][j]); + } + if (s[i] != '0') { + ad(dp[now][f(s[i] - '0')],1); + } + ad(answer, dp[now][0]); + last ^= 1; + + + } + printf(""%d\n"",answer); + + return 0; + }",not-set,2016-04-24T02:02:46,2016-04-24T02:02:46,C++ +111,2534,sherlock-and-probability,Sherlock and Probability,"[Download Pdf version](http://hr-filepicker.s3.amazonaws.com/infinitum-jul14/2534-sherlock-and-probability.pdf) + +Watson gave a string $S$ to Sherlock. It is $N$ characters long and consists of only `1`s and `0`s. Now he asks: Given an integer $K$, I'll pick two indices $i$ and $j$ at random between $1$ and $N$, both inclusive. What's the probability that both $S[i]$ and $S[j]$ are `1` and $|i - j| \le K$? + +**Input Format** +First line contains $T$, the number of testcases. Each testcase consists of $N$(the length of $S$) and $K$ in one line and string in second line. + +**Output Format** +Print the required probability as an irreducible fraction. If required answer is `0`, output `0/1`. + +**Constraints** +$1 \le T \le 10^5$ +$1 \le N \le 10^5$ +$1 \le K \le N$ +$1 \le \text{Sum of N over all testcases in one file} \le 10^5$ + +**Sample input** + + 2 + 4 3 + 1011 + 4 1 + 1011 + +**Sample output** + + 9/16 + 5/16 + +**Explanation** +test1: Out of 16 choices, 9 pairs of $(i,j)$ satisfy our condition. +test2: Out of 16 choices, 5 pairs of $(i,j)$ satisfy our condition. ",code,Help Sherlock in finding the probability.,ai,2014-05-17T18:44:48,2022-09-02T09:55:25,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING. +# The function accepts following parameters: +# 1. INTEGER n +# 2. INTEGER k +# 3. STRING s +# + +def solve(n, k, s): + # 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]) + + s = input() + + result = solve(n, k, s) + + fptr.write(result + '\n') + + fptr.close() +","Watson gave a string $S$ to Sherlock. It is $N$ characters long and consists of only `1`s and `0`s. Now he asks: Given an integer $K$, I'll pick two indices $i$ and $j$ at random between $1$ and $N$, both inclusive. What's the probability that both $S[i]$ and $S[j]$ are `1` and $|i - j| \le K$? + +**Input Format** +First line contains $T$, the number of testcases. Each testcase consists of $N$(the length of $S$) and $K$ in one line and string in second line. + +**Output Format** +Print the required probability as an irreducible fraction. If required answer is `0`, output `0/1`. + +**Constraints** +$1 \le T \le 10^5$ +$1 \le N \le 10^5$ +$1 \le K \le N$ +$1 \le \text{Sum of N over all testcases in one file} \le 10^5$ + +**Sample input** + + 2 + 4 3 + 1011 + 4 1 + 1011 + +**Sample output** + + 9/16 + 5/16 + +**Explanation** +test1: Out of 16 choices, 9 pairs of $(i,j)$ satisfy our condition. + + (1,1), (1,3), (1,4), (3,1), (3,3), (3,4), (4,1), (4,3), (4,4) + +test2: Out of 16 choices, 5 pairs of $(i,j)$ satisfy our condition. + + (1,1), (3,3), (4,4), (4,3), (3,4) ",0.5721649484536082,"[""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,,,,,,,2014-07-01T08:20:40,2016-12-06T00:10:42,setter,"###C++ +```cpp +#include +using namespace std; +#define pb push_back +#define mp make_pair +#define clr(x) x.clear() +#define sz(x) ((int)(x).size()) +#define F first +#define S second +#define REP(i,a,b) for(i=a;i PII; +typedef vector VPII; +typedef vector VI; +typedef vector VVI; +typedef long long LL; +#define MOD 1000000007 +LL mpow(LL a, LL n) +{LL ret=1;LL b=a;while(n) {if(n&1) +ret=(ret*b)%MOD;b=(b*b)%MOD;n>>=1;} +return (LL)ret;} +LL gcd(LL a, LL b) +{ + if(b==0)return a;return gcd(b,a%b); +} +LL pre[100005]={}; +int main() +{ + int t; + cin >> t; + while(t--) + { + string s; + LL n,k,i,j,ans=0; + cin >> n >> k; + cin >> s; + for(i=0; i<=n; i++)pre[i]=0; + for(i=1; i<=n; i++) + { + pre[i]=pre[i-1]; + if(s[i-1]=='1')pre[i]++; + } + for(i=1; i<=n; i++) + { + if(s[i-1]=='0')continue; + ans += pre[min(n,i+k)]-pre[max(0ll,i-k-1)]; + } + LL gc=gcd(ans,n*n); + cout << ans/gc << ""/"" << (n*n)/gc << endl; + } + return 0; +} +``` +",not-set,2016-04-24T02:02:46,2016-07-23T19:13:21,C++ +112,2461,rirb,Random Integers Random Bits,"[Download PDF Version](http://hr-filepicker.s3.amazonaws.com/infinitum-jul14/2461-rirb.pdf) + +Given an integer range [A,B], + +1. What’s the probability to get a 1-bit if we first randomly choose a number x in the range and then randomly choose a bit from x? +2. What’s the expected number of bit 1s if we randomly choose a number x in the range? + +**Input Format** +The first line of input is the number of test cases $T$ +Each test cases is a line contains 2 integers $A$ and $B$ separated by a space. + +**Output Format** +For each test case output a line containing 2 float numbers separated by a space. The first one is the probability and the second one is the expected number. You should output the number accurate to 5 fractional digits.  + + +**Constraints** +$1 \le T \le 200$ +$1 \le A \le B \le 10^{10}$ + +**Sample Input** + + 1 + 2 4 + +**Sample Output** + + 0.61111 1.33333 + +**Explanation** +(10) (11) (100) +(1) So we got a one in $\frac{1}{3} \times \frac{1}{2} + \frac{1}{3} \times \frac{1}{1} + \frac{1}{3} \times \frac{1}{3} = \frac{11}{18}$ +(2) The expected 1 we have is : $1 \times \frac{1}{3} + 2 \times \frac{1}{3} + 1 \times \frac{1}{3} = \frac{4}{3}$ + + +",code,Find the probability and expectation value of the given problem,ai,2014-04-29T09:43:01,2022-09-02T09:55:40,,,,"Given an integer range [A,B], + +1. What’s the probability to get a 1-bit if we first randomly choose a number x in the range and then randomly choose a bit from x? +2. What’s the expected number of bit 1s if we randomly choose a number x in the range? + +**Input Format** +The first line of input is the number of test cases $T$ +Each test cases is a line contains 2 integers $A$ and $B$ separated by a space. + +**Output Format** +For each test case output a line containing 2 float numbers separated by a space. The first one is the probability and the second one is the expected number. You should output the number accurate to 5 fractional digits.  + + +**Constraints** +$1 \le T \le 200$ +$1 \le A \le B \le 10^{10}$ + +**Sample Input** + + 1 + 2 4 + +**Sample Output** + + 0.61111 1.33333 + +**Explanation** +(10) (11) (100) +(1) So we got a one in $\frac{1}{3} \times \frac{1}{2} + \frac{1}{3} \times \frac{1}{1} + \frac{1}{3} \times \frac{1}{3} = \frac{11}{18}$ +(2) The expected 1 we have is : $1 \times \frac{1}{3} + 2 \times \frac{1}{3} + 1 \times \frac{1}{3} = \frac{4}{3}$ + + +",0.4657534246575342,"[""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,,,,,,,2014-07-01T08:47:19,2016-12-29T20:45:07,tester,"###Python 2 +```python +LIM = 1111 +S = [0.0]*LIM # precompute S[n] = sum(0<=k>1, b) << 1 + +def b2(n): + if n == 0: return 0 + return (b2(n>>1) << 1) + (n>>1) + +for cas in xrange(input()): + A, B = map(int, raw_input().strip().split()) + C = B+1. - A + + lA, bA = bit_length(A), bit_sum(A) + lB, bB = bit_length(B+1), bit_sum(B+1) + fA = S[lA] + bA/float(lA) + fB = S[lB] + bB/float(lB) + + print ""%.5f %.5f"" % ( + (fB - fA) / C, + (bB - bA) / C, + ) +``` +",not-set,2016-04-24T02:02:46,2016-07-23T19:17:03,Python +113,2619,maximum-subarray-sum,Maximum Subarray Sum,"You are given an array of size _N_ and another integer _M_.Your target is to maximise the value of sum of subarray modulo M. + +**Input Format** + +First line contains T , number of test cases to follow. +Each test case consits of exactly 2 lines. +First line of each test case contain N M , size of the array and modulo value M. +Second line contains N space separated integers representing the elements of the array. + +**Output Format** + +For every test case output the maximum value asked above. + +**Constraints** + +2 ≤ N ≤ 105 +1 ≤ M ≤ 1014 +1 ≤ elements of the array ≤ 1018 +2 ≤ Sum of N over all test cases ≤ 500000 + +**Sample Input** + + 1 + 5 7 + 3 3 9 9 5 + +**Sample Output** + + 6 + +**Explanation** + +Max Possible Sum taking Modulo 7 is 6 , and we can get 6 by adding first and second element of the array",code,Find the maximal value of any (subarray sum % m) in an array.,ai,2014-06-15T09:19:08,2022-08-31T08:14:21,"# +# Complete the 'maximumSum' function below. +# +# The function is expected to return a LONG_INTEGER. +# The function accepts following parameters: +# 1. LONG_INTEGER_ARRAY a +# 2. LONG_INTEGER m +# + +def maximumSum(a, 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') + + q = int(input().strip()) + + for q_itr in range(q): + first_multiple_input = input().rstrip().split() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + a = list(map(int, input().rstrip().split())) + + result = maximumSum(a, m) + + fptr.write(str(result) + '\n') + + fptr.close() +","We define the following: + +- A *subarray* of array $a$ of length $n$ is a contiguous segment from $a[i]$ through $a[j]$ where $0 \le i \le j \lt n$. +- The *sum* of an array is the sum of its elements. + +Given an $n$ element array of integers, $a$, and an integer, $m$, determine the maximum value of the sum of any of its subarrays modulo $m$. + +**Example** +$a=[1,2,3]$ +$m=2$ + +The following table lists all subarrays and their moduli: + +``` + sum %2 +[1] 1 1 +[2] 2 0 +[3] 3 1 +[1,2] 3 1 +[2,3] 5 1 +[1,2,3] 6 0 +``` +The maximum modulus is $1$. + +**Function Description** + +Complete the *maximumSum* function in the editor below. + +maximumSum has the following parameter(s): + +- *long a[n]:* the array to analyze +- *long m:* the modulo divisor + +**Returns** +- *long:* the maximum (subarray sum modulo $m$) ",0.5,"[""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""]","The first line contains an integer $q$, the number of queries to perform. + +The next $q$ pairs of lines are as follows: + +- The first line contains two space-separated integers $n$ and (long)$m$, the length of $a$ and the modulo divisor. +- The second line contains $n$ space-separated long integers $a[i]$.", ,"
+STDIN		Function
+-----		--------
+1			q = 1
+5 7			a[] size n = 5, m = 7
+3 3 9 9 5
+
", 6,Hard,,,,,,,2014-07-01T08:52:28,2018-06-06T20:37:56,setter,"###C++ +```cpp +#include +using namespace std; + +typedef long long int ll; + +void solve() +{ + ll N,M; + ll x,prefix=0,maxim=0; + cin>>N>>M; + set S; + S.insert(0); + for(int i=1;i<=N;i++){ + cin>>x; + prefix = (prefix + x)%M; + maxim = max(maxim,prefix); + set::iterator it = S.lower_bound(prefix+1); + if( it != S.end() ){ + maxim = max(maxim,prefix - (*it) + M ); + } + S.insert(prefix); + } + cout< +The salary given to the person i follows this formula:
+ + Salary[i] = extra[i] + SUM( Salary[j] ), for any j that i is direct boss of j. + +Each employee has a value related to him/her as the extra salary he/she gets, which is represented as extra[i] for person i.

+As the owner of the company, Baba'ee can swap any two employees in the structure, but he can't change the structure of the company.
+If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees? + +__Input Format__
+The first line contains **T**, the number of testcases. +__T__ testcases follow. Each testcase consists of 3 lines. +The first line contains **n**, and the second line contains __n-1__ space separated integers, the i-th number is the boss of the (i+1)-th person. +The third line of each test case contains __n__ space separated integers, i-th number in this line is extra[i]. +**Use Fast IO.** + +__Output Format__
+For each test case, output the minimum total salary Baba'ee has to pay to the employees? + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 105
+1 ≤ extra[i] ≤ 106
+ +__Sample Input__
+ + 1 + 3 + 1 1 + 7 12 13 + +__Sample Output__
+ + 51 + +__Explanation__ + + In the sample test 1 is boss of 2 and boss of 3. + It is optimal to swap person 1 and person 3.",code,Help Baba'ee save Kahoo company from Bankruptcy. ,ai,2014-07-02T08:53:33,2016-09-09T09:47:30,,,,"Baba'ee dream finally came true and he bought the Kahoo Company. The structure of the company is like a rooted Tree. There is the +general manager as the root, and any worker except general manager has a direct boss. General Manager is represented by 1, all other employees are demonstrated with integers in range [2, n] both inclusive.
+The salary given to the person i follows this formula:
+ + Salary[i] = extra[i] + SUM( Salary[j] ), for any j that i is direct boss of j. + +Each employee has a value related to him/her as the extra salary he/she gets, which is represented as extra[i] for person i.

+As the owner of the company, Baba'ee can swap any two employees in the structure, but he can't change the structure of the company.
+If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees? + +__Input Format__
+The first line contains **T**, the number of testcases. +__T__ testcases follow. Each testcase consists of 3 lines. +The first line contains **n**, and the second line contains __n-1__ space separated integers, the i-th number is the boss of the (i+1)-th person. +The third line of each test case contains __n__ space separated integers, i-th number in this line is extra[i]. +**Use Fast IO.** + +__Output Format__
+For each test case, output the minimum total salary Baba'ee has to pay to the employees? + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 105
+1 ≤ extra[i] ≤ 106
+ +__Sample Input__
+ + 1 + 3 + 1 1 + 7 12 13 + +__Sample Output__
+ + 51 + +__Explanation__ + + In the sample test 1 is boss of 2 and boss of 3. + It is optimal to swap person 1 and person 3.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""visualbasic"",""java8"",""python"",""cpp14""]",,,,,Hard,,,,,,,2014-07-02T09:06:45,2017-01-02T06:15:11,setter," #include + #include + #include + #include + #include + using namespace std; + + typedef long long ll; + const ll N = 100000+10; + + ll extra[N]; + ll depth[N]; + vector adj[N]; + + queue q; + void bfs() + { + depth[0] = 1; + q.push( 0 ); + + int node; + while(!q.empty()) + { + node = q.front(); + q.pop(); + for(int i = 0; i < adj[node].size(); i ++) + { + depth[ adj[node][i] ] = depth[node] + 1; + q.push( adj[node][i] ); + } + } + } + + int main() + { + int test; + int n, par; + + cin >> test; + while(test --) + { + cin >> n; + for(int i = 0; i < n; i ++) + adj[i].clear(); + + for(int i = 1; i < n; i ++) + { + cin >> par; + adj[ par-1 ].push_back( i ); + } + for(int i = 0; i < n; i ++) + cin >> extra[i]; + + bfs(); + + sort(extra, extra+n, greater()); + sort(depth, depth+n); + ll res = 0; + for(int i = 0; i < n; i ++) + res += depth[i] * extra[i]; + cout << res << endl; + } + + return 0; + }",not-set,2016-04-24T02:02:47,2016-04-24T02:02:47,C++ +116,3193,kahoo-company,Kahoo Company,"Baba'ee dream finally came true and he bought the Kahoo Company. The structure of the company is like a rooted Tree. There is the +general manager as the root, and any worker except general manager has a direct boss. General Manager is represented by 1, all other employees are demonstrated with integers in range [2, n] both inclusive.
+The salary given to the person i follows this formula:
+ + Salary[i] = extra[i] + SUM( Salary[j] ), for any j that i is direct boss of j. + +Each employee has a value related to him/her as the extra salary he/she gets, which is represented as extra[i] for person i.

+As the owner of the company, Baba'ee can swap any two employees in the structure, but he can't change the structure of the company.
+If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees? + +__Input Format__
+The first line contains **T**, the number of testcases. +__T__ testcases follow. Each testcase consists of 3 lines. +The first line contains **n**, and the second line contains __n-1__ space separated integers, the i-th number is the boss of the (i+1)-th person. +The third line of each test case contains __n__ space separated integers, i-th number in this line is extra[i]. +**Use Fast IO.** + +__Output Format__
+For each test case, output the minimum total salary Baba'ee has to pay to the employees? + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 105
+1 ≤ extra[i] ≤ 106
+ +__Sample Input__
+ + 1 + 3 + 1 1 + 7 12 13 + +__Sample Output__
+ + 51 + +__Explanation__ + + In the sample test 1 is boss of 2 and boss of 3. + It is optimal to swap person 1 and person 3.",code,Help Baba'ee save Kahoo company from Bankruptcy. ,ai,2014-07-02T08:53:33,2016-09-09T09:47:30,,,,"Baba'ee dream finally came true and he bought the Kahoo Company. The structure of the company is like a rooted Tree. There is the +general manager as the root, and any worker except general manager has a direct boss. General Manager is represented by 1, all other employees are demonstrated with integers in range [2, n] both inclusive.
+The salary given to the person i follows this formula:
+ + Salary[i] = extra[i] + SUM( Salary[j] ), for any j that i is direct boss of j. + +Each employee has a value related to him/her as the extra salary he/she gets, which is represented as extra[i] for person i.

+As the owner of the company, Baba'ee can swap any two employees in the structure, but he can't change the structure of the company.
+If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees? + +__Input Format__
+The first line contains **T**, the number of testcases. +__T__ testcases follow. Each testcase consists of 3 lines. +The first line contains **n**, and the second line contains __n-1__ space separated integers, the i-th number is the boss of the (i+1)-th person. +The third line of each test case contains __n__ space separated integers, i-th number in this line is extra[i]. +**Use Fast IO.** + +__Output Format__
+For each test case, output the minimum total salary Baba'ee has to pay to the employees? + +__Constraints__
+1 ≤ T ≤ 20
+1 ≤ n ≤ 105
+1 ≤ extra[i] ≤ 106
+ +__Sample Input__
+ + 1 + 3 + 1 1 + 7 12 13 + +__Sample Output__
+ + 51 + +__Explanation__ + + In the sample test 1 is boss of 2 and boss of 3. + It is optimal to swap person 1 and person 3.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""visualbasic"",""java8"",""python"",""cpp14""]",,,,,Hard,,,,,,,2014-07-02T09:06:45,2017-01-02T06:15:11,tester," #include + + using namespace std; + + int main() + { + int t, n, temp; + cin >> t; + map parent; + map height; + map height_count; + vector extra; + assert(1 <= t and t <= 20); + while(t--) + { + cin >> n; + parent.clear(); + height.clear(); + height_count.clear(); + extra.resize(n); + height_count[0] = 0; + height_count[1] = 1; + parent[1] = 0; + height[0] = 0; + height[1] = 1; + for(int i = 0; i < n - 1; i++) + { + cin >> temp; + parent[i + 2] = temp; + height[i + 2] = height[temp] + 1; + height_count[height[i + 2]] += 1; + } + + for(int i = 0; i < n; i++) + cin >> extra[i]; + + sort(extra.begin(), extra.end()); + + int h = 1, height_iter; + long long answer = 0; + for(int i = 1; i < height_count.size(); i++) + { + height_iter = height_count[i]; + while(height_iter--) + { + answer = answer + (long long)h * extra.back(); + extra.pop_back(); + } + h += 1; + } + cout << answer << endl; + } + return 0; + }",not-set,2016-04-24T02:02:47,2016-04-24T02:02:47,C++ +117,3200,cutting-paper,Cutting paper,"**Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click [here](https://www.hackerrank.com/auth/create_team/csindia) to register as a team, if you have NOT already registered.** + +Yami is taking a Physics class in her school. She doesn't like Physics and gets bored very fast. As a hyperactive girl, she wants to use this time in a productive manner. So she takes a rectangular sheet of paper and a pair of scissors and decides to cut the paper. While cutting the paper, the following rules are followed + ++ Paper is cut along a line that is parallel to one of the sides of the paper. ++ Paper is cut such that the resultant dimensions are always integers. + +The process stops when all the pieces are squares. What is the *minimum* number of paper pieces cut by Yami such that all are squares? + +**Input Format** +The first line of the input is number T, the number of test cases. +Each test case contains two space separated integers N and M, the dimensions of the sheet. + +**Constraints** +1<=T<=100 +1<=N,M<=100 + +**Output Format** +For each testcase, print in a newline the minimum number of squares that can be cut by Yami. + +**Sample Input** + + 2 + 1 1 + 1 2 + +**Sample Output** + + 1 + 2 + +**Explanation** + ++ For the first testcase, the minimum number of squares that can be cut is just 1 ( the original paper ) ++ For the second testcase, the minimum number of squares that can be cut is 2 ( the paper is cut horizontally along the smaller side in the middle ). +",code,Can you find the minimun value?,ai,2014-07-03T01:36:17,2016-09-09T09:47:33,,,,"**Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click [here](https://www.hackerrank.com/auth/create_team/csindia) to register as a team, if you have NOT already registered.** + +Yami is taking a Physics class in her school. She doesn't like Physics and gets bored very fast. As a hyperactive girl, she wants to use this time in a productive manner. So she takes a rectangular sheet of paper and a pair of scissors and decides to cut the paper. While cutting the paper, the following rules are followed + ++ Paper is cut along a line that is parallel to one of the sides of the paper. ++ Paper is cut such that the resultant dimensions are always integers. + +The process stops when all the pieces are squares. What is the *minimum* number of paper pieces cut by Yami such that all are squares? + +**Input Format** +The first line of the input is number T, the number of test cases. +Each test case contains two space separated integers N and M, the dimensions of the sheet. + +**Constraints** +1<=T<=100 +1<=N,M<=100 + +**Output Format** +For each testcase, print in a newline the minimum number of squares that can be cut by Yami. + +**Sample Input** + + 2 + 1 1 + 1 2 + +**Sample Output** + + 1 + 2 + +**Explanation** + ++ For the first testcase, the minimum number of squares that can be cut is just 1 ( the original paper ) ++ For the second testcase, the minimum number of squares that can be cut is 2 ( the paper is cut horizontally along the smaller side in the middle ). +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-07-03T01:38:40,2017-04-12T09:10:12,setter," + #include< stdio.h > + #include< iostream > + #include< sstream > + #include< string.h> + #include< algorithm> + #include< stdlib.h> + #define maxn 105 + using namespace std; + int dp[maxn][maxn],n,m; + void precalc() + { + memset(dp,1,sz(dp)); + for(int i = 0; i <=100;i++) + dp[i][0] = 0; + for(int i=0; i<=100;i++) + dp[0][i] = 0; + for(int i=1;i<=100;i++) + { + for(int j=1;j<=100;j++) + { + if(i == j) { + dp[i][j] = 1; + }else + { + for(int k = 1;k>tt; + while(tt--) + { + cin>>n>>m; + cout< + + using namespace std; + + int mat[101][101]; + + void solve() + { + mat[0][0] = 0; + mat[0][1] = 0; + mat[1][0] = 0; + + for(int i = 1; i <= 100; i++) + { + mat[i][1] = i; + mat[1][i] = i; + } + for(int i = 2; i <= 100; i++) + { + for(int j = 2; j <= 100; j++) + { + int min = i * j, val; + if(i == j) + { + min = 1; + } + else + { + for(int k = 1; k < i; k++) + { + val = mat[k][j] + mat[i - k][j]; + if(val < min) + min = val; + } + for(int k = 1; k < j; k++) + { + val = mat[i][k] + mat[i][j - k]; + if(val < min) + min = val; + } + } + mat[i][j] = min; + } + } + } + + int main() + { + int n, x, y; + cin >> n; + solve(); + for(int i = 0; i < n; i++) + { + cin >> x >> y; + cout << mat[x][y] << endl; + } + return 0; + }",not-set,2016-04-24T02:02:48,2016-04-24T02:02:48,C++ +119,3215,crazy-country,Crazy country,"

+In some place, there is a country which is formed by N cities connected by N-1 roads. There is just one way in going from one city to the other, it is by using the shortest path. The president is crazy, he continuously changed the country's capital. So the people are getting into trouble. Now the people want your help. They travel a lot, so +they are interested to pass by the closest city to the capital if they travel from one city to other. They always take the shortest path. Currently the capital's city is the number 1. +

+
Input format
+
+The first line of the input contains one integer N (1 ≤ N ≤ 100000)the number of cities. Next N−1 lines describe a road. Each of these lines contains a pair of integers ai, bi (1 ≤ ai,bi ≤ N) specifying the numbers of the cities connected by corresponding road, each road has the same length. The next line has an integer +Q (1 ≤ Q ≤ 100000) representing the number of queries. The Q queries follow on a single line each. There are two type of query: type '1' and type '2' (quotes for clarity only). In the case of a '1' query, it will be in the form '1 X', where X is the new capital elected, (1≤X≤N). In the case of a '2' query, it will be in the form '2 X Y', (1 ≤ X, Y ≤ N), where X and Y are two cities. +
+ +
Output format
+
+For every '2' query output one line containing the closer city to the capital in the path between the two cities provided. +
+ +
Sample input
+
10 +
1 8 +
8 9 +
9 4 +
4 2 +
9 5 +
9 6 +
6 7 +
6 10 +
10 3 +
6 +
1 5 +
2 10 1 +
1 4 +
1 8 +
1 10 +
2 7 10 +
+ +
Sample output
+
9 +
10",code,Can you solve this queries?,ai,2014-07-04T20:45:41,2016-09-09T09:47:40,,,,"

+In some place, there is a country which is formed by N cities connected by N-1 roads. There is just one way in going from one city to the other, it is by using the shortest path. The president is crazy, he continuously changed the country's capital. So the people are getting into trouble. Now the people want your help. They travel a lot, so +they are interested to pass by the closest city to the capital if they travel from one city to other. They always take the shortest path. Currently the capital's city is the number 1. +

+
Input format
+
+The first line of the input contains one integer N (1 ≤ N ≤ 100000)the number of cities. Next N−1 lines describe a road. Each of these lines contains a pair of integers ai, bi (1 ≤ ai,bi ≤ N) specifying the numbers of the cities connected by corresponding road, each road has the same length. The next line has an integer +Q (1 ≤ Q ≤ 100000) representing the number of queries. The Q queries follow on a single line each. There are two type of query: type '1' and type '2' (quotes for clarity only). In the case of a '1' query, it will be in the form '1 X', where X is the new capital elected, (1≤X≤N). In the case of a '2' query, it will be in the form '2 X Y', (1 ≤ X, Y ≤ N), where X and Y are two cities. +
+ +
Output format
+
+For every '2' query output one line containing the closer city to the capital in the path between the two cities provided. +
+ +
Sample input
+
10 +
1 8 +
8 9 +
9 4 +
4 2 +
9 5 +
9 6 +
6 7 +
6 10 +
10 3 +
6 +
1 5 +
2 10 1 +
1 4 +
1 8 +
1 10 +
2 7 10 +
+ +
Sample output
+
9 +
10",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-07-04T20:46:40,2016-05-13T00:00:36,setter,"
+#include 
+#include 
+
+#include 
+#include 
+
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+using namespace std;
+
+struct node {
+	int val;
+	bool rev;
+	node *l, *r, *p;
+
+	node(){}
+
+	node(int val) {
+		this->val = val;
+		l = r = p = NULL;
+	}
+
+	bool root() {
+		return (!p || (p->l != this && p->r != this));
+	}
+
+	void propagate() {
+		if(rev) {
+			rev = 0;
+			swap(l, r);
+			if(l) l->rev ^= 1;
+			if(r) r->rev ^= 1;
+		}
+	}
+};
+
+void zig(node *x) {
+	node *p = x->p;
+	node *q = p->p;
+	if( (p->l = x->r) ) p->l->p = p;
+	x->r = p, p->p = x;
+	if( (x->p = q) ) {
+		if(q->r == p) q->r = x;
+		if(q->l == p) q->l = x;
+	}
+}
+
+void zag(node *x) {
+	node *p = x->p;
+	node *q = p->p;
+	if( (p->r = x->l) ) p->r->p = p;
+	x->l = p, p->p = x;
+	if( (x->p = q) ) {
+		if(q->r == p) q->r = x;
+		if(q->l == p) q->l = x;
+	}
+}
+
+void push_down(node *x) {
+	if(!x->root()) push_down(x->p);
+	x->propagate();
+}
+
+void splay(node *x) {
+	push_down(x);
+	while(!x->root()) {
+		node *p = x->p;
+		if(p->root()) {
+			if(p->l == x) zig(x); else
+				zag(x);
+		} else {
+			node *q = p->p;
+			if(p->l == x) {
+				if(q->l == p) zig(p), zig(x); else
+					zig(x), zag(x);
+			} else {
+				if(q->l == p) zag(x), zig(x); else
+					zag(p), zag(x);
+			}
+		}
+	}
+}
+
+void expose(node *x) {
+	node *r = NULL;
+	for(node *p=x;p;p=p->p) {
+		splay(p);
+		p->r = r;
+		r = p;
+	}
+}
+
+void evert(node *x) {
+	expose(x), splay(x);
+	x->rev ^= 1;
+}
+
+void link(node *x, node *y) {
+	evert(x);
+	x->p = y;
+}
+
+int lca(node *x, node *y) {
+	expose(x);
+	splay(x);
+
+	node *p = y;
+	for(;p;p=p->p) {
+		splay(p);
+		if(!p->p) break;
+	}
+	return p->val;
+}
+
+int op;
+int n, q, a, b;
+node *tree[100005];
+
+int main(){
+	scanf(""%d"", &n);
+	for(int i = 1;i<=n;i++) {
+		tree[i] = new node( i );
+	}
+
+	for(int i = 1;i",not-set,2016-04-24T02:02:48,2016-04-24T02:02:48,C++
+120,3232,sherlock-and-subarray,Sherlock and Subarray,"Watson gives an array $A_{1},A_{2}...A_{N}$ to Sherlock. He asks him to count the number of valid contiguous subarrays.        
+A subarray $A_{i},A_{i+1}...A_{j}$ such that $1 \leq i \leq j \leq N$ is valid if the the largest element of that subarray occurs only once in that subarray.    
+
+**Input**  
+First line contains $T$, the number of testcases. Each testcase contains an integer $N$ in the first line. This is followed by $N$ integers denoting the array $A$ in the second line.      
+
+**Output**   
+For each testcase, print the required answer in one line.    
+
+**Constraints**    
+$1 \leq T \leq 10$     
+$1 \leq N \leq 10^{5}$     
+$1 \leq A_{i} \leq 10^{5}$     
+
+**Sample input**    
+	
+    2
+	3
+    1 2 3
+    4
+    2 2 1 2
+    
+**Sample output**    
+
+	6
+    6
+    
+**Explanation**    
+Let's denote $A_{i},A_{i+1}...A_{j}$ by $S[i,j]$     
+First testcase:   
+All subarrays satisfy.    
+Second testcase:    
+$S[1,1], S[2,2], S[3,3], S[4,4], S[2,3], S[3,4]$ satisfy.",code,Help Sherlock in counting Special type of subarrays.,ai,2014-07-06T14:03:49,2019-07-02T13:58:42,,,,"Watson gives an array $A_{1},A_{2}...A_{N}$ to Sherlock. He asks him to count the number of contiguous subarrays $A_{i},A_{i+1}...A_{j}$ such that $1 \leq i \leq j \leq N$ and the largest element of that subarray occurs only once in that subarray.    
+
+**Input Format**  
+First line contains $T$, the number of testcases.  
+Each testcase contains an integer $N$ in the first line. This is followed by $N$ integers denoting the array $A$ in the second line.      
+
+**Output Format**   
+For each testcase, print the required answer in one line.    
+
+**Constraints**    
+$1 \leq T \leq 10$     
+$1 \leq N \leq 10^{5}$     
+$1 \leq A_{i} \leq 10^{5}$     
+
+**Sample Input**  
+	
+    2
+	3
+    1 2 3
+    4
+    2 2 1 2
+    
+**Sample Output**  
+
+	6
+    6
+    
+**Explanation**  
+Let's denote $A_{i},A_{i+1}...A_{j}$ by $S[i,j]$     
+
+First testcase:   
+All subarrays satisfy.    
+Second testcase:    
+$S[1,1], S[2,2], S[3,3], S[4,4], S[2,3], S[3,4]$ satisfy.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]", , , , ,Hard,,,,,,,2014-07-06T14:03:58,2016-05-13T00:00:34,setter,"    #include
+    using namespace std;
+    #define pb push_back
+    #define mp make_pair
+    #define clr(x) x.clear()
+    #define sz(x) ((int)(x).size())
+    #define F first
+    #define S second
+    #define REP(i,a,b) for(i=a;i PII;
+    typedef vector VPII;
+    typedef vector VI;
+    typedef vector VVI;
+    typedef long long LL;
+    #define INF 1000000007
+    int main()
+    {
+        int n,arr[100009],i,j,k;
+        int prntl[100009],prntr[100009];
+        int t;
+        cin >> t;
+        while(t--)
+        {
+            cin >> n;
+            for(i=0; i> arr[i];
+            prntl[0]=INF;
+            prntr[n-1]=INF;
+            for(i=1; i=arr[i])break;
+                        j=prntl[j];
+                    }
+                    prntl[i]=j;
+                }
+            }
+            for(i=n-2; i>=0; i--)
+            {
+                if(arr[i]<=arr[i+1])prntr[i]=i+1;
+                else
+                {
+                    j=prntr[i+1];
+                    while(1)
+                    {
+                        if(j==INF || arr[j]>=arr[i])break;
+                        j=prntr[j];
+                    }
+                    prntr[i]=j;
+                }
+            }
+            LL ans=0,p,q;
+            for(i=0; ith friend and $P$.    
+
+If $K$'th road connects friend $A$ and friend $B$ you should print distance of chosen point from $A$. Also, print the $max(dist(i))$ for all $1 \leq i \leq N$. If there is more than one solution, print the one in which the point $P$ is closest to $A$.     
+
+Note: 
+
++ Use scanf/printf instead of cin/cout. Large input files.
++ Order of $A$ and $B$ as given in the input must be maintained. If P is at a distance of 8 from $A$ and 2 from $B$, you should print 8 and not 2.  
+
+**Input Format**   
+First line contain $T$, the number of testcases.   
+T testcases follow.  
+First Line of each testcase contains 3 space separated integers $N, M, K$ .  
+Next $M$ lines contain description of the $i$th road : three space separated integers $A, B, C$, where $C$ is the length of road connecting $A$ and $B$.      
+
+**Output Format**   
+For each testcase, print two space separated values in one line. The first value is the distance of $P$ from the point $A$ and the second value is the maximum of all the possible shortest paths between $P$ and all of Savita's and her friends' houses. Round both answers to $5$ decimal digits and print exactly $5$ digits after the decimal point.   
+
+**Constraints**    
+$1 \leq T \leq 10$    
+$2 \leq N, M \leq 10^{5}$    
+$N-1 \leq M \leq N*(N-1)/2$     
+$1 \leq A, B \leq N$     
+$1 \leq C \leq 10^9$    
+$1 \leq K \leq M$    
+
+**Sample Input**    
+
+    2
+    2 1 1
+    1 2 10
+    4 4 1
+	1 2 10
+	2 3 10
+	3 4 1
+	4 1 5
+
+
+**Sample Output**    
+
+    5.00000 5.00000
+    2.00000 8.00000
+
+**Explanation**  
+
+First testcase:  
+As $K$ = 1, they will meet at the point $P$ on the road that connects friend $1$ with friend $2$. If we choose mid point then distance for both of them will be $5$. In any other position the maximum of distance will be more than $5$.
+
+Second testcase:   
+As $K$ = 1, they will meet at a point $P$ on the road connecting friend $1$ and friend $2$. If we choose point at a distance of $2$ from friend $1$:
+Friend $1$ will have to travel distance $2$.    
+Friend $2$ will have to travel distance $8$.    
+Friend $3$ will have to travel distance $8$.   
+Friend $4$ will have to travel distance $7$.   
+So, the maximum will be $8$.   
+In any other position of point choosen, the maximum distance will be more than $8$.   
+
+**Timelimits**
+
+Timelimits for this problem is 2 times the environment limit.  ",code,Savita and Friends are meeting after a long time. Help Savita to organize the meeting.,ai,2014-07-08T10:47:13,2022-08-31T08:14:30,"#
+# Complete the 'solve' function below.
+#
+# The function is expected to return a DOUBLE_ARRAY.
+# The function accepts following parameters:
+#  1. INTEGER n
+#  2. INTEGER k
+#  3. 2D_INTEGER_ARRAY roads
+#
+
+def solve(n, k, roads):
+    # 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])
+
+        k = int(first_multiple_input[2])
+
+        roads = []
+
+        for _ in range(m):
+            roads.append(list(map(int, input().rstrip().split())))
+
+        result = solve(n, k, roads)
+
+        fptr.write(' '.join(map(str, result)))
+        fptr.write('\n')
+
+    fptr.close()
+","After completing her final semester, Savita is back home. She is excited to meet all her friends. Her $N$ friends live in different houses spread across the city.    
+
+There are $M$ roads connecting the houses. The road network formed is connected and does not contain self loops and multiple roads between same pair of houses. Savita and Friends decide to meet.  
+
+Savita wants to choose a point(not necessarily an integer) $P$ on the road numbered $K$, such that, the maximum of $dist(i)$ for all $1 \leq i \leq N$ is minimised,  
+where $dist(i)$ is the shortest distance between the $i$'th friend and $P$.    
+
+If $K$'th road connects friend $A$ and friend $B$ you should print distance of chosen point from $A$. Also, print the $max(dist(i))$ for all $1 \leq i \leq N$. If there is more than one solution, print the one in which the point $P$ is closest to $A$.     
+
+Note: 
+
++ Use scanf/printf instead of cin/cout. Large input files.
++ Order of $A$ and $B$ as given in the input must be maintained. If P is at a distance of 8 from $A$ and 2 from $B$, you should print 8 and not 2.  
+",0.5,"[""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""]","First line contain $T$, the number of testcases.   
+T testcases follow.  
+First Line of each testcase contains 3 space separated integers $N, M, K$ .  
+Next $M$ lines contain description of the $i$th road : three space separated integers $A, B, C$, where $C$ is the length of road connecting $A$ and $B$.      
+","For each testcase, print two space separated values in one line. The first value is the distance of $P$ from the point $A$ and the second value is the maximum of all the possible shortest paths between $P$ and all of Savita's and her friends' houses. Round both answers to $5$ decimal digits and print exactly $5$ digits after the decimal point.   
+","    2
+    2 1 1
+    1 2 10
+    4 4 1
+	1 2 10
+	2 3 10
+	3 4 1
+	4 1 5
+","    5.00000 5.00000
+    2.00000 8.00000
+",Hard,,,,,,,2014-07-08T10:47:24,2016-12-02T16:44:29,tester,"###C++  
+```cpp  
+#include
+using namespace std;
+#define pb push_back
+#define mp make_pair
+#define F first
+#define S second
+typedef long long LL;
+typedef pair< LL , LL> PII;
+typedef vector VPII;
+typedef vector VI;
+const LL INF = 1000000000000000000ll;
+vector edges[100009];
+VI dijk(int N, int s)
+{
+    priority_queue, greater > Q;
+    vector< LL > dist(N, INF), dad(N, -1);
+    Q.push (make_pair (0ll, (LL)s));
+    dist[s] = 0;
+    while (!Q.empty()){
+        PII p = Q.top();
+        Q.pop();
+        LL here = p.second;
+        for (vector::iterator it=edges[here].begin(); it!=edges[here].end(); it++){
+            if (dist[here] + it->first < dist[it->second]){
+                dist[it->second] = dist[here] + it->first;
+                dad[it->second] = here;
+                Q.push (make_pair (dist[it->second], it->second));
+            }
+        }
+    }
+    return dist;
+}
+int main()
+{
+    int t;
+    cin >> t;
+    while(t--)
+    {
+        LL N,M,s,a,b,c,K,s1,s2,l;
+        scanf(""%lld %lld %lld"",&N,&M,&K);
+        for(int i=0; i<100009; i++)
+            edges[i].clear();
+        for(int i=0; i dist1=dijk(N,s1);
+        vector < LL > dist2=dijk(N,s2);
+    /*    for(int i=0; i=0; i--)
+        {
+            if(fin[i].F <= prevx && fin[i].S <= prevy)continue;
+            prevx=fin[i].F;
+            prevy=fin[i].S;
+            w.push_back(fin[i]);
+        }
+        int P=w.size();
+        //    sort(w.begin(),w.end());
+        double ans=min(w[0].F,w[P-1].S),finans;
+        if(w[0].F<=w[P-1].S)finans=0;
+        else finans=l;
+        for(int i=0; i9  
+min(_M, N_) % 2 == 0  
+1 <= _aij_ <= 108, where _i_ ∈ _[1..M]_ & _j_ ∈ _[1..N]_  
+
+**Sample Input #00**
+
+    4 4 1
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #00**
+
+    2 3 4 8
+    1 7 11 12
+    5 6 10 16
+    9 13 14 15
+
+**Sample Input #01**
+
+    4 4 2
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #01**
+
+    3 4 8 12
+    2 11 10 16
+    1 7 6 15
+    5 9 13 14
+
+
+**Sample Input #02**
+
+    5 4 7
+    1 2 3 4
+    7 8 9 10
+    13 14 15 16
+    19 20 21 22
+    25 26 27 28
+
+**Sample Output #02**
+
+    28 27 26 25
+    22 9 15 19
+    16 8 21 13
+    10 14 20 7
+    4 3 2 1
+
+
+
+**Sample Input #03**
+
+    2 2 3
+    1 1
+    1 1
+
+**Sample Output #03**
+
+    1 1
+    1 1
+
+
+**Explanation**  
+*Sample Case #00:* Here is an illustration of what happens when the matrix is rotated once.
+
+     1  2  3  4      2  3  4  8
+     5  6  7  8      1  7 11 12
+     9 10 11 12  ->  5  6 10 16
+    13 14 15 16      9 13 14 15
+
+*Sample Case #01:* Here is what happens when to the matrix after two rotations.
+
+     1  2  3  4      2  3  4  8      3  4  8 12
+     5  6  7  8      1  7 11 12      2 11 10 16
+     9 10 11 12  ->  5  6 10 16  ->  1  7  6 15
+    13 14 15 16      9 13 14 15      5  9 13 14
+
+*Sample Case #02:* Following are the intermediate states.
+
+    1  2  3  4      2  3  4 10    3  4 10 16    4 10 16 22
+    7  8  9 10      1  9 15 16    2 15 21 22    3 21 20 28
+    13 14 15 16 ->  7  8 21 22 -> 1  9 20 28 -> 2 15 14 27 ->
+    19 20 21 22    13 14 20 28    7  8 14 27    1  9  8 26
+    25 26 27 28    19 25 26 27    13 19 25 26   7 13 19 25
+
+
+
+    10 16 22 28    16 22 28 27    22 28 27 26    28 27 26 25
+     4 20 14 27    10 14  8 26    16  8  9 25    22  9 15 19
+     3 21  8 26 ->  4 20  9 25 -> 10 14 15 19 -> 16  8 21 13
+     2 15  9 25     3 21 15 19     4 20 21 13    10 14 20  7
+     1  7 13 19     2  1  7 13     3  2  1  7     4  3  2  1
+
+*Sample Case #03:* As all elements are same, any rotation will reflect the same matrix.
+
+---
+**Tested by:** [Tusshar Singh](/tussharsingh13), [Abhiranjan](/abhiranjan)
+",code,Rotate the elements of the matrix.,ai,2014-05-13T15:51:08,2016-09-01T16:26:21,,,,"[Here](https://www.hackerrank.com/challenges/matrix-rotation-algo) is the non-FP version of this challenge, with all languages enabled.
+
+---
+You are given a 2D  matrix, _a_, of dimension *MxN* and a positive integer _R_. You have to rotate the matrix _R_ times and print the resultant matrix. Rotation should be in anti-clockwise direction.  
+
+Rotation of a _4x5_ matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only (refer sample tests for more clarity).
+
+
+![matrix-rotation](https://hr-challenge-images.s3.amazonaws.com/2517/matrix-rotation.png)
+
+It is guaranteed that the minimum of _M_ and _N_ will be even.  
+
+**Input**  
+First line contains three space separated integers, *M*, *N* and *R*, where _M_ is the number of rows, _N_ is number of columns in matrix, and _R_ is the number of times the matrix has to be rotated.  
+Then *M* lines follow, where each line contains *N* space separated positive integers. These *M* lines  represent the matrix.  
+
+**Output**  
+Print the rotated matrix.
+
+**Constraints**  
+2 <= *M*, *N* <= 300  
+1 <= *R* <= 109  
+min(_M, N_) % 2 == 0  
+1 <= _aij_ <= 108, where _i_ ∈ _[1..M]_ & _j_ ∈ _[1..N]_  
+
+**Sample Input #00**
+
+    4 4 1
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #00**
+
+    2 3 4 8
+    1 7 11 12
+    5 6 10 16
+    9 13 14 15
+
+**Sample Input #01**
+
+    4 4 2
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #01**
+
+    3 4 8 12
+    2 11 10 16
+    1 7 6 15
+    5 9 13 14
+
+
+**Sample Input #02**
+
+    5 4 7
+    1 2 3 4
+    7 8 9 10
+    13 14 15 16
+    19 20 21 22
+    25 26 27 28
+
+**Sample Output #02**
+
+    28 27 26 25
+    22 9 15 19
+    16 8 21 13
+    10 14 20 7
+    4 3 2 1
+
+
+
+**Sample Input #03**
+
+    2 2 3
+    1 1
+    1 1
+
+**Sample Output #03**
+
+    1 1
+    1 1
+
+
+**Explanation**  
+*Sample Case #00:* Here is an illustration of what happens when the matrix is rotated once.
+
+     1  2  3  4      2  3  4  8
+     5  6  7  8      1  7 11 12
+     9 10 11 12  ->  5  6 10 16
+    13 14 15 16      9 13 14 15
+
+*Sample Case #01:* Here is what happens when to the matrix after two rotations.
+
+     1  2  3  4      2  3  4  8      3  4  8 12
+     5  6  7  8      1  7 11 12      2 11 10 16
+     9 10 11 12  ->  5  6 10 16  ->  1  7  6 15
+    13 14 15 16      9 13 14 15      5  9 13 14
+
+*Sample Case #02:* Following are the intermediate states.
+
+    1  2  3  4      2  3  4 10    3  4 10 16    4 10 16 22
+    7  8  9 10      1  9 15 16    2 15 21 22    3 21 20 28
+    13 14 15 16 ->  7  8 21 22 -> 1  9 20 28 -> 2 15 14 27 ->
+    19 20 21 22    13 14 20 28    7  8 14 27    1  9  8 26
+    25 26 27 28    19 25 26 27    13 19 25 26   7 13 19 25
+
+
+
+    10 16 22 28    16 22 28 27    22 28 27 26    28 27 26 25
+     4 20 14 27    10 14  8 26    16  8  9 25    22  9 15 19
+     3 21  8 26 ->  4 20  9 25 -> 10 14 15 19 -> 16  8 21 13
+     2 15  9 25     3 21 15 19     4 20 21 13    10 14 20  7
+     1  7 13 19     2  1  7 13     3  2  1  7     4  3  2  1
+
+*Sample Case #03:* As all elements are same, any rotation will reflect the same matrix.
+
+---
+**Tested by:** [Tusshar Singh](/tussharsingh13), [Abhiranjan](/abhiranjan)
+",0.5,"[""haskell"",""clojure"",""scala"",""erlang"",""sbcl"",""ocaml"",""fsharp"",""racket"",""elixir""]", , , , ,Hard,,,,,,,2014-07-08T12:57:25,2016-12-13T21:51:24,setter,"    import scala.collection.mutable.HashMap;
+
+    object Solution{
+
+        def main(args:Array[String]) = {
+            val in = readLine.split("" "").map(_.toInt);
+            var arr = new Array[Array[Int]](in(0));
+            for(i <- 1 to in(0)) 
+                arr(i-1) = readLine.split("" "").map(_.toInt);
+            println(rotate(arr, in(2)));
+        }
+
+        def rotate(arr:Array[Array[Int]], r:Int):String = {
+            var b = Array.fill(arr.size){ new Array[Int](arr(0).size) };
+            var m = arr.size;
+            var n = arr(0).size;
+            val min = Math.min(m/2, n/2);
+            for(i <- 1 to min){
+                val map = getMap(m, n);
+                val len = map.keys.size;
+                for(j <- map.keys){
+                    val cur = map(j);
+                    val next = map((j+r)%len);
+                    b(next._1 + i-1)(next._2 + i-1) = arr(cur._1 + i-1)(cur._2 + i-1);
+                }
+                m-=2;
+                n-=2;
+            }
+            return b.map(x => x.mkString("" "")).mkString(""\n"");
+        }
+
+        def getMap(m:Int, n:Int):HashMap[Int, Tuple2[Int, Int]] = {
+            var map = new HashMap[Int, Tuple2[Int, Int]]();
+            val len = 2*(m+n-2)-1;
+            for(i <- 0 to len) map += (i -> getLoc(i, m, n));
+            return map;
+        }
+
+        def getLoc(i:Int, m:Int, n:Int):Tuple2[Int, Int] = {
+            if(i < m-1) 
+                return (i, 0);
+            else if(i < m+n-2) 
+                return (m-1, (i - m + 1) % n);
+            else if(i < 2*m + n - 3) 
+                return (2*m + n-3-i, n-1);
+            else 
+                return (0, 2*(m+n-2)-i);
+        }
+    }",not-set,2016-04-24T02:02:49,2016-04-24T02:02:49,Python
+123,2517,matrix-rotation,Matrix Rotation,"You are given a 2D  matrix, _a_, of dimension *MxN* and a positive integer _R_. You have to rotate the matrix _R_ times and print the resultant matrix. Rotation should be in anti-clockwise direction.  
+
+Rotation of a _4x5_ matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only (refer sample tests for more clarity).
+
+
+![matrix-rotation](https://hr-challenge-images.s3.amazonaws.com/2517/matrix-rotation.png)
+
+It is guaranteed that the minimum of _M_ and _N_ will be even.  
+
+**Input**  
+First line contains three space separated integers, *M*, *N* and *R*, where _M_ is the number of rows, _N_ is number of columns in matrix, and _R_ is the number of times the matrix has to be rotated.  
+Then *M* lines follow, where each line contains *N* space separated positive integers. These *M* lines  represent the matrix.  
+
+**Output**  
+Print the rotated matrix.
+
+**Constraints**  
+2 <= *M*, *N* <= 300  
+1 <= *R* <= 109  
+min(_M, N_) % 2 == 0  
+1 <= _aij_ <= 108, where _i_ ∈ _[1..M]_ & _j_ ∈ _[1..N]_  
+
+**Sample Input #00**
+
+    4 4 1
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #00**
+
+    2 3 4 8
+    1 7 11 12
+    5 6 10 16
+    9 13 14 15
+
+**Sample Input #01**
+
+    4 4 2
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #01**
+
+    3 4 8 12
+    2 11 10 16
+    1 7 6 15
+    5 9 13 14
+
+
+**Sample Input #02**
+
+    5 4 7
+    1 2 3 4
+    7 8 9 10
+    13 14 15 16
+    19 20 21 22
+    25 26 27 28
+
+**Sample Output #02**
+
+    28 27 26 25
+    22 9 15 19
+    16 8 21 13
+    10 14 20 7
+    4 3 2 1
+
+
+
+**Sample Input #03**
+
+    2 2 3
+    1 1
+    1 1
+
+**Sample Output #03**
+
+    1 1
+    1 1
+
+
+**Explanation**  
+*Sample Case #00:* Here is an illustration of what happens when the matrix is rotated once.
+
+     1  2  3  4      2  3  4  8
+     5  6  7  8      1  7 11 12
+     9 10 11 12  ->  5  6 10 16
+    13 14 15 16      9 13 14 15
+
+*Sample Case #01:* Here is what happens when to the matrix after two rotations.
+
+     1  2  3  4      2  3  4  8      3  4  8 12
+     5  6  7  8      1  7 11 12      2 11 10 16
+     9 10 11 12  ->  5  6 10 16  ->  1  7  6 15
+    13 14 15 16      9 13 14 15      5  9 13 14
+
+*Sample Case #02:* Following are the intermediate states.
+
+    1  2  3  4      2  3  4 10    3  4 10 16    4 10 16 22
+    7  8  9 10      1  9 15 16    2 15 21 22    3 21 20 28
+    13 14 15 16 ->  7  8 21 22 -> 1  9 20 28 -> 2 15 14 27 ->
+    19 20 21 22    13 14 20 28    7  8 14 27    1  9  8 26
+    25 26 27 28    19 25 26 27    13 19 25 26   7 13 19 25
+
+
+
+    10 16 22 28    16 22 28 27    22 28 27 26    28 27 26 25
+     4 20 14 27    10 14  8 26    16  8  9 25    22  9 15 19
+     3 21  8 26 ->  4 20  9 25 -> 10 14 15 19 -> 16  8 21 13
+     2 15  9 25     3 21 15 19     4 20 21 13    10 14 20  7
+     1  7 13 19     2  1  7 13     3  2  1  7     4  3  2  1
+
+*Sample Case #03:* As all elements are same, any rotation will reflect the same matrix.
+
+---
+**Tested by:** [Tusshar Singh](/tussharsingh13), [Abhiranjan](/abhiranjan)
+",code,Rotate the elements of the matrix.,ai,2014-05-13T15:51:08,2016-09-01T16:26:21,,,,"[Here](https://www.hackerrank.com/challenges/matrix-rotation-algo) is the non-FP version of this challenge, with all languages enabled.
+
+---
+You are given a 2D  matrix, _a_, of dimension *MxN* and a positive integer _R_. You have to rotate the matrix _R_ times and print the resultant matrix. Rotation should be in anti-clockwise direction.  
+
+Rotation of a _4x5_ matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only (refer sample tests for more clarity).
+
+
+![matrix-rotation](https://hr-challenge-images.s3.amazonaws.com/2517/matrix-rotation.png)
+
+It is guaranteed that the minimum of _M_ and _N_ will be even.  
+
+**Input**  
+First line contains three space separated integers, *M*, *N* and *R*, where _M_ is the number of rows, _N_ is number of columns in matrix, and _R_ is the number of times the matrix has to be rotated.  
+Then *M* lines follow, where each line contains *N* space separated positive integers. These *M* lines  represent the matrix.  
+
+**Output**  
+Print the rotated matrix.
+
+**Constraints**  
+2 <= *M*, *N* <= 300  
+1 <= *R* <= 109  
+min(_M, N_) % 2 == 0  
+1 <= _aij_ <= 108, where _i_ ∈ _[1..M]_ & _j_ ∈ _[1..N]_  
+
+**Sample Input #00**
+
+    4 4 1
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #00**
+
+    2 3 4 8
+    1 7 11 12
+    5 6 10 16
+    9 13 14 15
+
+**Sample Input #01**
+
+    4 4 2
+    1 2 3 4
+    5 6 7 8
+    9 10 11 12
+    13 14 15 16
+
+**Sample Output #01**
+
+    3 4 8 12
+    2 11 10 16
+    1 7 6 15
+    5 9 13 14
+
+
+**Sample Input #02**
+
+    5 4 7
+    1 2 3 4
+    7 8 9 10
+    13 14 15 16
+    19 20 21 22
+    25 26 27 28
+
+**Sample Output #02**
+
+    28 27 26 25
+    22 9 15 19
+    16 8 21 13
+    10 14 20 7
+    4 3 2 1
+
+
+
+**Sample Input #03**
+
+    2 2 3
+    1 1
+    1 1
+
+**Sample Output #03**
+
+    1 1
+    1 1
+
+
+**Explanation**  
+*Sample Case #00:* Here is an illustration of what happens when the matrix is rotated once.
+
+     1  2  3  4      2  3  4  8
+     5  6  7  8      1  7 11 12
+     9 10 11 12  ->  5  6 10 16
+    13 14 15 16      9 13 14 15
+
+*Sample Case #01:* Here is what happens when to the matrix after two rotations.
+
+     1  2  3  4      2  3  4  8      3  4  8 12
+     5  6  7  8      1  7 11 12      2 11 10 16
+     9 10 11 12  ->  5  6 10 16  ->  1  7  6 15
+    13 14 15 16      9 13 14 15      5  9 13 14
+
+*Sample Case #02:* Following are the intermediate states.
+
+    1  2  3  4      2  3  4 10    3  4 10 16    4 10 16 22
+    7  8  9 10      1  9 15 16    2 15 21 22    3 21 20 28
+    13 14 15 16 ->  7  8 21 22 -> 1  9 20 28 -> 2 15 14 27 ->
+    19 20 21 22    13 14 20 28    7  8 14 27    1  9  8 26
+    25 26 27 28    19 25 26 27    13 19 25 26   7 13 19 25
+
+
+
+    10 16 22 28    16 22 28 27    22 28 27 26    28 27 26 25
+     4 20 14 27    10 14  8 26    16  8  9 25    22  9 15 19
+     3 21  8 26 ->  4 20  9 25 -> 10 14 15 19 -> 16  8 21 13
+     2 15  9 25     3 21 15 19     4 20 21 13    10 14 20  7
+     1  7 13 19     2  1  7 13     3  2  1  7     4  3  2  1
+
+*Sample Case #03:* As all elements are same, any rotation will reflect the same matrix.
+
+---
+**Tested by:** [Tusshar Singh](/tussharsingh13), [Abhiranjan](/abhiranjan)
+",0.5,"[""haskell"",""clojure"",""scala"",""erlang"",""sbcl"",""ocaml"",""fsharp"",""racket"",""elixir""]", , , , ,Hard,,,,,,,2014-07-08T12:57:25,2016-12-13T21:51:24,tester,"    --- {{{
+    import Data.List
+    import Data.Char
+    import qualified Data.ByteString.Char8 as BS -- BS.getContents
+    import qualified Data.Vector as V
+    import qualified Data.Map as Map
+    import qualified Data.HashMap.Strict as HM
+    import Control.Applicative
+    import Text.Printf                           -- printf ""%0.6f"" (1.0)
+    import Data.Tuple
+    import Data.Maybe
+    -- }}}
+
+    type Index = (Int, Int)
+    type MatrixIndex = Map.Map Index Index
+
+    main :: IO ()
+    main = BS.getContents >>= putStrLn. validate. map getIntArray. BS.lines
+
+    showMatrix :: (Show a) => [[a]] -> String
+    showMatrix = unlines. map(unwords. map show)
+
+    validate ([n, m, r]:matrix)
+      | n < 2 || n > 300  = error $ printf ""n = %d"" n
+      | m < 2 || m > 300  = error $ printf ""m = %d"" m
+      | odd (min n m)     = error $ printf ""min is not even: n = %d, m = %d"" n m
+      | r < 1 || r > 10^9 = error $ printf ""r = %d"" r
+      | any (any (\x -> x < 1 || x > 10^8)) matrix = error ""element of matrix is out of bound""
+      | otherwise = showMatrix ans
+        where
+          vMatrix = V.fromList (map V.fromList matrix)
+          (layers, revLayers) = getIndices (n, m)
+          layers' = map (rotate r) layers
+          layersMap = Map.fromList. concat $ layers'
+          revLayersMap = Map.fromList. concat $ revLayers
+          indexMatrix = getMatrix (n, m) layersMap revLayersMap
+          ans = [ [ vMatrix V.! r V.! c| (r, c) <- rows] | rows <- indexMatrix]
+
+    getMatrix :: Index -> MatrixIndex -> MatrixIndex -> [[(Int, Int)]]
+    getMatrix    (n, m)   matIdx revMatIdx = [ [ getValue r c |c <- [0..m-1]]| r <- [0..n-1]]
+      where
+        getValue r c =
+          let
+            idx = fromJust. Map.lookup (r, c) $ revMatIdx
+          in
+            fromJust. Map.lookup idx $ matIdx
+
+
+    getIndices :: Index -> ([[(Index, Index)]], [[(Index, Index)]])
+    getIndices (n, m) = (layers,  layersRev)
+      where
+        mn = min (n+1) (m+1)
+        layers = map (\(r, c) -> getLayer r (n-2*r, m-2*c)) $ indicesAdd
+        layersRev = map (map swap) layers
+        indicesAdd = take (mn`div`2)(zip [0..] [0..])
+
+    rotate :: Int -> [(Index, Index)] -> [(Index, Index)]
+    rotate k idx = zip lt (b++a)
+      where
+        lt = map fst idx
+        rt = map snd idx
+        (a, b) = splitAt (k `rem` (length idx)) rt
+
+    getLayer :: Int -> Index -> [(Index, Index)]
+    getLayer layerIdx rc@(r, c)
+      | r == 0 || c == 0 =
+        let
+          dr = signum r
+          dc = signum c
+          arr = zipWith (\d (x, y) -> (x+d*dr, y+d*dc)) [0..] (replicate (max r c) (layerIdx, layerIdx))
+        in
+          zip (zip (repeat layerIdx) [0..]) arr
+      | otherwise = getLayer' 0 (layerIdx, layerIdx) (0, 1)
+        where
+          getLayer' :: Int -> Index ->        Index ->         [(Index, Index)]
+          getLayer'    idx    curPos@(r', c') add1@(rAdd, cAdd)
+            | idx == 2*(r-1+c-1) = []
+            | otherwise = ((layerIdx, idx), curPos): ans'
+              where
+                ans' = getLayer' (idx+1) (r'+rAdd', c'+cAdd') add2
+                add2@(rAdd', cAdd') = if idx == c-1
+                                        then (1, 0)
+                                        else if idx == r-1+c-1
+                                          then (0, -1)
+                                          else if idx == c-1+r-1+c-1
+                                            then (-1, 0)
+                                            else add1
+
+
+    ---------------User Defined Functions----------------- {{{
+    getIntArray = readIntArray
+    readIntArray input_pqr =
+        case x_yzpqr of
+            Just (a_yzpqr, xs_pqr) -> a_yzpqr : readIntArray (BS.drop 1 xs_pqr)
+            Nothing -> []
+        where
+            x_yzpqr = BS.readInt input_pqr
+
+    ------------------------------------------------------ }}}
+
+",not-set,2016-04-24T02:02:49,2016-04-24T02:02:49,Python
+124,3244,nimrod-and-the-bricks,Nimrod and the bricks,"Nimrod  likes to play bricks. He has an interesting bricks construction in the back yard. The bricks are arranged into a row of N stacks in such a way that the first one is a stack of 1 brick, the second one is a stack of 2 bricks, the third one is a stack of 3 bricks, and so on.
+
+Nimrod has unlimited amount of bricks that are not forming part of the construction. As he likes to play bricks, he sets a contiguous interval of the construction with equal number of bricks in each stack, adding or removing bricks. It takes 1 unit of time to remove one brick from one stack or add a brick to one stack. He can not move a brick from one stack to another.
+
+But there is a problem. He may have a chance to make a mess and be scolded by his mother. Therefore, he wants to know how much time it will take to restore an interval to its original form.
+
+Nimrod is asking for your help.
+
+Input format
+
+The first line of the input contains two integers N (1 ≤ N ≤ 100000) — the number of contiguous stacks at the bricks construction, and Q (1 ≤ Q ≤ 100000) — the number of operations. Next Q lines describe an operation. There are two types of operations. Operation '1', is when Nimrod sets a whole interval starting at the A stack and ending at the B stack, to X bricks in each stack. It is in the form '1 A B X', where (1 ≤ A ≤ B ≤ N) and (1 ≤ X ≤ 10^8). Operation '2' is when Nimnrod wants to know how much time it will take to restore an interval to its original form. It is in the form '2 A B', where (1 ≤ A ≤ B ≤ N). (quotes for clarity only).
+
+Output format
+
+For every '2' query output one line containing the how much time it will take to restore an interval to its original form.
+
+Sample input
+
5 5 +
1 4 5 1 +
1 5 5 2 +
2 2 5 +
1 5 5 1 +
2 5 5 + + +Sample output +
6 +
4 +",code,Can you solve this queries?,ai,2014-07-09T02:01:17,2016-09-09T09:47:48,,,,"Nimrod likes to play bricks. He has an interesting bricks construction in the back yard. The bricks are arranged into a row of N stacks in such a way that the first one is a stack of 1 brick, the second one is a stack of 2 bricks, the third one is a stack of 3 bricks, and so on. + +Nimrod has unlimited amount of bricks that are not forming part of the construction. As he likes to play bricks, he sets a contiguous interval of the construction with equal number of bricks in each stack, adding or removing bricks. It takes 1 unit of time to remove one brick from one stack or add a brick to one stack. He can not move a brick from one stack to another. + +But there is a problem. He may have a chance to make a mess and be scolded by his mother. Therefore, he wants to know how much time it will take to restore an interval to its original form. + +Nimrod is asking for your help. + +Input format + +The first line of the input contains two integers N (1 ≤ N ≤ 100000) — the number of contiguous stacks at the bricks construction, and Q (1 ≤ Q ≤ 100000) — the number of operations. Next Q lines describe an operation. There are two types of operations. Operation '1', is when Nimrod sets a whole interval starting at the A stack and ending at the B stack, to X bricks in each stack. It is in the form '1 A B X', where (1 ≤ A ≤ B ≤ N) and (1 ≤ X ≤ 10^8). Operation '2' is when Nimnrod wants to know how much time it will take to restore an interval to its original form. It is in the form '2 A B', where (1 ≤ A ≤ B ≤ N). (quotes for clarity only). + +Output format + +For every '2' query output one line containing the how much time it will take to restore an interval to its original form. + +Sample input +
5 5 +
1 4 5 1 +
1 5 5 2 +
2 2 5 +
1 5 5 1 +
2 5 5 + + +Sample output +
6 +
4 +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-07-09T02:01:31,2016-05-13T00:00:13,setter,"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+using namespace std;
+
+typedef long long ll;
+
+int t;
+int n, x, y, q,m, op, r, k, p, c, d;
+
+long long val[500000];
+int prop[500000];
+
+ll calc(ll a, ll b, ll x) {
+	if(x < a) {
+		ll nn = (b-a+1LL);
+		return nn * (nn + 1LL)/2LL + (a - x - 1LL) * nn;
+	} else
+	if(x > b) {
+		ll nn = (b-a+1LL);
+		return nn * (nn + 1LL)/2LL + (x - b - 1LL) * nn;
+	}
+
+	ll n1 = x - a;
+	ll n2 = b - x;
+
+	return n1 * (n1 + 1LL) / 2LL + n2 * (n2 + 1LL) / 2LL;
+}
+
+void push(int index, int a, int b) {
+	prop[2*index] = prop[index];
+	prop[2*index+1] = prop[index];
+
+	int m = (a+b)/2;
+
+	val[2*index] = calc(a,m, prop[index]);
+	val[2*index+1] = calc(m+1,b, prop[index]);
+
+	prop[index] = 0;
+}
+
+void update(int index, int a, int b) {
+	if(a > d || b < c) return;
+	if(a >= c && b <= d) {
+		prop[index] = x;
+		val[index] = calc(a,b,x);
+		return;
+	}
+
+	if(prop[index]) {
+		push(index, a, b);
+	}
+
+	update(2*index, a, (a+b)/2);
+	update(2*index+1, (a+b)/2+1, b);
+
+	val[index] = val[2*index] + val[2*index+1];
+}
+
+ll querie(int index, int a, int b) {
+	if(a > d || b < c) return 0;
+	if(a >= c && b <= d) {
+		return val[index];
+	}
+
+	if(prop[index]) {
+		push(index, a, b);
+	}
+
+	return querie(2*index, a, (a+b)/2) +
+	querie(2*index+1, (a+b)/2+1, b);
+}
+
+
+int main() {
+
+	scanf(""%d%d"", &n, &q);
+
+	while(q--) {
+		scanf(""%d"", &op);
+		if(op == 1) {
+			scanf(""%d%d%d"", &c, &d, &x);
+			assert(c >= 1 && d <= n && c <= d && x > 0 && x <= 100000000);
+			update(1,1,n);
+		} else {
+			scanf(""%d%d"", &c, &d);
+			assert(c >= 1 && d <= n && c <= d);
+			printf(""%lld\n"", querie(1,1,n));
+		}
+	}
+	return 0;
+}",not-set,2016-04-24T02:02:49,2016-04-24T02:02:49,C++
+125,3259,radioactive-cubes,Radioactive cubes,"You have been hired by a company to develop a software to solve the following problem.
+
+There are N radioactive objects with cubic shape. They are in three dimensions with a particular length, width, and height. Also, there are M holes in the ground with rectangular shape. The company needs to bury the radioactive cubes in the ground. Therefore, the company wants to know what is the maximum amount of radioactive cubes can be buried into holes.
+
+Only one radioactive cube can be put in each hole because radioactive cubes might react with each other and explode.
+The depth of each hole is negligible. The cubes can be rotated.
+
+**Input format**
+
+The first line contains two integers, N the amount of cubes and M, the amount of holes.
+Next follow N lines. Each line contains three numbers A,B,C, the dimensions of each cube. Next follow M lines. Each line contains two numbers D, E the dimensions of each hole .
+
+**Constraints**
+
+1 ≤ N,  M ≤ 1000  
+0.00 ≤ A, B, C ≤ 10.00  
+0.00 ≤ D, E ≤ 10.00  
+
+**Output format**
+
+The output will consist of one single line, the maximum number of radioactive cubes can be introduced into the holes.
+
+**Sample input**
+
+    2 2
+    3.00 2.00 2.00
+    2.00 2.00 3.00
+    2.00 2.00
+    1.00 1.00
+
+**Sample output**
+
+    1",code,Can you find out the maximum?,ai,2014-07-11T18:59:23,2016-09-09T09:47:53,,,,"You have been hired by a company to develop a software to solve the following problem.
+
+There are N radioactive objects with cubic shape. They are in three dimensions with a particular length, width, and height. Also, there are M holes in the ground with rectangular shape. The company needs to bury the radioactive cubes in the ground. Therefore, the company wants to know what is the maximum amount of radioactive cubes can be buried into holes.
+
+Only one radioactive cube can be put in each hole because radioactive cubes might react with each other and explode.
+The depth of each hole is negligible. The cubes can be rotated.
+
+**Input format**
+
+The first line contains two integers, N the amount of cubes and M, the amount of holes.
+Next follow N lines. Each line contains three numbers A,B,C, the dimensions of each cube. Next follow M lines. Each line contains two numbers D, E the dimensions of each hole .
+
+**Constraints**
+
+1 ≤ N,  M ≤ 1000  
+0.00 ≤ A, B, C ≤ 10.00  
+0.00 ≤ D, E ≤ 10.00  
+
+**Output format**
+
+The output will consist of one single line, the maximum number of radioactive cubes can be introduced into the holes.
+
+**Sample input**
+
+    2 2
+    3.00 2.00 2.00
+    2.00 2.00 3.00
+    2.00 2.00
+    1.00 1.00
+
+**Sample output**
+
+    1",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-07-11T18:59:43,2016-05-13T00:00:06,setter,"
+	#include
+ #include< cstdio >
+ #include < cmath >
+ #include < queue >
+ #include < cstring >
+ #include < algorithm >
+ #include < stack >
+ #include < map >
+ #include < cassert >
+ #include < set >
+ #include < deque >
+ #include < complex >
+using namespace std;
+
+typedef long long ll;
+typedef unsigned long long ull;
+
+//rectangle c x d fit into a x b
+bool fit(double c, double d, double a, double b) {
+	if (a > b) swap(a, b);
+	if (c > d) swap(c, d);
+	if (c > a) return 0;
+	if (d-1e-12 < b) return 1;
+	double l = sqrt(c*c+d*d);
+	double alfa = atan2(d, c)-acos(a/l);
+	return (c*sin(alfa)+d*cos(alfa)-1e-12) < b;
+}
+
+
+bool check(double a, double b, double c, double x, double y) {
+	if(fit(a, b, x, y) || fit(a, c, x, y) || fit(b, c, x, y))
+		return true;
+	return false;
+}
+
+const int MAXV = 200001;
+const int MAXV1 = 2 * MAXV;
+int N, M;
+vector ady[MAXV];
+int D[MAXV1], Mx[MAXV], My[MAXV];
+
+
+bool BFS() {
+	int u, v, i, e;
+	queue cola;
+	bool f = 0;
+	for (i = 0; i < N + M; i++)
+		D[i] = 0;
+	for (i = 0; i < N; i++)
+		if (Mx[i] == -1)
+			cola.push(i);
+	while (!cola.empty()) {
+		u = cola.front();
+		cola.pop();
+		for (e = ady[u].size() - 1; e >= 0; e--) {
+			v = ady[u][e];
+			if (D[v + N])
+				continue;
+			D[v + N] = D[u] + 1;
+			if (My[v] != -1) {
+				D[My[v]] = D[v + N] + 1;
+				cola.push(My[v]);
+			} else
+				f = 1;
+		}
+	}
+	return f;
+}
+
+int DFS(int u) {
+	for (int v, e = ady[u].size() - 1; e >= 0; e--) {
+		v = ady[u][e];
+		if (D[v + N] != D[u] + 1)
+			continue;
+		D[v + N] = 0;
+		if (My[v] == -1 || DFS(My[v])) {
+			Mx[u] = v;
+			My[v] = u;
+			return 1;
+		}
+	}
+	return 0;
+}
+
+int hopcroft_karp() {
+	int i, flow = 0;
+	for (i = max(N, M); i >= 0; i--)
+		Mx[i] = My[i] = -1;
+	while (BFS())
+		for (i = 0; i < N; i++)
+			if (Mx[i] == -1 && DFS(i))
+				++flow;
+	return flow;
+}
+
+double x,y,z;
+pair > cubes[1005];
+pair holes[1005];
+
+int main() {
+
+	scanf(""%d%d"", &N, &M);
+
+	assert(N > 0 && N <= 1000 && M > 0 && M <= 1000);
+
+	for(int i = 0;i0 && x <= 10 && y>0 && y <= 10  && z>0 && z <= 10);
+		cubes[i] = make_pair(x, make_pair(y,z));
+	}
+
+	for(int i = 0;i0 && x <= 10 && y>0 && y <= 10);
+		holes[i] = make_pair(x,y);
+	}
+
+	for(int i = 0;i3 3
+
1 2 3 +
4 5 6 +
7 8 9 +
2 2 +
2 1 +
3 4 + +**Sample output** +
1 1 4",code,Just match the pictures!!,ai,2014-07-12T02:40:46,2016-09-09T09:47:54,,,,"You have been assigned to an important job. The software company you are working with requires you to develop a module for his new social network. This task is simple as they will provide you a big and a smaller picture as a pattern. They are looking for the part within the big one which is more likely to be the pattern. + +The more likely part is the one which minimizes the sum of the squared differences over all H * W.Each pixel in the big picture and the pattern picture is an integer with absolute value at most 30. + +**Input specification** + +The input starts with the description of the big picture. It is described from the top to bottom and from left to right. The dimension of the big one, R and C (1 <= R, C <= 500) are given in the first line, followed by R lines of C integer, describing each pixel of the big picture. Following is the description of a pattern picture, starting with dimensions  H and W (1 <= H, W <= 499), and then H lines of W integers. + +**Output specification** + +Output is exactly one line, in the form of 'R C V', where V is the least sum of squared differences over all H * W, the one which starts at row R and col C. If there are several solutions, prints the closest to the top of the big picture. If there is still several solutions, chooses the closest to the left.(quotes for clarity only). + +**Sample input** +
3 3 +
1 2 3 +
4 5 6 +
7 8 9 +
2 2 +
2 1 +
3 4 + +**Sample output** +
1 1 4",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-07-12T02:40:55,2016-05-13T00:00:04,setter,"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+using namespace std;
+
+typedef unsigned long long ll;
+
+#define XX double
+
+struct P {
+	XX x, y;
+	P() {
+
+	}
+	P(XX x, XX y) :
+		x(x), y(y) {
+	}
+	inline P operator-(const P b) {
+		return P(x - b.x, y - b.y);
+	}
+	inline P operator+(const P b) {
+		return P(x + b.x, y + b.y);
+	}
+	inline P operator*(const P b) {
+		return P(x * b.x - y * b.y, x * b.y + y * b.x);
+	}
+	inline P operator/(const P b) {
+		P s = P(x * b.x + y * b.y, y * b.x - x * b.y);
+		s.x /= (b.x * b.x + b.y * b.y);
+		s.y /= (b.x * b.x + b.y * b.y);
+		return s;
+	}
+};
+// (a,b) * (c,d) = (ac-bd, ad+bc)
+// (a,b) / (c,d) = ( (ac+bd) / (c^2+d^2), (bc-ad) / (c^2+d^2) )
+
+
+const double PI = 3.141592653589793;
+
+void fft(P *a, int n, bool invert) {
+	for (register int i = 1, j = 0; i < n; ++i) {
+		int bit = n >> 1;
+		for (; j >= bit; bit >>= 1)
+			j -= bit;
+		j += bit;
+		if (i < j)
+			swap(a[i], a[j]);
+	}
+	for (register int len = 2; len <= n; len <<= 1) {
+		double ang = 2 * PI / len * (invert ? -1 : 1);
+		P wlen(cos(ang), sin(ang));
+		for (int i = 0; i < n; i += len) {
+			P w(1, 0);
+			for (int j = 0; j < len / 2; ++j) {
+				P u = a[i + j], v = a[i + j + len / 2] * w;
+				a[i + j] = u + v;
+				a[i + j + len / 2] = u - v;
+				w = w * wlen;
+			}
+		}
+	}
+	if (invert)
+		for (int i = 0; i < n; ++i)
+			a[i].x /= n, a[i].y /= n;
+}
+
+int R, C, H, W, k, ii, jj;
+int F[700][700];
+int Pa[700][700];
+int SumSumF[700][700];
+
+P A[2200000], B[2200000];
+
+int ptr;
+
+ll SumSumP , score;
+
+inline int correct(double val) {
+	if(val < 0) return val - 0.5;
+	return val + 0.5;
+}
+
+int rs, cs;
+ll sol;
+
+int main() {
+
+	sol = 2 * 1e18;
+
+	scanf(""%d%d"", &R, &C);
+	for(int i = 0;i4  
+2 ≤ N ≤ 1018  
+
+**Output Format**  
+For each testcase, print in a newline, the number of such necklaces that are possible.  If the answer is greater than or equal to 109+7, print the answer modulo ( % ) 109+7.
+
+**Sample Input**
+
+    2
+    2
+    3
+
+**Sample Output**
+
+    3
+    4
+
+**Explanation**
+
+For the first testcase, valid arrangement of beads are 
+
+    BR RB RR
+
+For the second testcase, valid arrangement of beads are
+
+    BRR RBR RRR RRB",code,Help Mr. X impress his girlfriend !,ai,2014-07-14T09:08:38,2022-09-02T09:55:11,,,,"Mr. X wants to buy a necklace for his girlfriend.
+The available necklaces are bi-colored (red and blue beads).
+
+Mr. X desperately wants to impress his girlfriend and knows that she will like the necklace only if **every prime length continuous sub-sequence of beads in the necklace** has more or equal number of red beads than blue beads.
+
+Given the number of beads in the necklace N, Mr. X wants to know the number of all possible such necklaces.
+
+_Note: - It is given that the necklace is a single string and not a loop._
+
+
+**Input Format**  
+The first line of the input contains an integer *T*, the number of testcases.  
+*T* lines follow, each line containing *N*, the number of beads in the necklace.  
+
+**Constraints**  
+1 ≤ T ≤ 104  
+2 ≤ N ≤ 1018  
+
+**Output Format**  
+For each testcase, print in a newline, the number of such necklaces that are possible.  If the answer is greater than or equal to 109+7, print the answer modulo ( % ) 109+7.
+
+**Sample Input**
+
+    2
+    2
+    3
+
+**Sample Output**
+
+    3
+    4
+
+**Explanation**
+
+For the first testcase, valid arrangement of beads are 
+
+    BR RB RR
+
+For the second testcase, valid arrangement of beads are
+
+    BRR RBR RRR RRB",0.5918367346938775,"[""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,,,,,,,2014-07-14T09:08:57,2016-12-05T16:43:28,setter,"###C++  
+```cpp  
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+#define MOD 1000000007
+#define LL  long long
+int i,j;
+void multiplyMM(LL F[3][3], LL M[3][3])
+{
+    LL l[3][3];
+    
+    l[0][0]=((F[0][0]*M[0][0])%MOD+(F[0][1]*M[1][0])%MOD+(F[0][2]*M[2]    [0])%MOD)%MOD;
+    l[0][1]=((F[0][0]*M[0][1])%MOD+(F[0][1]*M[1][1])%MOD+(F[0][2]*M[2][1])%MOD)%MOD;
+    l[0][2]=((F[0][0]*M[0][2])%MOD+(F[0][1]*M[1][2])%MOD+(F[0][2]*M[2][2])%MOD)%MOD;
+    l[1][0]=((F[1][0]*M[0][0])%MOD+(F[1][1]*M[1][0])%MOD+(F[1][2]*M[2][0])%MOD)%MOD;
+    l[1][1]=((F[1][0]*M[0][1])%MOD+(F[1][1]*M[1][1])%MOD+(F[1][2]*M[2][1])%MOD)%MOD;
+    l[1][2]=((F[1][0]*M[0][2])%MOD+(F[1][1]*M[1][2])%MOD+(F[1][2]*M[2][2])%MOD)%MOD;
+    l[2][0]=((F[2][0]*M[0][0])%MOD+(F[2][1]*M[1][0])%MOD+(F[2][2]*M[2][0])%MOD)%MOD;
+    l[2][1]=((F[2][0]*M[0][1])%MOD+(F[2][1]*M[1][1])%MOD+(F[2][2]*M[2][1])%MOD)%MOD;
+    l[2][2]=((F[2][0]*M[0][2])%MOD+(F[2][1]*M[1][2])%MOD+(F[2][2]*M[2][2])%MOD)%MOD;
+    for(i=0;i<3;i++)
+    {
+        for(j=0;j<3;j++)
+            {
+                F[i][j]=l[i][j];
+            }
+      }
+}
+
+void multiplyMF(LL m[3][3],LL a[3])
+{
+    LL x =((a[0]*m[0][0])%MOD+((a[1]*m[0][1])%MOD)+((a[2]*m[0][2])%MOD))%MOD;
+    LL y =((a[0]*m[1][0])%MOD+((a[1]*m[1][1])%MOD)+((a[2]*m[1][2])%MOD))%MOD;
+    LL z =((a[0]*m[2][0])%MOD+((a[1]*m[2][1])%MOD)+((a[2]*m[2][2])%MOD))%MOD;
+    a[0]=x;
+    a[1]=y;
+    a[2]=z;
+}
+
+void powerM(LL f[3][3],LL n)
+{
+    if(n==0||n==1||n<0)
+    return;
+    LL M[3][3]={{0,0,1},{1,0,0},{0,1,1}};
+    powerM(f, n/2);
+    multiplyMM(f,f);
+    if(n%2!=0)
+    multiplyMM(f, M);
+}
+LL func(LL n)
+{
+    LL f[3]={1,1,1};
+    if(n<3)
+    return f[n];
+    LL M[3][3]={{0,0,1},{1,0,0},{0,1,1}};
+    powerM(M,n-1);
+    multiplyMF(M,f);
+    return(f[0]);
+}
+LL N;
+int main()
+{
+  // freopen(""input.txt"",""r"",stdin);
+  //freopen(""output.txt"",""w"",stdout);
+    int t;
+    cin>>t;
+    while(t--)
+    {
+        cin>>N;
+        if(N==0 || N==1)
+        cout<<""0""<4  
+2 ≤ N ≤ 1018  
+
+**Output Format**  
+For each testcase, print in a newline, the number of such necklaces that are possible.  If the answer is greater than or equal to 109+7, print the answer modulo ( % ) 109+7.
+
+**Sample Input**
+
+    2
+    2
+    3
+
+**Sample Output**
+
+    3
+    4
+
+**Explanation**
+
+For the first testcase, valid arrangement of beads are 
+
+    BR RB RR
+
+For the second testcase, valid arrangement of beads are
+
+    BRR RBR RRR RRB",code,Help Mr. X impress his girlfriend !,ai,2014-07-14T09:08:38,2022-09-02T09:55:11,,,,"Mr. X wants to buy a necklace for his girlfriend.
+The available necklaces are bi-colored (red and blue beads).
+
+Mr. X desperately wants to impress his girlfriend and knows that she will like the necklace only if **every prime length continuous sub-sequence of beads in the necklace** has more or equal number of red beads than blue beads.
+
+Given the number of beads in the necklace N, Mr. X wants to know the number of all possible such necklaces.
+
+_Note: - It is given that the necklace is a single string and not a loop._
+
+
+**Input Format**  
+The first line of the input contains an integer *T*, the number of testcases.  
+*T* lines follow, each line containing *N*, the number of beads in the necklace.  
+
+**Constraints**  
+1 ≤ T ≤ 104  
+2 ≤ N ≤ 1018  
+
+**Output Format**  
+For each testcase, print in a newline, the number of such necklaces that are possible.  If the answer is greater than or equal to 109+7, print the answer modulo ( % ) 109+7.
+
+**Sample Input**
+
+    2
+    2
+    3
+
+**Sample Output**
+
+    3
+    4
+
+**Explanation**
+
+For the first testcase, valid arrangement of beads are 
+
+    BR RB RR
+
+For the second testcase, valid arrangement of beads are
+
+    BRR RBR RRR RRB",0.5918367346938775,"[""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,,,,,,,2014-07-14T09:08:57,2016-12-05T16:43:28,tester,"###C++  
+```cpp  
+#include
+
+using namespace std;
+
+#define MOD 1000000007
+
+class Matrix {
+    public:
+        int **mat;
+        int row;
+        int col;
+
+        Matrix()
+        {
+        }
+
+        Matrix(int row = 2, int col = 2)
+        {
+            this->row = row;
+            this->col = col;
+            mat = new int*[row];
+            for(int i = 0; i < row; i++)
+                mat[i] = new int[col];
+        }
+
+        Matrix(int **n, int row, int col, int mod)
+        {
+            this->row = row;
+            this->col = col;
+            mat = new int*[row];
+            for(int i = 0; i < row; i++)
+            {
+                mat[i] = new int[col];
+                for(int j = 0; j < col; j++)
+                {
+                    mat[i][j] = n[i][j];
+                }
+            }
+        }
+
+        Matrix operator * (const Matrix &b)
+        {
+            Matrix *c = new Matrix(this->row, b.col);
+            assert(this->col == b.row);
+            // This might be wrong. Please be careful
+            for(int i = 0; i < this->row; i++)
+            {
+                for(int j = 0; j < this->col; j++)
+                {
+                    c->mat[i][j] = 0;
+                    for(int k = 0; k < this->col; k++)
+                    {
+                        long long val = (long long)mat[i][k] * (long long)b.mat[k][j];
+                        assert(val >= 0);
+                        val = val % MOD;
+                        assert(val >= 0);
+                        c->mat[i][j] = (c->mat[i][j] + val) % MOD;
+                        assert(c->mat[i][j] >= 0);
+                    }
+                }
+            }
+            return *c;
+        }
+
+        void print_matrix()
+        {
+            for(int i = 0; i < row; i++)
+            {
+                for(int j = 0; j < col; j++)
+                {
+                    cout << mat[i][j] << "" "";
+                }
+                cout << endl;
+            }
+        }
+};
+
+Matrix raised_to_pow(Matrix a, long long n)
+{
+    if(n == 1)
+        return a;
+
+    Matrix b = raised_to_pow(a, n/2);
+    Matrix c = b * b;
+    if(n&1)
+        c = c * a;
+
+    return c;
+}
+
+int main()
+{
+    int **a = new int*[3];
+    a[0] = new int[3];
+    a[1] = new int[3];
+    a[2] = new int[3];
+    a[0][0] = a[0][1] = a[1][2] = a[2][0] = 1;
+    a[0][2] = a[1][0] = a[1][1] = a[2][1] = a[2][2] = 0;
+
+    int **b = new int*[1];
+    b[0] = new int[3];
+    b[0][0] = 3;
+    b[0][1] = 2;
+    b[0][2] = 1;
+
+    Matrix *row_mat = new Matrix(b, 1, 3, MOD);
+    Matrix *x = new Matrix(a, 3, 3, MOD);
+
+    int t;
+    long long n;
+    cin >> t;
+    assert(1 <= t and t <= 1e4);
+    while(t--)
+    {
+        cin >> n;
+        assert(2 <= n and n <= 1e18);
+        if(n == 1)
+            cout << 1 << endl;
+        else if(n == 2)
+            cout << 3 << endl;
+        else if(n == 3)
+            cout << 4 << endl;
+        else if(n == 4)
+            cout << 6 << endl;
+        else if(n == 0)
+            cout << 0 << endl;
+        else
+        {
+            Matrix c = raised_to_pow(*x, n - 4);
+            Matrix answer = (*row_mat) * c;
+            long long x = 0;
+            for(int i = 0; i < 3; i++)
+            {
+                x += answer.mat[0][i];
+                if(x >= MOD)
+                    x -= MOD;
+            }
+           
+            cout << x << endl;
+        }
+    }
+    return 0;
+}
+```
+",not-set,2016-04-24T02:02:51,2016-07-23T18:59:18,C++
+129,3081,littlepandapower,Little Panda Power,"**Little Panda** has a thing for powers and modulus and he likes challenges. His friend **Lucy**, however, is impractical and challenges **Panda** to find both positive and negative powers of a number modulo a particular number. We all know that $A^{-1}\bmod X$ refers to the modular inverse of $A$ modulo $X$ (see [Wikipedia](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse)).  
+
+Since **Lucy** is impractical, she says that $A^{-n}\bmod  X = (A^{-1}\bmod  X)^n\bmod X$ for $n \gt 0$.  
+
+Now she wants **Panda** to compute $A^B\bmod X$.   
+
+She also thinks that this problem can be very difficult if the constraints aren't given properly. **Little Panda** is very confused and leaves the problem to the worthy programmers of the world. Help him in finding the solution.
+
+**Input Format**  
+The first line contains $T$, the number of test cases.  
+Then $T$ lines follow, each line containing $A$, $B$ and $X$.  
+
+**Output Format**  
+Output the value of $A^B\bmod  X$.  
+
+**Constraints**  
+$1 \le T \le 1000$  
+$1 \le A \le 10^6$  
+$-10^6 \le B \le 10^6$  
+$1 \le X \le 10^6$  
+$A$  and $X$ are coprime to each other (see [Wikipedia](http://en.wikipedia.org/wiki/Coprime_integers))  
+
+**Sample Input**  
+
+    3  
+    1 2 3  
+    3 4 2  
+    4 -1 5
+
+**Sample Output**  
+
+    1  
+    1  
+    4  
+
+**Explanation**  
+*Case 1:* $1^2\bmod  3 = 1 \bmod  3 = 1$  
+*Case 2:* $3^4\bmod  2 = 81 \bmod  2 = 1$  
+*Case 3:* $4^{-1}\bmod  5 = 4$  ",code,Compute A^B mod X,ai,2014-06-18T19:51:02,2022-09-02T09:54:23,"#
+# Complete the 'solve' function below.
+#
+# The function is expected to return an INTEGER.
+# The function accepts following parameters:
+#  1. INTEGER a
+#  2. INTEGER b
+#  3. INTEGER x
+#
+
+def solve(a, b, x):
+    # 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()
+
+        a = int(first_multiple_input[0])
+
+        b = int(first_multiple_input[1])
+
+        x = int(first_multiple_input[2])
+
+        result = solve(a, b, x)
+
+        fptr.write(str(result) + '\n')
+
+    fptr.close()
+","**Little Panda** has a thing for powers and modulus and he likes challenges. His friend **Lucy**, however, is impractical and challenges **Panda** to find both positive and negative powers of a number modulo a particular number. We all know that $A^{-1}\bmod X$ refers to the modular inverse of $A$ modulo $X$ (see [Wikipedia](http://en.wikipedia.org/wiki/Modular_multiplicative_inverse)).  
+
+Since **Lucy** is impractical, she says that $A^{-n}\bmod  X = (A^{-1}\bmod  X)^n\bmod X$ for $n \gt 0$.  
+
+Now she wants **Panda** to compute $A^B\bmod X$.   
+
+She also thinks that this problem can be very difficult if the constraints aren't given properly. **Little Panda** is very confused and leaves the problem to the worthy programmers of the world. Help him in finding the solution.
+
+**Input Format**  
+The first line contains $T$, the number of test cases.  
+Then $T$ lines follow, each line containing $A$, $B$ and $X$.  
+
+**Output Format**  
+Output the value of $A^B\bmod  X$.  
+
+**Constraints**  
+$1 \le T \le 1000$  
+$1 \le A \le 10^6$  
+$-10^6 \le B \le 10^6$  
+$1 \le X \le 10^6$  
+$A$  and $X$ are coprime to each other (see [Wikipedia](http://en.wikipedia.org/wiki/Coprime_integers))  
+
+**Sample Input**  
+
+    3  
+    1 2 3  
+    3 4 2  
+    4 -1 5
+
+**Sample Output**  
+
+    1  
+    1  
+    4  
+
+**Explanation**  
+*Case 1:* $1^2\bmod  3 = 1 \bmod  3 = 1$  
+*Case 2:* $3^4\bmod  2 = 81 \bmod  2 = 1$  
+*Case 3:* $4^{-1}\bmod  5 = 4$  ",0.5945945945945946,"[""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,,,,,,,2014-07-18T17:51:42,2016-12-05T11:56:17,setter,"###C++  
+```cpp  
+/*******************
+    Akash Agrawall
+    IIIT HYDERABAD
+    akash.agrawall094@gmail.com
+    ***********************/
+
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+using namespace std;
+#define ll long long int
+#define FOR(i,a,b) for(i= (int )a ; i < (int )b ; ++i)
+#define rep(i,n) FOR(i,0,n)
+#define INF INT_MAX
+#define pb push_back
+#define max(a,b) ((a)>(b)?(a):(b))
+#define min(a,b) ((a)<(b)?(a):(b))
+#define pi(n) printf(""%d "",n)
+#define pd(n) printf(""%lf "",n)
+#define pdl(n) printf(""%lf\n"",n)
+#define pin(n) printf(""%d\n"",n)
+#define pl(n) printf(""%lld"",n)
+#define pln(n) printf(""%lld\n"",n)
+#define si(n) scanf(""%d"",&n)
+#define sl(n) scanf(""%lld"",&n)
+#define scan(v,n) vector v;rep(i,n){ int j;si(j);v.pb(j);}
+#define mod (int)(1e9 + 7)
+
+int isprime[1000006]; 
+vector primeit;
+void seive()
+{
+    int i,j;
+    int MAX=1000006;
+    isprime[0] = isprime[1] = 1; 
+    for (i = 4; i < MAX; i += 2)
+        isprime[i] = 1; 
+    for (i = 3; i * i < MAX; i += 2) 
+    {
+        if (!isprime[i]) 
+        {
+            for (j = i * i; j < MAX; j += 2 * i)
+                {
+                    isprime[j] = 1; 
+                }
+        }
+    }
+    for(i=2;i<=MAX;i++)
+        if(!isprime[i])
+            primeit.pb(i);
+}
+ll gcd(ll a, ll b)
+{
+    ll c;
+    while(a!=0)
+    {
+        c=a;
+        a=b%a;
+        b=c;
+    }
+    return b;
+}
+ll powerit(ll a, ll b, ll c)
+{
+    ll x=1;
+    while(b!=0)
+    {
+        if(b&01==1)
+        {
+            x*=a;
+            if(x>=c)
+                x%=c;
+        }
+        a=a*a;
+        if(a>=c)
+            a%=c;
+        b>>=1;
+    }
+    return x;
+}
+
+int main()
+{
+    int t,cnt;
+    ll a,b,c,sqrtit,calc1,calc2,calcit,b1,ansit,c4,c1;
+    //Finding all prime factors which will be required to compute phi(n)
+    seive();
+    si(t);
+    while(t--)
+    {
+        b1=1;
+        sl(a);
+        sl(b);
+        sl(c);
+        c1=c;
+        if(b<0)
+        {
+            cnt=0;
+            calc1=c;
+            calc2=1;
+            //Calculating phi(n)
+            //Using the formula phi(n)=n*(1-1/p1)*(1-1/p2)* ..... where pi refers to all prime divisors
+            sqrtit=sqrt(calc1);
+            sqrtit++;
+            //Finding all prime factors which is less than sqrt(n) and using the formula above
+            while(primeit[cnt]<=sqrtit)
+            {
+                calcit=primeit[cnt];
+                if(c%calcit==0)
+                {
+                    calc1*=(calcit-1);
+                    calc2*=calcit;
+                    c4=gcd(calc1,calc2);
+                    calc1/=c4;
+                    calc2/=c4;
+                    while(c%calcit==0)
+                        c/=calcit;
+                }
+                cnt++;
+            }
+            if(c!=1 && isprime[c]==0)
+            {
+                calc1*=(c-1);
+                calc2*=c;
+            }
+            calc1/=calc2;
+            //phi(n) is calculated and stored in calc1
+            b1=calc1-1;
+            b=-b;
+        }
+        //To calculate ansit=A^(-1)%x using phi(x) 
+        ansit=powerit(a,b1,c1);
+        //To calculate ansit=(ansit^b)%x
+        ansit=powerit(ansit,b,c1);
+        pln(ansit);
+    }
+    return 0;
+}
+```
+",not-set,2016-04-24T02:02:51,2016-07-23T17:33:50,C++
+130,3327,director-and-room-alottments,Director and room Alottments,"As we all know rooms have been alloted randomly this time.
+
+Earlier students with same IQ level used to live together. But now students
+with different IQ levels live in a distributed way. Some have positive IQ 
+and some have negative IQ.
+
+Assume that __single student lives in a single room.__
+Now director wants to make a team for coding club. He can only chose a 
+continous subset of rooms and select all guys in this chosen subset. Now he 
+has to chose the __continous subset__ in such a way so that the sum of IQ 
+level of all students in chosen continous subset of rooms is __less than 'K' 
+and as close as K as possible__. Output the __maximum IQ sum__ that the 
+director can chose.
+
+__INPUT FORMAT__
+
+First line will contain the number of test cases t.
+Second line will contain N (total number of rooms) and K(maximum sum IQ level that director can take)
+Third line will contain number N numbers 'ai' that will be IQ level of students in ith room
+ +__CONSTRAINTS__ + +1<=t<=10
+1<=N<=100000
+-10^15<=K<=10^15
+-10^9<=ai<=10^9
+ +__OUTPUT__ + +Single integer per line denoting the maximum IQ level sum that director can pick according to condition. + +__Sample Input__
+ +2
+6 8
+3 -2 1 3 2 0
+8 -3
+-1 0 -2 -2 3 4 5 1
+ +__OUTPUT__
+7
+-4
+###Explanation
+test case 1:7 because subarray from index 1-5 will contain sum 3+(-2)+1+3+2=7 that +is less than 8 and and is such that it is maximum among subarray sums less +than 8 + + +test case 2:-4 because subarray from index 3-4 will contain sum -2+(-2)=-4 +that is less than -3 and and is such that it is maximum among subarray sums +less than -3 + + +",code,Help the college to create a coding team :),ai,2014-07-19T13:47:52,2016-09-09T09:48:17,,,,"As we all know rooms have been alloted randomly this time. + +Earlier students with same IQ level used to live together. But now students +with different IQ levels live in a distributed way. Some have positive IQ +and some have negative IQ. + +Assume that __single student lives in a single room.__ +Now director wants to make a team for coding club. He can only chose a +continous subset of rooms and select all guys in this chosen subset. Now he +has to chose the __continous subset__ in such a way so that the sum of IQ +level of all students in chosen continous subset of rooms is __less than 'K' +and as close as K as possible__. Output the __maximum IQ sum__ that the +director can chose. + +__INPUT FORMAT__ + +First line will contain the number of test cases t.
+Second line will contain N (total number of rooms) and K(maximum sum IQ level that director can take)
+Third line will contain number N numbers 'ai' that will be IQ level of students in ith room
+ +__CONSTRAINTS__ + +1<=t<=10
+1<=N<=100000
+-10^15<=K<=10^15
+-10^9<=ai<=10^9
+ +__OUTPUT__ + +Single integer per line denoting the maximum IQ level sum that director can pick according to condition. + +__Sample Input__
+ +2
+6 8
+3 -2 1 3 2 0
+8 -3
+-1 0 -2 -2 3 4 5 1
+ +__OUTPUT__
+7
+-4
+###Explanation
+test case 1:7 because subarray from index 1-5 will contain sum 3+(-2)+1+3+2=7 that +is less than 8 and and is such that it is maximum among subarray sums less +than 8 + + +test case 2:-4 because subarray from index 3-4 will contain sum -2+(-2)=-4 +that is less than -3 and and is such that it is maximum among subarray sums +less than -3 + + +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-07-19T13:59:27,2016-05-12T23:59:43,setter," #include + #include + #include + #include + using namespace std; + int main() + { + int i,n; + long long int maxi=-1e18,k; + int a[100009]; + + long long int cum=0; + int t; + cin>>t; + while(t--) + { + cin>>n>>k; + cum=0; + maxi=-1e18; + for(i=0;i>a[i]; + set myset; + myset.clear(); + myset.insert(0); + for(i=0;i::iterator it; + it=myset.upper_bound(cum-k); + if(it!=myset.end()) + { + long long int val=cum-*it; + if(val>maxi) + { + maxi=val; + } + } + myset.insert(cum); + } + if(maxi==-1e18) + cout<<0< +#include +#include +#include +#include +#include +using namespace std; +#define ll long long int +#define FOR(i,a,b) for(i= (int )a ; i < (int )b ; ++i) +#define rep(i,n) FOR(i,0,n) +#define si(n) scanf(""%d"",&n) +#define sl(n) scanf(""%lld"",&n) +int main() +{ + int t,i; + ll sum=0,low,high,mid,x,calc,calc1; + si(t); + while(t--) + { + sl(x); + low=0; + high=1000000; + while(low<=high) + { + mid=(low+high)/2; + calc=(mid*(mid+1)*(2*mid+1))/6; + calc1=((mid+1)*(mid+2)*(2*(mid+1)+1))/6; + if(calc<=x && calc1>x) + { + printf(""%lld\n"",mid); + break; + } + else if(calc +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +typedef long long int ll; + +#define For(i,s,e) for(int i=(s);i<=(e);i++) +#define mp(a,b) make_pair((a),(b)) + +ll modulo ; + +#define mod0 1711276033L +#define s0 1223522572 //this is the root and it will make it 2^19th modulo mod0 + +#define mod1 1790967809L +#define s1 1110378081 //2^19th root of unity modulo mod1 + +ll power_of_s0[25]; +ll power_of_s1[25]; + +ll M; + +int flag ; + +void integral_fft_constant() +{ + power_of_s0[0] = s0; + power_of_s1[0] = s1; + for(int i=1;i<24;i++) power_of_s0[i] = ((ll)power_of_s0[i-1]*(ll)power_of_s0[i-1])%mod0; + for(int i=1;i<24;i++) power_of_s1[i] = ((ll)power_of_s1[i-1]*(ll)power_of_s1[i-1])%mod1; +} + +ll powmod(ll a,ll b,ll m) +{ + ll ans = 1%m; + while(b){ + if(b&1){ + ans = ( (ll)ans*(ll)a )%m; + b--; + } + else{ + a = ( (ll)a*(ll)a )%m; + b>>=1; + } + } + return ans; +} +void integral_fft(ll input[],ll output[] ,int skip ,int size ,int iteration) +{ + if(size==1){ + output[0] = input[0]; + return ; + } + integral_fft(input,output,skip*2,size/2,iteration+1); + integral_fft(input+skip , output+size/2 , skip*2 , size/2 ,iteration+1); + ll var1 , var2= 1,odd,even,store; + //var1 is sizeth root of unity. + if ( flag == 0) var1 = power_of_s0[iteration]; + else var1 = power_of_s1[iteration]; + for(int k=0;k=0;i--) A[i] = (A[i+1]*(N-1-i))%M; + B[0]= 1; + for(int i=1;i m ) ans -= m ; + b--; + } + else{ + a = a+ a; + if ( a> m) a-= m; + b>>=1; + } + } + return ans; +} + +ll CRT(ll rem[] , ll mod[],int t) //t is the number of pairs of rem and mod +{ + ll M1=1 ; + for(int i=0;i A,B; + scanf(""%d"",&n); + for(int i=0;i 1: + j = h + i >> 1 + if A[j] <= M: + h = j + else: + i = j + + # at this point, A[i-1] <= M < A[i] + print S[i] * perms * inv[N-i+1] % P +``` +",not-set,2016-04-24T02:02:52,2016-07-23T18:42:22,Python +134,2324,akhil-and-gf,Akhil and GF,"After dating for a long time, Akhil is finally going to propose to his girlfriend. She is very strong in mathematics, and will accept his proposal, if and only if Akhil solves a problem given by her. The problem is given below. Help Akhil solve it. + +Akhil is given two numbers N and M, and he has to tell her the remainder when $111\cdots \text{(N times)}$ is divided by $M$. + +**Input Format** +The first line contains an integer $T$ i.e. the number of test cases. +Each of the next $T$ lines contain two space separated integers, $N$ and $M$. + +**Output Format** +$T$ lines each containing ouptut for the corresponding test case. + +**Constraints** +$1 \le T \le 10001$ +$1 \le N \le 10^{16}$ +$2 \le M \le 10^9$ + +**Sample Input 00** + + 3 + 3 3 + 4 7 + 5 18 + +**Sample Output 00** + + 0 + 5 + 5 + +**Explanation** + + 111 % 3 = 0 + 1111 % 7 = 5 + 11111%18 = 5 ",code,Help Akhil in impressing his girlfriend,ai,2014-04-08T07:07:53,2022-09-02T09:54:30,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. LONG_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() +","After dating for a long time, Akhil is finally going to propose to his girlfriend. She is very strong in mathematics, and will accept his proposal, if and only if Akhil solves a problem given by her. The problem is given below. Help Akhil solve it. + +Akhil is given two numbers N and M, and he has to tell her the remainder when $111\cdots \text{(N times)}$ is divided by $M$. + +**Input Format** +The first line contains an integer $T$ i.e. the number of test cases. +Each of the next $T$ lines contain two space separated integers, $N$ and $M$. + +**Output Format** +$T$ lines each containing ouptut for the corresponding test case. + +**Constraints** +$1 \le T \le 10001$ +$1 \le N \le 10^{16}$ +$2 \le M \le 10^9$ + +**Sample Input 00** + + 3 + 3 3 + 4 7 + 5 18 + +**Sample Output 00** + + 0 + 5 + 5 + +**Explanation** + + 111 % 3 = 0 + 1111 % 7 = 5 + 11111%18 = 5 ",0.4939759036144578,"[""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,,,,,,,2014-07-29T10:04:09,2016-12-01T20:29:14,setter,"###C++ +```cpp +#include + +using namespace std; + +long long int power(long long int a, long long int b, long long int c) +{ + if(b==0) + return 1; + if(b==1) + return a%c; + if(b%2 == 0) + { + long long int temp = power(a,b/2,c); + return (temp*temp)%c; + } + else + { + long long int temp = power(a,b/2,c); + temp = (temp*temp)%c; + return (temp*a)%c; + } +} + +long long int func(long long int n, long long int m) +{ + if(n< 6) + { + if(n==0) + return 0; + if(n==1) + return 1; + if(n==2) + return 11%m; + if(n==3) + return 111%m; + if(n==4) + return 1111%m; + if(n==5) + return 11111%m; + } + if(n%2 == 0) + { + long long int temp = func(n/2 , m)%m; + long long int temp1 = (power(10,n/2,m)*temp + temp)%m; + return temp1; + } + else + { + long long int temp = func(n/2 , m)%m; + long long int temp1 = (power(10,n/2+1,m)*temp + temp*10 + 1)%m; + return temp1; + } +} + +int main() +{ + int t; + cin>>t; + while(t--) + { + long long int n,m; + cin>>n>>m; + assert(n > 0); + assert(m > 0); + cout< +#include +#include +#include +using namespace std; +#define PB push_back +const double PI = 4*atan(1); +typedef complex base; +vector omega; +long long FFT_N,mod=100003; +void init_fft(long long n) +{ + FFT_N = n; + omega.resize(n); + double angle = 2 * PI / n; + for(int i = 0; i < n; i++) + omega[i] = base( cos(i * angle), sin(i * angle)); +} +void fft (vector & a) +{ + long long n = (long long) a.size(); + if (n == 1) return; + long long half = n >> 1; + vector even (half), odd (half); + for (int i=0, j=0; i & a, const vector & b, vector & res) +{ + vector fa (a.begin(), a.end()), fb (b.begin(), b.end()); + long long n = 1; + while (n < 2*max (a.size(), b.size())) n <<= 1; + fa.resize (n), fb.resize (n); + + init_fft(n); + fft (fa), fft (fb); + for (size_t i=0; i inp,res; + vector > calc[20]; + cin>>n; + p=0;l=n; + for(i=0;i>x; + inp.PB(1); + inp.PB(x); + calc[0].PB(inp); + } + while(l>1) + { + p++; + for(i=0;i>q; + while(q--) + { + cin>>k; + cout< +#include +#include +#include +#define fo(i,a,b) dfo(int,i,a,b) +#define fr(i,n) dfr(int,i,n) +#define fe(i,a,b) dfe(int,i,a,b) +#define fq(i,n) dfq(int,i,n) +#define nfo(i,a,b) dfo(,i,a,b) +#define nfr(i,n) dfr(,i,n) +#define nfe(i,a,b) dfe(,i,a,b) +#define nfq(i,n) dfq(,i,n) +#define dfo(d,i,a,b) for (d i = (a); i < (b); i++) +#define dfr(d,i,n) dfo(d,i,0,n) +#define dfe(d,i,a,b) for (d i = (a); i <= (b); i++) +#define dfq(d,i,n) dfe(d,i,1,n) +#define ffo(i,a,b) dffo(int,i,a,b) +#define ffr(i,n) dffr(int,i,n) +#define ffe(i,a,b) dffe(int,i,a,b) +#define ffq(i,n) dffq(int,i,n) +#define nffo(i,a,b) dffo(,i,a,b) +#define nffr(i,n) dffr(,i,n) +#define nffe(i,a,b) dffe(,i,a,b) +#define nffq(i,n) dffq(,i,n) +#define dffo(d,i,a,b) for (d i = (b)-1; i >= (a); i--) +#define dffr(d,i,n) dffo(d,i,0,n) +#define dffe(d,i,a,b) for (d i = (b); i >= (a); i--) +#define dffq(d,i,n) dffe(d,i,1,n) +#define ll long long +#define alok(n,t) ((t*)malloc((n)*sizeof(t))) +#define pf printf +#define sf scanf +#define pln pf(""\n"") + +#define mod 100003 + +#define MOD0 1484783617LL +#define ROOT0 270076864LL + +#define MOD1 1572864001LL +#define ROOT1 682289494LL + +#define IMOD0MOD1 898779447LL +#define IMOD1MOD0 636335819LL + +#define SH 22 + +ll ROOTS0[SH+1]; +ll ROOTS1[SH+1]; +ll IROOTS0[SH+1]; +ll IROOTS1[SH+1]; + +ll *A = alok(811111, ll); +ll *B = alok(811111, ll); +ll *C0 = alok(811111, ll); +ll *C1 = alok(811111, ll); + +void fft(ll *A, int m, int ms, ll *rs, int MOD) { + if (!ms) return; + for (int k = 0; k < m; k++) C1[k] = A[k]; + int cc = 0; + for (int k = 0; k < m; k += 2) A[cc++] = C1[k]; + for (int k = 1; k < m; k += 2) A[cc++] = C1[k]; + m >>= 1; + ll r = rs[ms--]; + fft(A ,m,ms,rs,MOD); + fft(A+m,m,ms,rs,MOD); + ll pr = 1; + for (int k = 0, km = m; k < m; k++, km++) { + ll fE = A[k], fO = A[km]*pr; + A[k ] = (fE + fO) % MOD; + A[km] = (fE - fO) % MOD; + pr = pr * r % MOD; + } +} + +ll x, y; +void egcd(ll a, ll b) { + if (!b) { + x = 1; + y = 0; + } else { + egcd(b, a % b); + ll t = x - (a / b) * y; + x = y; + y = t; + } +} +ll inv(ll a, ll n) { + egcd(a, n); + return x % n; +} + +#define chinese(a1,m1,a2,m2) ((a1 * I##m2##m1 % m1 * m2 + a2 * I##m1##m2 % m2 * m1) % (m1 * m2)) + +#define mulp(res,rc,C,MOD,ROOTS,IROOTS) do {\ + fft(A,res,rc,ROOTS,MOD);\ + fft(B,res,rc,ROOTS,MOD);\ + fr(i,res) A[i] = A[i] * B[i] % MOD;\ + fft(A,res,rc,IROOTS,MOD);\ + ll iv = inv(res,MOD);\ + fr(i,res) C[i] = A[i] * iv % MOD;\ +} while (0) + +int res; +ll *mul(ll *A_, int m, ll *B_, int n) { + if (m <= 20000 / n) { + res = m + n - 1; + ll *C = alok(res, ll); + fr(i,res) C[i] = 0; + fr(i,m) fr(j,n) C[i + j] = (C[i + j] + A_[i] * B_[j]) % mod; + return C; + } else { + res = m + n + 2; + res |= res >> 1; + res |= res >> 2; + res |= res >> 4; + res |= res >> 8; + res |= res >> 16; + res ^= res >> 1; + res <<= 1; + int rc = 0; + while (1 << rc != res) rc++; + fr(i,res) A[i] = B[i] = 0; + fr(i,m) A[i] = A_[i]; + fr(i,n) B[i] = B_[i]; + mulp(res, rc, C0, MOD0, ROOTS0, IROOTS0); + fr(i,res) A[i] = B[i] = 0; + fr(i,m) A[i] = A_[i]; + fr(i,n) B[i] = B_[i]; + mulp(res, rc, C1, MOD1, ROOTS1, IROOTS1); + res = m + n - 1; + ll *C = alok(res, ll); + fr(i,res) { + ll t = chinese(C0[i],MOD0,C1[i],MOD1); + if (t < 0) t += MOD0*MOD1; + C[i] = t % mod; + } + return C; + } +} +ll *V = alok(111111, ll); +ll *get(int i, int j) { + if (j - i == 1) { + res = 2; + ll *t = alok(2, ll); + t[0] = V[i]; + t[1] = 1; + return t; + } + int k = i + j >> 1; + ll *A = get(i,k); + int m = res; + ll *B = get(k,j); + int n = res; + return mul(A, m, B, n); +} +int main() { + ROOTS0[SH] = ROOT0; + ROOTS1[SH] = ROOT1; + IROOTS0[SH] = inv(ROOT0,MOD0); + IROOTS1[SH] = inv(ROOT1,MOD1); + ffr(i,SH) { + ROOTS0[i] = ROOTS0[i+1] * ROOTS0[i+1] % MOD0; + ROOTS1[i] = ROOTS1[i+1] * ROOTS1[i+1] % MOD1; + IROOTS0[i] = IROOTS0[i+1] * IROOTS0[i+1] % MOD0; + IROOTS1[i] = IROOTS1[i+1] * IROOTS1[i+1] % MOD1; + } + int n; + sf(""%d"", &n); + fr(i,n) sf(""%lld"", V + i); + ll *W = get(0,n); + int q; + sf(""%d"", &q); + while (q--) { + int k; + sf(""%d"", &k); + ll s = W[n-k] % mod; + if (s < 0) s += mod; + pf(""%lld\n"", s); + } +} +``` +",not-set,2016-04-24T02:02:53,2016-07-23T18:59:58,C++ +137,3436,the-lovers,The Lovers,"**Description:** + +Once upon a time there was a man who had multiple girlfriends. Each girl thought she was the only one in the man's heart but this was not true. He was cheating concurrently on all of them. + +There are **N** houses lined up in the town. Each house has exactly one of his girlfriends living there. + +One day he wanted to visit **K** of his girlfriends but he then realized that he couldn't visit two consecutive houses. It would be too dangerous. + +How many different ways did the man have for visiting his girlfriends? The ordering of houses does not matter. i.e, how many different combinations of houses could the man consider. + + +**Input Format** + +The first line contains an integer **T** - this is the number of test cases. +Next follow **T** lines, each containing two space separated integers, **N** and **K**. + +**Constraints** + + + 1 <= T <= 10 + 1 <= N <= 10^15 + 1 <= K <= 10^15 + + + +**Output format** + +The output must contain **T** lines, each containing **one** integer - which is the number of ways the man can visit his girlfriends. Output the answer **modulo 100003**. + + +**Sample input** + + 4 + 7 3 + 8 5 + 10 5 + 100000 555 + + +**Sample output** + + 10 + 0 + 6 + 14258 + +**Hint** + +For example, in the first test case, there are 7 houses, and the lover will visit 3 of them without visiting two in consecutive positions. The 10 ways are these: + + X0X0X00 + X0X00X0 + X0X000X + X00X0X0 + X00X00X + X000X0X + 0X0X0X0 + 0X0X00X + 0X00X0X + 00X0X0X",code,Count the ways in which a lover may visit his girlfriends. ,ai,2014-08-01T00:08:23,2019-07-02T13:58:45,,,,"**Description:** + +Once upon a time there was a man who had multiple girlfriends. Each girl thought she was the only one in the man's heart but this was not true. He was cheating on all of them. + +**N** houses were situated in a row and each house had exactly one of his girlfriends living there. + +One day he wanted to visit **K** of his girlfriends but he then realized that he couldn't visit two consecutive houses. That would be too dangerous. + +How many different ways did the man have for visiting his girlfriends? + +The ordering of houses does not matter. i.e, how many different combinations of houses could the man consider. + + +**Input Format** + +The first line contains an integer **T** - the number of test cases. +Next follow **T** lines, each containing two space separated integers, **N** and **K**. + +**Constraints** + + + 1 <= T <= 10 + 1 <= N <= 10^15 + 1 <= K <= 10^15 + + + +**Output format** + +The output must contain **T** lines, each containing **one** integer - the number of ways the man can visit his girlfriends. Output the answer **modulo 100003**. + + +**Sample input** + + 4 + 7 3 + 8 5 + 10 5 + 100000 555 + + +**Sample output** + + 10 + 0 + 6 + 14258 + +**Hint** + +For example, in the first test case, there are 7 houses, and the lover will visit 3 of them without visiting two in consecutive positions. The 10 ways are these: + + X0X0X00 + X0X00X0 + X0X000X + X00X0X0 + X00X00X + X000X0X + 0X0X0X0 + 0X0X00X + 0X00X0X + 00X0X0X",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-01T00:08:47,2016-05-12T23:59:12,setter," import java.io.BufferedReader; + import java.io.IOException; + import java.io.InputStreamReader; + + + public class Main { + static int T; + static long N, K; + static long MOD = 100003; + static long factorial[]; + + public static long POW(long a, long b){ + if(b == 0) return 1; + if(b == 1) return a % MOD; + if(b % 2 == 1) return ((a%MOD) * POW(a, b-1)) % MOD; + long k = POW(a, b/2); + return (k*k)%MOD; + } + + public static long binomial(int n, int k) { + if( n < k) return 0; + long up = factorial[n]; + long down = (factorial[n - k] * factorial[k]) % MOD; + long inv = POW(down, MOD - 2); + return (up * inv) % MOD; + } + + public static long lucas(long n, long k) { + return ( binomial((int) (n/MOD/MOD%MOD),(int) (k/MOD/MOD%MOD)) * binomial((int) (n/MOD%MOD),(int) (k/MOD%MOD)) * binomial((int) (n%MOD),(int) (k%MOD)) ) % MOD; + } + + public static void main(String[] args) throws NumberFormatException, IOException { + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + T = Integer.parseInt(br.readLine()); + String cad[]; + + factorial = new long[100015]; + factorial[0] = 1; + factorial[1] = 1; + + for (int i = 2; i < 100010; i++) + factorial[i] = (((long) i) * factorial[i-1]) % MOD; + + + while(T--> 0) { + cad = br.readLine().split("" ""); + N = Long.parseLong(cad[0]); + K = Long.parseLong(cad[1]); + + if(N - K + 1 < K) System.out.println(0); else + System.out.println(lucas(N - K + 1, K)); + } + } + +}",not-set,2016-04-24T02:02:53,2016-04-24T02:02:53,Python +138,3437,training-the-army,Training the army,"In the magical kingdom of Kasukabe, people strive to possess only one skillset. Higher the number of skillset present among the people, the more content people will be. + + +There are $N$ types of skill set present and initially there exists $C_i$ people possessing $i^{th}$ skill set, where $i \in [1, N]$. + +There are $T$ wizards in the kingdom and they have the ability to transform the skill set of a person into another skill set. Each of the these wizards has two list of skill sets associated with them, $A$ and $B$. He can only transform the skill set of person whose initial skill set lies in list $A$ and that final skill set will be an element of list $B$. That is, if $A = [2, 3, 6]$ and $B = [1, 2]$ then following transformation can be done by that trainer. + +$$\begin{align*} +2 \rightarrow 1\\\ +2 \rightarrow 2\\\ +3 \rightarrow 1\\\ +3 \rightarrow 2\\\ +6 \rightarrow 1\\\ +6 \rightarrow 2\\\ +\end{align*}$$ + +Once a transformation is done, both skill is removed from the respective lists. In the above example, if he perform $3 \rightarrow 1$ transformation on a person, list $A$ will be updated to $[2, 6]$ and list $B$ will be $[2]$. This updated list will be used for next transformation and so on. + +Few points to note are: + +- A wizard can perform 0 or more transformation as long as they satisfies the above criteria. +- A person can go through multiple transformation of skill set. +- Same class transformation is also possible. That is a person' skill set can be transformed into his current skill set. Eg. $2 \rightarrow 2$ in the above example. + +Your goal is to design a series of transformation which results into maximum number of skill set with non-zero acquaintance. + +**Input Format** +The first line contains two numbers, $N\ T$, where $N$ represent the number of skill set and $T$ represent the number of wizards. +Next line contains $N$ space separated integers, $C_1\ C_2\ \ldots\ C_N$, where $C_i$ represents the number of people with $i^{th}$ skill. +Then follows $2 \times T$ lines, where each pair of line represent the configuration of each wizard. +First line of the pair will start with the length of list $A$ and followed by list $A$ in the same line. Similarly second line of the pair starts with the length of list $B$ and then the list $B$. + +**Output Format** +The output must consist of one number, the maximum number of distinct skill set that can the people of country learn, after making optimal transformation steps. + +**Constraints** +$1 \le N \le 200$ +$0 \le T \le 30$ +$0 \le C_i \le 10$ +$0 \le |A| \le 50$ +$1 \le A_i \le N$ +$A_i \ne A_j, 1 \le i < j \le |A|$ +$0 \le |B| \le 50$ +$1 \le B_i \le N$ +$B_i \ne B_j, 1 \le i < j \le |B|$ + + +**Sample Input** + + 3 1 + 3 0 0 + 1 1 + 2 2 3 + +**Sample Output** + + 2 + +**Explanation** +There are 3 types of skill set present and only 1 wizard. +Initially all three people know $1^{st}$ skill set, while no one knows $2^{nd}\ and\ 3^{rd}$ skill set. +First, and only, wizard' initial list are: $A = [1]\ and\ B = [2, 3]$. So he can perform any of the $1 \rightarrow 2\ or\ 1 \rightarrow 3$ transformation. Suppose he go for $1 \rightarrow 2$ transformation on any of person with $1^{st}$ skill set, then list $A$ will be updated to an empty list $[]$ and and list $B$ will be $[3]$. Now he can't perform another transformation as list $A$ is empty. So there will be two people with $1^{st}$ skill set, and 1 people with $2^{nd}$ skill set. So there are two skill sets available in the kingdom.",code,Design a series of transformation which results into maximum number of skill set with non-zero acquaintance.,ai,2014-08-01T00:35:38,2022-09-02T10:10:38,,,,"In the magical kingdom of Kasukabe, people strive to possess skillsets. Higher the number of skillset present among the people, the more content people will be. + + +There are $N$ types of skill set present and initially there exists $C_i$ people possessing $i^{th}$ skill set, where $i \in [1, N]$. + +There are $T$ wizards in the kingdom and they have the ability to transform the skill set of a person into another skill set. Each of the these wizards has two **lists** of skill sets associated with them, $A$ and $B$. He can only transform the skill set of person whose initial skill set belongs to the list $A$ to one of the final skill set which belongs to the list $B$. That is, if $A = [2, 3, 6]$ and $B = [1, 2]$ then following transformation can be done by that trainer. + +$$\begin{align*} +2 \rightarrow 1\\\ +2 \rightarrow 2\\\ +3 \rightarrow 1\\\ +3 \rightarrow 2\\\ +6 \rightarrow 1\\\ +6 \rightarrow 2\\\ +\end{align*}$$ + +Once a transformation is done, both skill is removed from the respective lists. In the above example, if he perform $3 \rightarrow 1$ transformation on a person, list $A$ will be updated to $[2, 6]$ and list $B$ will be $[2]$. This updated list will be used for further transformations. + +Few points to note are: + +- One person can possess only one skill set. +- A wizard can perform zero or more transformation as long as they satisfies the above criteria. +- A person can go through multiple transformation of skill set. +- Same class transformation is also possible. That is a person' skill set can be transformed into his current skill set. Eg. $2 \rightarrow 2$ in the above example. + +Your goal is to design a series of transformation which results into maximum number of skill set with non-zero number of people knowing it.",0.5454545454545454,"[""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"",""visualbasic"",""whitespace"",""typescript""]","The first line contains two numbers, $N\ T$, where $N$ represent the number of skill set and $T$ represent the number of wizards. +Next line contains $N$ space separated integers, $C_1\ C_2\ \ldots\ C_N$, where $C_i$ represents the number of people with $i^{th}$ skill. +Then follows $2 \times T$ lines, where each pair of line represent the configuration of each wizard. +First line of the pair will start with the length of list $A$ and followed by list $A$ in the same line. Similarly second line of the pair starts with the length of list $B$ and then the list $B$. ","The output must consist of one number, the maximum number of distinct skill set that can the people of country learn, after making optimal transformation steps."," 3 3 + 3 0 0 + 1 1 + 2 2 3 + 1 2 + 1 3 + 1 1 + 1 2 ", 2 ,Hard,,,,,,,2014-08-01T00:35:56,2016-07-23T14:07:35,setter,"###C++ +```cpp +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +using namespace std; +const int MAXA = 400005; +const int MAXV = 1005; + +int A,V,source,dest,id,oo = 1000000001; +int cap[MAXA],flow[MAXA],ady[MAXA],next[MAXA],last[MAXV]; +int now[MAXA],level[MAXV],Q[MAXV]; + +void ADD(int u,int v,int c) +{ + cap[A] = c;flow[A] = 0;ady[A] = v;next[A]=last[u];last[u]=A++; + cap[A] = 0;flow[A] = 0;ady[A] = u;next[A]=last[v];last[v]=A++; +} + +bool BFS(int fuente,int dest) +{ + int ini,end,u,v; + memset(level,-1,sizeof(level)); + + ini = end = level[fuente] = 0; + Q[end++] = source; + + while(inilevel[u] && flow[i] < cap[i]) + { + res = DFS(v, min(auxflow,cap[i]-flow[i])); + if(res>0) + { + flow[i]+=res; + flow[i^1]-=res; + return res; + } + } + } + return 0; +} + + +long long Dinic() +{ + register long long flow = 0; + register long long aum; + + while(BFS(source,dest)) + { + for(int i=0;i<=V;i++) now[i] = last[i]; + while((aum = DFS(source,oo))>0) flow+=aum; + } + return flow; +} + +int n, m, v, cc; +int main() { + memset(last,-1,sizeof(last)); + scanf(""%d%d"", &n, &m); + + assert(n >= 1 && n <= 200 && m >= 0 && m <= 30); + + source = 0; + dest = n + m + 1; + V = dest; + + for(int i = 1;i<=n;i++) { + scanf(""%d"", &v); + assert(v >= 0 && v <= 10); + if(v) + ADD(source, i, v); + ADD(i, dest, 1); + } + + for(int i = 1;i<=m;i++) { + scanf(""%d"", &cc); + assert(cc >= 0 && cc <= 50); + for(int j = 0;j= 1 && v <= n); + ADD(v, n + i, 1); + } + + scanf(""%d"", &cc); + assert(cc >= 0 && cc <= 50); + for(int j = 0;j= 1 && v <= n); + ADD(n + i, v, 1); + } + } + + printf(""%lld\n"", Dinic()); +} +``` +",not-set,2016-04-24T02:02:53,2016-07-23T14:07:35,C++ +139,3465,gdragon,Goku and Dragon Balls,"Goku was finally successful in collecting all the Dragon Balls (total n of them), each having a unique color. Now for becoming super-powerful, he has to put the Dragon Balls in the holy temple, such that each ball is placed in the room which does NOT have the same color as that particular Dragon Ball. The temple, also has n unique rooms, each having same colors as the Dragon Balls which Goku collected. +
He is wondering how many possible ways there are to place the balls in such a manner. Since Goku is tired after collecting all the Dragon Balls, help him calculate the number of ways. As he is tired, he cannot comprehend large numbers, so tell him the answer modulo (10^9 + 7). + +###Input: +First line will contain a single integer T, which denotes the number of test cases. The T test cases will then follow. Each test case contains a single integer n, which denotes the number of Dragon Balls that Goku collected as well as the number of rooms in the temple. +
0 < T <= 10^6 +
0 <= n <= 10^7 + +###Output: +For each test case, print number of ways to place the Dragon Balls such that each one is placed in the room that does NOT have same color as itself (print the answer modulo 10^9 + 7). + +###Sample Input: +2 +
2 +
1 + +###Sample Output: +1 +
0 + +###Explanation: +For the first case, assume the two colors are R and B. There is exactly one way to do , place R in B colored room and vice versa. +
For the second case, there is no way Goku can satisfy the condition. No superpower for Goku. :(",code,,ai,2014-08-02T05:17:43,2016-09-09T09:48:54,,,,"Goku was finally successful in collecting all the Dragon Balls (total n of them), each having a unique color. Now for becoming super-powerful, he has to put the Dragon Balls in the holy temple, such that each ball is placed in the room which does NOT have the same color as that particular Dragon Ball. The temple, also has n unique rooms, each having same colors as the Dragon Balls which Goku collected. +
He is wondering how many possible ways there are to place the balls in such a manner. Since Goku is tired after collecting all the Dragon Balls, help him calculate the number of ways. As he is tired, he cannot comprehend large numbers, so tell him the answer modulo (10^9 + 7). + +###Input: +First line will contain a single integer T, which denotes the number of test cases. The T test cases will then follow. Each test case contains a single integer n, which denotes the number of Dragon Balls that Goku collected as well as the number of rooms in the temple. +
0 < T <= 10^6 +
0 <= n <= 10^7 + +###Output: +For each test case, print number of ways to place the Dragon Balls such that each one is placed in the room that does NOT have same color as itself (print the answer modulo 10^9 + 7). + +###Sample Input: +2 +
2 +
1 + +###Sample Output: +1 +
0 + +###Explanation: +For the first case, assume the two colors are R and B. There is exactly one way to do , place R in B colored room and vice versa. +
For the second case, there is no way Goku can satisfy the condition. No superpower for Goku. :(",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-02T05:19:44,2016-12-22T22:43:16,setter," #include + #define mod 1000000007 + using namespace std; + long long int arr[10000008]; + + int main () + { + arr[0] = 1; + arr[1] = 0; + for (int i = 2; i <= 10000000; i++) + arr[i] = ( (i-1) * (( arr[i-1] + arr[i-2] ) % mod) ) % mod; + int cases, n; + scanf(""%d"", &cases); + while(cases--) + { + scanf(""%d"", &n); + printf(""%lld\n"", arr[n]); + } + return 0; + }",not-set,2016-04-24T02:02:54,2016-04-24T02:02:54,C++ +140,3511,the-frustrated-sam,The Frustrated Sam,"This is placement season. _Sam_ got frustated because of his batch mates. They all have a good OGPA. Odds are not in favor of _Sam_. But _Sam_ have a cool idea of project that will get him into any dream company. Project is calculation of frustration among engineers. So after a lot of research he formulated measure of frustration as follows: + +$\ \ \ \ A(n) = a_{1} \cdot A(n - 1) + b_{1} \cdot B(n - 1) + c_{1}$ +$\ \ \ \ B(n) = a_{2} \cdot A(n - 1) + b_{2} \cdot B(n - 1) + c_{2}$ + +As value of $n$ will be larged please help _Sam_ to calculate $A(n)$ and $B(n)$ and get a good job. Given that $A(1) = 1$ and $B(1) = 2$. + +**INPUT** +First line will contain single integer $T$, number of test cases. +After that Each line will follow $7$ integers $a_{1}, b_{1}, c_{1}, a_{2}, b_{2}, c_{2}, n$ + +**OUTPUT** +For each testcase, print in a newline, two integers separated by single space i.e. value of $A(n)$ and $B(n)$. +As value of $A(n)$ and $B(n)$ can be really large, output them by taking modulo $1000000007$. + +**CONSTRAINTS** +$1 <= T <= 10^4$ +$1 <= a_{1}, b_{1}, c_{1}, a_{2}, b_{2}, c_{2} <= 10$ +$1 <= n <= 10^{12}$ + + +**Sample Input** + + 2 + 1 2 3 4 5 6 3 + 1 2 3 4 5 6 5 + +**Sample Output** + + 51 138 + 2133 5826 +",code,Do you know how to measure frustration? It is Sam's project.,ai,2014-08-07T17:53:54,2016-09-09T09:49:10,,,,"This is placement season. _Sam_ got frustated because of his batch mates. They all have a good OGPA. Odds are not in favor of _Sam_. But _Sam_ have a cool idea of project that will get him into any dream company. Project is calculation of frustration among engineers. So after a lot of research he formulated measure of frustration as follows: + +$\ \ \ \ A(n) = a_{1} \cdot A(n - 1) + b_{1} \cdot B(n - 1) + c_{1}$ +$\ \ \ \ B(n) = a_{2} \cdot A(n - 1) + b_{2} \cdot B(n - 1) + c_{2}$ + +As value of $n$ will be larged please help _Sam_ to calculate $A(n)$ and $B(n)$ and get a good job. Given that $A(1) = 1$ and $B(1) = 2$. + +**INPUT** +First line will contain single integer $T$, number of test cases. +After that Each line will follow $7$ integers $a_{1}, b_{1}, c_{1}, a_{2}, b_{2}, c_{2}, n$ + +**OUTPUT** +For each testcase, print in a newline, two integers separated by single space i.e. value of $A(n)$ and $B(n)$. +As value of $A(n)$ and $B(n)$ can be really large, output them by taking modulo $1000000007$. + +**CONSTRAINTS** +$1 <= T <= 10^4$ +$1 <= a_{1}, b_{1}, c_{1}, a_{2}, b_{2}, c_{2} <= 10$ +$1 <= n <= 10^{12}$ + + +**Sample Input** + + 2 + 1 2 3 4 5 6 3 + 1 2 3 4 5 6 5 + +**Sample Output** + + 51 138 + 2133 5826 +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-07T17:54:20,2016-05-12T23:58:57,setter," import java.io.*; + import java.util.StringTokenizer; + + class Matrix { + + public static long mod = 1000000007; + public final long[][] data; + public final int rowCount; + public final int columnCount; + + public Matrix(int rowCount, int columnCount) { + this.rowCount = rowCount; + this.columnCount = columnCount; + this.data = new long[rowCount][columnCount]; + } + + public static Matrix multiply(Matrix first, Matrix second) { + Matrix result = new Matrix(first.rowCount, second.columnCount); + for (int i = 0; i < first.rowCount; i++) { + for (int j = 0; j < second.rowCount; j++) { + for (int k = 0; k < second.columnCount; k++) + result.data[i][k] = (result.data[i][k] + first.data[i][j] * second.data[j][k]) % mod; + } + } + return result; + } + + public static Matrix identityMatrix(int size) { + Matrix result = new Matrix(size, size); + for (int i = 0; i < size; i++) + result.data[i][i] = 1; + return result; + } + + public Matrix power(long exponent) { + if (exponent == 0) + return identityMatrix(rowCount); + if (exponent == 1) + return this; + Matrix result = power(exponent >> 1); + result = multiply(result, result); + if ((exponent & 1) == 1) + result = multiply(result, this); + return result; + } + + } + + public class Solution { + + static BufferedReader reader; + static StringTokenizer st; + static final long MOD = 1000000007; + static long[] memo; + + public static void main(String[] args) throws IOException { + reader = new BufferedReader(new InputStreamReader(System.in)); + int test = nextInt(); + while(test-- > 0) { + int a1 = nextInt(), b1 = nextInt(), c1 = nextInt(); + int a2 = nextInt(), b2 = nextInt(), c2 = nextInt(); + long N = nextLong(); + Matrix offset = new Matrix(3, 3); + offset.data[0][0] = a1; offset.data[0][1] = b1; offset.data[0][2] = c1; + offset.data[1][0] = a2; offset.data[1][1] = b2; offset.data[1][2] = c2; + offset.data[2][0] = 0; offset.data[2][1] = 0; offset.data[2][2] = 1; + offset = offset.power(N - 1); + long A = ( offset.data[0][0] * 1 + offset.data[0][1] * 2 + offset.data[0][2] * 1) % MOD; + long B = ( offset.data[1][0] * 1 + offset.data[1][1] * 2 + offset.data[1][2] * 1) % MOD; + System.out.println(A + "" "" + B); + } + } + + public static long nextLong() throws IOException { + return Long.parseLong(next()); + } + + public static int nextInt() throws IOException { + return Integer.parseInt(next()); + } + + public static String next() throws IOException { + while(st == null || !st.hasMoreTokens()) + st = new StringTokenizer(reader.readLine()); + return st.nextToken(); + } + + }",not-set,2016-04-24T02:02:55,2016-04-24T02:02:55,Python +141,3542,geek-concert,Geek concert,"The big country Geeko where every person is known as geek-ian, is organising a concert of geeks. The arrangements are all set for the concert. All **N** geek-ians are waiting in line to enter the concert. Geek-ians get bored waiting so they turn and look for someone familiar in the line. + +Two geek-ians P and Q standing in line can see each other if they're standing right next to each other or if **no geek-ian between them is strictly taller** than geek-ian P or geek-ian Q. +So till the entrance is not allowed into the concert, you should determine the number of pairs of geek-ians that can see each other. + +**Input Format** + +The first line of input contains an integer N, the number of geek-ians standing in line. Next line will contains N integers, the height of each geek-ian in nanometres. Everyone will be shorter than 2^31 nanometres. The heights are given in the order in which geek-ians are standing in line. + +**Output Format** + +Output the number of pairs of geek-ians that can see each other on a single line. + +**Constraints** + + 1 ≤ N ≤ 500 000 + +**Sample Input** + + + 7 + 2 4 1 2 2 5 1 + + +**Sample Output** + + + 10 + ",code,,ai,2014-08-10T08:21:34,2016-09-09T09:49:21,,,,"The big country Geeko where every person is known as geek-ian, is organising a concert of geeks. The arrangements are all set for the concert. All **N** geek-ians are waiting in line to enter the concert. Geek-ians get bored waiting so they turn and look for someone familiar in the line. + +Two geek-ians P and Q standing in line can see each other if they're standing right next to each other or if **no geek-ian between them is strictly taller** than geek-ian P or geek-ian Q. +So till the entrance is not allowed into the concert, you should determine the number of pairs of geek-ians that can see each other. + +**Input Format** + +The first line of input contains an integer N, the number of geek-ians standing in line. Next line will contains N integers, the height of each geek-ian in nanometres. Everyone will be shorter than 2^31 nanometres. The heights are given in the order in which geek-ians are standing in line. + +**Output Format** + +Output the number of pairs of geek-ians that can see each other on a single line. + +**Constraints** + + 1 ≤ N ≤ 500 000 + +**Sample Input** + + + 7 + 2 4 1 2 2 5 1 + + +**Sample Output** + + + 10 + ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-10T08:36:09,2016-05-12T23:58:51,setter," + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #define si(n) scanf(""%d"",&n) + #define sll(n) scanf(""%lld"",&n) + #define mod 1000000007 // 10**9 + 7 + #define INF 1e9 + #define FOR(i,a,b) for(int (i) = (a); (i) < (b); ++(i)) + #define RFOR(i,a,b) for(int (i) = (a)-1; (i) >= (b); --(i)) + #define CLEAR(a) memset((a),0,sizeof(a)) + #define mp(a, b) make_pair(a, b) + #define pb(a) push_back(a) + #define rep(i, a, b) for (int i = a; i < b; i++) + #define rrep(i, b, a) for (int i = b; i > a; i--) + #define all(v) v.begin(), v.end() + #define GETCHAR getchar_unlocked + #define pi(n) printf(""%d\n"",n) + #define pll(n) printf(""%lld\n"",n) + #define rk() int t; scanf(""%d"",&t); while(t--) + using namespace std; + const double pi = acos(-1.0); + //freopen(""in"",""r"",stdin); + //freopen(""out"",""w"",stdout); + + const int er[8] = {-1,-1,0,1,1,1,0,-1}; + const int ec[8] = {0,1,1,1,0,-1,-1,-1}; + const int fr[4] = {-1,1,0,0}; + const int fc[4] = {0,0,1,-1}; + typedef unsigned long long ull; + typedef long long ll; + typedef long l; + typedef pair pii; + typedef vector vec; + typedef vector vpii; + ll po(ll a,ll p) + {ll ret = 1;while(p){if(p&1)ret = (ret*a)%mod;a=(a*a)%mod;p=p>>1;}return ret%mod;} + + stackS; + int main(){ + int n; + scanf(""%d"",&n); + + ll ret = 0; + for(int i=0;i + +Given the value of $N$ and a function $\scriptsize {\text{rand}()} $ which uniformly produces a value between $0$ and $N-1$, let's define +$$ +\scriptsize{ +f(N) = \sqrt{1 + \text{rand}() \% N + { \sqrt{ 1 + \text{rand}() \% N + { \sqrt { 1 + \text{rand}() \% N + \sqrt { 1 + \text{rand}() \% N + \cdots }}}} }} +}$$ + +Find out the expected value of $f(N)$. + +**Input Format** +The first line contains an integer $T$ i.e. the number of test cases.
+Next $T$ lines contain an integer $N$.
+ +**Output Format** +Print output corresponding to each test case in seperate line correct upto 5 decimal place. + +**Constraints** + +$ 1\le T \le 100$ +$ 1\le N \le 10^{4}$ + +OR + +$ 1\le T \le 10$ +$ 1\le N \le 5*10^{5}$ + + +**Sample Input** + + 3 + 1 + 5 + 10 + + +**Sample Output** + + 1.61803398875 + 2.27532378545 + 2.8422345835 + + +**Explanation** + +For the $N=1$, $F(N)$ can have only one value i.e. $\sqrt{1 + { \sqrt{ 1 + { \sqrt { 1 + \sqrt { 1 + \cdots }}}} }}$ which will be $1.61803398875$. +",code,Find Expected value of function,ai,2014-08-10T20:06:35,2019-07-02T13:58:46,,,,"When students solved the first problem quickly, Kevinsogo gave them a harder problem. Students need your help in solving this problem.
+ +Given the value of $N$ and a function $\scriptsize {\text{rand}()} $ which uniformly produces an integer value between $0$ and $N-1$, let's define +$$ +\scriptsize{ +f(N) = \sqrt{1 + \text{rand}() + { \sqrt{ 1 + \text{rand}() + { \sqrt { 1 + \text{rand}() + \sqrt { 1 + \text{rand}() + \cdots }}}} }} +}$$ + +Find out the expected value of $f(N)$. + +**Input Format** +The first line contains an integer $T$ i.e. the number of test cases.
+Next $T$ lines contain an integer $N$.
+ +**Output Format** +Print output corresponding to each test case in seperate line correct to 5 decimal place. + +**Constraints** + +$ 1\le T \le 100$ +$ 1\le N \le 10^{4}$ + +OR + +$ 1\le T \le 10$ +$ 1\le N \le 5 \times 10^{5}$ + + +**Sample Input** + + 3 + 1 + 5 + 10 + + +**Sample Output** + + 1.61803398875 + 2.27532378545 + 2.8422345835 + + +**Explanation** + +For the $N=1$, $F(N)$ can have only one value i.e. $\sqrt{1 + { \sqrt{ 1 + { \sqrt { 1 + \sqrt { 1 + \cdots }}}} }}$ which will be $1.61803398875$. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-10T20:06:54,2016-05-12T23:58:49,tester," #include + #include + + int n,i,T; + double l,r,c,ans; + + int main() + { + scanf(""%d"",&T); + while(T--) + { + scanf(""%d"",&n); + l=0; + r=n*2; + while(r-l>1e-6) + { + c=(l+r)/2; + ans=0; + for(i=1;i<=n;i++) + ans+=c-sqrt(i+c); + if(ans>0) + r=c; + else + l=c; + } + printf(""%.5lf\n"",l); + } + return 0; + }",not-set,2016-04-24T02:02:55,2016-04-24T02:02:55,C++ +143,3547,mehta-and-his-laziness,Mehta and his Laziness,"Mehta is a very lazy boy. He always sleeps in Maths class. One day his teacher catches him sleeping and tells him that she would mark him absent for the whole semester. While she pretends to be strict, she is actually very kind-hearted. So she wants to give Mehta a chance to prove himself. She gives him a problem. If Mehta can answer it correctly, she will forgive him. Can you help Mehta find the answer to this problem? + +The problem: The teacher gives Mehta a number $N$ and asks him to find out the probability that any proper divisor of $N$ would be an even perfect square. + +**Note: Even perfect square means the number should be even and a perfect square.** + +**Input Format** +The first line of input contains an integer $T$, the number of test cases. +$T$ lines follow, each line containing $N$, the number that the teacher provides. + +**Output Format** +For each test case, print in a newline the output in $p/q$ format where $p$ and $q$ are positive coprime integers. +if $p$ is 0, you should simply output `0`. + +**Constraints** +$1 \le T \le 4 \times 10^4$ +$2 \le N \le 10^6$ + +**Sample Input** + + 4 + 2 + 8 + 36 + 900 + +**Sample Output** + + 0 + 1/3 + 1/8 + 3/26 + +**Explaination** +For the first case $N = 2$, the set of proper divisors is $\{1\}$. Since $1$ is not an even perfect square, the probability is $0$. +For the second case $N = 8$, the set of proper divisors is $\{1,2,4\}$ and only $4$ is an even perfect square among them, so probability = $1/3$. +For the third case $N = 36$, the set of proper divisors is $\{1,2,3,4,6,9,12,18\}$, and only $4$ is an even perfect square, so probability = $1/8$. +For the fourth case $N = 900$, there will be total of $26$ proper divisors and $3$ of them $\{4,36,100\}$ are even perfect squares. ",code,How will Mehta do these calculations?,ai,2014-08-11T10:38:55,2022-09-02T10:08:00,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING. +# The function accepts INTEGER n as parameter. +# + +def solve(n): + # 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): + n = int(input().strip()) + + result = solve(n) + + fptr.write(result + '\n') + + fptr.close() +","Mehta is a very lazy boy. He always sleeps in Maths class. One day his teacher catches him sleeping and tells him that she would mark him absent for the whole semester. While she pretends to be strict, she is actually very kind-hearted. So she wants to give Mehta a chance to prove himself. She gives him a problem. If Mehta can answer it correctly, she will forgive him. Can you help Mehta find the answer to this problem? + +The problem: The teacher gives Mehta a number $N$ and asks him to find out the probability that any proper divisor of $N$ would be an even perfect square. + +**Note: Even perfect square means the number should be even and a perfect square.** + +**Input Format** +The first line of input contains an integer $T$, the number of test cases. +$T$ lines follow, each line containing $N$, the number that the teacher provides. + +**Output Format** +For each test case, print in a newline the output in $p/q$ format where $p$ and $q$ are positive coprime integers. +if $p$ is 0, you should simply output `0`. + +**Constraints** +$1 \le T \le 4 \times 10^4$ +$2 \le N \le 10^6$ + +**Sample Input** + + 4 + 2 + 8 + 36 + 900 + +**Sample Output** + + 0 + 1/3 + 1/8 + 3/26 + +**Explaination** +For the first case $N = 2$, the set of proper divisors is $\{1\}$. Since $1$ is not an even perfect square, the probability is $0$. +For the second case $N = 8$, the set of proper divisors is $\{1,2,4\}$ and only $4$ is an even perfect square among them, so probability = $1/3$. +For the third case $N = 36$, the set of proper divisors is $\{1,2,3,4,6,9,12,18\}$, and only $4$ is an even perfect square, so probability = $1/8$. +For the fourth case $N = 900$, there will be total of $26$ proper divisors and $3$ of them $\{4,36,100\}$ are even perfect squares. ",0.4736842105263157,"[""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,,,,,,,2014-08-11T10:39:05,2016-12-06T10:15:06,setter,"###C++ +```cpp +#include + +using namespace std; + +pair A[1000005]; + +bool chk(int x) +{ + int p = (int)sqrt(x); + if ( p*p == x || (p-1)*(p-1) == x || (p+1)*(p+1) == x ) return true; + return false; +} + +void pre() +{ + for ( int i = 1; i <= 1000; i++ ) { + for ( int j = i; j <= 1000000; j += i ) { + A[j].second++; + if ( (i%2 == 0) && chk(i) ) A[j].first++; + if ( (j/i > 1000) && (i != j/i) ) { + A[j].second++; + if ( ((j/i)%2 == 0) && chk(j/i) ) A[j].first++; + } + } + } + for ( int i = 1; i <= 1000000; i++ ) { + A[i].second--; + if ( (i%2 == 0) && chk(i) ) A[i].first--; + } + return; +} + +int main() +{ + int t,x,val; + pre(); + scanf(""%d"",&t); + while ( t-- ) { + scanf(""%d"",&x); + if (A[x].first == 0 ) { + printf(""0\n""); + continue; + } + val = __gcd(A[x].first,A[x].second); + A[x].first /= val; + A[x].second /= val; + printf(""%d/%d\n"",A[x].first,A[x].second); + } + return 0; +} +``` +",not-set,2016-04-24T02:02:55,2016-07-23T17:39:08,C++ +144,3547,mehta-and-his-laziness,Mehta and his Laziness,"Mehta is a very lazy boy. He always sleeps in Maths class. One day his teacher catches him sleeping and tells him that she would mark him absent for the whole semester. While she pretends to be strict, she is actually very kind-hearted. So she wants to give Mehta a chance to prove himself. She gives him a problem. If Mehta can answer it correctly, she will forgive him. Can you help Mehta find the answer to this problem? + +The problem: The teacher gives Mehta a number $N$ and asks him to find out the probability that any proper divisor of $N$ would be an even perfect square. + +**Note: Even perfect square means the number should be even and a perfect square.** + +**Input Format** +The first line of input contains an integer $T$, the number of test cases. +$T$ lines follow, each line containing $N$, the number that the teacher provides. + +**Output Format** +For each test case, print in a newline the output in $p/q$ format where $p$ and $q$ are positive coprime integers. +if $p$ is 0, you should simply output `0`. + +**Constraints** +$1 \le T \le 4 \times 10^4$ +$2 \le N \le 10^6$ + +**Sample Input** + + 4 + 2 + 8 + 36 + 900 + +**Sample Output** + + 0 + 1/3 + 1/8 + 3/26 + +**Explaination** +For the first case $N = 2$, the set of proper divisors is $\{1\}$. Since $1$ is not an even perfect square, the probability is $0$. +For the second case $N = 8$, the set of proper divisors is $\{1,2,4\}$ and only $4$ is an even perfect square among them, so probability = $1/3$. +For the third case $N = 36$, the set of proper divisors is $\{1,2,3,4,6,9,12,18\}$, and only $4$ is an even perfect square, so probability = $1/8$. +For the fourth case $N = 900$, there will be total of $26$ proper divisors and $3$ of them $\{4,36,100\}$ are even perfect squares. ",code,How will Mehta do these calculations?,ai,2014-08-11T10:38:55,2022-09-02T10:08:00,"# +# Complete the 'solve' function below. +# +# The function is expected to return a STRING. +# The function accepts INTEGER n as parameter. +# + +def solve(n): + # 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): + n = int(input().strip()) + + result = solve(n) + + fptr.write(result + '\n') + + fptr.close() +","Mehta is a very lazy boy. He always sleeps in Maths class. One day his teacher catches him sleeping and tells him that she would mark him absent for the whole semester. While she pretends to be strict, she is actually very kind-hearted. So she wants to give Mehta a chance to prove himself. She gives him a problem. If Mehta can answer it correctly, she will forgive him. Can you help Mehta find the answer to this problem? + +The problem: The teacher gives Mehta a number $N$ and asks him to find out the probability that any proper divisor of $N$ would be an even perfect square. + +**Note: Even perfect square means the number should be even and a perfect square.** + +**Input Format** +The first line of input contains an integer $T$, the number of test cases. +$T$ lines follow, each line containing $N$, the number that the teacher provides. + +**Output Format** +For each test case, print in a newline the output in $p/q$ format where $p$ and $q$ are positive coprime integers. +if $p$ is 0, you should simply output `0`. + +**Constraints** +$1 \le T \le 4 \times 10^4$ +$2 \le N \le 10^6$ + +**Sample Input** + + 4 + 2 + 8 + 36 + 900 + +**Sample Output** + + 0 + 1/3 + 1/8 + 3/26 + +**Explaination** +For the first case $N = 2$, the set of proper divisors is $\{1\}$. Since $1$ is not an even perfect square, the probability is $0$. +For the second case $N = 8$, the set of proper divisors is $\{1,2,4\}$ and only $4$ is an even perfect square among them, so probability = $1/3$. +For the third case $N = 36$, the set of proper divisors is $\{1,2,3,4,6,9,12,18\}$, and only $4$ is an even perfect square, so probability = $1/8$. +For the fourth case $N = 900$, there will be total of $26$ proper divisors and $3$ of them $\{4,36,100\}$ are even perfect squares. ",0.4736842105263157,"[""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,,,,,,,2014-08-11T10:39:05,2016-12-06T10:15:06,tester,"###Python 2 +```python +from math import sqrt +from fractions import gcd + +N = 10**6 + +# calculate good numbers (i.e., even perfect squares) +is_good = [False]*(N+1) +for i in xrange(1,int(sqrt(N))+1): + if i % 2 == 0: + is_good[i * i] = 1 + +# calculate good divisors of numbers in O(N log N) +goods = [0]*(N+1) +total = [0]*(N+1) +for i in xrange(1,N+1): + for j in xrange(i<<1,N+1,i): + total[j] += 1 + if is_good[i]: + for j in xrange(i<<1,N+1,i): + goods[j] += 1 + +for cas in xrange(input()): + n = input() + if goods[n] == 0: + print 0 + else: + g = gcd(goods[n], total[n]) + print ""%s/%s"" % (goods[n] / g, total[n] / g) +``` +",not-set,2016-04-24T02:02:55,2016-07-23T17:39:18,Python +145,3548,mehta-and-the-typical-supermarket,Mehta and the Typical Supermarket,"Mehta is a very rich guy. He has $N$ types of coins, and each type of coin is available in an unlimited supply. + +So Mehta goes to a supermarket to buy monthly groceries. There he sees that every item has a unique price, that is, no two items have the same price. + +Now, the supermarket owner tells Mehta that they are selling items in the price range $[L, R]$ only on that particular day. He also tells Mehta that for every price, there is an item in the shop. + +The supermarket has recently adopted a weird new tradition: they will only take one type of coins for selling any item. + +As you know Mehta is very weak at calculations, so he wants you to do these calculations for him and tell how many different types of items he can buy. + +**Input Format** +The first line of input contains $N$, the number of types of coins Mehta has. +Then the next $N$ lines contain an integer each: the *ith* line contains $A[i]$, the value of Mehta's *ith* type of coin. + +Then the next line contains a number $D$, the number of days Mehta goes shopping. +Then each of the next $D$ lines contains numbers $L$ and $R$, denoting that they are selling items in price range $[L, R]$ on that particular day. + + +**Output format** +There will be $D$ lines, each containing the number of distinct items that can be bought at that particular day. + +**Constraints** +$1 \le N \le 17$ +$1 \le A[i] \le 51$ +$1 \le D \le 101$ +$1 \le L \le R \le 10^{18}$ + +**Sample Input** + + 4 + 2 + 3 + 4 + 5 + 3 + 1 10 + 2 20 + 3 7 + +**Sample output** + + 8 + 14 + 4 + +**Explanation** +For $L = 1$ and $R = 10$ you can buy items of price $\{2,3,4,5,6,8,9,10\}$. +For $L = 2$ and $R = 20$ you can buy items of price $\{2,3,4,5,6,8,9,10,12,14,15,16,18,20\}$. +For $L = 3$ and $R = 7$ you can buy items of price $\{3,4,5,6\}$. +",code,Help Mehta in shopping,ai,2014-08-11T11:00:03,2022-09-02T09:54:52,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. INTEGER_ARRAY a +# 2. 2D_INTEGER_ARRAY days +# + +def solve(a, days): + # 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') + + a_count = int(input().strip()) + + a = [] + + for _ in range(a_count): + a_item = int(input().strip()) + a.append(a_item) + + d = int(input().strip()) + + days = [] + + for _ in range(d): + days.append(list(map(int, input().rstrip().split()))) + + result = solve(a, days) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() +","Mehta is a very rich guy. He has $N$ types of coins, and each type of coin is available in an unlimited supply. + +So Mehta goes to a supermarket to buy monthly groceries. There he sees that every item has a unique price, that is, no two items have the same price. + +Now, the supermarket owner tells Mehta that they are selling items in the price range $[L, R]$ only on that particular day. He also tells Mehta that for every price, there is an item in the shop. + +The supermarket has recently adopted a weird new tradition: Mehta may only use a single type of coin for each item he purchases. For example, he could pay for an item of price 4 with two 2-coins, but not with a 3-coin and a 1-coin. + +As you know Mehta is very weak at calculations, so he wants you to do these calculations for him and tell how many different types of items he can buy. + +**Input Format** +The first line of input contains $N$, the number of types of coins Mehta has. +Then the next $N$ lines contain an integer each: the *ith* line contains $A[i]$, the value of Mehta's *ith* type of coin. + +Then the next line contains a number $D$, the number of days Mehta goes shopping. +Then each of the next $D$ lines contains numbers $L$ and $R$, denoting that they are selling items in price range $[L, R]$ on that particular day. + + +**Output format** +There will be $D$ lines, each containing the number of distinct items that can be bought at that particular day. + +**Constraints** +$1 \le N \le 17$ +$1 \le A[i] \le 51$ +$1 \le D \le 101$ +$1 \le L \le R \le 10^{18}$ + +**Sample Input** + + 4 + 2 + 3 + 4 + 5 + 3 + 1 10 + 2 20 + 3 7 + +**Sample output** + + 8 + 14 + 4 + +**Explanation** +For $L = 1$ and $R = 10$ you can buy items of price $\{2,3,4,5,6,8,9,10\}$. +For $L = 2$ and $R = 20$ you can buy items of price $\{2,3,4,5,6,8,9,10,12,14,15,16,18,20\}$. +For $L = 3$ and $R = 7$ you can buy items of price $\{3,4,5,6\}$. +",0.4210526315789473,"[""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,,,,,,,2014-08-11T11:00:18,2016-12-04T05:30:50,setter,"###C++ +```cpp +#include +using namespace std; +pair pre[200000]; +long long a[25],N; +#define INF 2000000000000000000LL +long long trunc_mul(long long a, long long b) +{ + return a <= INF / b ? a * b : INF; +} +void compute() +{ + int limit = 1<=0;j--) + { + if(k&i) + { + lcm = trunc_mul(lcm/__gcd(lcm,a[j]), a[j]); + + } + k = k<<1; + } + pre[i].first = lcm; + } + return ; +} +int main() +{ + cin >> N; + for(int i = 0;i < N;i++) + { + cin >> a[i]; + } + compute(); + int limit = 1<> Q; + while(Q--){ + long long L,R; + cin >> L >> R; + long long ans = 0; + L--; + for(int i = 1;i <= limit;i++) + { + if(pre[i].second%2 == 1)ans+=((long long)(R/pre[i].first)-(long long)(L/pre[i].first)); + else ans-=((long long)(R/pre[i].first)-(long long)(L/pre[i].first)); + } + cout << ans << endl; + } + + return 0; +} +``` +",not-set,2016-04-24T02:02:56,2016-07-23T18:32:35,C++ +146,3548,mehta-and-the-typical-supermarket,Mehta and the Typical Supermarket,"Mehta is a very rich guy. He has $N$ types of coins, and each type of coin is available in an unlimited supply. + +So Mehta goes to a supermarket to buy monthly groceries. There he sees that every item has a unique price, that is, no two items have the same price. + +Now, the supermarket owner tells Mehta that they are selling items in the price range $[L, R]$ only on that particular day. He also tells Mehta that for every price, there is an item in the shop. + +The supermarket has recently adopted a weird new tradition: they will only take one type of coins for selling any item. + +As you know Mehta is very weak at calculations, so he wants you to do these calculations for him and tell how many different types of items he can buy. + +**Input Format** +The first line of input contains $N$, the number of types of coins Mehta has. +Then the next $N$ lines contain an integer each: the *ith* line contains $A[i]$, the value of Mehta's *ith* type of coin. + +Then the next line contains a number $D$, the number of days Mehta goes shopping. +Then each of the next $D$ lines contains numbers $L$ and $R$, denoting that they are selling items in price range $[L, R]$ on that particular day. + + +**Output format** +There will be $D$ lines, each containing the number of distinct items that can be bought at that particular day. + +**Constraints** +$1 \le N \le 17$ +$1 \le A[i] \le 51$ +$1 \le D \le 101$ +$1 \le L \le R \le 10^{18}$ + +**Sample Input** + + 4 + 2 + 3 + 4 + 5 + 3 + 1 10 + 2 20 + 3 7 + +**Sample output** + + 8 + 14 + 4 + +**Explanation** +For $L = 1$ and $R = 10$ you can buy items of price $\{2,3,4,5,6,8,9,10\}$. +For $L = 2$ and $R = 20$ you can buy items of price $\{2,3,4,5,6,8,9,10,12,14,15,16,18,20\}$. +For $L = 3$ and $R = 7$ you can buy items of price $\{3,4,5,6\}$. +",code,Help Mehta in shopping,ai,2014-08-11T11:00:03,2022-09-02T09:54:52,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. INTEGER_ARRAY a +# 2. 2D_INTEGER_ARRAY days +# + +def solve(a, days): + # 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') + + a_count = int(input().strip()) + + a = [] + + for _ in range(a_count): + a_item = int(input().strip()) + a.append(a_item) + + d = int(input().strip()) + + days = [] + + for _ in range(d): + days.append(list(map(int, input().rstrip().split()))) + + result = solve(a, days) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() +","Mehta is a very rich guy. He has $N$ types of coins, and each type of coin is available in an unlimited supply. + +So Mehta goes to a supermarket to buy monthly groceries. There he sees that every item has a unique price, that is, no two items have the same price. + +Now, the supermarket owner tells Mehta that they are selling items in the price range $[L, R]$ only on that particular day. He also tells Mehta that for every price, there is an item in the shop. + +The supermarket has recently adopted a weird new tradition: Mehta may only use a single type of coin for each item he purchases. For example, he could pay for an item of price 4 with two 2-coins, but not with a 3-coin and a 1-coin. + +As you know Mehta is very weak at calculations, so he wants you to do these calculations for him and tell how many different types of items he can buy. + +**Input Format** +The first line of input contains $N$, the number of types of coins Mehta has. +Then the next $N$ lines contain an integer each: the *ith* line contains $A[i]$, the value of Mehta's *ith* type of coin. + +Then the next line contains a number $D$, the number of days Mehta goes shopping. +Then each of the next $D$ lines contains numbers $L$ and $R$, denoting that they are selling items in price range $[L, R]$ on that particular day. + + +**Output format** +There will be $D$ lines, each containing the number of distinct items that can be bought at that particular day. + +**Constraints** +$1 \le N \le 17$ +$1 \le A[i] \le 51$ +$1 \le D \le 101$ +$1 \le L \le R \le 10^{18}$ + +**Sample Input** + + 4 + 2 + 3 + 4 + 5 + 3 + 1 10 + 2 20 + 3 7 + +**Sample output** + + 8 + 14 + 4 + +**Explanation** +For $L = 1$ and $R = 10$ you can buy items of price $\{2,3,4,5,6,8,9,10\}$. +For $L = 2$ and $R = 20$ you can buy items of price $\{2,3,4,5,6,8,9,10,12,14,15,16,18,20\}$. +For $L = 3$ and $R = 7$ you can buy items of price $\{3,4,5,6\}$. +",0.4210526315789473,"[""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,,,,,,,2014-08-11T11:00:18,2016-12-04T05:30:50,tester,"###Python 2 +```python +from fractions import gcd + +def lcm(a,b): + return a / gcd(a,b) * b + +n = input() + +bitcount = [0]*(1<th wire one by one. So he starts with wire 1, then with wire 2 and so on. + +A group can start playing their game, only if all the members are connected (if not directly, then there must exist a path connecting them). They want to start playing as soon as possible. + +For each game, find out the wire after adding which the group can start playing. It is also possible that a group will never get connected. In such a case, this group starts crying and you should display `-1`. + +**Input Format** + +On the first line there will be $N$, $M$ and $Q$ each separated by a single space. On the second line we will give you $N$ integers separated by a single space: The $i$-th integer denotes the game friend $i$ wants to play (all between $1$ and $M$). The next $Q$ lines will denote $Q$ wires: ith line denotes ith wire and is denoted by $u_i$ and $v_i$ pairs each separated by a single space. + +**Output Format** + +Print on the $i$th line the answer for the $i$th game. + +**Constraints** +$1 \leq N, M \leq 10^5$ For each game $i$, the number of players playing $i$ will be positive. +$0 \leq Q \leq 10^5$ + +**Note** +Each game is chosen by at least one player. If a group consists of only one member, then print `0`, since this lucky (?) lone player can start right away! + + +**Sample Input** + + 5 2 4 + 1 2 2 2 1 + 1 2 + 2 3 + 1 5 + 4 5 + +**Sample Output** + + 3 + 4 + +**Explanation** + +The group with the game 1 can play after the 3rd wire is added. The group with game 2 can play only after the 4th wire has been added because after adding the 4th wire, a path between (2,3) (3,4) and (2,4) gets created.",code,"Jim is planning a LAN party in the basement of his big burger restaurant, but they stumbled upon a problem. Please help them.",ai,2014-08-15T10:42:28,2022-09-02T10:10:39,"# +# Complete the 'lanParty' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts following parameters: +# 1. INTEGER_ARRAY games +# 2. 2D_INTEGER_ARRAY wires +# 3. INTEGER m +# + +def lanParty(games, wires, 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') + + first_multiple_input = input().rstrip().split() + + n = int(first_multiple_input[0]) + + m = int(first_multiple_input[1]) + + q = int(first_multiple_input[2]) + + games = list(map(int, input().rstrip().split())) + + wires = [] + + for _ in range(q): + wires.append(list(map(int, input().rstrip().split()))) + + result = lanParty(games, wires, m) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() +","During the Steam Summer Sale, Jim's $N-1$ friends have purchased $M$ games, which are numbered from $1$ to $M$. The games are multiplayer. Jim has invited his friends to his basement where they will play by making a LAN-Party. + +Each friend has already decided the game he would like to play for the rest of the day. So there will be a group of friends who will play the same game together. + +But then, they face a problem: Currently, none of the friends' PCs are connected. So they have to be connected using the available $Q$ wires. Jim decides to connect friends $u_i$ and $v_i$ with the $i$th wire one by one. So he starts with wire 1, then with wire 2 and so on. + +A group can start playing their game, only if all the members are connected (if not directly, then there must exist a path connecting them). They want to start playing as soon as possible. + +For each game, find out the wire after adding which the group can start playing. It is also possible that a group will never get connected. In such a case, this group starts crying and you should display `-1`. +",0.5,"[""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""]","On the first line there will be $N$, $M$ and $Q$ each separated by a single space. On the second line we will give you $N$ integers separated by a single space: The $i$-th integer denotes the game friend $i$ wants to play (all between $1$ and $M$). The next $Q$ lines will denote $Q$ wires: ith line denotes ith wire and is denoted by $u_i$ and $v_i$ pairs each separated by a single space. +","Print on the $i$th line the answer for the $i$th game. +"," 5 2 4 + 1 2 2 2 1 + 1 2 + 2 3 + 1 5 + 4 5 +"," 3 + 4 +",Hard,,,,,,,2014-08-15T10:42:46,2016-12-02T11:12:23,setter,"###C++ +```cpp +#include +#include +using namespace std; +#define SZ(x) ( (int) (x).size() ) +const int MAX_N = 100000 + 1; +int N, M, Q; +int color[MAX_N]; +vector cpos[MAX_N]; +vector q[MAX_N]; +int qu[MAX_N], qv[MAX_N]; +int lo[MAX_N], hi[MAX_N]; +// implementation of UFDS +int f[MAX_N]; +int getf(int x){ + return f[x] == x ? x : f[x] = getf(f[x]); +} +void mergef(int x, int y){ + f[getf(x)] = getf(y); +} +void initf(){ + for(int i = 1; i <= N; i++){ + f[i] = i; + } +} + +void reloadQueries(){ + for(int i = 0; i <= Q; i++){ + q[i].clear(); + } + for(int i = 1; i <= M; i++){ + q[(lo[i] + hi[i]) / 2].push_back(i); + } +} + +void answerQuery(int c){ + bool connected = true; + for(int i = 1; i < (int) cpos[c].size(); i++){ + connected &= getf(cpos[c][i]) == getf(cpos[c][i - 1]); + } + int mid = (lo[c] + hi[c]) / 2; + if(!connected){ + lo[c] = mid + 1; + } else { + hi[c] = mid; + } +} + +int main(){ + ios::sync_with_stdio(false); + cin >> N >> M >> Q; + for(int i = 1; i <= N; i++){ + cin >> color[i]; + cpos[color[i]].push_back(i); + } + for(int i = 1; i <= M; i++){ + lo[i] = 0, hi[i] = Q; + } + for(int i = 1; i <= Q; i++){ + cin >> qu[i] >> qv[i]; + } + for(int times = 25; times >= 0; times --){ + initf(); + reloadQueries(); + for(int i = 0; i <= Q; i++){ + if(i > 0) + mergef(qu[i], qv[i]); + for(int j = 0; j < SZ(q[i]); j++){ + answerQuery(q[i][j]); + } + } + } + for(int i = 1; i <= M; i++){ + if(lo[i] > Q){ + cout << -1 << '\n'; + } else { + cout << lo[i] << '\n'; + } + } + return 0; +} +``` +",not-set,2016-04-24T02:02:56,2016-07-23T14:08:33,C++ +148,3666,chandrima-and-xor,Chandrima and XOR,"Chandrima likes the XOR operation very much and keeps finding and solving related problems. One day she comes across a problem and gets stuck on it, which makes her sad. You being her friend decide to help her out by writing a code for the same. + +Consider a list of all natural numbers. Now you remove all numbers whose binary representation has at least two consecutive $1$ bits, from the list, hence generating a new list having elements $1,2,4,5,8,...$ and so on. Now you are given $N$ numbers from this newly generated list. You have to find the XOR of these numbers. + +**Input Format** +The first line has an integer $N$, denoting the number of integers in list $A$. +The next line contains $N$ space-separated integers. $A_i$ represents the $A_i^{\text{th}}$ number of the generated list. Since the answer can be very large, print the answer modulo $(10^9+7)$. + +**Output Format** +Just print one line containing the final answer. + + +**Constraints** +$1 \le N \le 5\cdot 10^5$ +$1 \le A_i \le 10^{18}$ + +**Sample Input 1** + + 3 + 1 2 3 + +**Sample Output 1** + + 7 + +**Sample Input 2** + + 3 + 1 3 4 + +**Sample Output 2** + + 0 + +**Explanation** + +*Sample 1:* +The values to be considered are $1,2,4$, and the answer is $1\oplus2\oplus4 = 7$. + +*Sample 2:* +The values to be considered are $1,4,5$, and the answer is $1\oplus4\oplus5 = 0$. +",code,Help Chandrima find the XOR of N numbers,ai,2014-08-17T03:33:11,2022-09-02T09:54:42,"# Complete the solve function below. +def solve(a): + +","#!/bin/python3 + +import os +import sys + +","if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + a_count = int(input()) + + a = list(map(int, input().rstrip().split())) + + result = solve(a) + + fptr.write(str(result) + '\n') + + fptr.close() +","Chandrima likes the XOR operation very much and keeps finding and solving related problems. One day she comes across a problem and gets stuck on it, which makes her sad. You being her friend decide to help her out by writing a code for the same. + +Consider a list of all natural numbers. Now you remove all numbers whose binary representation has at least two consecutive $1$ bits, from the list, hence generating a new list having elements $1,2,4,5,8,...$ and so on. Now you are given $N$ numbers from this newly generated list. You have to find the XOR of these numbers. + +**Input Format** +The first line has an integer $N$, denoting the number of integers in list $A$. +The next line contains $N$ space-separated integers. $A_i$ represents the $A_i^{\text{th}}$ number of the generated list. Since the answer can be very large, print the answer modulo $(10^9+7)$. + +**Output Format** +Just print one line containing the final answer. + + +**Constraints** +$1 \le N \le 5\cdot 10^5$ +$1 \le A_i \le 10^{18}$ + +**Sample Input 1** + + 3 + 1 2 3 + +**Sample Output 1** + + 7 + +**Sample Input 2** + + 3 + 1 3 4 + +**Sample Output 2** + + 0 + +**Explanation** + +*Sample 1:* +The values to be considered are $1,2,4$, and the answer is $1\oplus2\oplus4 = 7$. + +*Sample 2:* +The values to be considered are $1,4,5$, and the answer is $1\oplus4\oplus5 = 0$. +",0.5925925925925926,"[""c"",""clojure"",""cpp"",""cpp14"",""csharp"",""erlang"",""go"",""haskell"",""java"",""java8"",""javascript"",""kotlin"",""lua"",""objectivec"",""perl"",""php"",""pypy3"",""python3"",""ruby"",""scala"",""swift""]",,,,,Hard,,,,,,,2014-08-17T03:33:24,2016-12-02T14:47:34,setter,"###C++ +```cpp +#include +#include +#define pb push_back +using namespace std; +long long mod=1000000007; +vector fibo,power; +void two_pow() +{ + long long p; + power.pb(1); + for(int i=1;i<100;i++) + { + power.pb(power[i-1]+power[i-1]); + if(power[i]>=mod) + power[i]-=mod; + } +} +void fib() +{ + long long o=1,n=1; + fibo.pb(1); + while(1) + { + n=n+o; + o=n-o; + fibo.pb(n); + if(n>1e18) + break; + } +} +int main() +{ + long long n,inp,cnt,x,ans=0; + int sol[100]; + fib(); + two_pow(); + for(int i=0;i<100;i++) + sol[i]=0; + cin>>n; + for(int i=0;i>inp; + for(int i=0;iinp) + { + cnt=i-1; + break; + } + } + for(int i=cnt;i>=0;i--) + { + if(inp>=fibo[i]) + { + x=1; + inp-=fibo[i]; + } + else + x=0; + sol[i]^=x; + } + } + + for(int i=0;i<100;i++) + { + if(sol[i]) + ans+=power[i]; + if(ans>=mod) + ans-=mod; + } + cout< +#include +using namespace std; +typedef unsigned char byte; +const int MAXN = 1e6; +byte S[2][MAXN]; +int reverse_bits(int x) { + x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1); + x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2); + x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4); + x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8); + x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16); + return x; +} +int main() { + register int N, K, i, j, x, rev_x, rev_K; + char c; + for (scanf(""%d%d\n"", &N, &K), i = 0; i < N; ++i) { + c = getchar(); + assert('A' <= c && c <= 'D'); + S[0][i] = c - 'A'; + } + assert(1 <= i && i <= MAXN); + for (rev_K = reverse_bits(K), j = 0; K; K -= x, rev_K -= rev_x, j ^= 1) { + rev_x = rev_K & -rev_K; + x = reverse_bits(rev_x); + for (i = 0; i < N; ++i) + S[j ^ 1][i] = S[j][i] ^ S[j][(i + x) % N]; + } + for (i = 0; i < N; ++i) { + printf(""%c"", S[j][i] + 'A'); + } + printf(""\n""); + return 0; +} +``` +",not-set,2016-04-24T02:02:58,2016-07-23T18:14:05,C++ +150,3900,grow-the-tree,Grow the tree," + +The Utopian tree goes through 2 cycles of growth every year. The first growth cycle of the tree occurs during the monsoon, when it doubles in height. The second growth cycle of the tree occurs during the summer, when its height increases by 1 meter. +Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after N growth cycles? + +Input Format +The first line contains an integer, T, the number of test cases. +T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case. + +Constraints +1 <= T <= 10 +0 <= N <= 60 + +Output Format +For each test case, print the height of the Utopian tree after N cycles. + +Sample Input #00: + +2 +0 +1 + +Sample Output #00: + +1 +2 + +Explanation #00: +There are 2 test cases. When N = 0, the height of the tree remains unchanged. When N = 1, the tree doubles its height as it's planted just before the onset of monsoon. + +Sample Input: #01: + +2 +3 +4 + +Sample Output: #01: + +6 +7 + +Explanation: #01: +There are 2 testcases. +N = 3: +the height of the tree at the end of the 1st cycle = 2 +the height of the tree at the end of the 2nd cycle = 3 +the height of the tree at the end of the 3rd cycle = 6 + +N = 4: +the height of the tree at the end of the 4th cycle = 7 + +",code,,ai,2014-08-22T07:05:17,2016-09-09T09:50:28,,,," + +The Utopian tree goes through 2 cycles of growth every year. The first growth cycle of the tree occurs during the monsoon, when it doubles in height. The second growth cycle of the tree occurs during the summer, when its height increases by 1 meter. +Now, a new Utopian tree sapling is planted at the onset of the monsoon. Its height is 1 meter. Can you find the height of the tree after N growth cycles? + +Input Format +The first line contains an integer, T, the number of test cases. +T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case. + +Constraints +1 <= T <= 10 +0 <= N <= 60 + +Output Format +For each test case, print the height of the Utopian tree after N cycles. + +Sample Input #00: + +2 +0 +1 + +Sample Output #00: + +1 +2 + +Explanation #00: +There are 2 test cases. When N = 0, the height of the tree remains unchanged. When N = 1, the tree doubles its height as it's planted just before the onset of monsoon. + +Sample Input: #01: + +2 +3 +4 + +Sample Output: #01: + +6 +7 + +Explanation: #01: +There are 2 testcases. +N = 3: +the height of the tree at the end of the 1st cycle = 2 +the height of the tree at the end of the 2nd cycle = 3 +the height of the tree at the end of the 3rd cycle = 6 + +N = 4: +the height of the tree at the end of the 4th cycle = 7 + +",0.5,"[""java"",""cpp"",""c"",""cpp14""]",,,,,Hard,,,,,,,2014-08-22T07:08:29,2016-05-12T23:58:07,setter,"#include +int treegrowth(int s) + {int a,c=1,i; + a=s/2; + if(s%2==0) + { + for(i=0;i + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + using namespace std; + + #define fore(i, l, r) for(int i = (l); i < (r); ++i) + #define forn(i, n) fore(i, 0, n) + #define fori(i, l, r) fore(i, l, (r) + 1) + #define sz(v) int((v).size()) + #define all(v) (v).begin(), (v).end() + #define pb push_back + #define mp make_pair + #define X first + #define Y second + + typedef long long li; + typedef long double ld; + typedef pair pt; + + template T abs(T a) { return a < 0 ? -a : a; } + template T sqr(T a) { return a*a; } + + const int INF = (int)1e9; + const ld EPS = 1e-9; + const ld PI = 3.1415926535897932384626433832795; + + /* + + This is just to check correctness of input + + */ + int readInt(int l, int r){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int in range [%d, %d], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int in range [%d, %d], but found %d!"", l, r, x); + throw; + } + return x; + } + int readInt(int l, int r, string name){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int %s in range [%d, %d], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int %s in range [%d, %d], but found %d!"", name.c_str(), l, r, x); + throw; + } + return x; + } + li readLong(li l, li r){ + li x; + if(scanf(""%lld"", &x) != 1){ + fprintf(stderr, ""Expected long long in range [%lld, %lld], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected long long in range [%lld, %lld], but found %lld!"", l, r, x); + throw; + } + return x; + } + li readLong(li l, li r, string name){ + li x; + if(scanf(""%lld"", &x) != 1){ + fprintf(stderr, ""Expected long long %s in range [%lld, %lld], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected long long %s in range [%lld, %lld], but found %lld!"", name.c_str(), l, r, x); + throw; + } + return x; + } + const ld __EPS__ = 1e-15; + ld readDouble(double l, double r){ + double x; + if(scanf(""%lf"", &x) != 1){ + fprintf(stderr, ""Expected double in range [%lf, %lf], but haven't found!"", l, r); + throw; + } + if(!(l <= x + __EPS__ && x <= r + __EPS__)){ + fprintf(stderr, ""Expected double in range [%lf, %lf], but found %lf!"", l, r, x); + throw; + } + return x; + } + ld readDouble(double l, double r, string name){ + double x; + if(scanf(""%lf"", &x) != 1){ + fprintf(stderr, ""Expected double %s in range [%lf, %lf], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x + __EPS__ && x <= r + __EPS__)){ + fprintf(stderr, ""Expected double %s in range [%lf, %lf], but found %lf!"", name.c_str(), l, r, x); + throw; + } + return x; + } + + struct explicit_treap{ + struct node{ + int cnt, pr, info; + bool rev; + node *l, *r, *par; + node(){ + cnt = 1; + pr = info = 0; + rev = false; + l = r = par = 0; + } + }; + typedef node* tree; + + tree root; + + explicit_treap(){ + root = 0; + } + + int random(){ + return ((rand() & ((1 << 15) - 1)) << 15) ^ rand(); + } + + tree allocate(int info){ + tree cur = new node(); + cur->pr = random(); + cur->info = info; + return cur; + } + + int get_cnt(tree t){ + return !t ? 0 : t->cnt; + } + + void rev(tree t){ + if(!t) + return; + t->rev ^= 1; + } + + template + void swap(T& o1, T& o2){ + T tmp = o1; + o1 = o2; + o2 = tmp; + } + + void push(tree t){ + if(!t) return; + + if(t->rev){ + swap(t->l, t->r); + rev(t->l), rev(t->r); + t->rev ^= 1; + } + } + + void update(tree t){ + if(t){ + t->cnt = get_cnt(t->l) + get_cnt(t->r) + 1; + t->par = 0; + } + } + + void split(tree t, int key, tree& l, tree& r){ + push(t); + if(!t){ + l = r = 0; + return; + } + int ckey = get_cnt(t->l); + if(ckey < key){ + split(t->r, key - ckey - 1, t->r, r); + l = t; + }else{ + split(t->l, key, l, t->l); + r = t; + } + update(l), update(r); + } + + tree merge(tree l, tree r){ + push(l), push(r); + if(!l || !r) + return !l ? r : l; + tree t; + if(l->pr > r->pr){ + l->r = merge(l->r, r); + t = l; + }else{ + r->l = merge(l, r->l); + t = r; + } + update(t); + return t; + } + + void append(int number){ + tree t = allocate(number); + root = merge(root, t); + } + + void reverse(int l, int r){ + assert(0 <= l && l <= r && r < get_cnt(root)); + tree lf_t, mid_t, rg_t; + split(root, r + 1, mid_t, rg_t); + split(mid_t, l, lf_t, mid_t); + assert(get_cnt(mid_t) == r - l + 1); + rev(mid_t); + root = merge(lf_t, merge(mid_t, rg_t)); + } + + void swap(int l1, int r1, int l2, int r2){ + if(l1 > l2) + swap(l1, l2); + assert(0 <= l1 && l1 <= r1 && r1 < l2 && l2 <= r2 && r2 < get_cnt(root)); + tree p1, p2, p3, p4, p5; + split(root, r2 + 1, root, p5); + split(root, l2, root, p4); + split(root, r1 + 1, root, p3); + split(root, l1, p1, p2); + root = merge(p1, merge(p4, merge(p3, merge(p2, p5)))); + } + + void swap(int l, int r, explicit_treap& t2){ + assert(0 <= l && l <= r && r < get_cnt(root)); + assert(0 <= l && l <= r && r < get_cnt(t2.root)); + + tree lf_t, mid_t, rg_t; + split(root, r + 1, mid_t, rg_t); + split(mid_t, l, lf_t, mid_t); + + tree lf_t2, mid_t2, rg_t2; + split(t2.root, r + 1, mid_t2, rg_t2); + split(mid_t2, l, lf_t2, mid_t2); + + assert(get_cnt(mid_t) == r - l + 1); + assert(get_cnt(mid_t2) == r - l + 1); + + root = merge(lf_t, merge(mid_t2, rg_t)); + t2.root = merge(lf_t2, merge(mid_t, rg_t2)); + } + + void fill_dfs(tree t, vector& order){ + if(!t) + return; + push(t); + fill_dfs(t->l, order); + order.pb(t->info); + fill_dfs(t->r, order); + } + + void fill(int l, int r, vector& order){ + assert(0 <= l && l <= r && r < get_cnt(root)); + tree lf_t, mid_t, rg_t; + split(root, r + 1, mid_t, rg_t); + split(mid_t, l, lf_t, mid_t); + fill_dfs(mid_t, order); + root = merge(lf_t, merge(mid_t, rg_t)); + } + + void print(){ + vector tmp; + fill_dfs(root, tmp); + forn(i, sz(tmp)) + printf(""%d "", tmp[i]); + puts(""""); + } + }; + + struct point{ + ld x, y; + point(){ + x = y = 0; + } + point(ld _x, ld _y) : x(_x), y(_y) {} + }; + + point operator - (const point& a, const point& b){ + return point(a.x - b.x, a.y - b.y); + } + + point operator + (const point& a, const point& b){ + return point(a.x + b.x, a.y + b.y); + } + + point operator * (const point& a, const ld& b){ + return point(a.x * b, a.y * b); + } + + ld dot(const point& a, const point& b){ + return a.x * b.x + a.y * b.y; + } + + ld cross(const point& a, const point& b){ + return a.x * b.y - a.y * b.x; + } + + bool operator < (const point& o1, const point& o2){ + if(abs(o1.x - o2.x) > EPS) + return o1.x < o2.x; + return o1.y < o2.y; + } + + bool operator == (const point& o1, const point& o2){ + return abs(o1.x - o2.x) < EPS && abs(o1.y - o2.y) < EPS; + } + + ld dist(const point& o1, const point& o2){ + return sqrt(sqr(o1.x - o2.x) + sqr(o1.y - o2.y)); + } + + ld det(ld a, ld b, ld c, ld d){ + return a * d - b * c; + } + + bool inter(ld A1, ld B1, ld C1, ld A2, ld B2, ld C2, point& res){ + ld dt = det(A1, B1, A2, B2), + dx = -det(C1, B1, C2, B2), + dy = -det(A1, C1, A2, C2); + if(abs(dt) < EPS) + return false; + res.x = dx / dt, + res.y = dy / dt; + return true; + } + + pair circle(const point& a, const point& b, const point& c){ + point m1 = (a + b) * 0.5, + m2 = (a + c) * 0.5, + v1 = b - a, + v2 = c - a; + point o; + assert(inter(v1.x, v1.y, -dot(v1, m1), v2.x, v2.y, -dot(v2, m2), o)); + return make_pair(o, dist(o, a)); + } + + pair min_circle(vector p, point q, point w){ + pair ans((q + w) * 0.5, dist(q, w) * 0.5); + forn(i, sz(p)){ + if(dist(ans.first, p[i]) > ans.second + EPS){ + ans = circle(p[i], q, w); + } + } + return ans; + } + + pair min_circle(vector p, point q){ + pair ans((p[0] + q) * 0.5, dist(p[0], q) * 0.5); + fore(i, 1, sz(p)){ + if(dist(ans.first, p[i]) > ans.second + EPS){ + ans = min_circle(vector(p.begin(), p.begin() + i), p[i], q); + } + } + return ans; + } + + pair min_circle(vector p){ + if(p.empty()) + return pair(); + if(sz(p) == 1) + return make_pair(p[0], 0); + random_shuffle(all(p)); + pair ans((p[0] + p[1]) * 0.5, dist(p[0], p[1]) * 0.5); + fore(i, 2, sz(p)){ + if(dist(ans.first, p[i]) > ans.second + EPS){ + ans = min_circle(vector(p.begin(), p.begin() + i), p[i]); + } + } + return ans; + } + + int main(){ + #ifdef ssu1 + assert(freopen(""input.txt"", ""rt"", stdin)); + //assert(freopen(""output.txt"", ""wt"", stdout)); + #endif + int n, m; + n = readInt(1, 100000); + m = readInt(1, 100000); + explicit_treap t[2]; + forn(i, 2){ + forn(j, n){ + int v = readInt(0, 1000000); + t[i].append(v); + } + } + int sum = 0; + forn(mi, m){ + int type = readInt(1, 4) - 1; + if(type == 0){ + int id, l, r; + id = readInt(0, 1); + l = readInt(1, n); + r = readInt(l, n); + t[id].reverse(l - 1, r - 1); + }else if(type == 1){ + int id, l1, r1, l2, r2; + id = readInt(0, 1); + l1 = readInt(1, n); + r1 = readInt(l1, n); + l2 = readInt(r1 + 1, n); + r2 = readInt(l2, n); + t[id].swap(l1 - 1, r1 - 1, l2 - 1, r2 - 1); + }else if(type == 2){ + int l = readInt(1, n), r = readInt(l, n); + t[0].swap(l - 1, r - 1, t[1]); + }else if(type == 3){ + vector x, y; + int l = readInt(1, n), r = readInt(l, n); + t[0].fill(l - 1, r - 1, x); + t[1].fill(l - 1, r - 1, y); + sum += r - l; + assert(sum <= 1000000); + vector p(sz(x)); + forn(i, sz(p)){ + p[i].x = x[i], p[i].y = y[i]; + } + sort(all(p)); + p.erase(unique(all(p)), p.end()); + ld R = min_circle(p).second; + printf(""%.2lf\n"", double(R)); + } + } + return 0; + } +",not-set,2016-04-24T02:02:59,2016-04-24T02:02:59,C++ +152,3957,bangalore-bank,Bangalore Bank,"There is a famous old bank in Bangalore. It has just started the process of filling its database with bank account numbers of its clients. In order to put one account number to the database, an employee has to insert it from a piece of paper to a computer using a standard keyboard (without using number pad found on the right hand side of most keyboards). The weird thing is that every employee assigned to this task can type in using only 2 index fingers (one left hand index finger and one right hand index finger). +
+Below is the sample representation of number keys present in the keyboard. +
+![1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 0](http://hr-challenge-images.s3.amazonaws.com/3957/keyboard.jpg) +
+He can perform any one of the following steps: + +1. He can move any one of his fingers to adjacent keys. +2. He can press the key just below any of his fingers. But he can press only one key at a time. + +Each of the above steps takes 1 second. So moving a finger from key 3 to key 5 takes 2s, moving a finger from key 7 to key 2 takes 5s, and moving a finger from key 0 to key 8 takes 2s (Key 0 is the *rightmost key*). Similarly, pressing a single key takes 1 second. + +Write a program that computes the minimal time needed to add account number of an employee to the database. Before the process, an employee can place his finger wherever he wants. All digits should be inserted in the given order. + +**Note** + +* It is not necessary that left finger will always lie on the left side of right finger. They can also lie on the same key, and in opposite direction also. + +**Input** +In the first line, there is a number _n_ denoting the length of the bank account number. +In the second line, there are _n_ digits separated by a single space denoting the bank account number. + +**Output** +In one and only line, print the minimum time (in seconds) required to rewrite the bank account number according to the above rules. + +**Constraints** +1 ≤ _n_ ≤ 104 + +**Input #00** + + 2 + 1 2 + +**Output #00** + + 2 + +**Input #01** + + 3 + 1 0 3 + +**Output #01** + + 5 + +**Explanations** +
+*Test Case #00:* An employee can put his left finger on *key 1* and his right finger on *key 2* before the process, so the whole process takes 2 seconds. +
+*Test Case #01:* An employee can put his left finger on *key 1* and his right finger on *key 0* before the process. From that position, it takes 2 seconds to press first two keys. After that, he can move his left finger from *key 1* to *key 3*, which takes 2 seconds and then press it which takes additional second. The whole process takes 5 seconds. Note that *key 0* is the rightmost key. + +--- +**Tested by** [Ray Williams Robinson Valiente](/shaka_shadows), [abhiranjan](/abhiranjan) +",code,Account numbers,ai,2014-08-24T18:19:12,2018-05-23T18:41:29,,,,"There is a famous old bank in Bangalore. It has just started the process of filling its database with bank account numbers of its clients. In order to put one account number to the database, an employee has to insert it from a piece of paper to a computer using a standard keyboard (without using number pad found on the right hand side of most keyboards). The weird thing is that every employee assigned to this task can type in using only 2 index fingers (one left hand index finger and one right hand index finger). +
+Below is the sample representation of number keys present in the keyboard. +
+![1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 0](http://hr-challenge-images.s3.amazonaws.com/3957/keyboard.jpg) +
+He can perform any one of the following steps: + +1. He can move any one of his fingers to adjacent keys. +2. He can press the key just below any of his fingers. But he can press only one key at a time. + +Each of the above steps takes 1 second. So moving a finger from key 3 to key 5 takes 2s, moving a finger from key 7 to key 2 takes 5s, and moving a finger from key 0 to key 8 takes 2s (Key 0 is the *rightmost key*). Similarly, pressing a single key takes 1 second. + +Write a program that computes the minimal time needed to add account number of an employee to the database. Before the process, an employee can place his finger wherever he wants. All digits should be inserted in the given order. + +**Note** + +* It is not necessary that left finger will always lie on the left side of right finger. They can also lie on the same key, and in opposite direction also. + +**Input** +In the first line, there is a number _n_ denoting the length of the bank account number. +In the second line, there are _n_ digits separated by a single space denoting the bank account number. + +**Output** +In one and only line, print the minimum time (in seconds) required to rewrite the bank account number according to the above rules. + +**Constraints** +1 ≤ _n_ ≤ 104 + +**Input #00** + + 2 + 1 2 + +**Output #00** + + 2 + +**Input #01** + + 3 + 1 0 3 + +**Output #01** + + 5 + +**Explanations** +
+*Test Case #00:* An employee can put his left finger on *key 1* and his right finger on *key 2* before the process, so the whole process takes 2 seconds. +
+*Test Case #01:* An employee can put his left finger on *key 1* and his right finger on *key 0* before the process. From that position, it takes 2 seconds to press first two keys. After that, he can move his left finger from *key 1* to *key 3*, which takes 2 seconds and then press it which takes additional second. The whole process takes 5 seconds. Note that *key 0* is the rightmost key. + +--- +**Tested by** [Ray Williams Robinson Valiente](/shaka_shadows), [abhiranjan](/abhiranjan) +",0.5,"[""cobol"",""clojure"",""sbcl"",""elixir"",""erlang"",""fsharp"",""haskell"",""java"",""java8"",""kotlin"",""ocaml"",""racket"",""scala""]",,,,,Hard,,,,,,,2014-08-24T18:44:10,2016-12-04T15:53:15,tester," --Haskell + + import qualified Data.Vector as V + + oo = 10^8 :: Int + + main :: IO () + main = getContents >>= print. getAns. map (map read. words). lines + where + getAns ([n]:arr:[]) = solve (length arr) (V.fromList. map (\x -> (x-1+10)`rem`10) $ arr) + + solve :: Int -> V.Vector Int -> Int + solve n a = minimum [dp V.! (n-1) V.! x V.! y| x <- [0..9], y <- [0..9]] + where + dp = V.fromList [ + V.fromList [ + V.fromList[minSteps idx x y| y<-[0..9]] + | x<-[0..9]] + | idx<-[0..n-1] + ] + minSteps idx x y + | idx == 0 = if x == val || y == val then 1 else oo + | x == val && y == val = min xAns yAns + | x == val = xAns + | y == val = yAns + | otherwise = oo + where + val = a V.! idx + xAns = minimum. (oo:) $[(dp V.!(idx-1) V.!x1 V.!y)+abs (x1-x)+1 + | x1<-[0..9]] + yAns = minimum. (oo:) $[(dp V.!(idx-1) V.!x V.!y1) + abs (y1-y) + 1 + | y1<-[0..9]] + +",not-set,2016-04-24T02:02:59,2016-04-24T02:02:59,Python +153,3985,testproblem,testProblem,Print 100,code,Print 100,ai,2014-08-26T16:56:45,2016-09-09T09:50:57,,,,Print 100,0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-26T16:58:49,2016-05-12T23:57:55,setter,"include + +int main() +{ + + printf(""100""); + return 0; + +}",not-set,2016-04-24T02:02:59,2016-04-24T02:02:59,Unknown +154,3993,a-super-hero,A Super Hero,"**Ma5termind** is crazy about Action Games. He has just bought a new one and is ready to play with it. While Ma5termind usually finishes the levels of a game very quickly, today he got stuck at the very first level of this new game. **How come ?** Game rules state that the **Ma5termind** has to cross N levels and at each level of the game he has to face M enemies **(Well, time for the real action)**. + +Each enemy has its associated power and some number of bullets. So to kill an enemy, he needs to shoot them with one or multiple bullets whose collective power is equal to the the power of the enemy.If **Ma5termind** kills any one enemy at a level, rest of the enemies run away and the level is cleared. + +**Nice game, Isnt it?. Here comes the challenging task**, Ma5termind can use the bullets obtained after killing an enemy at **ith level** only till the **(i+1)th level**. However, there is an exception to this rule: the bullets obtained in the first round are always carried forward and can be used to kill the enemies. + +Now, Ma5termind has to guess the minimum number of bullets he must have in the first round so that he clears all the **N levels** successfully. + +**NOTE** + +1. Bullets carried in the first round can be used to kill an enemy at any level. + +2. For better understanding of the problem look at the sample testcases. + +**INPUT:** + +First line of input contains a single integer T denoting the number of test cases. First line of each test case contains two space separated integers N and M denoting the number of levels and number of enemies at each level respectively. Each of next N lines of a test case contain M space separated integers, where jth integer in the ith line denotes the power of jth enemy on the ith level. Each of next N lines of a test case contains M space separated integers, where jth integer in the ith line denotes the number of bullets jth enemy of ith level has. + + + +**OUTPUT:** + +For each test case, print the required answer . + + +**CONSTRAINTS:** + +1<=T<=100 + +1<=N<=100 + +1<=M<=5x10^5 + +1<=VALUE(POWER OR BULLETS)<=1000 + +For each test file, sum of NxM over all the test cases does not exceed 5x105. + +**SAMPLE INPUT:** + +1 + +3 3 + +3 2 1 + +1 2 3 + +3 2 1 + +1 2 3 + +3 2 1 + +1 2 3 + + +**SAMPLE OUTPUT:** + +1 + + +**EXPLANATION:** + +Let's say initially **Ma5termind** does not have any bullet. Now, For the 1st level he kills the 3rd enemy having power 1 and takes all his bullets. For this purpose, he must have at least 1 bullet initially. After finishing first level, Ma5termind proceeds to the second level, there he kills the enemy having maximum number of bullets because he is having 3 bullets which he acquired at the previous level and 3 bullets are sufficient to kill any enemy on the this level. He kills the 1st enemy at this level, acquires all his bullets and proceeds to the 3rd level. Ma5termind can again kill any of the enemy on this level because of the same reason as was on previous level. So, this way he finishes all the N levels of the game when he has only a single bullet in the first round. + +**NOTE:** + +1. There can be more than one way of getting the optimal answer but that does not matter in our case, because we need to answer the minimum number of bullets required. + +2. Large set of Input data. Prefer to use Fast Input/Output Methods.",code,Minimal number of bullets required to complete N levels of the game if you kill one enemy at each level and use its bullet for current and just next level,ai,2014-08-27T12:24:33,2022-08-31T08:14:48,"# +# Complete the 'superHero' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. 2D_INTEGER_ARRAY power +# 2. 2D_INTEGER_ARRAY bullets +# + +def superHero(power, bullets): + # 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]) + + power = [] + + for _ in range(n): + power.append(list(map(int, input().rstrip().split()))) + + bullets = [] + + for _ in range(n): + bullets.append(list(map(int, input().rstrip().split()))) + + result = superHero(power, bullets) + + fptr.write(str(result) + '\n') + + fptr.close() +","Ma5termind is crazy about Action Games. He just bought a new one and got down to play it. Ma5termind usually finishes all the levels of a game very fast. But, This time however he got stuck at the very first level of this new game. Can you help him play this game. + +To finish the game, Ma5termind has to cross $N$ levels. At each level of the game, Ma5termind has to face $M$ enemies. Each enemy has its associated power $P$ and some number of bullets $B$. To knock down an enemy, Ma5termind needs to shoot him with one or multiple bullets whose collective count is equal to the power of the enemy. If Ma5termind manages to knock down any one enemy at a level, the rest of them run away and the level is cleared. + +**Here comes the challenging part of the game.** +Ma5termind acquires all the bullets of an enemy once he has knocked him down. Ma5termind can use the bullets acquired after killing an enemy at $i^{th}$ level only till the $(i+1)^{th}$ level. + +However, the bullets Ma5termind carried before the start of the game can be taken forward and can be used to kill more enemies. + +Now, Ma5termind has to guess the minimum number of bullets he must have before the start of the game so that he clears all the $N$ levels successfully. + + +**NOTE** + +1. Bullets carried before the start of the game can be used to kill an enemy at any level. +2. One bullet decreases the power of an enemy by 1 Unit. +3. For better understanding of the problem look at the sample testcases. + +",0.5,"[""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""]","First line of input contains a single integer $T$ denoting the number of test cases. +First line of each test case contains two space separated integers $N$ and $M$ denoting the number of levels and number of enemies at each level respectively. +Each of next $N$ lines of a test case contain $M$ space separated integers, where $j^{th}$ integer in the $i^{th}$ line denotes the power $P$ of $j^{th}$ enemy on the $i^{th}$ level. +Each of the next $N$ lines of a test case contains $M$ space separated integers, where $j^{th}$ integer in the $i^{th}$ line denotes the number of bullets $B$ $j^{th}$ enemy of $i^{th}$ level has. + +**Constraints** +$1 \le T \le 100$ +$1 \le N \le 100$ +$1 \le M \le 5 \times 10^5$ +$1 \le P,B \le 1000$ +For each test file, sum of $N\times M$ over all the test cases does not exceed $5 \times 10^5$. + +","For each test case, print the required answer. "," 2 + 3 3 + 3 2 1 + 1 2 3 + 3 2 1 + 1 2 3 + 3 2 1 + 1 2 3 + 3 3 + 3 2 5 + 8 9 1 + 4 7 6 + 1 1 1 + 1 1 1 + 1 1 1 +"," 1 + 5 ",Hard,,,,,,,2014-08-27T12:25:04,2016-12-07T15:45:23,setter,"###C++ +```cpp +#include + +#define pb push_back + +#define mp make_pair + +#define all(x) x.begin(),x.end() + +#define PII pair + +#define ft first + +#define sd second + +#define inf 10000000 + +using namespace std; + +int main(){ + + int t; + cin >> t; + while(t--){ + int n,m; + cin >> n >> m; + int P[n][m],W[n][m],MW[n][m];; + for(int i=0;i>P[i][j]; + MW[i][j]=inf; + } + } + + for(int i=0;i>W[i][j]; + } + } + + int ans; + + vector > MS; + + for(int i=0;i t; + + for(int j=0;j=0){ + + while(k>=0&&MS[k].ft>=t[l].ft) + { + maxx=min(maxx,MS[k].sd); + k--; + } + MW[i][t[l].sd]=min(MW[i][t[l].sd],maxx); + l--; + } + + MS.clear(); + + for(int j=0;j + +#define sgn(x,y) ((x)+eps<(y)?-1:((x)>eps+(y)?1:0)) +#define rep(i,n) for(int i=0; i<(n); i++) +#define mem(x,val) memset((x),(val),sizeof(x)); +#define rite(x) freopen(x,""w"",stdout); +#define read(x) freopen(x,""r"",stdin); +#define all(x) x.begin(),x.end() +#define sz(x) ((int)x.size()) +#define sqr(x) ((x)*(x)) +#define pb push_back +#define clr clear() +#define inf (1<<28) +#define ins add +#define xx first +#define yy second +#define eps 1e-9 + +typedef long long i64; +typedef unsigned long long ui64; +typedef string st; +typedef vector < int > vi; +typedef vector < st > vs; +typedef map < int , int > mii; +typedef map < st , int > msi; +typedef set < int > si; +typedef set < st > ss; +typedef pair < i64 , i64 > pii; +typedef vector < pii > vpii; + +#define mx 2000010 + +i64 First[mx], Second[mx]; + +vpii poly; + +void add(i64 idx, pii x) { + while(poly.size() - idx > 1) { + int i = sz( poly ) - 2, j = sz( poly ) - 1; + i64 a = poly[j].yy - poly[i].yy ; + i64 b = poly[i].xx - poly[j].xx ; + i64 c = poly[j].yy - x.yy ; + i64 d = x.xx - poly[j].xx ; + if( a/b < c/d ) { + poly.pop_back(); + continue; + } + break; + } + poly.pb(x); +} + +#define which(v,x) ( v.yy + x * v.xx ) + +int main() { + ios_base::sync_with_stdio(0); + i64 n, k; + cin >> n >> k ; + if( !n || !k ) { + cout << 0 << endl; + return 0; + } + rep(i,n) cin >> First[i]; + poly.pb({-(First[n-1]<<1),sqr(First[n-1])}); + i64 res=0; + for(int i = n - 1 , idx = 0; i >= 0 ; i--) { + while( sz(poly)-idx > 1 && which(poly[idx], First[i]) > which(poly[idx+1], First[i])) idx++; + res = k + sqr( First[i] ) + which(poly[idx], First[i]); + add(idx, {-(First[i-1]<<1), res+sqr(First[i-1])}); + } + cout << res << endl; + return 0; +} +``` +",not-set,2016-04-24T02:03:00,2016-07-23T15:28:49,C++ +156,3994,police-operation,Police Operation,"Roy is helping the police department of his city in crime fighting. Today, they informed him about a new planned operation. + +Think of the city as a $2D$ plane. The road along the $X$-axis is very crime prone, because $n$ criminals live there. No two criminals live at the same position. + +To catch these criminals, the police department has to recruit some police officers and give each of them USD $h$ as wages. A police officer can start his operation from any point $a$, drive his car to point $b$ in a straight line, and catch all the criminals who live on this way. The cost of fuel used by the officer's car is equal to the square of the euclidean distance between points $a$ and $b$ (Euclidean distance between points $(x_1,y_1)$ and $(x_2,y_2)$ equals to $\sqrt{ (x_1-x_2)^2 + (y_1-y_2)^2 }$ ). + +The police department asks Roy to plan this operation. So Roy has to tell them the number of officers to recruit and the routes these officers should take in order to catch all the criminals. Roy has to provide this information while minimizing the total expenses of this operation. + +Find out the minimum amount of money required to complete the operation. + +**Input Format** + +The first line contains two integers $n$ $(0 \le n \le 2 \times 10^{6})$, number of criminals, and $h$ $( 0 \le h \le 10^{9} )$, the cost of recruiting a police officer. The next line contains $n$ space separated integers. The $i^{th}$ integer indicates the position of the $i^{th}$ criminal on $X$-axis (in other words, if the $i^{th}$ integer is $x$, then location of the $i^{th}$ criminal is $(x,0)$). The value of the positions are between $1$ and $10^9$ and are given in increasing order in the input. + +**Output Format** + +Print the minimum amount of money required to complete the operation. + +**Sample Input** + + 5 10 + 1 4 5 6 9 + +**Sample Output** + + 34 + +**Explanation** + +For the sample test case, police department recruits $3$ officers who get paid $3\times10=30$. The first officer starts at point $(1,0)$ and catches the criminal there. So he does not use any fuel. The second officer catches criminals at points $(4,0)$, $(5,0)$ and $(6,0)$. He burns fuel worth USD $4$. The third officer catches the criminal at point $(9,0)$. He also does not burn any fuel. The total money spent by the department is, $30+4=34$. + +**Timelimits** + +Timelimits for this challenge are given [here](http://hr-filepicker.s3.amazonaws.com/101aug14/3926-circle-city-timelimits.json)",code,"Given N points on X-axis, find M points such that these cover given points and distance between adjacent points is minimized.",ai,2014-08-27T17:05:08,2022-08-31T08:14:51,"# +# Complete the 'policeOperation' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER h +# 2. INTEGER_ARRAY criminals +# + +def policeOperation(h, criminals): + # 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() + + n = int(first_multiple_input[0]) + + h = int(first_multiple_input[1]) + + criminals = list(map(int, input().rstrip().split())) + + result = policeOperation(h, criminals) + + fptr.write(str(result) + '\n') + + fptr.close() +","Roy is helping the police department of his city in crime fighting. Today, they informed him about a new planned operation. + +Think of the city as a $2D$ plane. The road along the $X$-axis is very crime prone, because $n$ criminals live there. No two criminals live at the same position. + +To catch these criminals, the police department has to recruit some police officers and give each of them USD $h$ as wages. A police officer can start his operation from any point $a$, drive his car to point $b$ in a straight line, and catch all the criminals who live on this way. The cost of fuel used by the officer's car is equal to the square of the euclidean distance between points $a$ and $b$ (Euclidean distance between points $(x_1,y_1)$ and $(x_2,y_2)$ equals to $\sqrt{ (x_1-x_2)^2 + (y_1-y_2)^2 }$ ). + +The police department asks Roy to plan this operation. So Roy has to tell them the number of officers to recruit and the routes these officers should take in order to catch all the criminals. Roy has to provide this information while minimizing the total expenses of this operation. + +Find out the minimum amount of money required to complete the operation. +",0.4857142857142857,"[""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 two integers $n$ $(0 \le n \le 2 \times 10^{6})$, number of criminals, and $h$ $( 0 \le h \le 10^{9} )$, the cost of recruiting a police officer. The next line contains $n$ space separated integers. The $i^{th}$ integer indicates the position of the $i^{th}$ criminal on $X$-axis (in other words, if the $i^{th}$ integer is $x$, then location of the $i^{th}$ criminal is $(x,0)$). The value of the positions are between $1$ and $10^9$ and are given in increasing order in the input. +","Print the minimum amount of money required to complete the operation. +"," 5 10 + 1 4 5 6 9 +"," 34 +",Hard,,,,,,,2014-08-27T17:06:14,2016-12-02T08:39:51,tester,"###C++ +```cpp +#ifdef ssu1 +#define _GLIBCXX_DEBUG +#endif +#undef NDEBUG + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define fore(i, l, r) for(int i = (l); i < (r); ++i) +#define forn(i, n) fore(i, 0, n) +#define fori(i, l, r) fore(i, l, (r) + 1) +#define sz(v) int((v).size()) +#define all(v) (v).begin(), (v).end() +#define pb push_back +#define mp make_pair +#define X first +#define Y second + +typedef long long li; +typedef long double ld; +typedef pair pt; + +template T abs(T a) { return a < 0 ? -a : a; } +template T sqr(T a) { return a*a; } + +const int INF = (int)1e9; +const ld EPS = 1e-9; +const ld PI = 3.1415926535897932384626433832795; + +/* + + This is just to check correctness of input + +*/ +int readInt(int l, int r){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int in range [%d, %d], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int in range [%d, %d], but found %d!"", l, r, x); + throw; + } + return x; +} +int readInt(int l, int r, string name){ + int x; + if(scanf(""%d"", &x) != 1){ + fprintf(stderr, ""Expected int %s in range [%d, %d], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected int %s in range [%d, %d], but found %d!"", name.c_str(), l, r, x); + throw; + } + return x; +} +li readLong(li l, li r){ + li x; + if(scanf(""%lld"", &x) != 1){ + fprintf(stderr, ""Expected long long in range [%lld, %lld], but haven't found!"", l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected long long in range [%lld, %lld], but found %lld!"", l, r, x); + throw; + } + return x; +} +li readLong(li l, li r, string name){ + li x; + if(scanf(""%lld"", &x) != 1){ + fprintf(stderr, ""Expected long long %s in range [%lld, %lld], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x && x <= r)){ + fprintf(stderr, ""Expected long long %s in range [%lld, %lld], but found %lld!"", name.c_str(), l, r, x); + throw; + } + return x; +} +const ld __EPS__ = 1e-15; +ld readDouble(double l, double r){ + double x; + if(scanf(""%lf"", &x) != 1){ + fprintf(stderr, ""Expected double in range [%lf, %lf], but haven't found!"", l, r); + throw; + } + if(!(l <= x + __EPS__ && x <= r + __EPS__)){ + fprintf(stderr, ""Expected double in range [%lf, %lf], but found %lf!"", l, r, x); + throw; + } + return x; +} +ld readDouble(double l, double r, string name){ + double x; + if(scanf(""%lf"", &x) != 1){ + fprintf(stderr, ""Expected double %s in range [%lf, %lf], but haven't found!"", name.c_str(), l, r); + throw; + } + if(!(l <= x + __EPS__ && x <= r + __EPS__)){ + fprintf(stderr, ""Expected double %s in range [%lf, %lf], but found %lf!"", name.c_str(), l, r, x); + throw; + } + return x; +} + +struct line{ + li A, B; + int lf, rg; + line(){} + li eval(li x) const { + return A * x + B; + } +}; + +const int NMAX = 2500000, MAXX = int(1e9) + 100; + +int n, C, x[NMAX]; +li d[NMAX]; + +bool worse(const line& a, const line& b, li x){ + return a.eval(x) >= b.eval(x); +} + +bool worse(const line& a, const line& b){ + return worse(a, b, a.lf) && worse(a, b, a.rg); +} + +void add(vector& q, int idx){ + line cur; + cur.B = d[idx] + x[idx] * 1LL * x[idx]; + cur.A = -2LL * x[idx]; + + while(!q.empty() && worse(q.back(), cur)){ + q.pop_back(); + } + + if(q.empty()) + cur.lf = 1, cur.rg = MAXX; + else{ + cur.lf = q.back().rg + 1; + cur.rg = MAXX; + if(worse(q.back(), cur, q.back().rg)){ + assert(!worse(q.back(), cur, q.back().lf)); + int lf = q.back().lf, rg = q.back().rg; + while(rg - lf > 1){ + int mid = (lf + rg) >> 1; + if(worse(q.back(), cur, mid)) + rg = mid; + else + lf = mid; + } + q.back().rg = lf; + cur.lf = rg; + } + } + if(cur.lf <= cur.rg) + q.pb(cur); +} + +bool cmp(const line& o1, const line& o2){ + return o1.lf < o2.lf; +} + +li get_val(const vector& q, int x){ + line tmp; + tmp.lf = x; + int pos = int(upper_bound(all(q), tmp, cmp) - q.begin()); + pos--; + assert(q[pos].lf <= x && x <= q[pos].rg); + return q[pos].eval(x); +} + +int main(){ +#ifdef ssu1 + assert(freopen(""input.txt"", ""rt"", stdin)); + //assert(freopen(""output.txt"", ""wt"", stdout)); +#endif + + n = readInt(0, 2000000); + C = readInt(0, int(1e9)); + forn(i, n){ + x[i] = readInt(1, int(1e9)); + } + forn(i, n - 1){ + assert(x[i] <= x[i + 1]); + } + n = int(unique(x, x + n) - x); + + if(n == 0){ + puts(""0""); + exit(0); + } + + vector q; + + d[0] = 0; + add(q, 0); + + fore(i, 1, n + 1){ + d[i] = get_val(q, x[i - 1]) + x[i - 1] * 1LL * x[i - 1] + C; + add(q, i); + } + + cout << d[n] << endl; + return 0; +} +``` +",not-set,2016-04-24T02:03:00,2016-07-23T15:40:25,C++ +157,3997,annual-boat-challenge,Annual Boat Challenge,"The big day is approaching, the finals of the Annual Boat Challenge. + +The challenge consists of going down the river and earning the biggest number of points as possible. The circuit contains N checkpoints. It starts at the checkpoint number 0 and can finish at any checkpoint. At each checkpoint the +competitors have a set of options to take. There are some pathes to the left and others to the right, they lead +the competitors to a next checkpoint with a bigger number. + +The boats are always leaning to some side, to the left or to the right. If the competitor wants to take a next +checkpoint using a path to the right and the boat is currently leaning to the left, he must change the boat's +inclination for taking this way. The same happens if he wants to take the left way and the boat is leaning to the right. +If the sides match, there is no need to change the inclination. + +The contest rules state that the competitors are able to change boats inclination at most K times. + +At the beginning, all the boats start leaning to the left. + +The judges are interested in knowing how many points a competitor could make by taking wisely his path. + + +**Input specification:** + +The first line contains two integers N(1<=N<=300) and K(0<=K<=100). The second line contains N integers Pi(0<=Pi<=1000), +the points the competitors will earn when they visit checkpoint i. Next, follow 2 * (N-1) lines. Two lines for each +checkpoint i. (0<=i5 1 +
421 990 160 473 333 +
4 2 1 2 3 +
0 +
1 2 +
2 4 4 +
1 4 +
2 4 4 +
1 4 +
0 + +**Sample output** +
1904",code,Let's count! ,ai,2014-08-27T19:11:28,2016-09-09T09:51:01,,,,"The big day is approaching, the finals of the Annual Boat Challenge. + +The challenge consists of going down the river and earning the biggest number of points as possible. The circuit contains N checkpoints. It starts at the checkpoint number 0 and can finish at any checkpoint. At each checkpoint the +competitors have a set of options to take. There are some pathes to the left and others to the right, they lead +the competitors to a next checkpoint with a bigger number. + +The boats are always leaning to some side, to the left or to the right. If the competitor wants to take a next +checkpoint using a path to the right and the boat is currently leaning to the left, he must change the boat's +inclination for taking this way. The same happens if he wants to take the left way and the boat is leaning to the right. +If the sides match, there is no need to change the inclination. + +The contest rules state that the competitors are able to change boats inclination at most K times. + +At the beginning, all the boats start leaning to the left. + +The judges are interested in knowing how many points a competitor could make by taking wisely his path. + + +**Input specification:** + +The first line contains two integers N(1<=N<=300) and K(0<=K<=100). The second line contains N integers Pi(0<=Pi<=1000), +the points the competitors will earn when they visit checkpoint i. Next, follow 2 * (N-1) lines. Two lines for each +checkpoint i. (0<=i5 1 +
421 990 160 473 333 +
4 2 1 2 3 +
0 +
1 2 +
2 4 4 +
1 4 +
2 4 4 +
1 4 +
0 + +**Sample output** +
1904",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-27T19:12:35,2016-05-12T23:57:49,setter,"import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.util.Vector; + + +public class Main { + static int N, K, L, R; + static int points[]; + static Vector G[][]; + static String cad[]; + static int DP[][][]; + + static int solve(int x, int s, int kk) { + if(kk > K) + return 0; + + if(DP[x][s][kk] != -1) + return DP[x][s][kk]; + + int maxx = 0; + + for(int i = 0;i(); + G[i][1] = new Vector(); + } + + for(int i = 0;i5 5 3 +
1 5 4 4 1 + +**Sample output** +
7",code,How many special subsequence!,ai,2014-08-27T19:26:55,2016-09-09T09:51:01,,,,"N numbers are given to you A1, A2, A3, ... AN-1, AN. How many increasing subsequences exist with at most K numbers where the difference between two consecutive numbers is at most D. + +An increasing subsequence of K numbers is a sequence Ai1, Ai2, ... ,Aik-1, Aik where (1 <= i1 < i2 < ik-1 < ik <= N) +and (Ai1 < Ai2 < ... < Aik-1 < Aik). + +In this problem Ai - Ai-1 <= D for each two consecutive numbers in the subsequence. + +**Input specification** + +The first line contains three numbers N (1 <= N <= 10000), K (1 <= K <= 100) and D (1 <= D <= 1000). Next, follow one line with N numbers Ai. (1<=Ai<=100000). + +**Output specification** + +Output just one line containing the remainder of the division by 1000000007 of the required answer. + + +**Sample input** +
5 5 3 +
1 5 4 4 1 + +**Sample output** +
7",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-27T19:27:09,2016-05-12T23:57:49,setter,"import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + + + +public class Main { + + static int BIT[]; + static int MOD = (int) 1e9 + 7; + + static void update(int x, int v) { + for(int i = x;i<=100000;i+=(i&-i)) + BIT[i] = (BIT[i] + v) % MOD; + } + + static int query(int x) { + int res = 0; + for(int i = x;i>0;i-=(i&-i)) + res = (res + BIT[i]) % MOD; + return res; + } + + public static void main(String[] args) throws IOException { + int N, K, D, upper, lower; + int arr[]; + int DP[][]; + + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + String cad[] = br.readLine().split("" ""); + N = Integer.parseInt(cad[0]); + K = Integer.parseInt(cad[1]); + D = Integer.parseInt(cad[2]); + + arr = new int[N+1]; + DP = new int[K+1][N]; + BIT = new int[100001]; + + cad = br.readLine().split("" ""); + for(int i = 0;i= i) { + upper = query(arr[j]-1); + lower = query(Math.max(arr[j]-D-1, 0)); + DP[i][j] = (upper + MOD - lower) % MOD; + } + update(arr[j], DP[i-1][j]); + } + } + + int sol = 0; + for(int i = 1;i<=K;i++) + for(int j = 0;j1 1 1 +
10 +
15 +
1 1 + +**Sample output** +
15",code,Can you help the company to earn money?,ai,2014-08-27T19:54:53,2016-09-09T09:51:02,,,,"Making business and earning money, this is a fashion which will never get old. You, a business man , want to increase +your fortune of making good business. There are two companies in the town. Each of these companies has a set of services and they are willing to sell these services to you. You know how much you will earn acquiring each of services. But your sharpen business mind figured out something. There are some services from one company you can not buy together with some services from the other company because people will just use one of them. + + +**Input specification** + +The first line contains N (1<=N<=200) - the number of services one company is selling, M (1<=M<=200) - the number of +services the other company is selling and K (1<=K<=5000). Next follow two lines. The first one contains N integers Ai, +(0<=Ai<=100) A1, A2, ... AN-1, AN, it describes the incomes will generate if the i- th service from one company is +acquired. The second one contains M integers Bi (0<=Bi<=100), B1, B2, ... BM-1, BM, it describes the incomes will +generate if the i- th service is adquired from the other company. Finally follow K distinct lines in the form 'X Y' +(1<=X<=N) and (1<=Y<=M), it is not convenient to buy service X from one company and service Y from the other company +due to the previous reasons. + +**Output specification** + +Output just one line, the maximum profit of the business. + + +**Sample input** +
1 1 1 +
10 +
15 +
1 1 + +**Sample output** +
15",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-27T19:55:15,2016-05-12T23:57:48,setter,"import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.logging.Level; + +import javax.naming.spi.DirectoryManager; +import javax.swing.Box.Filler; + + + +public class Main { + static int MAXA = 100000; + static int MAXV = 500; + static int oo = (int) 1e9; + + static int A, V, source, dest; + + static int cap[], flow[], ady[], next[], last[]; + static int now[], level[], Q[]; + + static void add(int u, int v, int c){ + cap[A] = c;flow[A] = 0;ady[A] = v;next[A] = last[u];last[u] = A++; + cap[A] = 0;flow[A] = 0;ady[A] = u;next[A] = last[v];last[v] = A++; + } + + static void init() { + cap = new int[MAXA]; + flow = new int[MAXA]; + ady = new int[MAXA]; + next = new int[MAXA]; + last = new int[MAXV]; + now = new int[MAXV]; + level = new int[MAXV]; + Q = new int[MAXV]; + } + + static boolean BFS() { + int beg, end, u, v; + for(int i = 1;i<=V;i++) + level[i] = -1; + level[source] = beg = end = 0; + Q[end++] = source; + + while(beg < end && level[dest] == -1) { + u = Q[beg++]; + for(int i = last[u];i!=-1;i=next[i]) { + v = ady[i]; + if(level[v] == -1 && flow[i] < cap[i]) { + level[v] = level[u] + 1; + Q[end++] = v; + } + } + } + + return level[dest] != -1; + } + + static int DFS(int u, int aum) { + int v; + if(u == dest) return aum; + for(int i = now[u];i!=-1;now[u]=i=next[i]) { + v = ady[i]; + if(level[v] > level[u] && flow[i] < cap[i]){ + int res = DFS(v, Math.min(aum, cap[i]-flow[i])); + if(res>0) { + flow[i]+=res; + flow[i^1]-=res; + return res; + } + } + } + return 0; + } + + static int Dinic() { + int ff = 0, res; + while(BFS()){ + for(int i = 0;i<=V;i++) + now[i] = last[i]; + while((res = DFS(source, oo))>0) + ff+=res; + } + return ff; + } + + + + public static void main(String[] args) throws IOException { + int N, M, K, x, y; + + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + String cad[] = br.readLine().split("" ""); + N = Integer.parseInt(cad[0]); + M = Integer.parseInt(cad[1]); + K = Integer.parseInt(cad[2]); + + int total = 0; + + source = 0; + dest = N + M + 1; + V = dest; + A = 0; + init(); + + for(int i = 0;i<=V;i++) + last[i] = -1; + + cad = br.readLine().split("" ""); + for (int i = 0; i < N; i++) { + x = Integer.parseInt(cad[i]); + add(source, i+1, x); + total += x; + } + + cad = br.readLine().split("" ""); + for (int i = 0; i < M; i++) { + x = Integer.parseInt(cad[i]); + add(N + i + 1, dest, x); + total += x; + } + + while(K-->0) { + cad = br.readLine().split("" ""); + x = Integer.parseInt(cad[0]); + y = Integer.parseInt(cad[1]); + add(x, N + y, oo); + } + + System.out.println(total - Dinic()); + } +}",not-set,2016-04-24T02:03:00,2016-04-24T02:03:00,Python +160,4002,covering-the-stains,Covering the stains,"There is a huge blanket on your bed but unfortunately it has **N** stains. You cover them using +a single, rectangular silk cloth. The silk is expensive, which is why the rectangular piece needs to have the least area as possible. You love this blanket and decide to minimize the area covering the stains. You buy some cleaning liquid to remove the stains but sadly it isn't enough to clean all of them. You can just remove exactly **K** stains. The rest of the stains need to be covered using a single, rectangular fragment of silk cloth. + +Let **X** denote the area of the smallest possible silk cloth that may cover all the stains originally. You need to find the number of different ways in which you may remove **K** stains so that the remaining **N-K** stains can be covered with silk of **area less than X** (We are looking for any configuration that will reduce the cost). + +Assume that each stain is a point and that the rectangle is aligned parallel to the axes. + +**Input specification** + +The first line contains two integers **N** (1<=N<=1000) and **K** (0<=K<=N). +Next follow **N** lines, one for each stain. Each line contains two integers in the form 'X Y', (0<=X,Y<100000), the coordinates of each stain into the blanket. Each pair of coordinates is unique. + +**Output specification** + +Output a single integer. The remainder of the division by 1000000007 of the answer. + + + +**Sample input** + + 5 2 + 0 1 + 3 3 + 2 0 + 0 3 + 2 3 + + +**Sample output** + + 8 + +**Hint** + +We can clean two spots. So removing any of the following set of stains will lead us to a conbination that will need less amount of silk.(The numbers refer to the **indices of the stains** in the input and they begin from 1). + + 1, 4 + 2, 1 + 2, 3 + 2, 4 + 2, 5 + 3, 1 + 3, 4 + 3, 5 + +So there are 8 ways.",code,"Given N 2D points, we need to remove K points optimally such that remaining (N-K) points could be covered by using a rectangular cloth with minimum area covered.",ai,2014-08-27T20:10:20,2022-08-31T08:14:49,"# +# Complete the 'coveringStains' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER k +# 2. 2D_INTEGER_ARRAY coordinates +# + +def coveringStains(k, coordinates): + # 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() + + n = int(first_multiple_input[0]) + + k = int(first_multiple_input[1]) + + coordinates = [] + + for _ in range(n): + coordinates.append(list(map(int, input().rstrip().split()))) + + result = coveringStains(k, coordinates) + + fptr.write(str(result) + '\n') + + fptr.close() +","There is a huge blanket on your bed but unfortunately it has **N** stains. You cover them using +a single, rectangular silk cloth. The silk is expensive, which is why the rectangular piece needs to have the least area as possible. You love this blanket and decide to minimize the area covering the stains. You buy some cleaning liquid to remove the stains but sadly it isn't enough to clean all of them. You can just remove exactly **K** stains. The rest of the stains need to be covered using a single, rectangular fragment of silk cloth. + +Let **X** denote the area of the smallest possible silk cloth that may cover all the stains originally. You need to find the number of different ways in which you may remove **K** stains so that the remaining **N-K** stains can be covered with silk of **area strictly less than X** (We are looking for any configuration that will reduce the cost). + +Assume that each stain is a point and that the rectangle is aligned parallel to the axes. +",0.5,"[""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 two integers **N** (1<=N<=1000) and **K** (0<=K<=N). +Next follow **N** lines, one for each stain. Each line contains two integers in the form 'X Y', (0<=X,Y<100000), the coordinates of each stain into the blanket. Each pair of coordinates is unique. +","Output a single integer. The remainder of the division by 1000000007 of the answer. +"," 5 2 + 0 1 + 3 3 + 2 0 + 0 3 + 2 3 +"," 8 +",Hard,,,,,,,2014-08-27T20:10:35,2016-12-01T19:40:05,setter,"###Java +```java +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + + + +public class Main { + +static int MOD = (int) 1e9 + 7; + +public static void main(String[] args) throws IOException { + int N, K, mask; + int stains[][]; + int arr[]; + int DP[][][]; + int vals[]; + + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + String cad[] = br.readLine().split("" ""); + N = Integer.parseInt(cad[0]); + K = Integer.parseInt(cad[1]); + + K = N - K; + + if(K == 0) { + System.out.print(1); + System.exit(0); + } + + stains = new int[N+2][2]; + arr = new int[N+2]; + vals = new int[]{0,100000,0,100000}; + + for(int i = 1;i<=N;i++) { + cad = br.readLine().split("" ""); + stains[i][0] = Integer.parseInt(cad[0]); + stains[i][1] = Integer.parseInt(cad[1]); + + vals[0] = Math.max(vals[0], stains[i][0]); + vals[1] = Math.min(vals[1], stains[i][0]); + vals[2] = Math.max(vals[2], stains[i][1]); + vals[3] = Math.min(vals[3], stains[i][1]); + } + + + for(int i = 1;i<=N;i++) { + mask = 0; + for(int j = 0;j<4;j++) { + if(vals[j] == stains[i][j/2]) + mask |= (1<>= + mapM_ (putStrLn. unwords. map show). (\[[m], [r, c]] -> f (2^m) r c 1 1 []). map (map read.words). lines + + f :: Int -> Int -> Int -> Int -> Int -> [[Int]] -> [[Int]] + f 1 _ _ _ _ arr = arr + f n r c x y arr = curVal : curArr + where + m = n`div`2 + x0 = [x, x, x+m, x+m] + y0 = [y, y+m, y, y+m] + x1 = map (\v -> v+(m-1)) x0 + y1 = map (\v -> v+(m-1)) y0 + [part] = [i | i <- [0..3] + , x0!!i <= r && r <= x1!!i + , y0!!i <= c && c <= y1!!i] + curVal = + concat [ case i of + 0 -> [x1!!0 , y1!!0 ] + 1 -> [x1!!0 , 1+y1!!0] + 2 -> [1+x1!!0, y1!!0] + 3 -> [1+x1!!0, 1+y1!!0] + | i <- [0..3], i /= part + ] + curArr' = + foldl' + (\acc x -> + case x of + 0 -> f m (x1!!0) (y1!!0) (x0!!0) (y0!!0) acc + 1 -> f m (x1!!0) (1+y1!!0) (x0!!1) (y0!!1) acc + 2 -> f m (1+x1!!0) (y1!!0) (x0!!2) (y0!!2) acc + 3 -> f m (1+x1!!0) (1+y1!!0) (x0!!3) (y0!!3) acc + ) + arr + (filter (/= part) [0..3]) + curArr = f m r c (x0!!part) (y0!!part) curArr' +",not-set,2016-04-24T02:03:00,2016-04-24T02:03:00,Python +162,4032,working-with-boxes,Working with boxes,"A warehouse contains N boxes in a single line. The administrator of the warehouse wants to merge them to form a single stack. + +The workers can take 2 consecutive non-empty stacks of boxes i and i+1 (A single box is a stack as well) and merge them into a new stack at position i. This is counted as one operation. The time in minutes for the operation is the total weight (W1) multiplied by the number of boxes (N1) in one stack, plus, the total weight (W2) multiplied by the number of boxes (N2) in the other stack: W1 * N1 + W2 * N2. +Two operations cannot happen at the same time. + +The administrator sets a deadline of T minutes, so the work must be finished in T minutes or less. The workers can use a crane to work faster. This crane will reduce the time taken for every operation by C minutes, if you pay to the operator a non-negative amount of dollars(C). So this operation takes time: W1 * N1 + W2 * N2 - C. + +What is the minimum value of C that will ensure that the work is finished in no more than T minutes? + +**Update** +If the operation time < 0 at any point of time, the the time taken is 0. + +**Input Format** +The first line contains 2 numbers N and T . Next follows a line with N integers Wi - the weight of each box. + +**Constraints** + +$1 \le N \le 100$ +$1 \le T \le 10^6$ +$1 \le W_i \le 100$ + +**Output Format** +Output just one line, the minimum value of C that will ensure that the work is finished in T minutes or less. + +**Sample Input** + + 4 15 + 1 1 2 2 + +**Sample Output** + + 1 + +**Explanation** +
for C = 0: +
The optimal way to make a singe stack: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1. creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 creates a single stack. +The total time is 2 + 4 + 12 = 18. The dead line is 15 minutes and it is not reached. + +for C = 1: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1 - 1 creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 - 1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 - 1 creates a single stacks. +The total time is 1+3+11 = 15. Finally the deadline is reached for C = 1. + + ",code,Save money is your mission!! ,ai,2014-08-31T07:51:28,2016-09-09T09:51:11,,,,"A warehouse contains N boxes in a single line. The administrator of the warehouse wants to merge them to form a single stack. + +The workers can take 2 consecutive non-empty stacks of boxes i and i+1 (A single box is a stack as well) and merge them into a new stack at position i. This is counted as one operation. The time in minutes for the operation is the total weight (W1) multiplied by the number of boxes (N1) in one stack, plus, the total weight (W2) multiplied by the number of boxes (N2) in the other stack: W1 * N1 + W2 * N2. +Two operations cannot happen at the same time. + +The administrator sets a deadline of T minutes, so the work must be finished in T minutes or less. The workers can use a crane to work faster. This crane will reduce the time taken for every operation by C minutes, if you pay to the operator a non-negative amount of dollars(C). So this operation takes time: W1 * N1 + W2 * N2 - C. + +What is the minimum value of C that will ensure that the work is finished in no more than T minutes? + +**Update** +If the operation time < 0 at any point of time, the the time taken is 0. + +**Input Format** +The first line contains 2 numbers N and T . Next follows a line with N integers Wi - the weight of each box. + +**Constraints** + +$1 \le N \le 100$ +$1 \le T \le 10^6$ +$1 \le W_i \le 100$ + +**Output Format** +Output just one line, the minimum value of C that will ensure that the work is finished in T minutes or less. + +**Sample Input** + + 4 15 + 1 1 2 2 + +**Sample Output** + + 1 + +**Explanation** +
for C = 0: +
The optimal way to make a singe stack: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1. creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 creates a single stack. +The total time is 2 + 4 + 12 = 18. The dead line is 15 minutes and it is not reached. + +for C = 1: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1 - 1 creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 - 1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 - 1 creates a single stacks. +The total time is 1+3+11 = 15. Finally the deadline is reached for C = 1. + + ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-31T07:51:44,2016-12-05T00:09:48,setter," import java.io.BufferedReader; + import java.io.File; + import java.io.IOException; + import java.io.InputStreamReader; + + public class Main { + + static int N;; + static long T, L, R, M; + static long arr[]; + static long DP[][]; + + static long solve(int beg, int end) { + if(beg == end) return 0; + if(DP[beg][end]!=-1) + return DP[beg][end]; + + long minn = (long) 1e18; + for(int i = beg;i5){ + M = (R+L)/2; + if(check()) R = M; else + L = M; + } + + for(M=L;M<=R;M++) + if(check()) + break; + + System.out.println(M); + } + } +",not-set,2016-04-24T02:03:01,2016-04-24T02:03:01,Python +163,4032,working-with-boxes,Working with boxes,"A warehouse contains N boxes in a single line. The administrator of the warehouse wants to merge them to form a single stack. + +The workers can take 2 consecutive non-empty stacks of boxes i and i+1 (A single box is a stack as well) and merge them into a new stack at position i. This is counted as one operation. The time in minutes for the operation is the total weight (W1) multiplied by the number of boxes (N1) in one stack, plus, the total weight (W2) multiplied by the number of boxes (N2) in the other stack: W1 * N1 + W2 * N2. +Two operations cannot happen at the same time. + +The administrator sets a deadline of T minutes, so the work must be finished in T minutes or less. The workers can use a crane to work faster. This crane will reduce the time taken for every operation by C minutes, if you pay to the operator a non-negative amount of dollars(C). So this operation takes time: W1 * N1 + W2 * N2 - C. + +What is the minimum value of C that will ensure that the work is finished in no more than T minutes? + +**Update** +If the operation time < 0 at any point of time, the the time taken is 0. + +**Input Format** +The first line contains 2 numbers N and T . Next follows a line with N integers Wi - the weight of each box. + +**Constraints** + +$1 \le N \le 100$ +$1 \le T \le 10^6$ +$1 \le W_i \le 100$ + +**Output Format** +Output just one line, the minimum value of C that will ensure that the work is finished in T minutes or less. + +**Sample Input** + + 4 15 + 1 1 2 2 + +**Sample Output** + + 1 + +**Explanation** +
for C = 0: +
The optimal way to make a singe stack: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1. creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 creates a single stack. +The total time is 2 + 4 + 12 = 18. The dead line is 15 minutes and it is not reached. + +for C = 1: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1 - 1 creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 - 1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 - 1 creates a single stacks. +The total time is 1+3+11 = 15. Finally the deadline is reached for C = 1. + + ",code,Save money is your mission!! ,ai,2014-08-31T07:51:28,2016-09-09T09:51:11,,,,"A warehouse contains N boxes in a single line. The administrator of the warehouse wants to merge them to form a single stack. + +The workers can take 2 consecutive non-empty stacks of boxes i and i+1 (A single box is a stack as well) and merge them into a new stack at position i. This is counted as one operation. The time in minutes for the operation is the total weight (W1) multiplied by the number of boxes (N1) in one stack, plus, the total weight (W2) multiplied by the number of boxes (N2) in the other stack: W1 * N1 + W2 * N2. +Two operations cannot happen at the same time. + +The administrator sets a deadline of T minutes, so the work must be finished in T minutes or less. The workers can use a crane to work faster. This crane will reduce the time taken for every operation by C minutes, if you pay to the operator a non-negative amount of dollars(C). So this operation takes time: W1 * N1 + W2 * N2 - C. + +What is the minimum value of C that will ensure that the work is finished in no more than T minutes? + +**Update** +If the operation time < 0 at any point of time, the the time taken is 0. + +**Input Format** +The first line contains 2 numbers N and T . Next follows a line with N integers Wi - the weight of each box. + +**Constraints** + +$1 \le N \le 100$ +$1 \le T \le 10^6$ +$1 \le W_i \le 100$ + +**Output Format** +Output just one line, the minimum value of C that will ensure that the work is finished in T minutes or less. + +**Sample Input** + + 4 15 + 1 1 2 2 + +**Sample Output** + + 1 + +**Explanation** +
for C = 0: +
The optimal way to make a singe stack: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1. creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 creates a single stack. +The total time is 2 + 4 + 12 = 18. The dead line is 15 minutes and it is not reached. + +for C = 1: +
**Step 1:** Stacking 1st and 2nd boxes in time 1*1+1*1 - 1 creates a new line of stacks with weights 2 2 2 and amount of boxes 2 1 1. + +**Step 2:** Stacking 2nd and 3rd boxes in time 2*1 + 2*1 - 1 creates a new line of stacks with weights 2 4 and amount of boxes 2 2. + +**Step 3:** Stacking 1st and 2nd boxes in time 2*2 + 4*2 - 1 creates a single stacks. +The total time is 1+3+11 = 15. Finally the deadline is reached for C = 1. + + ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-31T07:51:44,2016-12-05T00:09:48,tester," #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 VPLL; + typedef vector VI; + typedef vector VL; + typedef vector VPII; + typedef vector VVI; + typedef vector VVPII; + #define MM(a,x) memset(a,x,sizeof(a)); + #define ALL(x) (x).begin(), (x).end() + #define P(x) cerr<<""[""#x<<"" = ""<<(x)<<""]""< ""#b"": ""<<1e3*(b-a)/CLOCKS_PER_SEC<<""ms]\n""; + #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 ostream& operator<<(ostream &o, pair t) {o << ""("" << t.x << "", "" << t.y << "")""; return o;} + template string tostring(T x, int len = 0, char c = '0') {stringstream ss; ss << x; string r = ss.str(); if(r.length() < len) r = string(len - r.length(), c) + r; return r;} + template void PV(T a, T b, int n = 0, int w = 0, string s = "" "") {int c = 0; while(a != b) {cout << tostring(*a++, w, ' '); if(a != b && (n == 0 || ++c % n)) cout << s; else cout << ""\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 LL linf = 0x3f3f3f3f3f3f3f3fLL; + const int inf = 0x3f3f3f3f; + const int mod = int(1e9) + 7; + const int N = 111; + + int n, T; + int w[N]; + int s[N]; + + int dp[N][N]; + + int check(int c) { + MM(dp, 0x3f); + for(int i = 0; i < n; i++) dp[i][i] = 0; + for(int l = 2; l <= n; l++) + for(int i = 0; i < n; i++) { + int j = i + l - 1; + if(j >= n) break; + + for(int k = i; k < j; k++) { + int cost = (s[k + 1] - s[i]) * (k - i + 1) + (s[j + 1] - s[k + 1]) * (j - k); + cost = max(cost - c, 0); + chmin(dp[i][j], dp[i][k] + dp[k + 1][j] + cost); + } + } + return dp[0][n - 1] <= T; + } + + int main() { + cin >> n >> T; + assert(1 <= n && n <= 100); + assert(1 <= T && T <= 1e6); + for(int i = 0; i < n; i++) { + cin >> w[i]; + assert(1 <= w[i] && w[i] <= 100); + s[i + 1] = s[i] + w[i]; + } + + int L = 0, R = inf; + + while(L < R) { + int M = (L + R) / 2; + + if(check(M)) { + R = M; + } else { + L = M + 1; + } + } + + cout << L << endl; + + return 0; + } +",not-set,2016-04-24T02:03:01,2016-04-24T02:03:01,C++ +164,4036,the-brumpys-colony,The brumpy's colony,"The scientists have discovered a new animal specie, the brumpies. This new specie is very funny and interesting. The scientists now are experimenting with their reproduction. This specie has asexual reproduction, which means they do not need a couple for the reproduction .T hey reproduce themselves by division. It has been discovered N different types of this specie. + +The moment of the reproduction is very interesting. When the brumpies try to reproduce, it has the same probability of reproducing or dying. If it reproduces, a new brumpy is born but if the new brumpy is the same type as is father, the father must abandon the colony. Each colony will just have one reproduction per day and will just involve one brumpy. Strange, isn't it? If there is just one brumpy at the colony , it will never die when it is reproducing. The colony never disappears. + +All the brumpies have the same probability of being selected on the colony for the reproduction into the current day. + +The scientists are interested in this reproduction process so they want to know the expected number of days for an +initial colony to become a colony with all the N brumpy's types present. + + +**Input specification** + +The first line contains N (1 <= N <= 8) - How many types of brumpy exist. The second line contains the +description of the initial colony. It starts with A(1 <= A <= N), how many brumpies there are. Follow A distinct +integers Ai(1 <= Ai <= N), the types of brumpies present in the initial colony. Next, follow N lines with N integers +Pij(1 <= Pij <= 100) for each line. Pij means the probability multiplied by 100 of obtaining a brumpy type-j when +a type-i is reproducing. This table is consistent, that means the summation of each row is 100. + +**Output specification** + +Just a simple line, the expected numbers of days for the initial colony to become a colony with all the N brumpy's +types present rounded up to 2 decimal places. + + +**Sample input** +
2 +
1 2 +
34 66 +
29 71 + +**Sample output** +
3.45",code,You have been challenged by the colony!!,ai,2014-08-31T09:06:13,2016-09-09T09:51:13,,,,"The scientists have discovered a new animal specie, the brumpies. This new specie is very funny and interesting. The scientists now are experimenting with their reproduction. This specie has asexual reproduction, which means they do not need a couple for the reproduction .T hey reproduce themselves by division. It has been discovered N different types of this specie. + +The moment of the reproduction is very interesting. When the brumpies try to reproduce, it has the same probability of reproducing or dying. If it reproduces, a new brumpy is born but if the new brumpy is the same type as is father, the father must abandon the colony. Each colony will just have one reproduction per day and will just involve one brumpy. Strange, isn't it? If there is just one brumpy at the colony , it will never die when it is reproducing. The colony never disappears. + +All the brumpies have the same probability of being selected on the colony for the reproduction into the current day. + +The scientists are interested in this reproduction process so they want to know the expected number of days for an +initial colony to become a colony with all the N brumpy's types present. + + +**Input specification** + +The first line contains N (1 <= N <= 8) - How many types of brumpy exist. The second line contains the +description of the initial colony. It starts with A(1 <= A <= N), how many brumpies there are. Follow A distinct +integers Ai(1 <= Ai <= N), the types of brumpies present in the initial colony. Next, follow N lines with N integers +Pij(1 <= Pij <= 100) for each line. Pij means the probability multiplied by 100 of obtaining a brumpy type-j when +a type-i is reproducing. This table is consistent, that means the summation of each row is 100. + +**Output specification** + +Just a simple line, the expected numbers of days for the initial colony to become a colony with all the N brumpy's +types present rounded up to 2 decimal places. + + +**Sample input** +
2 +
1 2 +
34 66 +
29 71 + +**Sample output** +
3.45",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-31T09:07:15,2016-05-12T23:57:39,setter,"import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; + + + +public class Main { + + static int N, A; + static int INITIAL=0; + static double P[][]; + static String cad[]; + static double M[][]; + + static String Round(double sol) { + sol = Math.round(sol * 100.0) / 100.0; + DecimalFormat format = new DecimalFormat(""0.00""); + DecimalFormatSymbols dfs = format.getDecimalFormatSymbols(); + dfs.setDecimalSeparator('.'); + format.setDecimalFormatSymbols(dfs); + + return format.format(sol); + } + + static void Gauss(int n){ + for(int col = 0;col < n;col++){ + int piv = col; + for(int row = col + 1; row < n;row++) + if(Math.abs(M[row][col]) > Math.abs(M[piv][col])) + piv = row; + for(int k = 0;k<=n;k++) { + double tmp = M[col][k]; + M[col][k] = M[piv][k]; + M[piv][k] = tmp; + } + for(int row = col + 1;row < n;row++){ + double m = M[row][col] / M[col][col]; + for(int k = col;k<=n;k++) + M[row][k] -= m * M[col][k]; + } + } + //inverse process + for(int row = n-1;row >= 0 ;row--){ + for(int col = row + 1;col 0) + ++cc; + + for(int j = 0;j0) { + double rep = (cc == 1 ? 1.0 : 0.5); + for(int k = 0;k1) + M[i-1][ (i ^ (1<5 1 +
8 1 9 5 6 + + +**Sample output** +
4 + +Hint: +
The maximum number of snipers could be are 2. +They could occupy the next buildings: +2 3 +4 5 +There are 4 buildings could contain snipers, bulding number 2,3,4 and 5.",code,Count the number of building!,ai,2014-08-31T21:30:18,2016-09-09T09:51:19,,,,"The National Security is in charge of the president's security. Tomorrow the president is going to speak to people. Today, everybody is crazy because there is a threat in progress. The agents believe there is a possibility of +a sniper attack. The city consists of just one road with N contiguous buildings. + +The experts say the snipers could take position on the roof of the buildings following the next assumptions: + +- If there is a sniper at building i-th with height Hi and there is other sniper at building j-th with height Hj,then Hi < Hj and j - i <= D for (1 <= i < j <= N). +- The terrorist are going to set as much snipers as they can, following the previous constraints in order to increase the success. + +The National Security wants you to make a program which helps them to know how many buildings could contain a +sniper. + +**Input specification** + +The first line contains two numbers N (1<=N<=100000) and D (1<=D<=10000). Next follow a line with N integers +Hi(1<=Hi<=100000), the height of the i-th building. (Hi != Hj, Max(i-D-1, 1) <= j < i). + +**Output specification** + +Output just a single line with the number of buildings could contain a sniper. + + +**Sample input** +
5 1 +
8 1 9 5 6 + + +**Sample output** +
4 + +Hint: +
The maximum number of snipers could be are 2. +They could occupy the next buildings: +2 3 +4 5 +There are 4 buildings could contain snipers, bulding number 2,3,4 and 5.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-31T21:33:45,2016-05-12T23:57:37,setter,"import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; + +public class Main { + static int N, D; + static String cad[]; + static int arr[],inc[]; + static int tree[]; + static int c, d, maxx, val, upper, remove, sol; + + static void update(int index, int a, int b) { + if(a > c || b < c) return; + if(a == b) { + tree[index] = d; + return; + } + + update(2*index, a, (a+b)/2); + update(2*index+1, (a+b)/2+1, b); + + tree[index] = Math.max(tree[2*index], tree[2*index+1]); + } + + static int querie(int index, int a, int b) { + if(a > d || b < c) return 0; + if(a >= c && b <= d) { + return tree[index]; + } + return Math.max(querie(2*index, a, (a+b)/2), querie(2*index+1, (a+b)/2+1, b)); + } + + public static void main(String[] args) throws IOException { + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + cad = br.readLine().split("" ""); + N = Integer.parseInt(cad[0]); + D = Integer.parseInt(cad[1]); + + arr = new int[N+2]; + inc = new int[N+2]; + + cad = br.readLine().split("" ""); + for (int i = 0; i < N; i++) { + arr[i] = Integer.parseInt(cad[i]); + upper = Math.max(upper, arr[i]); + } + + tree = new int[upper * 5 + 2]; + + maxx = 0; + for(int i = 0;i= 0) { + c = arr[remove]; + d = 0; + update(1,1,upper); + } + + c = 1; + d = arr[i] - 1; + if(c <= d) { + val = querie(1, 1, upper); + } else { + val = 0; + } + + inc[i] = val + 1; + maxx = Math.max(maxx, inc[i]); + + c = arr[i]; + d = inc[i]; + update(1, 1, upper); + } + + tree = new int[upper * 5 + 2]; + + for(int i = N-1;i>=0;i--) { + remove = i + D + 1; + if(remove < N) { + c = arr[remove]; + d = 0; + update(1,1,upper); + } + + c = arr[i] + 1; + d = upper; + if(c <= d) { + val = querie(1, 1, upper); + } else { + val = 0; + } + + if(inc[i] + val == maxx) { + ++sol; + } + + c = arr[i]; + d = val + 1; + update(1, 1, upper); + } + + System.out.println(sol); + } +}",not-set,2016-04-24T02:03:01,2016-04-24T02:03:01,Python +166,4050,city-x-and-the-cell-phone,City X and the cell phone companies,"City X is an amazing city with N citizens. There are K cell phone companies at City X. The citizens use the +cell phones in their normal lifes, so they are made contracts with the cell phone companies. Each citizen has made a +contract with just one company. + +**Input specification** + +The input consists of just one line with two integers, N (1<=N<=1000) and K (1<=K<=1000). + +**Output specification** + +The output consists of just one line with the probability of existing two citizens who use the same cell phone company +rounded up to 3 decimal places. + + +**Sample input** +
50 1000 + +**Sample output** +
0.712",code,Find the odds for the people!,ai,2014-08-31T22:06:16,2016-09-09T09:51:20,,,,"City X is an amazing city with N citizens. There are K cell phone companies at City X. The citizens use the +cell phones in their normal lifes, so they are made contracts with the cell phone companies. Each citizen has made a +contract with just one company. + +**Input specification** + +The input consists of just one line with two integers, N (1<=N<=1000) and K (1<=K<=1000). + +**Output specification** + +The output consists of just one line with the probability of existing two citizens who use the same cell phone company +rounded up to 3 decimal places. + + +**Sample input** +
50 1000 + +**Sample output** +
0.712",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-31T22:06:39,2016-05-12T23:57:35,setter,"import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.Arrays; + + +public class Main { + + static int N, K; + static double sol; + static String cad[]; + + + static String Round(double sol) { + sol = Math.round(sol * 1000.0) / 1000.0; + DecimalFormat format = new DecimalFormat(""0.000""); + DecimalFormatSymbols dfs = format.getDecimalFormatSymbols(); + dfs.setDecimalSeparator('.'); + format.setDecimalFormatSymbols(dfs); + + return format.format(sol); + } + + public static void main(String[] args) throws IOException { + + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + cad = br.readLine().split("" ""); + N = Integer.parseInt(cad[0]); + K = Integer.parseInt(cad[1]); + + if(N > K) { + System.out.println(""1.000""); + } else { + sol = 1; + for(int i = 0;i Ai+1. + +John is interested in how many permutations can be reached who starts with a stack of height K. + +**Input specification** + +The first line contains two numbers N (2<=N<=1000) and K(1<=K<=N). Next follow a line with N-1 numbers Pi(0<=P1<=1), +the description of the pattern. + +**Output specification** + +Output just one line with the numbers of permutations that can be reached and start with a stack of height K. + +**Sample input** +
4 3 +
1 0 1 + +**Sample output** +
2 + +**Hint:** +
3 1 4 2 +
3 2 4 1",code,If you like permutations solve this challenge!,ai,2014-08-31T22:52:42,2016-09-09T09:51:20,,,,"Our friend John has N consecutive lined up stacks Ai with height 1, 2, 3,..., N-1, N. John can do successive swaps among +these stacks and reach some permutations. + +A permutation is considered beautiful if it matches a pattern. A pattern is sequence of N-1 numbers Pi +where Pi = 0 if Ai < Ai+1, and Pi = 1 if Ai > Ai+1. + +John is interested in how many permutations can be reached who starts with a stack of height K. + +**Input specification** + +The first line contains two numbers N (2<=N<=1000) and K(1<=K<=N). Next follow a line with N-1 numbers Pi(0<=P1<=1), +the description of the pattern. + +**Output specification** + +Output just one line with the numbers of permutations that can be reached and start with a stack of height K. + +**Sample input** +
4 3 +
1 0 1 + +**Sample output** +
2 + +**Hint:** +
3 1 4 2 +
3 2 4 1",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-08-31T22:54:34,2016-05-12T23:57:34,setter,"import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Main { + + static int N, K; + static int P[]; + static int DP[][]; + static String cad[]; + static int MOD = (int) 1e9 + 7; + + public static void main(String[] args) throws IOException { + InputStreamReader sr = new InputStreamReader(System.in); + BufferedReader br = new BufferedReader(sr); + + cad = br.readLine().split("" ""); + + N = Integer.parseInt(cad[0]); + K = Integer.parseInt(cad[1]); + + P = new int[N]; + DP = new int[N+1][N+1]; + + cad = br.readLine().split("" ""); + for(int i = 0;i=0;i--) { + if(P[i] == 0) { + for(int j = 1;j <= N - i;j++) { + DP[i][j] = (DP[i][j] + (DP[i+1][N - i - 1] + MOD - DP[i+1][j-1]) % MOD ) % MOD; + DP[i][j] = (DP[i][j] + DP[i][j-1]) % MOD; + } + } else { + for(int j = 1;j <= N - i;j++) { + DP[i][j] = (DP[i][j] + DP[i+1][j-1]) % MOD; + DP[i][j] = (DP[i][j] + DP[i][j-1]) % MOD; + } + } + } + + System.out.println((DP[0][K] + MOD - DP[0][K-1]) % MOD); + } +}",not-set,2016-04-24T02:03:01,2016-04-24T02:03:01,Python +168,4059,lcs-deletion,LCS Deletion,"Manasa is teaching Algorithms to Akhil. Akhil is pretty excited after knowing about the longest common subsequence. Akhil thinks that he can solve any problem related to the longest common subsequence and asks Manasa to give a harder problem. Manasa gives a problem to him as described below.

+ +Given two list each containg $N$ numbers. Numbers in both lists are a permuation of $1,2,3 \cdots N$. In an operation, Akhil will have to choose the longest commong subsequence of the both strings and delete that substring from the first list. He will keep repeating the given procedure as long long as first list has one or more numbers. + +Your task is to find the number of the required steps. + +**Input Format** +The first line contains an integer $N$.
+Next two lines will contain $N$ integers. + +**Output Format** +Print the number of the required steps. + +**Constraints** + +$ 1\le N \le 5 \times 10^5$
+ + +**Sample Input 00** + + 3 + 1 2 3 + 1 2 3 + + + +**Sample Output 00** + + 1 + + +**Sample Input 01** + + 4 + 1 3 2 4 + 3 1 4 2 + +**Sample Output 01** + + 2 + ",code,Help Manasa in LCS Deletion ,ai,2014-09-01T17:04:31,2019-07-02T13:58:49,,,,"You are given two lists, each containg $N$ numbers. The numbers in both lists are a permuation of $1,2,3 \cdots N$. In an operation, Akhil will have to choose the longest common subsequence of both strings and delete that subsequence from the first list. The process is repeated as long as the first list has one or more numbers. + +So, for the given input, find the minimal number of operations that will be executed. + +**Input Format** +The first line contains an integer $N$. +The next two lines contain $N$ integers. + +**Constraints** +$ 1\le N \le 5 \times 10^5$ + +**Output Format** +Print the mimimal number of required operations. + +**Sample Input 00** + + 3 + 1 2 3 + 1 2 3 + +**Sample Output 00** + + 1 + +**Sample Input 01** + + 4 + 1 3 2 4 + 3 1 4 2 + +**Sample Output 01** + + 2 + ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-01T17:05:23,2016-12-02T17:55:45,setter," #include + + using namespace std; + + int a[510000]; + int b[510000]; + int arr[510000]; + + int MaxInSeq(int N) + { + int i; + set s; + set::iterator k; + for (i=0; i>n; + assert(1<=n); + assert(n<=500000); + for(int i=1 ; i<=n ; i++) + { + cin>>a[i]; + assert(1<=a[i]); + assert(a[i]<=n); + } + for(int i=1 ; i<= n ; i++) + { + int x; + cin>>x; + assert(1<=x); + assert(x<=n); + b[x] = i; + } + for(int i=1 ; i<=n ; i++) + { + a[i] = b[a[i]]; + } + for(int i=0 ; in-1-y) + { + x -= (n-1-y); + y = n-1; + } + else + { + y += (x-0); + x = 0; + } + if(c[x][y]==null) + c[x][y] = new cell(); + c[x][y].dia2+= a[i][j]; + + j++; + + } + } + + for(i = 0;in-1-y) + { + x -= (n-1-y); + y = n-1; + } + else + { + y += (x-0); + x = 0; + } + c[i][j].dia2 = c[x][y].dia2; + long t = c[i][j].dia1 + c[i][j].dia2 - a[i][j]; + if((i+j)%2==0 && t>max1) + { + max1 = t; x1 = i; y1 = j ; + } + else if((i+j)%2==1 && t>max2) + { + max2 = t; x2 = i; y2 = j; + } + + } + + } + System.out.println(max1+max2); + + } + + } + + class cell + { + long dia1,dia2; + }",not-set,2016-04-24T02:03:02,2016-04-24T02:03:02,Python +170,4094,mice-v2,Mice V2,"__n__ mice are playing in the desert, when one of them notices some hawks flying in the sky. It alerts the other mice who now realize that the hawks are going to attack them very soon. They are scared and want to get inside holes to ensure their safety.
+Mice and holes are placed on a straight line. There are __m__ holes on this line. Each hole can accommodate only 1 mouse. A mouse can either stay at its position, or move one step right from __x__ to __x+1__, or move one step left from __x__ to __x-1__. Any of these movements takes 1 minute.
+Assign mice to holes so that the time required for all the mice to move inside the holes is minimized. + +__Input Format__
+The first line contains an integer __T__, the number of test cases. This is followed by __T__ blocks of input:
+First line contains 2 positive integers **n** and **m** separated by a single space. +Next line contains __n__ space separated integers, denoting the positions of the mice. +Next line contains __m__ space separated integers, denoting the positions of the holes. +Note: No two holes have the same position. + +__Output Format__
+For each testcase, print the minimum time taken by all the mice to reach inside the holes. + +__Constraints__
+1 ≤ T ≤ 17
+1 ≤ n ≤ 131072
+1 ≤ m ≤ 131072
+n ≤ m
+-108 ≤ mouse[i] ≤ 108
+-108 ≤ hole[j] ≤ 108
+ + +__Sample Input__
+
+1
+3 4
+2 0 -4
+3 1 2 -1
+
+ +__Sample Output__
+
+3
+
+ +**Explanation** +One possible solution is :
+Assign mouse at position x=-4 to hole at position x=-1 -> 3 minutes
+Assign mouse at postion x=2 to hole at position x=2 -> 0 minutes
+Assign mouse at postion x=0 to hole at postion x=3 -> 3 minutes
+So the answer is 3, after 3 minutes all of the mice are in the holes.",code,,ai,2014-09-03T11:26:43,2016-09-09T09:51:34,,,,"__n__ mice are playing in the desert, when one of them notices some hawks flying in the sky. It alerts the other mice who now realize that the hawks are going to attack them very soon. They are scared and want to get inside holes to ensure their safety.
+Mice and holes are placed on a straight line. There are __m__ holes on this line. Each hole can accommodate only 1 mouse. A mouse can either stay at its position, or move one step right from __x__ to __x+1__, or move one step left from __x__ to __x-1__. Any of these movements takes 1 minute.
+Assign mice to holes so that the time required for all the mice to move inside the holes is minimized. + +__Input Format__
+The first line contains an integer __T__, the number of test cases. This is followed by __T__ blocks of input:
+First line contains 2 positive integers **n** and **m** separated by a single space. +Next line contains __n__ space separated integers, denoting the positions of the mice. +Next line contains __m__ space separated integers, denoting the positions of the holes. +Note: No two holes have the same position. + +__Output Format__
+For each testcase, print the minimum time taken by all the mice to reach inside the holes. + +__Constraints__
+1 ≤ T ≤ 17
+1 ≤ n ≤ 131072
+1 ≤ m ≤ 131072
+n ≤ m
+-108 ≤ mouse[i] ≤ 108
+-108 ≤ hole[j] ≤ 108
+ + +__Sample Input__
+
+1
+3 4
+2 0 -4
+3 1 2 -1
+
+ +__Sample Output__
+
+3
+
+ +**Explanation** +One possible solution is :
+Assign mouse at position x=-4 to hole at position x=-1 -> 3 minutes
+Assign mouse at postion x=2 to hole at position x=2 -> 0 minutes
+Assign mouse at postion x=0 to hole at postion x=3 -> 3 minutes
+So the answer is 3, after 3 minutes all of the mice are in the holes.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-03T11:27:32,2016-12-01T18:09:42,setter," const ll N = (1<<17)+10; + + int a[N]; + int b[N]; + int n, m; + + bool check(int tt) + { + int i = 0; + int j = 0; + while(i < n && j < m) + { + if(abs(a[i]-b[j]) <= tt) + { + i ++; + j ++; + } + else + { + j ++; + } + } + + if(i == n) + return true; + else + return false; + } + + + int main() + { + int test; + + scanf(""%d"", &test); + for(int cas = 1; cas <= test; cas ++) + { + scanf(""%d %d"", &n, &m); + for(int i = 0; i < n; i ++) + scanf(""%d"", &a[i]); + + for(int i = 0; i < m; i ++) + scanf(""%d"", &b[i]); + + sort(a, a+n); + sort(b, b+m); + + int L = 0; + int R = 210000000; + int mid; + while(L < R) + { + mid = (L+R)/2; + if(check(mid) == true) + R = mid; + else + L = mid+1; + } + + printf(""%d\n"", L); + } + + return 0; + }",not-set,2016-04-24T02:03:02,2016-04-24T02:03:02,Unknown +171,4101,gcd-sequence,GCD Sequence,"Devu likes to play around the magic world of the mathematics. Today he got stuck at a problem given by his friend. Problem can be described in simple manner as given below. + +How many non decreasing sequences are there of length $K$, with the condition that numbers in sequence can take values only from $1,2,3, \cdots N$ and gcd of all numbers in the sequence must be $1$. + +**Input Format** +The first line contains an integer $T$ i.e. the number of test cases.
+The each of next $T$ lines will contain two integerrs $N$ and $K$. + +**Output Format** +Print value of answer $\mod 10^9+7$. + +**Constraints** + +$ 1\le T \le 5$
+$ 1\le N \le 10^5$
+$ 1\le K \le 10^5$
+ + +**Sample Input** + + 4 + 2 4 + 3 4 + 5 2 + 1 10 + + +**Sample Output** + + 4 + 13 + 10 + 1 + + +**Explanation** + +In third case sequences are: + +$[1,1]$, $[1,2]$, $[1,3]$, $[1,4]$, $[1,5]$, $[2,3]$, $[2,5]$, $[3,4]$, $[3,5]$, $[4,5]$. + +",code,Help Devu in finding number of sequences.,ai,2014-09-04T05:14:08,2022-09-02T09:54:47,"# +# Complete the 'solve' function below. +# +# The function is expected to return an 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() +","How many non decreasing sequences are there of length $K$, with the condition that numbers in sequence can take values only from $1,2,3, \cdots N$ and gcd of all numbers in the sequence must be $1$. + +**Input Format** +The first line contains an integer $T$ i.e. the number of test cases.
+$T$ lines follow, each line containing two integers $N$ and $K$ separated by a single space. + +**Output Format** +For each testcase, print in a newline the answer $\mod(10^9+7)$. + +**Constraints** + +$ 1 \le T \le 5$ +$ 1 \le N \le 10^5$ +$ 1 \le K \le 10^5$ + + +**Sample Input** + + 4 + 2 4 + 3 4 + 5 2 + 1 10 + + +**Sample Output** + + 4 + 13 + 10 + 1 + + +**Explanation** + +For the first testcase, the sequences are + + (1,1,1,1), (1,1,1,2), (1,1,2,2), (1,2,2,2) = 4 + +For the second testcase, the sequences are + + (1,1,1,1), (1,1,1,2), (1,1,1,3), (1,1,2,2), (1,1,2,3), (1,1,3,3) + (1,3,3,3), (1,2,2,2), (1,2,2,3), (1,2,3,3), (2,2,2,3), (2,2,3,3), (2,3,3,3) + +which are 13 in number. + +For the third testcase, the sequences are + + (1,1), (1,2), (1,3), (1,4), (1,5), (2,3), (2,5), (3, 4), (3, 5), (4, 5) = 10 + +for the fourth testcase, the only sequence is + + (1,1,1,1,1,1,1,1,1,1) + +",0.5,"[""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,,,,,,,2014-09-04T05:17:07,2016-12-08T10:35:17,setter,"###C++ +```cpp +#include + +using namespace std; + + +#define ll long long int +#define MOD 1000000007 + +ll mu[666666]; +ll fact[1111111]; + +void pre(long long PP) +{ + long long i,j; + mu[1]=1; + for(i=1;i<=PP;++i) { + for(j=2*i;j<=PP;j+=i) { + mu[j]-=mu[i]; + } + } + return; +} + +ll pw(ll a , ll b) +{ + if(b==0) + return 1; + if(b%2 == 0) + { + ll temp = pw(a,b/2); + return (temp*temp)%MOD; + } + else + { + ll temp = pw(a,b/2); + temp = (temp*temp)%MOD; + return (temp*a)%MOD; + } +} + +ll func(ll n , ll r) // n+r-1 ... n +{ + ll ans = fact[n+r-1]; + ans = (ans*pw(fact[r],MOD-2))%MOD; + ans = (ans*pw(fact[n-1],MOD-2))%MOD; + return ans; +} + + +int main() +{ + int t; + cin>>t; + pre(555555); + fact[0] = 1; + for(ll i =1 ; i< 1111111 ; i++) + fact[i] = (fact[i-1]*i) %MOD; + // cout<>n>>k; //1.....N and length K + assert(1<=n && n<=100000); + assert(1<=k && k<= 100000); + ll ans = 0 ; + for(ll i =1 ; i<= n ; i++) + ans = (ans + MOD + func((n/i), k)*mu[i])%MOD; + cout<This problem is a programming version of [Problem 50](https://projecteuler.net/problem=50) from [projecteuler.net](https://projecteuler.net/) + +The prime $41$, can be written as the sum of six consecutive primes: +$$41 = 2 + 3 + 5 + 7 + 11 + 13$$ + +This is the longest sum of consecutive primes that adds to a prime below one-hundred. + +The longest sum of consecutive primes below one-thousand that adds to a prime, contains $21$ terms, and is equal to $953$. + +Which prime, $\le N$, can be written as the sum of the most consecutive primes? +**Note:** You have to print prime as well as the length of consecutive chain whose sum is prime. If such primes are more than 1, print the least. + +**Input Format** +The first line contains an integer $T$ , i.e., number of test cases. +Next $T$ lines will contain an integer $N$. + +**Output Format** +Print the values corresponding to each test case in a new line. + +**Constraints** +$1 \le T \le 10$ +$2 \le N \le 10^{12}$ + +**Sample Input** + + 2 + 100 + 1000 + +**Sample Output** + + 41 6 + 953 21",code,Consecutive prime sum,ai,2014-06-16T12:28:31,2022-09-02T10:36:47,,,,"This problem is a programming version of [Problem 50](https://projecteuler.net/problem=50) from [projecteuler.net](https://projecteuler.net/) + +The prime $41$, can be written as the sum of six consecutive primes: +$$41 = 2 + 3 + 5 + 7 + 11 + 13$$ + +This is the longest sum of consecutive primes that adds to a prime below one-hundred. + +The longest sum of consecutive primes below one-thousand that adds to a prime, contains $21$ terms, and is equal to $953$. + +Which prime, $\le N$, can be written as the sum of the most consecutive primes? +**Note:** You have to print prime as well as the length of consecutive chain whose sum is prime. If such primes are more than 1, print the least. + +",0.5,"[""ada"",""bash"",""c"",""clojure"",""coffeescript"",""cpp"",""cpp14"",""csharp"",""d"",""elixir"",""erlang"",""fortran"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""octave"",""pascal"",""perl"",""php"",""pypy3"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""visualbasic"",""whitespace"",""cpp20"",""java15"",""typescript""]","The first line contains an integer $T$ , i.e., number of test cases. +Next $T$ lines will contain an integer $N$. +","Print the values corresponding to each test case in a new line. +","```raw +2 +100 +1000 +```","```raw +41 6 +953 21 +```",Hard,,,,,,,2014-09-04T18:49:10,2016-05-12T23:57:12,tester,"```cs +using System; +using System.Collections.Generic; +using System.IO; +class Solution +{ + static int MAX = 10000000; + static int[] is_prime = new int[MAX]; + static List primes = new List(); // 664579 number of primes < MAX + static List psum = new List(); + + static int lower_bound(long P) + { + int be = 0, en = psum.Count - 1, res = psum.Count - 1; + while (be <= en) + { + int m = (be + en) / 2; + if (psum[m] >= P) + { + res = m; + en = m - 1; + } + else + be = m + 1; + } + return res; + } + + static bool is_primef(long N) + { + if (N < 2) return false; + for (long i = 2; i * i <= N; ++i) + if (N % i == 0) + return false; + return true; + } + + static void Main(String[] args) + { + for (int i = 0; i < MAX; ++i) is_prime[i] = 1; + is_prime[0] = is_prime[1] = 0; + long s = 0; + for (int i = 0; i < MAX; ++i) + if (is_prime[i] == 1) + { + primes.Add(i); + s += i; + psum.Add(s); + + if ((long)i*i >= MAX) continue; + for (int j = i * i; j < MAX; j += i) + is_prime[j] = 0; + } + + int OPTIMAL_ANSWER_DISTANCE = 20; + int T = Int32.Parse(Console.ReadLine()); + while (T-- > 0) + { + long N = Int64.Parse(Console.ReadLine()); + int index = lower_bound(N); // first m prime numbers: 2 + 3 + 5 + 7 + ... + p_index >= N + long bestp = 0, bestl = 0; + + for (int i = Math.Max(0, index - OPTIMAL_ANSWER_DISTANCE); i < Math.Min(index + OPTIMAL_ANSWER_DISTANCE, primes.Count); ++i) + { + for (int j = 0; j < 100 && j <= i-bestl; ++j) + { + long act_sum = psum[i] - (j > 0 ? psum[j - 1] : 0); + if (act_sum <= N && is_primef(act_sum)) + { + int act_len = i - j + 1; + if (act_len > bestl) + { + bestl = act_len; + bestp = act_sum; + } + } + } + } + + Console.WriteLine(bestp + "" "" + bestl); + + /*int bestp = 1, bestl = 0; + for (int p = 2; p <= N; ++p) + { + // 2 + 3 + 5 + 7 + 11 + 13 + 17 ... + pn = p + + if (is_prime[p] == 0) continue; + int index = lower_bound(p); + int sum = 0, i1 = 0; + for (int i2 = 0; primes[i2] < p; ++i2) + { + sum += primes[i2]; + while (sum > p) + sum -= primes[i1++]; + if (sum == p) + { + int l = i2 - i1 + 1; + if (l > bestl) + { + bestp = p; + bestl = l; + } + break; + } + } + //Console.WriteLine(p + "": "" + bestp + "" "" + bestl + "" "" + index); + }*/ + } + } +} +```",not-set,2016-04-24T02:03:03,2016-04-24T02:03:03,Ruby +173,3517,towers,Towers,"One day John had to take care of his little nephew Jim. He was very busy, so he gave Jim a big bag full of building bricks. The bricks are of various heights: at most 15 different heights. For each height, the bag contains infinitely many bricks. +
+Now, Jim’s task is to build every possible tower of height $N$ from the given bricks. Bricks are stacked vertically only and stand in an upright position. Two towers are different if their brick height sequences are different. +
+Jim is good at building towers and can build one tower in exactly 2 minutes, regardless of its height. John wants to know the time Jim requires to build all possible towers. + +**Input Format** +There are $3$ lines of input. First line contains an integer, $N$, the height of tower to be built. Second line contains another integer, $K$, which represents different heights of bricks available in the bag. Third line contains $K$ distinct integers representing the available heights. + + +**Output Format** +In one line print the number of minutes Jim requires to build all possible towers. As this number can be very large, print the number modulo $(10^9+7)$. + + +**Constraints** +$1 \le N \le 10^{18}$ +$1 \le K \le 15$ +All heights will be unique. +Height of each brick will lie in range [1, 15]. + +**Sample Input#00** + + 10 + 1 + 1 + +**Sample Output#00** + + 2 + +**Explanation#00:** There is exactly one type of brick, so there is exactly one tower of height 10. Building any tower takes 2 minutes, so the answer is 2. + +**Sample Input#01** + + 5 + 2 + 2 3 + +**Sample Output#01** + + 4 + +**Explanation #01:** There are two types of bricks. There are two different towers of height 5 which can be build from these types of bricks: $[2,3]$ and $[3,2]$. They are different, because the sequence of bricks in them is different. Building any tower takes 2 minutes, so the answer is $2 \times 2 = 4$. + +**Sample Input#03** + + 19 + 2 + 4 5 + +**Sample Output#03** + + 8 + +**Explanation #03:** There are two types of bricks. Jim can build 4 different towers of height $19$ from these bricks: $[5,5,5,4]$, $[5,5,4,5]$, $[5,4,5,5]$ and $[4,5,5,5]$. Building any tower takes 2 minutes, so the answer is $2 \times 4 = 8$. +",code,How many minutes will it take Jim to build all possible towers?,ai,2014-08-08T08:04:28,2022-09-02T09:54:57,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. LONG_INTEGER n +# 2. INTEGER_ARRAY heights +# + +def solve(n, heights): + # 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()) + + heights_count = int(input().strip()) + + heights = list(map(int, input().rstrip().split())) + + result = solve(n, heights) + + fptr.write(str(result) + '\n') + + fptr.close() +","One day John had to take care of his little nephew Jim. He was very busy, so he gave Jim a big bag full of building bricks. The bricks are of various heights: at most 15 different heights. For each height, the bag contains infinitely many bricks. +
+Now, Jim’s task is to build every possible tower of height $N$ from the given bricks. Bricks are stacked vertically only and stand in an upright position. Two towers are different if their brick height sequences are different. +
+Jim is good at building towers and can build one tower in exactly 2 minutes, regardless of its height. John wants to know the time Jim requires to build all possible towers. + +**Input Format** +There are $3$ lines of input. First line contains an integer, $N$, the height of tower to be built. Second line contains another integer, $K$, which represents different heights of bricks available in the bag. Third line contains $K$ distinct integers representing the available heights. + + +**Output Format** +In one line print the number of minutes Jim requires to build all possible towers. As this number can be very large, print the number modulo $(10^9+7)$. + + +**Constraints** +$1 \le N \le 10^{18}$ +$1 \le K \le 15$ +All heights will be unique. +Height of each brick will lie in range [1, 15]. + +**Sample Input#00** + + 10 + 1 + 1 + +**Sample Output#00** + + 2 + +**Explanation#00:** There is exactly one type of brick, so there is exactly one tower of height 10. Building any tower takes 2 minutes, so the answer is 2. + +**Sample Input#01** + + 5 + 2 + 2 3 + +**Sample Output#01** + + 4 + +**Explanation #01:** There are two types of bricks. There are two different towers of height 5 which can be build from these types of bricks: $[2,3]$ and $[3,2]$. They are different, because the sequence of bricks in them is different. Building any tower takes 2 minutes, so the answer is $2 \times 2 = 4$. + +**Sample Input#03** + + 19 + 2 + 4 5 + +**Sample Output#03** + + 8 + +**Explanation #03:** There are two types of bricks. Jim can build 4 different towers of height $19$ from these bricks: $[5,5,5,4]$, $[5,5,4,5]$, $[5,4,5,5]$ and $[4,5,5,5]$. Building any tower takes 2 minutes, so the answer is $2 \times 4 = 8$. +",0.5357142857142857,"[""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,,,,,,,2014-09-07T15:08:06,2016-12-07T22:23:36,setter,"###C++ +```cpp +--C++ +#include +#include +#include +#include +#include +#include +using namespace std; +#define FOR(i,n) for(int (i)=0;(i)<(n);++(i)) + +typedef unsigned long long ull; +typedef vector vi; +typedef vector > matrix; +const int MOD = 1000000000 + 7; + +matrix mmul(matrix M1, matrix M2) +{ + matrix R(15); + FOR(i, 15) + { + R[i].assign(15, 0); + FOR(j, 15) + { + FOR(k, 15) + { + R[i][j] = (R[i][j] + M1[i][k] * M2[k][j]) % MOD; + } + } + } + return R; +} + +matrix mpow(matrix M, ull n) +{ + if(n == 0) + { + matrix M1(15); + FOR(i, 15) + { + M1[i].assign(15, 0); + FOR(j, 15) + { + if(i == j) + M1[i][j] = 1; + } + } + return M1; + } + else if(n % 2 == 0) + { + matrix R = mpow(M, n / 2); + return mmul(R, R); + } + else + { + matrix R = mpow(M, n - 1); + return mmul(R, M); + } +} + +ull V[15]; +int main() +{ +//GENERATE M + matrix M(15); + FOR(i, 15) + { + M[i].assign(15, 0); + FOR(j, 15) + { + if(i + 1 == j) + { + M[i][j] = 1; + } + } + } +//INPUT + int k; + ull n; + vi jumps; + vi res; + ull tmp; + + cin >> n; + cin >> k; + FOR(i, 15) + { + V[i] = 0; + } + M[14].assign(15, 0); + FOR(i, k) + { + cin >> tmp; + M[14][14 - tmp + 1] = 1; + } + FOR(i, 15) + { + FOR(j, i + 1) + { + if(M[14][14 - j] == 1) + { + if(i - j == 0) + { + V[i]++; + } + else + { + V[i] += V[i - j - 1]; + } + } + } + } + if(n <= 15) + { + ull res = 0; + res = (V[n - 1] * 2) % MOD; + cout << res << endl; + } + else + { + matrix R = mpow(M, n - 15); + ull res = 0; + FOR(j, 15) + { + res = (res + R[14][j] * V[j]) % MOD; + } + res = (res * 2) % MOD; + cout << res << endl; + } + return 0; +} +``` +",not-set,2016-04-24T02:03:03,2016-07-23T18:41:05,C++ +174,1739,bcontest,Bit contest,"**Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click [here](https://www.hackerrank.com/auth/create_team/csindia) to register as a team, if you have NOT already registered.** + +Zodiac knights are taking part in a very special contest: the winner among them will have to defend the planet Earth from evil Hades in a deadly battle. The contest takes places in simple elimination rounds where the loser is taken out. + +In each round, 2 knights play the following game: *N* non-negative integers are given. Players take successive turns, and in each turn, they are allowed to flip active bits from any of the integers in the list. That is, they pick one (and only one) non-zero integer in the list and flip its as many active bits as desired. By flipping an active bit of an integer, we mean turning a bit from 1 to 0 in the binary representation of that integer. As this flipping continues, eventually all numbers in the list become zero. So the player who ends up turning the last non-zero integer to 0 in the list is the winner (or the player who cannot play on his turn loses). + +Being the Virgo's knight, Shaka is very concerned about his chances of winning the contest. Given a possible initial configuration, he needs help in determining if he can or cannot beat another player. Assume that both of them will play optimally (i.e. they do their best in each turn). Also assume that Shaka gets the first turn. + +**Input Format** +Input consists of several lines. First line contains an integer N indicating the size of the list. N lines follow, each containing a single integer from the aforementioned list. + +**Output Format** +Output a single line displaying ""Shaka :)"" without quotes if Shaka can beat his adversary on the given configuration. Otherwise, print ""The other player :("" without quotes. + +**Constraints:** + +1 <= N <= 10000
+All numbers in the list will fit in a **32-bit signed integer** and greater than 0.
+ +**Sample Input #00** + + 2 + 2 + 9 + +**Sample Output #00** + + Shaka :) + +**Explanation #00** + +In this test case, all that the first player needs to do is to flip a single bit from 9. That leads to a position where the second player will always lose, because he is forced to flip just a single bit from any of the remaining numbers, leaving the other one to first player and thus, allowing him to win. + +**Sample Input #01** + + 3 + 8 + 10 + 290 + +**Sample Output #01** + + The other player :( + +**Explanation #01** + +Here, no matter what the first player's move is, the second player will always have a winning strategy: + +1. If first player flips the only active bit in 8, a winning move for second player is to take away 1 bit from 290. From that position, second player needs to exactly copy the moves of first player. Following this strategy, second player will win. +2. If first player removes 1 bit from 10, it is easy to see that removing all 3 active bits from 290 is a winning move for second player. If, on the other hand, first player removes both active bits from 10, then taking away just 2 bits from 290 is the way to go for second player, as the game reaches a position similar to one reached in first sample test case. +3. For configurations reached by removing 1, 2 or 3 bits from 290, winning moves for second player are flipping the active bit from 8, flipping both active bits from 10 and flipping 1 bit from 10, respectively. The scenarios created as a result are similar to the ones already discussed. +",code,Are you able to find out who should face Hades?,ai,2014-01-23T22:59:59,2016-09-09T09:38:37,,,,"**Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click [here](https://www.hackerrank.com/auth/create_team/csindia) to register as a team, if you have NOT already registered.** + +Zodiac knights are taking part in a very special contest: the winner among them will have to defend the planet Earth from evil Hades in a deadly battle. The contest takes places in simple elimination rounds where the loser is taken out. + +In each round, 2 knights play the following game: *N* non-negative integers are given. Players take successive turns, and in each turn, they are allowed to flip active bits from any of the integers in the list. That is, they pick one (and only one) non-zero integer in the list and flip its as many active bits as desired. By flipping an active bit of an integer, we mean turning a bit from 1 to 0 in the binary representation of that integer. As this flipping continues, eventually all numbers in the list become zero. So the player who ends up turning the last non-zero integer to 0 in the list is the winner (or the player who cannot play on his turn loses). + +Being the Virgo's knight, Shaka is very concerned about his chances of winning the contest. Given a possible initial configuration, he needs help in determining if he can or cannot beat another player. Assume that both of them will play optimally (i.e. they do their best in each turn). Also assume that Shaka gets the first turn. + +**Input Format** +Input consists of several lines. First line contains an integer N indicating the size of the list. N lines follow, each containing a single integer from the aforementioned list. + +**Output Format** +Output a single line displaying ""Shaka :)"" without quotes if Shaka can beat his adversary on the given configuration. Otherwise, print ""The other player :("" without quotes. + +**Constraints:** + +1 <= N <= 10000
+All numbers in the list will fit in a **32-bit signed integer** and greater than 0.
+ +**Sample Input #00** + + 2 + 2 + 9 + +**Sample Output #00** + + Shaka :) + +**Explanation #00** + +In this test case, all that the first player needs to do is to flip a single bit from 9. That leads to a position where the second player will always lose, because he is forced to flip just a single bit from any of the remaining numbers, leaving the other one to first player and thus, allowing him to win. + +**Sample Input #01** + + 3 + 8 + 10 + 290 + +**Sample Output #01** + + The other player :( + +**Explanation #01** + +Here, no matter what the first player's move is, the second player will always have a winning strategy: + +1. If first player flips the only active bit in 8, a winning move for second player is to take away 1 bit from 290. From that position, second player needs to exactly copy the moves of first player. Following this strategy, second player will win. +2. If first player removes 1 bit from 10, it is easy to see that removing all 3 active bits from 290 is a winning move for second player. If, on the other hand, first player removes both active bits from 10, then taking away just 2 bits from 290 is the way to go for second player, as the game reaches a position similar to one reached in first sample test case. +3. For configurations reached by removing 1, 2 or 3 bits from 290, winning moves for second player are flipping the active bit from 8, flipping both active bits from 10 and flipping 1 bit from 10, respectively. The scenarios created as a result are similar to the ones already discussed. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-12T16:39:32,2016-12-30T04:48:50,setter," //============================================================================ + // Name : BGAME.cpp + // Author : Shaka + // Version : + // Copyright : Your copyright notice + // Description : Hello World in C++, Ansi-style + //============================================================================ + + #include + #include + using namespace std; + const int SIZE = 1 << 16, MASK = (1 << 16) - 1; + int tab[SIZE]; + + inline void make_tab() { + for (register int i = 1; i < SIZE; ++i) { + tab[i] = tab[i >> 1] + (i & 1); + } + } + + inline int bcount(int n) { + return tab[n & MASK] + tab[(n >> 16) & MASK]; + } + const int TEST = 0; + int main() { + /* + char inputstr[50]; + char outputstr[50]; + sprintf(inputstr, ""tests/input/input%02d.txt"", TEST); + sprintf(outputstr, ""tests/output/output%02d.txt"", TEST); + freopen(inputstr, ""r"", stdin); + freopen(outputstr, ""w"", stdout); + */ + + make_tab(); + register int i, N, rx, x; + for (scanf(""%d"", &N), i = rx = 0; i < N; ++i) { + scanf(""%d"", &x); + assert(x >= 0); + x = bcount(x); + rx ^= x; + } + printf(""%s\n"", rx == 0 ? ""The other player :("" : ""Shaka :)""); + return 0; + } +",not-set,2016-04-24T02:03:04,2016-04-24T02:03:04,C++ +175,1739,bcontest,Bit contest,"**Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click [here](https://www.hackerrank.com/auth/create_team/csindia) to register as a team, if you have NOT already registered.** + +Zodiac knights are taking part in a very special contest: the winner among them will have to defend the planet Earth from evil Hades in a deadly battle. The contest takes places in simple elimination rounds where the loser is taken out. + +In each round, 2 knights play the following game: *N* non-negative integers are given. Players take successive turns, and in each turn, they are allowed to flip active bits from any of the integers in the list. That is, they pick one (and only one) non-zero integer in the list and flip its as many active bits as desired. By flipping an active bit of an integer, we mean turning a bit from 1 to 0 in the binary representation of that integer. As this flipping continues, eventually all numbers in the list become zero. So the player who ends up turning the last non-zero integer to 0 in the list is the winner (or the player who cannot play on his turn loses). + +Being the Virgo's knight, Shaka is very concerned about his chances of winning the contest. Given a possible initial configuration, he needs help in determining if he can or cannot beat another player. Assume that both of them will play optimally (i.e. they do their best in each turn). Also assume that Shaka gets the first turn. + +**Input Format** +Input consists of several lines. First line contains an integer N indicating the size of the list. N lines follow, each containing a single integer from the aforementioned list. + +**Output Format** +Output a single line displaying ""Shaka :)"" without quotes if Shaka can beat his adversary on the given configuration. Otherwise, print ""The other player :("" without quotes. + +**Constraints:** + +1 <= N <= 10000
+All numbers in the list will fit in a **32-bit signed integer** and greater than 0.
+ +**Sample Input #00** + + 2 + 2 + 9 + +**Sample Output #00** + + Shaka :) + +**Explanation #00** + +In this test case, all that the first player needs to do is to flip a single bit from 9. That leads to a position where the second player will always lose, because he is forced to flip just a single bit from any of the remaining numbers, leaving the other one to first player and thus, allowing him to win. + +**Sample Input #01** + + 3 + 8 + 10 + 290 + +**Sample Output #01** + + The other player :( + +**Explanation #01** + +Here, no matter what the first player's move is, the second player will always have a winning strategy: + +1. If first player flips the only active bit in 8, a winning move for second player is to take away 1 bit from 290. From that position, second player needs to exactly copy the moves of first player. Following this strategy, second player will win. +2. If first player removes 1 bit from 10, it is easy to see that removing all 3 active bits from 290 is a winning move for second player. If, on the other hand, first player removes both active bits from 10, then taking away just 2 bits from 290 is the way to go for second player, as the game reaches a position similar to one reached in first sample test case. +3. For configurations reached by removing 1, 2 or 3 bits from 290, winning moves for second player are flipping the active bit from 8, flipping both active bits from 10 and flipping 1 bit from 10, respectively. The scenarios created as a result are similar to the ones already discussed. +",code,Are you able to find out who should face Hades?,ai,2014-01-23T22:59:59,2016-09-09T09:38:37,,,,"**Please note that this is a team event, and your submission will be accepted only as a part of a team, even single member teams are allowed. Please click [here](https://www.hackerrank.com/auth/create_team/csindia) to register as a team, if you have NOT already registered.** + +Zodiac knights are taking part in a very special contest: the winner among them will have to defend the planet Earth from evil Hades in a deadly battle. The contest takes places in simple elimination rounds where the loser is taken out. + +In each round, 2 knights play the following game: *N* non-negative integers are given. Players take successive turns, and in each turn, they are allowed to flip active bits from any of the integers in the list. That is, they pick one (and only one) non-zero integer in the list and flip its as many active bits as desired. By flipping an active bit of an integer, we mean turning a bit from 1 to 0 in the binary representation of that integer. As this flipping continues, eventually all numbers in the list become zero. So the player who ends up turning the last non-zero integer to 0 in the list is the winner (or the player who cannot play on his turn loses). + +Being the Virgo's knight, Shaka is very concerned about his chances of winning the contest. Given a possible initial configuration, he needs help in determining if he can or cannot beat another player. Assume that both of them will play optimally (i.e. they do their best in each turn). Also assume that Shaka gets the first turn. + +**Input Format** +Input consists of several lines. First line contains an integer N indicating the size of the list. N lines follow, each containing a single integer from the aforementioned list. + +**Output Format** +Output a single line displaying ""Shaka :)"" without quotes if Shaka can beat his adversary on the given configuration. Otherwise, print ""The other player :("" without quotes. + +**Constraints:** + +1 <= N <= 10000
+All numbers in the list will fit in a **32-bit signed integer** and greater than 0.
+ +**Sample Input #00** + + 2 + 2 + 9 + +**Sample Output #00** + + Shaka :) + +**Explanation #00** + +In this test case, all that the first player needs to do is to flip a single bit from 9. That leads to a position where the second player will always lose, because he is forced to flip just a single bit from any of the remaining numbers, leaving the other one to first player and thus, allowing him to win. + +**Sample Input #01** + + 3 + 8 + 10 + 290 + +**Sample Output #01** + + The other player :( + +**Explanation #01** + +Here, no matter what the first player's move is, the second player will always have a winning strategy: + +1. If first player flips the only active bit in 8, a winning move for second player is to take away 1 bit from 290. From that position, second player needs to exactly copy the moves of first player. Following this strategy, second player will win. +2. If first player removes 1 bit from 10, it is easy to see that removing all 3 active bits from 290 is a winning move for second player. If, on the other hand, first player removes both active bits from 10, then taking away just 2 bits from 290 is the way to go for second player, as the game reaches a position similar to one reached in first sample test case. +3. For configurations reached by removing 1, 2 or 3 bits from 290, winning moves for second player are flipping the active bit from 8, flipping both active bits from 10 and flipping 1 bit from 10, respectively. The scenarios created as a result are similar to the ones already discussed. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-12T16:39:32,2016-12-30T04:48:50,tester," #include + #include + + using namespace std; + int MAX = (1 << 16); + int MASK = MAX - 1; + int table[(1 << 16)]; + void set_tab() + { + table[0] = 0; + for(int i = 1; i < MAX; i++){ + table[i] = table[i >> 1] + (i & 1); + } + } + + int bit_count(int n) + { + return table[(n >> 16) & MASK] + table[n & MASK]; + } + + int main() + { + int n; + cin >> n; + set_tab(); + assert(1 <= n <= 1e5); + int x = 0; + for(int i = 0; i < n; i++) + { + int temp; + cin >> temp; + assert(1 <= temp <= 1e9); + x ^= bit_count(temp); + } + if(0 == x) + cout << ""The other player :("" << endl; + else + cout << ""Shaka :)"" << endl; + return 0; + } +",not-set,2016-04-24T02:03:04,2016-04-24T02:03:04,C++ +176,4291,playing-with-histograms,Playing with Histograms,"In statistics, a histogram is a graphical display of tabulated frequencies, shown as bars. It shows what proportion of cases fall into each of several categories. It is a polygon composed of a sequence of rectangles aligned at a common base line. In this problem all rectangles have a width of unit length, but their heights are distinct. Some permutation of the heights will give the maximum perimeter. Your task is to find the __maximum perimeter__ of the histogram and the __number of permutations__ that give the maximum perimeter. + +For example, you can have a histogram with heights {1,2,3,4} in order (1st sample test case) which has a perimeter of 16 units. One of the permutations of this set of heights, i.e. {3,1,2,4} has the maximum perimeter of 20 units. + +**Input:** +Input consists of multiple test cases. Each test case describes a histogram and starts with an integer N, 2 ≤ N ≤ 15, denoting the number of rectangles it is composed of. Next line consists of N space separated positive integers representing the heights of the rectangles. All heights are distinct and less than or equal to 100. N=0 indicates the end of tests. There are at most 50 test cases. + +**Output:** +For each test case, output the maximum possible perimeter of the histogram and the number of permutations that give maximum perimeter in a single line, separated by a single space. + +**Sample Input:** +4 +1 2 3 4 +3 +2 6 5 +0 + +**Sample Output:** +20 8 +24 2 + + +",code,"In statistics, a histogram is a graphical display of tabulated frequencies, shown as bars. It shows what proportion of cases fall into each of several categories. It is a polygon composed of a sequence of rectangles aligned at a common base line. ",ai,2014-09-17T17:38:30,2016-09-09T09:52:36,,,,"In statistics, a histogram is a graphical display of tabulated frequencies, shown as bars. It shows what proportion of cases fall into each of several categories. It is a polygon composed of a sequence of rectangles aligned at a common base line. In this problem all rectangles have a width of unit length, but their heights are distinct. Some permutation of the heights will give the maximum perimeter. Your task is to find the __maximum perimeter__ of the histogram and the __number of permutations__ that give the maximum perimeter. + +For example, you can have a histogram with heights {1,2,3,4} in order (1st sample test case) which has a perimeter of 16 units. One of the permutations of this set of heights, i.e. {3,1,2,4} has the maximum perimeter of 20 units. + +**Input:** +Input consists of multiple test cases. Each test case describes a histogram and starts with an integer N, 2 ≤ N ≤ 15, denoting the number of rectangles it is composed of. Next line consists of N space separated positive integers representing the heights of the rectangles. All heights are distinct and less than or equal to 100. N=0 indicates the end of tests. There are at most 50 test cases. + +**Output:** +For each test case, output the maximum possible perimeter of the histogram and the number of permutations that give maximum perimeter in a single line, separated by a single space. + +**Sample Input:** +4 +1 2 3 4 +3 +2 6 5 +0 + +**Sample Output:** +20 8 +24 2 + + +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-17T17:53:08,2016-05-12T23:56:41,setter," #include + #include + #include + #include + + using namespace std; + int perimeter(vector); + int ways(int); + int fact(int); + + int main() + { + int n; + while(1) + { + scanf(""%d"",&n); + if(!n) + break; + vector v(n); + int i; + for(i=0;i v) + { + sort(v.begin(),v.end()); + int lo=0; + int hi=v.size()-1; + int ans=v[hi]; + + int now; + int prev=v[hi]; + --hi; + bool f=true; + while(lo<=hi) + { + if(f) + { + now=v[lo]; + ++lo; + } + else + { + now=v[hi]; + --hi; + } + f=!f; + ans+=abs(now-prev); + prev=now; + } + ans+=prev; + + return ans+=2*v.size(); + } + + int ways(int n) + { + if(n%2) + return fact(n/2)*fact(n/2+1); + else + return n*fact(n/2)*fact(n/2-1); + } + + int fact(int n) + { + int ans=1; + int i; + for(i=2;i<=n;++i) + ans*=i; + return ans; + } +",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,C++ +177,4293,is-it-a-tree,Is It A Tree?,"A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties. +1. There is exactly one node, called the root, to which no directed edges point. +2. Every node except the root has exactly one edge pointing to it. +3. There is a unique sequence of directed edges from the root to each node. + +In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these, you are to determine _if the collection satisfies the definition of a tree or not._ + +**Input:** +The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes. Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero. + +**Output:** +For each test case display the line ""Case k is a tree."" or the line ""Case k is not a tree."", where k corresponds to the test case number (they are sequentially numbered starting with 1). + +**Sample Input:** +6 8 +5 3 +5 2 +6 4 +5 6 +0 0 + +8 1 +7 3 +6 2 +8 9 +7 5 +7 4 +7 8 +7 6 +0 0 + +3 8 +6 8 +6 4 +5 3 +5 6 +5 2 +0 0 +-1 -1 + +**Expected Output:** +Case 1 is a tree. +Case 2 is a tree. +Case 3 is not a tree. + + + + + +",code,A tree is a well-known data structure. Determine if the given collection satisfies the definition of a tree or not. Simple?,ai,2014-09-17T18:20:06,2016-09-09T09:52:37,,,,"A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties. +1. There is exactly one node, called the root, to which no directed edges point. +2. Every node except the root has exactly one edge pointing to it. +3. There is a unique sequence of directed edges from the root to each node. + +In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these, you are to determine _if the collection satisfies the definition of a tree or not._ + +**Input:** +The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes. Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero. + +**Output:** +For each test case display the line ""Case k is a tree."" or the line ""Case k is not a tree."", where k corresponds to the test case number (they are sequentially numbered starting with 1). + +**Sample Input:** +6 8 +5 3 +5 2 +6 4 +5 6 +0 0 + +8 1 +7 3 +6 2 +8 9 +7 5 +7 4 +7 8 +7 6 +0 0 + +3 8 +6 8 +6 4 +5 3 +5 6 +5 2 +0 0 +-1 -1 + +**Expected Output:** +Case 1 is a tree. +Case 2 is a tree. +Case 3 is not a tree. + + + + + +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-17T18:21:00,2016-05-12T23:56:41,setter," #include + + /* + The node numbers are not necessarily sequential and starting + with 1. Keep a list of all the node numbers used so far + in each case, and assign them indices from 0 to n-1 + */ + struct NodeNum { + int num; + NodeNum *next; + }; + NodeNum *node_num_list = 0; + + /* + Keep a list of all the edges + */ + struct Edge { + int from, to; + Edge *next; + Edge(int f, int t); + }; + Edge *edge_list; + + + // reset the node list + void ClearNodeNumList() { + NodeNum *p = node_num_list, *q; + while (p) { + q = p; + p = p->next; + delete q; + } + node_num_list = new NodeNum; + node_num_list->next = 0; + node_num_list->num = -42; + } + + + // generate an index for a node number; might be a node already + // assigned an index + int GetNodeNum(int n) { + NodeNum *p = node_num_list; + int c = 0; + while (p->next) { + p = p->next; + if (p->num == n) return c; + c++; + } + p->next = new NodeNum; + p = p->next; + p->num = n; + p->next = 0; + return c; + } + + + // return the number of nodes + int NumNodes() { + NodeNum *p = node_num_list->next; + int c = 0; + while (p) { + c++; p = p->next; + } + return c; + } + + // defined just for simplicity + Edge::Edge(int f, int t) { + from = GetNodeNum(f); + to = GetNodeNum(t); + } + + + // count how many edges are directed to this node + int NumEdgesTo(Edge *p, int node_no) { + int c = 0; + while (p) { + if (p->to == node_no) c++; + p = p->next; + } + return c; + } + + + // visit this node and all the nodes it points to + // when visiting, increment counter in visted[] so we + // can see how many times the node was visited + void Visit(Edge *edge_list, int node, int visited[]) { + Edge *p = edge_list; + visited[node]++; + while (p) { + if (p->from == node) { + Visit(edge_list, p->to, visited); + } + p = p->next; + } + } + + + // return 1 if the edge list describes a tree, 0 otherwise + int IsATree(Edge *edge_list) { + int n_nodes = NumNodes(); + int i, root_node = -1; + int n_edges_to; + + // if the structure is empty, it's a list + if (n_nodes == 0) return 1; + + for (i=0; inext = edge_list; + edge_list = new_edge; + fscanf(inf, ""%d %d"", &from, &to); + } + + int is_tree = IsATree(edge_list); + printf(""Case %d is %sa tree.\n"", case_no++, is_tree ? """" : ""not ""); + + // erase the edge list; never know if the memory might be needed + while (edge_list) { + Edge *e = edge_list; + edge_list = edge_list->next; + delete e; + } + } + return 0; + } + +",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,C++ +178,4294,non-stop-travel,Non-Stop Travel,"Fast Phil works the late shift and leaves his company's parking lot at precisely 2:00 AM every morning. His route home is by a straight road which has one or more traffic signals. Phil has always wondered if, given the locations and cycles of each of the traffic signals, are there velocities he can travel home without ever having to speed up or slow down on account of a red light. You are to write a program to satisfy his curiosity. +Your program should find all integer speeds (in miles per hour) which can be used for Phil's trip home. Each speed is a rate (in miles per hour) he can maintain the moment he leaves the parking lot at 2:00 AM until he arrives home (we assume Phil has a long driveway in which to decelerate) such that he never passes through a red signal. He is allowed to pass throgh a signal at the exact moment it turns from yellow to red, or at the exact moment a red signal turns green. Since Phil is a relatively law-abiding citizen, you need only consider speeds less than or equal to 60 mph. Likewise, Phil isn't interested in travelling too slowly, so you should not consider speeds lower than 30 mph. + +**Input:** +Input will consist of one or more sets of data describing a set of traffic signals, followed by the integer -1. The first integer in each set will contain the value N (specifying the number of traffic signals). N will be no larger than 6. This value will be followed by N sets of numbers, each containing values (in order) for L, G, Y and R. L is a positive real number indicating the location of a traffic signal, in miles, from the parking lot. G, Y and R are the lengths of time (in seconds) of the green, yellow, and red periods of the corresponding traffic signal's cycle. Phil has learned from an informant in the Highway Department that all N traffic signals start their green period precisely at 2:00 AM. + +**Output:** +Output should consist of the input case number (starting with 1) followed by a list of all valid integer speeds Phil may drive to avoid the red signals. Consecutive integer speeds should be specified in interval notation of the form L-H, where L and H are the lowest and highest speeds for the interval. Intervals of the form L-L (that is, an interval of length 1) shold just be written as L. Intervals should be separated by commas. If there are no valid speeds, you program should display the phrase No acceptable speeds. The Expected Output below illustrates this format. + +**Sample Input:** +1 +5.5 40 8 25 + +3 +10.7 10 2 75 +12.5 12 5 57 +17.93 15 4 67 + +-1 + +**Expected Output:** +Case 1: 30, 32-33, 36-38, 41-45, 48-54, 59-60 +Case 2: No acceptable speeds. +",code,Fast Phil works the late shift at his company. His route home is by a straight road which has one or more traffic signals. Phil has always wondered if there are velocities he can travel home without ever having to speed up or slow down. You are to write a program to satisfy his curiosity.,ai,2014-09-17T18:48:00,2016-09-09T09:52:38,,,,"Fast Phil works the late shift and leaves his company's parking lot at precisely 2:00 AM every morning. His route home is by a straight road which has one or more traffic signals. Phil has always wondered if, given the locations and cycles of each of the traffic signals, are there velocities he can travel home without ever having to speed up or slow down on account of a red light. You are to write a program to satisfy his curiosity. +Your program should find all integer speeds (in miles per hour) which can be used for Phil's trip home. Each speed is a rate (in miles per hour) he can maintain the moment he leaves the parking lot at 2:00 AM until he arrives home (we assume Phil has a long driveway in which to decelerate) such that he never passes through a red signal. He is allowed to pass throgh a signal at the exact moment it turns from yellow to red, or at the exact moment a red signal turns green. Since Phil is a relatively law-abiding citizen, you need only consider speeds less than or equal to 60 mph. Likewise, Phil isn't interested in travelling too slowly, so you should not consider speeds lower than 30 mph. + +**Input:** +Input will consist of one or more sets of data describing a set of traffic signals, followed by the integer -1. The first integer in each set will contain the value N (specifying the number of traffic signals). N will be no larger than 6. This value will be followed by N sets of numbers, each containing values (in order) for L, G, Y and R. L is a positive real number indicating the location of a traffic signal, in miles, from the parking lot. G, Y and R are the lengths of time (in seconds) of the green, yellow, and red periods of the corresponding traffic signal's cycle. Phil has learned from an informant in the Highway Department that all N traffic signals start their green period precisely at 2:00 AM. + +**Output:** +Output should consist of the input case number (starting with 1) followed by a list of all valid integer speeds Phil may drive to avoid the red signals. Consecutive integer speeds should be specified in interval notation of the form L-H, where L and H are the lowest and highest speeds for the interval. Intervals of the form L-L (that is, an interval of length 1) shold just be written as L. Intervals should be separated by commas. If there are no valid speeds, you program should display the phrase No acceptable speeds. The Expected Output below illustrates this format. + +**Sample Input:** +1 +5.5 40 8 25 + +3 +10.7 10 2 75 +12.5 12 5 57 +17.93 15 4 67 + +-1 + +**Expected Output:** +Case 1: 30, 32-33, 36-38, 41-45, 48-54, 59-60 +Case 2: No acceptable speeds. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-17T18:48:47,2016-05-12T23:56:40,setter," #include + #include + + typedef struct { + double dist; + int g, y, r; /* actually, all you need is g + y, they are equivalent */ + } Light; + + + int LightIsGreenishYellow(Light *light, double time) { + /* mod out any complete cycles + for example, if the timings for green, yellow and red + are 1, 2, 3, then a cycle is 6 seconds long. If the + time is 20 seconds, then 20=(6*3)+2, so it is 2 seconds + into the cycle */ + time = fmod(time, light->g + light->y + light->r); + + /* if we are in the green or yellow parts of the cycle, + we're all good */ + return time <= (light->g + light->y); + } + + + /* check if a given speed will work for the given pattern + of traffic lights */ + int MustGoFaster_MustGoFaster(Light lights[6], int n_lights, int speed) { + double time; + int light_no; + + for (light_no = 0; light_no < n_lights; light_no++) { + /* compute the time at which Fast Eddie, I mean, + Fast Phil, will hit this light */ + time = lights[light_no].dist / speed * 3600.0; + + /* check what part of its cycle this light will be + at at that time */ + if ( ! LightIsGreenishYellow(lights+light_no, time)) return 0; + } + return 1; + } + + + + int main() { + int c=1, n, i, speed; + Light lights[6]; + int speeds[62]; /* a flag for each valid speed, with [61]==0 */ + int any; /* were there any speeds that worked? */ + FILE *inf = fopen(""prob_4.in"", ""r""); + double f; /* need to declare this just to the floating + point formats get linked */ + + while (fscanf(inf, ""%d"", &n), n != -1) { + /* read in the light definitions */ + for (i=0; i 60) break; + span_start = speed; + while (speeds[speed]) span_end = speed++; + + if (first) { + first = 0; + } else { + printf("", ""); + } + + if (span_start == span_end) { + printf(""%d"", span_start); + } else { + printf(""%d-%d"", span_start, span_end); + } + } + putchar('\n'); + } + } + + return 0; + } + + +",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,Go +179,4302,secret-message-pad,Secret Message Pad,"Hearing stories from the Oracle that a programmer named Neo may possibly be ""The One"", Trinity risks going into the Matrix to observe Neo. While in the Matrix, her communications are intercepted and Trinity is almost caught by Agent Smith and two other agents. Safely back in the hovercraft Nebuchadnezzar, Trinity decides to add another level of encryption to her communication using a ""one-time pad"". The idea is that given a sequence of numbers (a pad), any message can be proven to be securely encrypted if each character in the string is encoded by a number from the pad, if each number from the pad is only used once. Trinity decides to use the one-time pad to encrypt her messages by shifting each letter in the message by k positions later in the alphabet, where k is determined by the one-time pad. Shifts occur in alphabetical order, between the letters “a” and “z”. If a letter is shifted past “z”, it starts back at “a” and continues shifting. For example, shifting each letter by k = 2, the word “car” is transformed into “ect”, while the word “yaz” is shifted to “acb”. + +**Input format:** +The input will begin with the size of the one-time pad, followed by a sequence of numbers for the pad. The remaining input consists of a series of words to be encrypted using the keyword. The input will be terminated by a line containing only -1. +You may assume that the maximum size of the pad is 100 numbers, all numbers in the pad are between 0 and 25, and that all input will be lowercase letters. + +**Output Format:** +For each word to be encrypted, output a line containing the encrypted word. + + +**Sample Input 1:** +10 +1 2 3 4 5 4 3 2 1 0 +aaaaa zzzzz +-1 + +**Sample Output 1:** +bcdef +dcbaz + +**Sample Input 2:** +40 +1 5 2 21 3 8 4 25 11 9 +6 7 8 9 11 12 3 0 11 4 +14 21 9 0 1 3 12 7 2 11 +5 9 20 12 1 19 4 9 8 24 +humans make good batteries +gnlr esrf +-1 + +**Sample Output 2:** +izovqa +qzvn +mvwm +mmwtpvwzb +good +luck ",code,"Hearing from the Oracle that a programmer named Neo may possibly be ""The One"", Trinity goes into the Matrix to observe him, but her communications are intercepted. Back in the hovercraft Nebuchadnezzar, Trinity decides to add another level of encryption to her communication using a ""one-time pad"".",ai,2014-09-18T09:46:05,2016-09-09T09:52:40,,,,"Hearing stories from the Oracle that a programmer named Neo may possibly be ""The One"", Trinity risks going into the Matrix to observe Neo. While in the Matrix, her communications are intercepted and Trinity is almost caught by Agent Smith and two other agents. Safely back in the hovercraft Nebuchadnezzar, Trinity decides to add another level of encryption to her communication using a ""one-time pad"". The idea is that given a sequence of numbers (a pad), any message can be proven to be securely encrypted if each character in the string is encoded by a number from the pad, if each number from the pad is only used once. Trinity decides to use the one-time pad to encrypt her messages by shifting each letter in the message by k positions later in the alphabet, where k is determined by the one-time pad. Shifts occur in alphabetical order, between the letters “a” and “z”. If a letter is shifted past “z”, it starts back at “a” and continues shifting. For example, shifting each letter by k = 2, the word “car” is transformed into “ect”, while the word “yaz” is shifted to “acb”. + +**Input format:** +The input will begin with the size of the one-time pad, followed by a sequence of numbers for the pad. The remaining input consists of a series of words to be encrypted using the keyword. The input will be terminated by a line containing only -1. +You may assume that the maximum size of the pad is 100 numbers, all numbers in the pad are between 0 and 25, and that all input will be lowercase letters. + +**Output Format:** +For each word to be encrypted, output a line containing the encrypted word. + + +**Sample Input 1:** +10 +1 2 3 4 5 4 3 2 1 0 +aaaaa zzzzz +-1 + +**Sample Output 1:** +bcdef +dcbaz + +**Sample Input 2:** +40 +1 5 2 21 3 8 4 25 11 9 +6 7 8 9 11 12 3 0 11 4 +14 21 9 0 1 3 12 7 2 11 +5 9 20 12 1 19 4 9 8 24 +humans make good batteries +gnlr esrf +-1 + +**Sample Output 2:** +izovqa +qzvn +mvwm +mmwtpvwzb +good +luck ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T09:48:35,2016-05-12T23:56:39,setter," #include + #include + #include + #include ""apstring.h"" + #include ""apstring.cpp"" + + //----------------------------------------------------------------------- + // main + //----------------------------------------------------------------------- + + int main() + { + apstring key; + apstring buf; + int pad[100]; // max pad is 100 chars + char code[100]; // store encrypted string + int i,len,padsize,padindex; + unsigned int c; + + cin >> padsize; + padindex = 0; + + for (i = 0; i> pad[i]; + assert((pad[i] >= 0) && (pad[i] <= 25)); + } + + cin >> buf; + while (buf != ""-1"") { // look at each string + + len = buf.length(); + for (i = 0; i < len; i++) { + assert((buf[i] >= 'a') && (buf[i] <= 'z')); + c = (unsigned int) (buf[i] + pad[padindex++]); + if (c > (unsigned int) 'z') + c -= 26; // 26 letters + code[i] = (char) c; + } + + assert(i < 100); + code[i] = '\0'; + cout << code << endl; // print output + cin >> buf; // get next string + } + } +",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,C++ +180,4303,sarumans-secret-message,Saruman's Secret Message,"Saruman occasionally sends top-secret messages to his orc commanders using a horde of bats. Because each bat can only carry a limited amount of weight, Saruman breaks up each message into many smaller fragments, with each bat carrying a single message fragment. To reduce the possibility of detection in case one or more bats are captured, Saruman sends many copies of each message, with copies fragmented in different ways. + +To decode the message, the recipient must combine the different message fragments, using the overlapping regions as hints. For instance, the fragment ""abcde"" can be combined with the fragment ""cdefgh"" to form ""abcdefgh"". Though there may be many ways to combine the message fragments, the shortest combination is generally taken to be the most correct result. For instance, given the fragments ""abaca"" and ""acada"", two possible combinations are ""abacada"" and ""abacacada"". To simplify decoding the message, Saruman always begins each message with the marker ""ZZZ"". + +If parts of the message are lost, it is possible that the message fragments cannot be combined into a single contiguous message. You may assume this did not happen with your message. Even without losing any fragments, assembling a single message can be difficult (or impossible) in the general case. For simplicity you may assume that the shortest combination (with maximum overlap) yields the correct message, and that there is only one such combination (i.e., at each step only one message fragment will have the maximum overlap). + +A few days ago Saruman sent you and your fellow orcs to track down and ""take care"" of some troublesome hobbits near your tower. You can tell you are getting close and are looking forward to having a little ""snack"" upon completion of your task, when bats begin arriving with many message fragments. You sigh and begin the laborious task of putting the coded message together, wondering in the back of your mind whether wizards will ever discover some spell to magically assemble such messages. + +**Input Format:** +The number of message fragments (as an integer), followed by each message fragment (as a string) on a separate line. You may assume that all message fragments are exactly 12 letters, and that you will receive at most 100 message fragments. If there are multiple ways to overlap fragments, choose the combination which yields the shortest result (i.e., maximum overlap). You may assume the fragment with the maximum overlap is unique. +The beginning of each message always contains the marker ""ZZZ"". + +**Output Format:** +The text of the complete message, without the beginning ""ZZZ"" marker. + +**Sample Input:** +17 +em.down!.Do. +l.they.are.f +ZZZHunt.them +o.not.stop.u +.until.they. +t.them.down! +Hunt.them.do +n!.Do.not.st +y.are.found. +p.until.they +.them.down!. +they.are.fou +.not.stop.un +.Do.not.stop +down!.Do.not +t.stop.until +.stop.until. + + +**Sample Output:** +Hunt.them.down!.Do.not.stop.until.they.are.found. + + +",code,"Saruman sends top-secret messages to his orc commanders using a horde of bats. He breaks up each message into many fragments, with each bat carrying a single message fragment. To decode the message, the recipient must combine the different message fragments, using the overlapping regions as hints.",ai,2014-09-18T09:56:49,2016-09-09T09:52:41,,,,"Saruman occasionally sends top-secret messages to his orc commanders using a horde of bats. Because each bat can only carry a limited amount of weight, Saruman breaks up each message into many smaller fragments, with each bat carrying a single message fragment. To reduce the possibility of detection in case one or more bats are captured, Saruman sends many copies of each message, with copies fragmented in different ways. + +To decode the message, the recipient must combine the different message fragments, using the overlapping regions as hints. For instance, the fragment ""abcde"" can be combined with the fragment ""cdefgh"" to form ""abcdefgh"". Though there may be many ways to combine the message fragments, the shortest combination is generally taken to be the most correct result. For instance, given the fragments ""abaca"" and ""acada"", two possible combinations are ""abacada"" and ""abacacada"". To simplify decoding the message, Saruman always begins each message with the marker ""ZZZ"". + +If parts of the message are lost, it is possible that the message fragments cannot be combined into a single contiguous message. You may assume this did not happen with your message. Even without losing any fragments, assembling a single message can be difficult (or impossible) in the general case. For simplicity you may assume that the shortest combination (with maximum overlap) yields the correct message, and that there is only one such combination (i.e., at each step only one message fragment will have the maximum overlap). + +A few days ago Saruman sent you and your fellow orcs to track down and ""take care"" of some troublesome hobbits near your tower. You can tell you are getting close and are looking forward to having a little ""snack"" upon completion of your task, when bats begin arriving with many message fragments. You sigh and begin the laborious task of putting the coded message together, wondering in the back of your mind whether wizards will ever discover some spell to magically assemble such messages. + +**Input Format:** +The number of message fragments (as an integer), followed by each message fragment (as a string) on a separate line. You may assume that all message fragments are exactly 12 letters, and that you will receive at most 100 message fragments. If there are multiple ways to overlap fragments, choose the combination which yields the shortest result (i.e., maximum overlap). You may assume the fragment with the maximum overlap is unique. +The beginning of each message always contains the marker ""ZZZ"". + +**Output Format:** +The text of the complete message, without the beginning ""ZZZ"" marker. + +**Sample Input:** +17 +em.down!.Do. +l.they.are.f +ZZZHunt.them +o.not.stop.u +.until.they. +t.them.down! +Hunt.them.do +n!.Do.not.st +y.are.found. +p.until.they +.them.down!. +they.are.fou +.not.stop.un +.Do.not.stop +down!.Do.not +t.stop.until +.stop.until. + + +**Sample Output:** +Hunt.them.down!.Do.not.stop.until.they.are.found. + + +",0.4,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T09:57:09,2016-05-12T23:56:39,setter," #include + #include + #include + + // Uncomment the following lines if using APCS classes + // #include ""apvector.h"" + // #include ""apmatrix.h"" + // #include ""apstack.h"" + // #include ""apqueue.h"" + + #include ""apstring.cpp"" + + //----------------------------------------------------------------------- + // main + //----------------------------------------------------------------------- + + int main() + { + const int FRAGSIZE = 12; + const int MAXFRAG = 100; + apstring frag[MAXFRAG], result, str, marker, head, tail; + int numFrag, i, k, maxOverlap, overlapIdx, overlapIdx2, slen; + bool found; + + // read in all fragments + + cin >> numFrag; + for (i = 0; i < numFrag; i++) { + cin >> frag[i]; + if (frag[i].length() != FRAGSIZE) { + cout << ""ERROR, illegal fragment size "" << frag[i] << endl; + } + } + + // find beginning marker, use as current result + + marker = apstring(""ZZZ""); + slen = marker.length(); + found = false; + + for (i = 0; i < numFrag; i++) { + if (marker == frag[i].substr(0, slen)) { + result = apstring(frag[i]); + frag[i] = frag[--numFrag]; + found = true; + break; + } + } + + if (!found) { + cout << ""ERROR, no fragment with initial marker "" << marker << endl; + } + + // assemble fragments + + while (numFrag > 0) { + + // find fragment with greatest overlap to end of current result + + maxOverlap = 0; + overlapIdx2 = -1; + + for (i = 0; i < numFrag; i++) { + + // check if entire fragment is subsumed in string + while (result.find(frag[i]) != npos) { + frag[i] = frag[--numFrag]; + } + + if (i == numFrag) // no more fragments + break; + + for (k = maxOverlap+1; k < FRAGSIZE; k++) { + head = frag[i].substr(0,k); + tail = result.substr(result.length() - k, k); + if (head == tail) { + if (k > maxOverlap) { + maxOverlap = k; + overlapIdx = i; + } + else if (k == maxOverlap) { + overlapIdx2 = i; + } + } + } + } + + // append fragment with greatest overlap to end of current result + + if (maxOverlap > 0) { + // cout << ""Merging "" << maxOverlap << "" "" << result << "" "" << frag[overlapIdx]; + result += frag[overlapIdx].substr(maxOverlap, FRAGSIZE-maxOverlap); + frag[overlapIdx] = frag[--numFrag]; + + if (overlapIdx2 >= 0) { + cout << ""Error, found multiple fragments with max overlap: "" << endl; + cout << frag[overlapIdx] << "" && "" << frag[overlapIdx2] << endl; + } + } + else { + cout << ""Error, unable to assemble complete message "" << endl; + cout << ""Remaining fragments: \n""; + for (k = 0; k < numFrag; k++) { + cout << frag[k] << endl; + } + break; + } + } + + cout << result.substr(slen, result.length()-slen) << endl; + + return 0; + } + + +",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,C++ +181,2591,strongly-connected-digraphs,Strongly Connected Digraphs,"Count the number of [labeled strongly connected digraphs](http://en.wikipedia.org/wiki/Directed_graph) with the given number of vertices. + +**Input Format** +The first line contains $T$, the number of queries. +Following are $T$ lines. Each line contains one integer $N$, denoting the number of vertices. + +**Output Format** +Output $T$ lines. Each line is the number of labeled strongly connected digraphs with $N$ vertices, modulo $(10^9 + 7)$. + +**Constraints** +$1 \le T \le 1000$ +$1 \le N \le 1000$ + +**Sample Input** + + 5 + 1 + 2 + 3 + 4 + 1000 + +**Sample Output** + + 1 + 1 + 18 + 1606 + 871606913 + +**Explanation** + +You can refer to [oeis](http://oeis.org/A003030). +",code,Count the number of labeled strongly connected digraphs with the given number of vertices.,ai,2014-06-10T12:27:33,2022-09-02T09:55:01,,,,"Count the number of [labeled strongly connected digraphs](http://en.wikipedia.org/wiki/Directed_graph) with the given number of vertices. + +**Input Format** +The first line contains $T$, the number of queries. +Following are $T$ lines. Each line contains one integer $N$, denoting the number of vertices. + +**Output Format** +Output $T$ lines. Each line is the number of labeled strongly connected digraphs with $N$ vertices, modulo $(10^9 + 7)$. + +**Constraints** +$1 \le T \le 1000$ +$1 \le N \le 1000$ + +**Sample Input** + + 5 + 1 + 2 + 3 + 4 + 1000 + +**Sample Output** + + 1 + 1 + 18 + 1606 + 871606913 + +**Explanation** + +You can refer to [oeis](http://oeis.org/A003030). +",0.5454545454545454,"[""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,,,,,,,2014-09-18T10:14:19,2016-12-24T11:27:40,tester,"###Python 2 +```python +''' +Use the ff: +http://www.emis.de/journals/AUSM/C5-1/math51-5.pdf +http://people.brandeis.edu/~gessel/homepage/students/ostroffthesis.pdf +(Beware, they both have mistakes!) +''' + +mod = 10**9+7 +MAX = 1001 + +C = [[0]*MAX for i in xrange(MAX)] +e = [0]*MAX +s = [0]*MAX +for n in xrange(MAX): + for r in xrange(n+1): + C[n][r] = 1 if r == 0 or r == n else (C[n-1][r-1] + C[n-1][r]) % mod + e[n] = (pow(2, n*(n-1), mod) - sum(C[n][i]*pow(2, (n-1)*(n-i), mod)*e[i] for i in xrange(1,n))) % mod + s[n] = (e[n] + sum(C[n-1][i-1]*s[i]*e[n-i] for i in xrange(1,n))) % mod + +for cas in xrange(input()): + print s[input()] +``` +",not-set,2016-04-24T02:03:05,2016-07-23T18:47:35,Python +182,4305,go-back-home,Go Back Home,"Corporal Klinger is a member of the 4077th Mobile Army Surgical +Hospital in the Korean War; and he will do just about anything to get +out. The U.S. Army has made an offer for a lottery that will choose +some number of lucky people (X) to return to the states for a +recruiting tour. Klinger needs your help getting out. + +The lottery is run by lining up all the members of the unit at +attention and eliminating members by counting off the members from 1 to +N where N is a number chosen by pulling cards off of the top of a deck. +Every time N is reached, that person falls out of the line, and +counting begins again at 1 with the next person in line. When the end +of the line has been reached (with whatever number that may be), the +next card on the top of the deck will be taken, and counting starts +again at 1 with the first person in the remaining line. The last X +people in line get to go home. + +Klinger has found a way to trade a stacked deck with the real deck just +before the selection process begins. However, he will not know how +many people will show up for the selection until the last minute. Your +job is to write a program that will use the deck Klinger supplies and +the number of people in line that he counts just before the selection +process begins and tell him what position(s) in the line to get in to +assure himself of a trip home. You are assured that Klinger's deck +will get the job done by the time the 20th card is used. + +A simple example with 10 people, 2 lucky spots, and the numbers from +cards 3, 5, 4, 3, 2 would show that Klinger should get in positions 1 +or 8 to go home. + +**Input Format:** +For each selection, you will be given a line of 22 integers. The first +integer (1 <= N <= 50) tells how many people will participate in the +lottery. The second integer (1 <= X <= N) is how many lucky ""home"" +positions will be selected. The next 20 integers are the values of the +first 20 cards in the deck. Card values are interpretted to integer +values between 1 and 11 inclusive. +_'0' in a new line marks the end of input._ + +**Output Format:** +For each input line, you are to print the message ""Selection #A"" on a +line by itself where A is the number of the selection starting with 1 +at the top of the input file. The next line will contain a list of +""lucky"" positions that Klinger should attempt to get into. *The list of +""lucky"" positions is then followed by a blank line.* + + +**Sample Input:** + + 47 6 11 2 7 3 4 8 5 10 7 8 3 7 4 2 3 9 10 2 5 3 + 0 + +**Sample Output:** + + Selection #1 + 1 3 16 23 31 47 + + ",code,Corporal Klinger is a member of the 4077th Mobile Army Surgical Hospital in the Korean War and will do just about anything to get out. The U.S. Army has made an offer for a lottery to choose some number lucky people to return to the states for a recruiting tour. Klinger needs your help getting out. ,ai,2014-09-18T10:15:08,2016-09-09T09:52:42,,,,"Corporal Klinger is a member of the 4077th Mobile Army Surgical +Hospital in the Korean War; and he will do just about anything to get +out. The U.S. Army has made an offer for a lottery that will choose +some number of lucky people (X) to return to the states for a +recruiting tour. Klinger needs your help getting out. + +The lottery is run by lining up all the members of the unit at +attention and eliminating members by counting off the members from 1 to +N where N is a number chosen by pulling cards off of the top of a deck. +Every time N is reached, that person falls out of the line, and +counting begins again at 1 with the next person in line. When the end +of the line has been reached (with whatever number that may be), the +next card on the top of the deck will be taken, and counting starts +again at 1 with the first person in the remaining line. The last X +people in line get to go home. + +Klinger has found a way to trade a stacked deck with the real deck just +before the selection process begins. However, he will not know how +many people will show up for the selection until the last minute. Your +job is to write a program that will use the deck Klinger supplies and +the number of people in line that he counts just before the selection +process begins and tell him what position(s) in the line to get in to +assure himself of a trip home. You are assured that Klinger's deck +will get the job done by the time the 20th card is used. + +A simple example with 10 people, 2 lucky spots, and the numbers from +cards 3, 5, 4, 3, 2 would show that Klinger should get in positions 1 +or 8 to go home. + +**Input Format:** +For each selection, you will be given a line of 22 integers. The first +integer (1 <= N <= 50) tells how many people will participate in the +lottery. The second integer (1 <= X <= N) is how many lucky ""home"" +positions will be selected. The next 20 integers are the values of the +first 20 cards in the deck. Card values are interpretted to integer +values between 1 and 11 inclusive. +_'0' in a new line marks the end of input._ + +**Output Format:** +For each input line, you are to print the message ""Selection #A"" on a +line by itself where A is the number of the selection starting with 1 +at the top of the input file. The next line will contain a list of +""lucky"" positions that Klinger should attempt to get into. *The list of +""lucky"" positions is then followed by a blank line.* + + +**Sample Input:** + + 47 6 11 2 7 3 4 8 5 10 7 8 3 7 4 2 3 9 10 2 5 3 + 0 + +**Sample Output:** + + Selection #1 + 1 3 16 23 31 47 + + ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T10:15:20,2016-05-12T23:56:37,setter," #include + + int cards[20], participants, lucky, sim_count; + FILE *inp, *outp; + + void find_positions(void) + { int positions[50], i, j, k, num_left; + + for (i=0; i<50; i++) + { positions[i] = 1; } + + for (i = 0, num_left = participants; num_left > lucky; i++) + { k = 0; + for (j = 0; (j < participants) && num_left > lucky; j++) + { if (positions[j]) + { if (++k == cards[i]) + { num_left--; + k = 0; + positions[j] = 0; + } + } + } + } + + fprintf(outp, ""Selection #%1d\n"", ++sim_count); + for (i = 0; i + + /* return 1 if this number of coconuts can be divided up + properly between this number of people */ + int SplitCoco(long n_coco, long n_people) { + long i; + + for (i=0; i 1; n_people--) { + if (SplitCoco(n_coco, n_people)) { + printf(""%ld coconuts, %ld people and 1 monkey\n"", + n_coco, n_people); + goto found; + + /* OK, so yea, I put a 'goto' in my code :-) + it was quick and it works. I don't do + it often, I swear. */ + + } + } + /* if no number of people greater than 1 works, there is + no solution */ + printf(""%ld coconuts, no solution\n"", n_coco); + found: + } + return 0; + } + +",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,C++ +184,4310,character-alternations,Character Alternations,"On the long long road to Mordor, Sam and Frodo get to talking... + +**Sam:** “Mr. Frodo, I am quite exasperated with our situation.” + +**Frodo:** “Sam, that is an interesting choice of words. Note that in the word ‘exasperated’ the letters ‘e’ and ‘a’ alternate 5 times.” + + exasperated + ↑ ↑ ↑ ↑ ↑ + +**Sam:** “Dear Mr. Frodo. We are starving and being hunted by nasty orcs and giant spiders, I find your sudden interest in spelling most counterintuitive."" + +**Frodo:**“My goodness Sam! You just topped yourself. The word ""counterintuitive"" has fully 6 alternations, involving the letters ‘t’ and ‘i’!” + + counterintuitive + ↑ ↑ ↑ ↑↑↑ + +**Sam:** “Master Frodo, we are starving. I want to go home! Please stop talking about such insignificant matters, or I will surely turn around and quit this instant.” + +**Frodo:** “Oh my goodness Sam, you just did it again. The word ‘insignificant’ also has 6 alternations!” + + insignificant + ↑↑ ↑ ↑ ↑ ↑ + +**Sam:** “That does it. I’m heading back to the shire. You can keep the blasted ring.” + +**Smeagol:** “Sssilly hobbitssess.” + +Frodo loves to find alternating patterns of letters in words. An alternation is defined to be two +distinct characters (letters, digits, or punctuation) that alternate at least three times as the word is read from left to right, as shown in the above examples. Thus, the word “boo” has no alternations, but “booboo” has “bobo” as an alternation of length 4. Upper and lower case characters are considered to be different, and so, “aragorn” contains the 4-element alternation “arar”, but “Aragorn” only has the 3-element alternation “rar”. Digits and punctuation may be used, so “a2b-c2d-” has the alternation “2-2-”. + +The objective of this problem is to write a program to find the length of the longest alternation in a word. + +**Input Format:** +Your program will read in a series of strings, one per line. Each string will contain no embedded spaces,but may contain punctuation symbols and digits. *End of input strings is marked by a 0 in a new line.* + +**Output Format:** +Your program will output the word and the length of the longest alternation. (It does not need to +output the actual letters.) If there is no alternation of length 3 or more, then it outputs 0 as the length. See the example below. + +**Example:** + + Input: Output: + ------------------------------------------------------------ + exasperated exasperated has 5 alternations + counterintuitive counterintuitive has 6 alternations + insignificant insignificant has 6 alternations + Aragorn Aragorn has 3 alternations + a2b-c2d- a2b-c2d- has 4 alternations + cat cat has 0 alternations + ca ca has 0 alternations + c c has 0 alternations + 0",code,"Frodo loves finding alternating patterns of letters in words. An alternation is when two distinct characters (letters, digits, or punctuation) alternate at least three times in the word from left to right. The objective of this problem is to find the length of the longest alternation in a word.",ai,2014-09-18T12:56:21,2016-09-09T09:52:43,,,,"On the long long road to Mordor, Sam and Frodo get to talking... + +**Sam:** “Mr. Frodo, I am quite exasperated with our situation.” + +**Frodo:** “Sam, that is an interesting choice of words. Note that in the word ‘exasperated’ the letters ‘e’ and ‘a’ alternate 5 times.” + + exasperated + ↑ ↑ ↑ ↑ ↑ + +**Sam:** “Dear Mr. Frodo. We are starving and being hunted by nasty orcs and giant spiders, I find your sudden interest in spelling most counterintuitive."" + +**Frodo:**“My goodness Sam! You just topped yourself. The word ""counterintuitive"" has fully 6 alternations, involving the letters ‘t’ and ‘i’!” + + counterintuitive + ↑ ↑ ↑ ↑↑↑ + +**Sam:** “Master Frodo, we are starving. I want to go home! Please stop talking about such insignificant matters, or I will surely turn around and quit this instant.” + +**Frodo:** “Oh my goodness Sam, you just did it again. The word ‘insignificant’ also has 6 alternations!” + + insignificant + ↑↑ ↑ ↑ ↑ ↑ + +**Sam:** “That does it. I’m heading back to the shire. You can keep the blasted ring.” + +**Smeagol:** “Sssilly hobbitssess.” + +Frodo loves to find alternating patterns of letters in words. An alternation is defined to be two +distinct characters (letters, digits, or punctuation) that alternate at least three times as the word is read from left to right, as shown in the above examples. Thus, the word “boo” has no alternations, but “booboo” has “bobo” as an alternation of length 4. Upper and lower case characters are considered to be different, and so, “aragorn” contains the 4-element alternation “arar”, but “Aragorn” only has the 3-element alternation “rar”. Digits and punctuation may be used, so “a2b-c2d-” has the alternation “2-2-”. + +The objective of this problem is to write a program to find the length of the longest alternation in a word. + +**Input Format:** +Your program will read in a series of strings, one per line. Each string will contain no embedded spaces,but may contain punctuation symbols and digits. *End of input strings is marked by a 0 in a new line.* + +**Output Format:** +Your program will output the word and the length of the longest alternation. (It does not need to +output the actual letters.) If there is no alternation of length 3 or more, then it outputs 0 as the length. See the example below. + +**Example:** + + Input: Output: + ------------------------------------------------------------ + exasperated exasperated has 5 alternations + counterintuitive counterintuitive has 6 alternations + insignificant insignificant has 6 alternations + Aragorn Aragorn has 3 alternations + a2b-c2d- a2b-c2d- has 4 alternations + cat cat has 0 alternations + ca ca has 0 alternations + c c has 0 alternations + 0",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T12:56:58,2016-05-12T23:56:36,setter," import java.io.*; + import java.util.StringTokenizer; + + /** + * The program inputs a string and outputs the maximum number of + * alternations of two distinct characters in the string. For example, + * the string ""international"" has 5 alternations involving the letters + * n and t: + * + * i n t e r n a t i o n a l + * ^ ^ ^ ^ ^ + * + * Case is significant (so ""AbaB"" has no alternations), and any + * character may be used in an alternation (so ""ab1f-gh1-cd1"" has + * the alternating sequence ""1-1-1"" of length 5). + * + * The smallest sized alternation is of length 3 (e.g., ""..a..b..a..""). + * Sequences of 2 or fewer (as in ""..a..b.."") are not considered to be + * alternations, and hence the result is 0 in this case (rather than 2). + * + * + */ + public class Alternations { + + public static void main(String[] args) { + try { + InputStreamReader isr = new InputStreamReader(System.in); + BufferedReader stdin = new BufferedReader(isr); + String line = stdin.readLine(); + while (line != null) { + StringTokenizer tokenizer = new StringTokenizer(line); + // read first string + String word = tokenizer.nextToken(); + // convert to char array + char[] letters = word.toCharArray(); + // get number of alternations + int nAlts = getMaxAlternations(letters); + System.out.println(word + "" has "" + nAlts + "" alternations""); + line = stdin.readLine(); // next line + } + } + // Catch input errors + catch (Exception exception) { + System.out.println(""I/O error.""); + } + } + + private static int getMaxAlternations(char[] letters) { + // -------------- ADD YOUR CODE HERE ---------------------- + int maxAlts = 0; // initially no alternations + for (int i = 0; i < letters.length; i++) { + char x = letters[i]; // first character + for (int j = i+1; j < letters.length; j++) { + char y = letters[j]; // second character + if (x != y) { + int nAlts = getMaxXYAlternations(x, y, letters); + if (nAlts > maxAlts) maxAlts = nAlts; + } + } + } + return maxAlts; + } + + private static int getMaxXYAlternations(char x, char y, char[] letters) { + char[] theChars = new char[2]; // stogage for the characters + theChars[0] = x; + theChars[1] = y; + int nextMatch = 0; // start matching with x + int altCount = 0; // alternation count + for (int i = 0; i < letters.length; i++) { + if (letters[i] == theChars[nextMatch]) { + altCount++; // increase count + nextMatch = 1 - nextMatch; // go to other character + } + } + return (altCount < 3 ? 0 : altCount); // return 3 or more + } + }",not-set,2016-04-24T02:03:05,2016-04-24T02:03:05,Python +185,4311,the-dangerous-seven,The Dangerous Seven,"Super Mario is studying how to use a mysterious Power Square. The Power Square is n×n with integer values between 0 and n^2 − 1. +A number y is a neighbor of another number x in the Power Square if y is directly above or below +x, or directly to the left or right of x. Rosalina asks Super Mario to find all the numbers in the Power Square that are neighbors of the number 7, since she can tell that those numbers are quite nervous. +""Why are the numbers scared of seven?"" Mario asks Rosalina. +""Because seven ate nine!"" Rosalina exclaims. + +**Input/Output Format:** +Input is a description of of the Power Square, followed by a number of commands. The first line is the size of the Power Square n. You may assume n ≤ 100. The second line contains the n^2 values in the Power Square, separated by spaces. Values start from the top left corner and move from left to right, moving down one row to the leftmost position when a row is filled. + +Following the Power Square description are a number of commands, with each command on a separate line. Each command begins with the name of the command, followed by any additional command parameters. + +* The command ”SHOW” causes the current state of the Power Square to be displayed in n × n form (each row of n values on a single line, separated by spaces), followed by a blank line. +* The command ”NEIGHBORS” is followed by a value x in the Power Square. The values neighbouring x are output and displayed on a single line (in the order: above, left, right and below x), separated by spaces. You may assume that x is always in the power square. + +**Example:** + + Input: + + 3 + 8 7 6 5 4 3 2 1 0 + SHOW + NEIGHBORS 7 + NEIGHBORS 1 + NEIGHBORS 4 + + Output: + + 8 7 6 + 5 4 3 + 2 1 0 + 8 6 4 + 4 2 0 + 7 5 3 1 +",code,"Super Mario is studying how to use a mysterious Power Square. The Power Square is n×n with integer values between 0 and n^2 − 1. Rosalina asks Super Mario to find all the numbers in the Power Square that are neighbors of the number 7, ""Because seven ate nine!""",ai,2014-09-18T13:41:19,2016-09-09T09:52:43,,,,"Super Mario is studying how to use a mysterious Power Square. The Power Square is n×n with integer values between 0 and n^2 − 1. +A number y is a neighbor of another number x in the Power Square if y is directly above or below +x, or directly to the left or right of x. Rosalina asks Super Mario to find all the numbers in the Power Square that are neighbors of the number 7, since she can tell that those numbers are quite nervous. +""Why are the numbers scared of seven?"" Mario asks Rosalina. +""Because seven ate nine!"" Rosalina exclaims. + +**Input/Output Format:** +Input is a description of of the Power Square, followed by a number of commands. The first line is the size of the Power Square n. You may assume n ≤ 100. The second line contains the n^2 values in the Power Square, separated by spaces. Values start from the top left corner and move from left to right, moving down one row to the leftmost position when a row is filled. + +Following the Power Square description are a number of commands, with each command on a separate line. Each command begins with the name of the command, followed by any additional command parameters. + +* The command ”SHOW” causes the current state of the Power Square to be displayed in n × n form (each row of n values on a single line, separated by spaces), followed by a blank line. +* The command ”NEIGHBORS” is followed by a value x in the Power Square. The values neighbouring x are output and displayed on a single line (in the order: above, left, right and below x), separated by spaces. You may assume that x is always in the power square. + +**Example:** + + Input: + + 3 + 8 7 6 5 4 3 2 1 0 + SHOW + NEIGHBORS 7 + NEIGHBORS 1 + NEIGHBORS 4 + + Output: + + 8 7 6 + 5 4 3 + 2 1 0 + 8 6 4 + 4 2 0 + 7 5 3 1 +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T13:42:33,2016-05-12T23:56:36,setter," import java.io.File; + import java.io.FileInputStream; + import java.io.FileOutputStream; + import java.io.PrintStream; + import java.util.Random; + import java.util.Scanner; + + + public class Puzzle { + static final int maxPuzzle = 1000; // size of puzzle + static int puzzleSize = 1; // size of puzzle + static int puzzleTiles; // number of tiles & 1 space in puzzle + + static int puzzle[]; + + public static void main(String[] args) throws Exception { + long time; + int rowNum = 0; + int row[] = new int [maxPuzzle]; + int idx; + + time = System.currentTimeMillis(); + time = System.currentTimeMillis() - time; + // System.out.println(""Solve Time = ""+(time/1000)); + + // read size of puzzle + Scanner sc = new Scanner( System.in ); + String line = sc.nextLine(); + Scanner lsc = new Scanner( line ); + + puzzleSize = lsc.nextInt(); + puzzleTiles = puzzleSize*puzzleSize; + puzzle = new int[puzzleTiles]; + + // read contents of puzzle + line = sc.nextLine(); + lsc = new Scanner( line ); + for (int i = 0; i< puzzleTiles; i++) { + puzzle[i] = lsc.nextInt(); + } + + // perform commands + while (sc.hasNextLine()) { + line = sc.nextLine(); + lsc = new Scanner( line ); + + // skip past empty lines + if (!lsc.hasNext()) + continue; + + String s = lsc.next(); + if (s.equals(""SHOW"")) { + printPuzzle(puzzle); + } + else if (s.equals(""NEIGHBORS"")) { + int target = lsc.nextInt(); + int neighbors[] = findNeighbors(target); + for (int i = 0; i< neighbors.length; i++) { + System.out.print(neighbors[i] + "" ""); + } + System.out.println(); + } + else if (s.equals(""SOLUTION"")) { + boolean solved = isSolution(puzzle); + System.out.println(solved); + } + else if (s.equals(""DIRECTIONS"")) { + int target = lsc.nextInt(); + takeSteps(target); + } + else if (s.equals(""SOLVE"")) { + int maxSteps = lsc.nextInt(); + solvePuzzle(maxSteps); + } + else { + System.out.println(""Illegal input "" + s); + return; + } + } + } + + public static boolean isSolution(int p[]) { + // values must be in sorted order, except for last position + for (int i = 0; i < (puzzleTiles) - 2; i++) { + if (p[i] > p[i+1]) + return false; + } + // last position in puzzle must be 0 + return (p[puzzleTiles-1] == 0); + } + + public static int row_col_to_pos(int size, int r, int c) { + return (r*size)+c; + } + + public static int pos_to_row(int size, int pos) { + return pos/size; + } + + public static int pos_to_col(int size, int pos) { + return pos % size; + } + + public static int[] findNeighbors(int target) { + int i; + + for (i = 0; i < (puzzleTiles); i++) { + if (puzzle[i] == target) + break; + } + if (i == puzzleTiles) { + System.out.println(""Not found""); + return null; + } + + int row = i/puzzleSize; + int col = i%puzzleSize; + int numNeighbors = 0; + int neighbors[] = new int[4]; + + // top neighbor + if ((row - 1) >= 0) { + neighbors[numNeighbors] = puzzle[i-puzzleSize]; + numNeighbors++; + } + // left neighbor + if ((col - 1) >= 0) { + neighbors[numNeighbors] = puzzle[i-1]; + numNeighbors++; + } + // right neighbor + if ((col + 1) < puzzleSize) { + neighbors[numNeighbors] = puzzle[i+1]; + numNeighbors++; + } + // bottom neighbor + if ((row + 1) < puzzleSize) { + neighbors[numNeighbors] = puzzle[i+puzzleSize]; + numNeighbors++; + } + + int retVal[] = new int[numNeighbors]; + + for (int k = 0; k < numNeighbors; k++) { + retVal[k] = neighbors[k]; + } + + return retVal; + } + + public static void takeSteps(int target) { + + } + + public static void solvePuzzle(int maxSteps) { + + } + + public static void printPuzzle(int p[]) { + for (int i = 0; i + #include + + int main() + { + /* number of tasks */ + unsigned int N; + /* sides of rectangles */ + unsigned int A, B, C, D; + /* diagonals */ + double X, Y; + /* distances of intersection */ + double K, L; + /* the longest possible shorter side of the inner rectangle */ + double DMax; + + scanf(""%d"", &N); + for (; N > 0; N--) + { + /* + * Read in the data + */ + + /* the first (outer) and the second (inner) rectangle */ + scanf(""%d %d %d %d"", &A, &B, &C, &D); + /* first, normalize rectangles to one single case (A >= B, C >= D) */ + if (A < B) + { + unsigned int tmp = A; + A = B; + B = tmp; + } + if (C < D) + { + unsigned int tmp = C; + C = D; + D = tmp; + } + + /* + * Next, compute whether the rectangles can be put together + */ + + /* trivial case */ + if (A > C && B > D) + printf(TEXT_YES); + else + if (D >= B) + printf(TEXT_NO); + else + { + /* outer rectangle's diagonal */ + X = sqrt((double)A * (double)A + (double)B * (double)B); + /* inner rectangle's diagonal */ + Y = sqrt((double)C * (double)C + (double)D * (double)D); + /* check for marginal conditions */ + if (Y < B) + printf(TEXT_YES); /* the inner rectangle can freely rotate inside */ + else + if (Y > X) + /* there is no way how to put inner rectangle inside of the outer + one with the diagonal of the inner longer than the diagonal of + the outer */ + printf(TEXT_NO); + else + { + /* + * now, we compute intersection of inner rectangle's diagonal and + * sides of the outer one + */ + /* distance between the closest corner and the intersection */ + L = (B - sqrt(Y * Y - (double)A * (double)A)) / 2; + /* distance of the same corner and the second intersection */ + K = (A - sqrt(Y * Y - (double)B * (double)B)) / 2; + /* maximal possible shorter side of the inner rectangle with give + diagonal */ + DMax = sqrt(L * L + K * K); + /* if the actual side is longer, rectangles do not pass, but + they pass otherwise */ + if (D >= DMax) + printf(TEXT_NO); + else + printf(TEXT_YES); + } + } + } + return 0; + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +187,4320,bulk-mailing,Bulk Mailing,"An organization that wishes to make a large mailing can save postage by following U.S. Postal Service rules for a bulk mailing. Letters in zip code order are bundled into packets of 10-15 letters each. Bundles may consist of letters in which all 5 digits of zip code are the same (5-digit bundles), or they may consist of letters in which only the first 3 digits of zip code are the same (3-digit bundles). If there are fewer than 10 letters to make up a bundle of either type, those letters are mailed first class. + +You are to write a program to read a data set of 5-digit zip codes, one per line. Input ends when a negative number is entered. Your program should count the number of 5-digit bundles, 3-digit bundles, and first class letters. + +You should include as many letters as possible in 5-digit bundles first, then as many as possible in 3-digit bundles, with as few bundles of 10 to 15 letters as possible. For example, if there are 31 letters with the same zip code, they must be combined into exactly three 5-digit bundles. + +Not all zip codes in the data set will be valid. A valid zip code consists of exactly 5 digits (0-9), all of which cannot be 0. Non-numeric characters are not allowed. At the end of your output, print the invalid zip codes found. (Duplicates need only be printed once.) + +Print a report that lists 5-digit zip code bundles first, with the number of letters and number of bundles for each zip code. Next list all 3-digit zip code bundles with the same two counts, followed by all zip codes that are not bundled and to be sent first class. + +At the end print totals of letters and bundles, followed by the number of invalid zip codes and a list of these. Single space the report, and print blank lines following the heading, before the total line, and between the three groups of zip codes. For 3-digit bundles, print the zip codes in the form dddxx, where ddd represents the three significant digits and xx represents the last two digits to be omitted. Your output should be similar to that shown in the sample. + +**Sample:** +*SAMPLE INPUT:* +95864 +95864 +95864 +95867 +95920 +9j876 +95616 +95616 +95747 +95814 +95818 +95818 +8976 +95818 +95818 +95819 +95819 +00000 +95819 +95819 +95819 +95819 +95819 +95825 +95825 +95825 +95825 +95825 +95826 +95826 +95826 +95826 +95826 +95826 +95827 +8976 +95833 +95833 +95833 +95833 +95819 +95819 +95819 +95819 +95833 +95833 +95833 +95864 +95864 +95864 +123456 +95864 +95864 +95864 +95864 +-1 + +*SAMPLE OUTPUT:* + + ZIP LETTERS BUNDLES + + 95819 11 1 + 95864 10 1 + + 958xx 25 2 + + 95616 2 0 + 95747 1 0 + 95920 1 0 + + TOTALS 50 4 + + INVALID ZIP CODES + 9j876 + 8976 + 00000 + 123456 + +",code,An organization that wishes to make a large mailing can save postage by following U.S. Postal Service rules for a bulk mailing. You are to write a program to read a data set and sort letters into bundles.,ai,2014-09-18T17:24:55,2016-09-09T09:52:46,,,,"An organization that wishes to make a large mailing can save postage by following U.S. Postal Service rules for a bulk mailing. Letters in zip code order are bundled into packets of 10-15 letters each. Bundles may consist of letters in which all 5 digits of zip code are the same (5-digit bundles), or they may consist of letters in which only the first 3 digits of zip code are the same (3-digit bundles). If there are fewer than 10 letters to make up a bundle of either type, those letters are mailed first class. + +You are to write a program to read a data set of 5-digit zip codes, one per line. Input ends when a negative number is entered. Your program should count the number of 5-digit bundles, 3-digit bundles, and first class letters. + +You should include as many letters as possible in 5-digit bundles first, then as many as possible in 3-digit bundles, with as few bundles of 10 to 15 letters as possible. For example, if there are 31 letters with the same zip code, they must be combined into exactly three 5-digit bundles. + +Not all zip codes in the data set will be valid. A valid zip code consists of exactly 5 digits (0-9), all of which cannot be 0. Non-numeric characters are not allowed. At the end of your output, print the invalid zip codes found. (Duplicates need only be printed once.) + +Print a report that lists 5-digit zip code bundles first, with the number of letters and number of bundles for each zip code. Next list all 3-digit zip code bundles with the same two counts, followed by all zip codes that are not bundled and to be sent first class. + +At the end print totals of letters and bundles, followed by the number of invalid zip codes and a list of these. Single space the report, and print blank lines following the heading, before the total line, and between the three groups of zip codes. For 3-digit bundles, print the zip codes in the form dddxx, where ddd represents the three significant digits and xx represents the last two digits to be omitted. Your output should be similar to that shown in the sample. + +**Sample:** +*SAMPLE INPUT:* +95864 +95864 +95864 +95867 +95920 +9j876 +95616 +95616 +95747 +95814 +95818 +95818 +8976 +95818 +95818 +95819 +95819 +00000 +95819 +95819 +95819 +95819 +95819 +95825 +95825 +95825 +95825 +95825 +95826 +95826 +95826 +95826 +95826 +95826 +95827 +8976 +95833 +95833 +95833 +95833 +95819 +95819 +95819 +95819 +95833 +95833 +95833 +95864 +95864 +95864 +123456 +95864 +95864 +95864 +95864 +-1 + +*SAMPLE OUTPUT:* + + ZIP LETTERS BUNDLES + + 95819 11 1 + 95864 10 1 + + 958xx 25 2 + + 95616 2 0 + 95747 1 0 + 95920 1 0 + + TOTALS 50 4 + + INVALID ZIP CODES + 9j876 + 8976 + 00000 + 123456 + +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T17:25:10,2016-05-12T23:56:35,setter," //This is sample code when data is read from an input file until end of file + /*----------------------------- bulk.c ---------------------------------- + + Bulk Mail + + Read zip codes, validate and sort them, omitting bad codes. + Combine into bundles of 10-20 letters each. Create bundles + by matching all 5 digits first, then by matching first 3 + digits. Other letters go first class. Print report by + zip code with totals, and print invalid codes. + */ + #define DATA ""bulk.dat"" + #define MAX 20 + #define MIN 10 + #include + #include + #include + #include + #include + + void main(void) + { + FILE *fp; + long zip[500], zip2[500], num, comp, valid(char*); + int letters, bundles, prev, count; + int flag, i, j, k, n, savi, nzip, nerr; + int printout(int, long, int), adderr(char[][12], char*, int); + char s[12], err[20][12]; + + if((fp = fopen(DATA, ""r"")) == NULL) + { puts(""Can't open file""); exit(0); } + letters = bundles = 0; + i = n = 0; + printf(""ZIP LETTERS BUNDLES\n\n""); + while(fgets(s, 12, fp) != NULL) { + s[strlen(s)-1] = '\0'; + if((num = valid(s)) > 0) + zip[i++] = num; + else + n = adderr(err, s, n); + } + nzip = i; + nerr = n; + for(i = 0; i < nzip-1; ++i) /* sort the zips */ + for(j = 0; j < nzip-1; ++j) + if(zip[j] > zip[j+1]) { + comp = zip[j]; + zip[j] = zip[j+1]; + zip[j+1] = comp; + } + i = prev = k = 0; + flag = 0; /* first pass for 5-digit codes */ + while(i < nzip) { + count = 0; + comp = zip[i]; + savi = i; + while(zip[i] == comp && i < nzip) + i++; + count = i - savi; + if(count >= MIN) { + letters += count; + bundles += printout(count, comp, flag); + for(j = prev; j < savi; ++j) /* copy nonbundled to zip2 */ + zip2[k++] = zip[j]; + prev = i; + } + } /* end while i < nzip */ + for(j = prev; j < nzip; ++j) + zip2[k++] = zip[j]; /* end first pass */ + putchar('\n'); + i = 0; + nzip = k; + flag = 1; /* 2nd pass for 3-digit codes */ + while(i < nzip) { + savi = i; + comp = zip2[i++] / 100; + while(zip2[i]/100 == comp && i < nzip) + i++; + count = i - savi; + if(count >= MIN) { + letters += count; + bundles += printout(count, comp, flag); + for(j = savi; j < i; ++j) /* zero out bundled positions */ + zip2[j] = 0; + } + } /* end while i < nzip and end of 2nd pass */ + putchar('\n'); + i = 0; + while(i < nzip) { /* last pass for first class zips */ + while(zip2[i] == 0 && i < nzip) + i++; + comp = zip2[i++]; + count = 1; + while(zip2[i] == comp && i < nzip) { + count++; + i++; + } + printf(""%ld %3d 0\n"", comp, count); + letters += count; + } /* end while i < nzip and end last pass */ + printf(""\nTOTALS %3d %2d\n\n"", letters, bundles); + printf(""INVALID ZIP CODES\n\n""); + for(n = 0; n < nerr; ++n) + printf(""%s\n"", err[n]); + getch(); + } + long valid (char *s) + { + int i; + + if(strlen(s) != 5) + return -1; + for(i = 0; isdigit(s[i]); ++i) + ; + if(i != 5) /* if < 5 it's nonnumeric */ + return -1; + return atol(s); /* convert to numeric */ + } + int printout(int count, long comp, int flag) + { + int k, rem; /* k is no. bundles */ + + k = count / MAX; + rem = count % MAX; + if(rem > 0) + k++; + if(flag == 1) + printf(""%3ldxx"", comp); + else + printf(""%5ld"", comp); + printf("" %3d %2d\n"", count, k); + return k; + } + int adderr(char err[][12], char *s, int n) + { + int i; + + for(i = 0; i < n; ++i) + if(strcmp(err[i], s) == 0) + return n; + strcpy(err[n], s); + /* printf(""%s %s\n"", err[n], s); */ + return ++n; + } + + ",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +188,4322,rainbow-ride,Rainbow Ride,"Mr.Raju and his extended family are on vacation in Chennai. They visit MGM and see the Rainbow ride. They want to enjoy the ride. However, there are some problems. +Each person in the family likes some other people in the family. Each person insists that he or she will go on the ride only if all the people whom that person likes and all the people who like that person also go on the ride. If someone doesn't like anyone and no one likes him, he may come for the ride. + +You have been roped in to solve this dilemma. Given the weight of the each person in the family, and the list of people they like, and the maximum weight that the Rainbow can bear safely, calculate the maximum number of people in the family who can go on the rainbow. + +**Input Format:** +There will be multiple test cases in the input. For our convenience the family +members are numbered from 1 to n. Each test case begins with a line containing +two integers n ( 1 ≤ n ≤ 1000 ) and C ( 0 ≤ C ≤ 1000 ), where n is the number +of people in the family and C the maximum capacity of the ride in kilograms. +The next line contains n space separated integers with the ith integer giving the +weight of the i th family member. These weights are positive and less than or +equal to 200 kilograms. Then n lines follow. Each line contains a sequence of +integers separated by spaces. The first integer ki gives the number of people in +the family person i likes, followed by the persons i likes. An empty line separates +each test case. The end of input is indicated by n=0 and C=0 and it should not be +processed. There are atmost 50 test cases. + +**Output Format:** +For each test case output on a separate line the maximum number of persons +that can take the ride under the given conditions. + +**Example:** +*Input:* +5 200 +50 50 50 50 50 +1 2 +1 3 +0 +1 5 +1 4 +3 200 +100 100 100 +1 2 +1 3 +1 1 +0 0 + +*Output:* +3 +0 ",code,"Mr.Raju and his extended family are on vacation in Chennai. They visit MGM and see the Rainbow ride. They want to enjoy the ride. However, there are some problems. You have been roped in to solve their dilemma.",ai,2014-09-18T17:52:22,2016-09-09T09:52:47,,,,"Mr.Raju and his extended family are on vacation in Chennai. They visit MGM and see the Rainbow ride. They want to enjoy the ride. However, there are some problems. +Each person in the family likes some other people in the family. Each person insists that he or she will go on the ride only if all the people whom that person likes and all the people who like that person also go on the ride. If someone doesn't like anyone and no one likes him, he may come for the ride. + +You have been roped in to solve this dilemma. Given the weight of the each person in the family, and the list of people they like, and the maximum weight that the Rainbow can bear safely, calculate the maximum number of people in the family who can go on the rainbow. + +**Input Format:** +There will be multiple test cases in the input. For our convenience the family +members are numbered from 1 to n. Each test case begins with a line containing +two integers n ( 1 ≤ n ≤ 1000 ) and C ( 0 ≤ C ≤ 1000 ), where n is the number +of people in the family and C the maximum capacity of the ride in kilograms. +The next line contains n space separated integers with the ith integer giving the +weight of the i th family member. These weights are positive and less than or +equal to 200 kilograms. Then n lines follow. Each line contains a sequence of +integers separated by spaces. The first integer ki gives the number of people in +the family person i likes, followed by the persons i likes. An empty line separates +each test case. The end of input is indicated by n=0 and C=0 and it should not be +processed. There are atmost 50 test cases. + +**Output Format:** +For each test case output on a separate line the maximum number of persons +that can take the ride under the given conditions. + +**Example:** +*Input:* +5 200 +50 50 50 50 50 +1 2 +1 3 +0 +1 5 +1 4 +3 200 +100 100 100 +1 2 +1 3 +1 1 +0 0 + +*Output:* +3 +0 ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T17:52:34,2016-05-12T23:56:35,setter," #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + using namespace std; + + template inline void checkmax(T &a,T b){if(b>a) a=b;} + + const int maxsize=1000+5; + + int n,m; + int f[maxsize]; + int father[maxsize]; + int A[maxsize]; + + int getfather(int v) + { + return (father[v]<0)?v:(father[v]=getfather(father[v])); + } + void merge(int u,int v) + { + u=getfather(u); + v=getfather(v); + if (u!=v) father[u]=v; + } + int main() + { + // freopen(""input.txt"",""r"",stdin); + while (scanf(""%d%d"",&n,&m)!=-1 && n!=0) + { + memset(father,255,sizeof(father)); + for (int i=1;i<=n;i++) scanf(""%d"",&A[i]); + for (int i=1;i<=n;i++) + { + int cnt; + scanf(""%d"",&cnt); + for (;cnt>0;cnt--) + { + int value; + scanf(""%d"",&value); + merge(i,value); + } + } + memset(f,0,sizeof(f)); + for (int i=1;i<=n;i++) if (father[i]<0) + { + int cnt=0; + int sum=0; + for (int j=1;j<=n;j++) if (getfather(j)==i) + cnt++,sum+=A[j]; + for (int k=m;k>=sum;k--) + checkmax(f[k],f[k-sum]+cnt); + } + printf(""%d\n"",f[m]); + } + return 0; + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +189,4325,taming-a-t-rex,Taming a T-Rex,"Although evolution theory suggests that mammals started to dominate this world only after the mass extinction of the dinosaurs, there are some people who say man and dinosaurs may have co-existed for some time. Some argue that man even tamed and used some of these animals like the Flintstones. Shankar is such a believer and Sunil is a skeptic. +One day Sunil asked Shankar, ""If your argument is right how would you tame a T-REX and what would you use it for?"". Shankar replied, ""We can use it for cow transportation from one village to another and we can keep it calm by feeding it at constant intervals"". Sunil argued that the T-REX would have a maximum capacity C to carry. Let us say the distance is d km. If it is long, the T-REX would eat all the cows before it reaches the other village. Shankar argued that he knew a method that takes the maximum possible number of cows M to the destination. +Sunil replied, ""Oh really? I will give a few conditions. The T-REX will eat 1 cow every km until it reaches the destination. It may do so at any time during a 1 km stretch. So, there can not be a situation where the TREX has no cow to eat. If you drop cows in the middle, you can do so only at distances which are a multiple of 1 km. And, finally all the cows at the destination need to be alive i.e you can not cut a cow (fractions are not allowed)"". +Shankar was stunned. He needs your help. Given I (the number of cows at the starting village) , d and C find M, the maximum number of cows that can be taken to the destination subject to the mentioned constraints. + +**Input Format:** +There will be multiple test cases in the input. The input begins with a line containing a single integer n,n ≤ 300, which gives the number of test cases. Then n lines follow each containing the three integers I, 1 ≤ I ≤ 106, d, 1 ≤ d ≤ 105, and C, 1 ≤ I ≤ 106, in that order separated by spaces. d is in kilometers. + +**Output Format:** +For each test case print on a separate line the maximum number of cows that can be transported to the destination village under the given conditions. + +**Example:** + +*Input:* +2 +3000 1000 1000 +30 10 10 + +*Output:* +533 +5 ",code,"Although evolution theory suggests that mammals started to dominate this world only after the mass extinction of the dinosaurs, there are some people who say man and dinosaurs may have co-existed for some time. You need to help one such believer.",ai,2014-09-18T18:16:28,2016-09-09T09:52:48,,,,"Although evolution theory suggests that mammals started to dominate this world only after the mass extinction of the dinosaurs, there are some people who say man and dinosaurs may have co-existed for some time. Some argue that man even tamed and used some of these animals like the Flintstones. Shankar is such a believer and Sunil is a skeptic. +One day Sunil asked Shankar, ""If your argument is right how would you tame a T-REX and what would you use it for?"". Shankar replied, ""We can use it for cow transportation from one village to another and we can keep it calm by feeding it at constant intervals"". Sunil argued that the T-REX would have a maximum capacity C to carry. Let us say the distance is d km. If it is long, the T-REX would eat all the cows before it reaches the other village. Shankar argued that he knew a method that takes the maximum possible number of cows M to the destination. +Sunil replied, ""Oh really? I will give a few conditions. The T-REX will eat 1 cow every km until it reaches the destination. It may do so at any time during a 1 km stretch. So, there can not be a situation where the TREX has no cow to eat. If you drop cows in the middle, you can do so only at distances which are a multiple of 1 km. And, finally all the cows at the destination need to be alive i.e you can not cut a cow (fractions are not allowed)"". +Shankar was stunned. He needs your help. Given I (the number of cows at the starting village) , d and C find M, the maximum number of cows that can be taken to the destination subject to the mentioned constraints. + +**Input Format:** +There will be multiple test cases in the input. The input begins with a line containing a single integer n,n ≤ 300, which gives the number of test cases. Then n lines follow each containing the three integers I, 1 ≤ I ≤ 106, d, 1 ≤ d ≤ 105, and C, 1 ≤ I ≤ 106, in that order separated by spaces. d is in kilometers. + +**Output Format:** +For each test case print on a separate line the maximum number of cows that can be transported to the destination village under the given conditions. + +**Example:** + +*Input:* +2 +3000 1000 1000 +30 10 10 + +*Output:* +533 +5 ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T18:16:49,2016-05-12T23:56:34,setter," #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + using namespace std; + + int solve(int n,int D,int C) + { + if (C==1) return 0; + while (1) + { + if (n<=D) return 0; + if (D==0) return n; + if (n<=C) return max(0,n-D); + int M=n%C; + int S=n/C; + if (M>=2) + { + int E=2*S+1; + int G=min(D,(M-2)/E+1); + D-=G; + n-=G*E; + } + else + { + D--; + n-=(M+2*S-1); + } + } + } + + int main() + { + // freopen(""input.txt"",""r"",stdin); + int testcase; + for (scanf(""%d"",&testcase);testcase>0;testcase--) + { + int n,D,C; + scanf(""%d%d%d"",&n,&D,&C); + int ret=solve(n,D,C); + printf(""%d\n"",ret); + } + return 0; + } +",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +190,4327,factorial-frequencies,Factorial Frequencies,"In an attempt to bolster her sagging palm-reading business, Madam Phoenix has decided to offer several numerological treats to her customers. She has been able to convince them that the frequency of occurrence of the digits in the decimal representation of factorials bear witness to their futures. Unlike palm-reading, however, she can't just conjure up these frequencies, so she has employed you to determine these values. + +Recall that the definition of n! (that is, n factorial) is just 1x2x3x...xn. As she expects to use the day of the week, the day of the month, or the day of the year as the value of n, you must be able to determine the number of occurrences of each decimal digit in numbers as large as 366 factorial (366!), which has 781 digits. + +The input data for the program is simply a list of integers for which the digit counts are desired. All of these input values will be less than or equal to 366 and greater than 0, except for the last integer, which will be zero. Don't bother to process this zero value; just stop your program at that point. The output format isn't too critical, but you should make your program produce results that look similar to those shown below. + +Madam Phoenix will be forever (or longer) in your debt; she might even give you a trip if you do your job well! + +**Sample Input:** + + 3 + 8 + 100 + 0 + +**Expected Output:** +(Hint: Make sure you match all the spaces exactly!) + + + 3! -- + + (0) 0 (1) 0 (2) 0 (3) 0 (4) 0 + + (5) 0 (6) 1 (7) 0 (8) 0 (9) 0 + + 8! -- + + (0) 2 (1) 0 (2) 1 (3) 1 (4) 1 + + (5) 0 (6) 0 (7) 0 (8) 0 (9) 0 + + 100! -- + + (0) 30 (1) 15 (2) 19 (3) 10 (4) 10 + + (5) 14 (6) 19 (7) 7 (8) 14 (9) 20",code,"In an attempt to bolster her palm-reading business, Madam Phoenix has decided to offer several numerological treats to her customers. She has employed you to help her.",ai,2014-09-18T18:48:34,2016-09-09T09:52:48,,,,"In an attempt to bolster her sagging palm-reading business, Madam Phoenix has decided to offer several numerological treats to her customers. She has been able to convince them that the frequency of occurrence of the digits in the decimal representation of factorials bear witness to their futures. Unlike palm-reading, however, she can't just conjure up these frequencies, so she has employed you to determine these values. + +Recall that the definition of n! (that is, n factorial) is just 1x2x3x...xn. As she expects to use the day of the week, the day of the month, or the day of the year as the value of n, you must be able to determine the number of occurrences of each decimal digit in numbers as large as 366 factorial (366!), which has 781 digits. + +The input data for the program is simply a list of integers for which the digit counts are desired. All of these input values will be less than or equal to 366 and greater than 0, except for the last integer, which will be zero. Don't bother to process this zero value; just stop your program at that point. The output format isn't too critical, but you should make your program produce results that look similar to those shown below. + +Madam Phoenix will be forever (or longer) in your debt; she might even give you a trip if you do your job well! + +**Sample Input:** + + 3 + 8 + 100 + 0 + +**Expected Output:** +(Hint: Make sure you match all the spaces exactly!) + + + 3! -- + + (0) 0 (1) 0 (2) 0 (3) 0 (4) 0 + + (5) 0 (6) 1 (7) 0 (8) 0 (9) 0 + + 8! -- + + (0) 2 (1) 0 (2) 1 (3) 1 (4) 1 + + (5) 0 (6) 0 (7) 0 (8) 0 (9) 0 + + 100! -- + + (0) 30 (1) 15 (2) 19 (3) 10 (4) 10 + + (5) 14 (6) 19 (7) 7 (8) 14 (9) 20",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-18T18:48:46,2016-05-12T23:56:34,setter," #include + + int main() { + int digits[1000]; + int digit_counts[10] = {0}; + int n_digits, digit_no; + int i, j; + int n, overflow, prod; + + + scanf(""%d"", &n); + + while (n) { + digits[0] = 1; + n_digits = 1; + + for (i=2; i<=n; i++) { + overflow = 0; + for (j=0; j + #include + #include + + #define INPUT_FILE_NAME ""import.in"" + #define OUTPUT_FILE_NAME ""import.out"" + + #define N 27 + #define INFINITY 100 + #define EARTH 26 + + int distance[N][N]; + double value[N]; + + FILE *infile, *outfile; + + + void Floyd_Warshall (void) + { + register int i, j, k; + + for (k = 0; k < N; ++k) + for (i = 0; i < N; ++i) + for (j = 0; j < N; ++j) + { + int distance_ikj = distance[i][k] + distance[k][j]; + if (distance_ikj < distance[i][j]) + distance[i][j] = distance_ikj; + } + } + + + void add_edge (char A, char B) + { + int i = (A == '*') ? EARTH : A-'A'; + int j = (B == '*') ? EARTH : B-'A'; + + distance[i][j] = 1; + distance[j][i] = 1; + } + + + void initialize (void) + { + int i, j; + + for (i = 0; i < N; ++i) + for (j = 0; j < N; ++j) + distance[i][j] = INFINITY; + + for (i = 0; i < N; ++i) + value[i] = 0.0; + } + + + double import_value (int planet) + { + if (distance[EARTH][planet] < INFINITY) + return + pow (0.95, distance[EARTH][planet] - 1) * value[planet]; + else + return 0.0; + } + + + void find_best () + { + double best = 0.0; + int i, planet = 0; + + for (i = 0; i < EARTH; ++i) + { + double v = import_value (i); + if (v > best) + { + best = v; + planet = i; + } + } + + fprintf (outfile, ""Import from %c\n"", planet + 'A'); + } + + + void do_galaxy (void) + { + int i, j, planets; + + initialize (); + fscanf (infile, ""%d\n"", &planets); + + for (i = 0; i < planets; ++i) + { + double v; + char p, neighbor[N]; + + fscanf (infile, ""%c %lf %s\n"", &p, &v, neighbor); + + value[p-'A'] = v; + for (j = 0; j < strlen (neighbor); ++j) + add_edge (p, neighbor[j]); + } + + Floyd_Warshall (); + find_best (); + } + + + + void main (void) + { + infile = fopen (INPUT_FILE_NAME, ""rt""); + outfile = fopen (OUTPUT_FILE_NAME, ""wt""); + + while (! feof (infile)) do_galaxy (); + + fclose (infile); + fclose (outfile); + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +192,4339,letter-sequence-analysis,Letter Sequence Analysis,"Cryptographic analysis makes extensive use of the frequency with which letters and letter sequences occur in a language. If an encrypted text is known to be in english, for example, a great deal can be learned from the fact that the letters E, L, N, R, S, and T are the most common ones used in written english. Even more can be learned if common letter pairs, triplets, etc. are known. + +For this problem you are to write a program which accepts text **input** of unspecified length and performs letter sequence analysis on it. The end of input is marked by '-1'. + +The program will **output** the five most frequent letter sequences for each set of sequences from one to five letters. That is, it will report the individual characters which occur with the five highest frequencies, the pairs of characters which occur with the five highest frequencies, and so on up to the letter sequences of five characters which occur with the five highest frequencies. + +The program should consider contiguous sequences of alphabetic characters only, and case should be ignored (e.g. an 'a' is the same as an 'A'). A report should be produced ** striclty using the format shown** in the example at the end of this problem description. For each sequence length from one to five, the report should list the sequences in *descending order of frequency*. If there are several sequences with the same frequency then all sequences should be listed in *alphabetical order* as shown (list all sequences in upper case). Finally, if there are less than five distinct frequencies for a particular sequence length, simply report as many distinct frequency lists as possible. + +**Example:** + +**Input:** + +Peter Piper Picks Pickles! +-1 + +**Desired output:** + + Analysis for Letter Sequences of Length 1 + + Frequency = 5, Sequence(s) = (P) + Frequency = 4, Sequence(s) = (E) + Frequency = 3, Sequence(s) = (I) + Frequency = 2, Sequence(s) = (C,K,R,S) + Frequency = 1, Sequence(s) = (L,T) + + Analysis for Letter Sequences of Length 2 + + Frequency = 3, Sequence(s) = (PI) + Frequency = 2, Sequence(s) = (CK,ER,IC,PE) + Frequency = 1, Sequence(s) = (ES,ET,IP,KL,KS,LE,TE) + + Analysis for Letter Sequences of Length 3 + + Frequency = 2, Sequence(s) = (ICK,PIC) + Frequency = 1, Sequence(s) = (CKL,CKS,ETE,IPE,KLE,LES,PER,PET,PIP,TER) + + Analysis for Letter Sequences of Length 4 + + Frequency = 2, Sequence(s) = (PICK) + Frequency = 1, Sequence(s) = (CKLE,ETER,ICKL,ICKS,IPER,KLES,PETE,PIPE) + + Analysis for Letter Sequences of Length 5 + + Frequency = 1, Sequence(s) = (CKLES,ICKLE,PETER,PICKL,PICKS,PIPER) + +**Input:** +When the first three paragraphs of this problem description are used as input, followed by a '-1' in the next line (to mark end of input), the output should appear as shown here: + +**Output:** + + Analysis for Letter Sequences of Length 1 + + Frequency = 201, Sequence(s) = (E) + Frequency = 112, Sequence(s) = (T) + Frequency = 96, Sequence(s) = (S) + Frequency = 90, Sequence(s) = (R) + Frequency = 84, Sequence(s) = (N) + + Analysis for Letter Sequences of Length 2 + + Frequency = 37, Sequence(s) = (TH) + Frequency = 33, Sequence(s) = (EN) + Frequency = 27, Sequence(s) = (HE) + Frequency = 24, Sequence(s) = (RE) + Frequency = 23, Sequence(s) = (NC) + + Analysis for Letter Sequences of Length 3 + + Frequency = 24, Sequence(s) = (THE) + Frequency = 21, Sequence(s) = (ENC,EQU,QUE,UEN) + Frequency = 12, Sequence(s) = (NCE,SEQ,TER) + Frequency = 9, Sequence(s) = (CES,FRE,IVE,LET,REQ,TTE) + Frequency = 8, Sequence(s) = (ETT,FIV) + + Analysis for Letter Sequences of Length 4 + + Frequency = 21, Sequence(s) = (EQUE,QUEN) + Frequency = 20, Sequence(s) = (UENC) + Frequency = 12, Sequence(s) = (ENCE,SEQU) + Frequency = 9, Sequence(s) = (FREQ,NCES,REQU) + Frequency = 8, Sequence(s) = (ETTE,FIVE,LETT,TTER) + + Analysis for Letter Sequences of Length 5 + + Frequency = 21, Sequence(s) = (EQUEN) + Frequency = 20, Sequence(s) = (QUENC) + Frequency = 12, Sequence(s) = (SEQUE,UENCE) + Frequency = 9, Sequence(s) = (ENCES,FREQU,REQUE) + Frequency = 8, Sequence(s) = (ETTER,LETTE)",code,Cryptographic analysis makes extensive use of the frequency with which letters and letter sequences occur in a language. You are required to perform one such analysis.,ai,2014-09-19T06:45:57,2016-09-09T09:52:53,,,,"Cryptographic analysis makes extensive use of the frequency with which letters and letter sequences occur in a language. If an encrypted text is known to be in english, for example, a great deal can be learned from the fact that the letters E, L, N, R, S, and T are the most common ones used in written english. Even more can be learned if common letter pairs, triplets, etc. are known. + +For this problem you are to write a program which accepts text **input** of unspecified length and performs letter sequence analysis on it. The end of input is marked by '-1'. + +The program will **output** the five most frequent letter sequences for each set of sequences from one to five letters. That is, it will report the individual characters which occur with the five highest frequencies, the pairs of characters which occur with the five highest frequencies, and so on up to the letter sequences of five characters which occur with the five highest frequencies. + +The program should consider contiguous sequences of alphabetic characters only, and case should be ignored (e.g. an 'a' is the same as an 'A'). A report should be produced ** striclty using the format shown** in the example at the end of this problem description. For each sequence length from one to five, the report should list the sequences in *descending order of frequency*. If there are several sequences with the same frequency then all sequences should be listed in *alphabetical order* as shown (list all sequences in upper case). Finally, if there are less than five distinct frequencies for a particular sequence length, simply report as many distinct frequency lists as possible. + +**Example:** + +**Input:** + +Peter Piper Picks Pickles! +-1 + +**Desired output:** + + Analysis for Letter Sequences of Length 1 + + Frequency = 5, Sequence(s) = (P) + Frequency = 4, Sequence(s) = (E) + Frequency = 3, Sequence(s) = (I) + Frequency = 2, Sequence(s) = (C,K,R,S) + Frequency = 1, Sequence(s) = (L,T) + + Analysis for Letter Sequences of Length 2 + + Frequency = 3, Sequence(s) = (PI) + Frequency = 2, Sequence(s) = (CK,ER,IC,PE) + Frequency = 1, Sequence(s) = (ES,ET,IP,KL,KS,LE,TE) + + Analysis for Letter Sequences of Length 3 + + Frequency = 2, Sequence(s) = (ICK,PIC) + Frequency = 1, Sequence(s) = (CKL,CKS,ETE,IPE,KLE,LES,PER,PET,PIP,TER) + + Analysis for Letter Sequences of Length 4 + + Frequency = 2, Sequence(s) = (PICK) + Frequency = 1, Sequence(s) = (CKLE,ETER,ICKL,ICKS,IPER,KLES,PETE,PIPE) + + Analysis for Letter Sequences of Length 5 + + Frequency = 1, Sequence(s) = (CKLES,ICKLE,PETER,PICKL,PICKS,PIPER) + +**Input:** +When the first three paragraphs of this problem description are used as input, followed by a '-1' in the next line (to mark end of input), the output should appear as shown here: + +**Output:** + + Analysis for Letter Sequences of Length 1 + + Frequency = 201, Sequence(s) = (E) + Frequency = 112, Sequence(s) = (T) + Frequency = 96, Sequence(s) = (S) + Frequency = 90, Sequence(s) = (R) + Frequency = 84, Sequence(s) = (N) + + Analysis for Letter Sequences of Length 2 + + Frequency = 37, Sequence(s) = (TH) + Frequency = 33, Sequence(s) = (EN) + Frequency = 27, Sequence(s) = (HE) + Frequency = 24, Sequence(s) = (RE) + Frequency = 23, Sequence(s) = (NC) + + Analysis for Letter Sequences of Length 3 + + Frequency = 24, Sequence(s) = (THE) + Frequency = 21, Sequence(s) = (ENC,EQU,QUE,UEN) + Frequency = 12, Sequence(s) = (NCE,SEQ,TER) + Frequency = 9, Sequence(s) = (CES,FRE,IVE,LET,REQ,TTE) + Frequency = 8, Sequence(s) = (ETT,FIV) + + Analysis for Letter Sequences of Length 4 + + Frequency = 21, Sequence(s) = (EQUE,QUEN) + Frequency = 20, Sequence(s) = (UENC) + Frequency = 12, Sequence(s) = (ENCE,SEQU) + Frequency = 9, Sequence(s) = (FREQ,NCES,REQU) + Frequency = 8, Sequence(s) = (ETTE,FIVE,LETT,TTER) + + Analysis for Letter Sequences of Length 5 + + Frequency = 21, Sequence(s) = (EQUEN) + Frequency = 20, Sequence(s) = (QUENC) + Frequency = 12, Sequence(s) = (SEQUE,UENCE) + Frequency = 9, Sequence(s) = (ENCES,FREQU,REQUE) + Frequency = 8, Sequence(s) = (ETTER,LETTE)",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T06:48:08,2016-05-12T23:56:32,setter," //When input and output are from and to files. (Logic remains the same.) + + #include + #include + #include + + ofstream out = ""sequence.out""; + + struct node { + char seq[6]; + int freq; + node* next; + }; + node* list = NULL; + + char sequence[6]; + int seqlen; + + + int isaseq() { + if (strlen( sequence ) < seqlen) return 0; + for (int i = 0; i < seqlen; i++) + if (!isalpha( sequence[i] )) return 0; + return 1; + } + + + void addchar( char c ) { + int n = strlen( sequence ); + if (n < seqlen) { + sequence[n] = c; + sequence[n+1] = '\0'; + return; + } + for (int i = 0; i < n - 1; i++) sequence[i] = sequence[i+1]; + sequence[n-1] = c; + } + + + void addseq( char* seq ) { + if (list == NULL || strcmp( seq, list->seq ) < 0) { + node* n = new node; + strcpy( n->seq, seq ); + n->freq = 1; + n->next = list; + list = n; + return; + } + if (strcmp( seq, list->seq ) == 0) { + list->freq += 1; + return; + } + node* p = list; + while (p->next != NULL && strcmp( seq, p->next->seq ) >= 0) p = p->next; + if (strcmp( seq, p->seq ) == 0) { + p->freq += 1; + return; + } + node* n = new node; + strcpy( n->seq, seq ); + n->freq = 1; + n->next = p->next; + p->next = n; + } + + + void freelist() { + while (list != NULL) { + node* d = list; + list = list->next; + delete d; + } + } + + + void printdelmax() { + int max = 0; + node* p = list; + while (p != NULL) { + if (p->freq > max) max = p->freq; + p = p->next; + } + if (max == 0) return; + out << ""Frequency = "" << max << "", Sequence(s) = (""; + int gotone = 0; + node* q = NULL; + p = list; + while (p != NULL) { + if (p->freq == max) { + if (gotone) out << ','; + out << p->seq; + gotone = 1; + node* d = p; + if (q == NULL) + list = p->next; + else + q->next = p->next; + p = p->next; + delete d; + } + else { + q = p; + p = p->next; + } + } + out << ')' << endl; + } + + + void report() { + out << ""Analysis for Letter Sequences of Length "" << seqlen << endl; + endl; + for (int i = 0; i < 5; i++) printdelmax(); + out << endl; + } + + + void count( int n ) { + sequence[0] = '\0'; + seqlen = n; + ifstream in = ""sequence.in""; + int c; + c = in.get(); + while (c != EOF) { + addchar( toupper( char( c ) ) ); + if (isaseq()) addseq( sequence ); + c = in.get(); + } + in.close(); + report(); + freelist(); + } + + + void main() { + for (int i = 1; i <= 5; i++) count( i ); + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +193,4342,basically-speaking,Basically Speaking,"The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super Neato Model I calculator. As a computer scientist you suggested to the company that it would be neato if this new calculator could convert among number bases. The company thought this was a stupendous idea and has asked your team to come up with the prototype program for doing base conversion. The project manager of the Super Neato Model I calculator has informed you that the calculator will have the following neato features: + +* It will have a 7-digital display. +* Its buttons will include the capital letters A through F in addition to the digits 0 through 9. +* It will support bases 2 through 16. + +**Input Format:** +The input for your prototype program will consist of one base conversion per line. There will be three numbers per line. The first number will be the number in the base you are converting from. The second number is the base you are converting from. The third number is the base you are converting to. There will be one or more blanks surrounding (on either side of) the numbers. There are several lines of input and your program should continue to read until the input given is `*`. + +**Output Format:** +The output will only be the converted number as it would appear on the display of the calculator. The number should be right justified in the 7-digit display. If the number is too large to appear on the display, then print `ERROR` right justified in the display. + +**Sample Input:** + + 1111000 2 10 + 1111000 2 16 + 2102101 3 10 + 2102101 3 15 + 12312 4 2 + 1A 15 2 + 1234567 10 16 + ABCD 16 15 + * + +**Expected Output:** + + 120 + 78 + 1765 + 7CA + ERROR + 11001 + 12D687 + D071",code,"The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super Neato Model I calculator. As a computer scientist you suggested to the company that it would be 'neato' if this new calculator could convert among number bases.",ai,2014-09-19T07:13:37,2016-09-09T09:52:54,,,,"The Really Neato Calculator Company, Inc. has recently hired your team to help design their Super Neato Model I calculator. As a computer scientist you suggested to the company that it would be neato if this new calculator could convert among number bases. The company thought this was a stupendous idea and has asked your team to come up with the prototype program for doing base conversion. The project manager of the Super Neato Model I calculator has informed you that the calculator will have the following neato features: + +* It will have a 7-digital display. +* Its buttons will include the capital letters A through F in addition to the digits 0 through 9. +* It will support bases 2 through 16. + +**Input Format:** +The input for your prototype program will consist of one base conversion per line. There will be three numbers per line. The first number will be the number in the base you are converting from. The second number is the base you are converting from. The third number is the base you are converting to. There will be one or more blanks surrounding (on either side of) the numbers. There are several lines of input and your program should continue to read until the input given is `*`. + +**Output Format:** +The output will only be the converted number as it would appear on the display of the calculator. The number should be right justified in the 7-digit display. If the number is too large to appear on the display, then print `ERROR` right justified in the display. + +**Sample Input:** + + 1111000 2 10 + 1111000 2 16 + 2102101 3 10 + 2102101 3 15 + 12312 4 2 + 1A 15 2 + 1234567 10 16 + ABCD 16 15 + * + +**Expected Output:** + + 120 + 78 + 1765 + 7CA + ERROR + 11001 + 12D687 + D071",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T07:15:54,2016-05-12T23:56:31,setter," //When the input is taken from a data file and output is printed to a data file. + #include + #include + #include + #include + + const int A_10 = 55; + const int ZERO = 48; + const int ASIZE = 8; + const int WSIZE = 7; + const int SIZE_1 = 6; + + long int power (int, int); + long int convert_to_10 (int, char *); + int convert_to_base (int, long int, char *); + + long int power (int base, int raise) + { + long int prod = 1; + int i; + + for (i = 0; i < raise; i++) + prod *= base; + + return prod; + } + + long int convert_to_10 (int base, char * cnum) + { + int len = strlen (cnum) - 1; + int i; + int raise = 0; + int num; + long int base10 = 0; + + for (i = len; i >= 0 && cnum[i] != ' '; i--) + { + if (cnum[i] >= '0' && cnum[i] <= '9') + num = cnum[i] - ZERO; + else + num = cnum[i] - A_10; + + base10 += num * power (base, raise); + + raise++; + } + + return base10; + } + + int convert_to_base (int base, long int number, char * cnum) + { + int pos = SIZE_1; + int valid = 1; + int remain; + char chremain; + + strcpy (cnum, "" ""); + + while (number > 0 && valid) + { + remain = number % base; + number /= base; + + if (remain < 10) + chremain = remain + ZERO; + else + chremain = remain + A_10; + + if (pos >= 0) + { + cnum[pos] = chremain; + pos--; + } + else + valid = 0; + } + + return valid; + } + + void main () + { + char old_cnum[ASIZE]; + char new_cnum[ASIZE]; + int base_from; + int base_to; + int valid; + long int number; + fstream in_file; + ofstream out_file; + + in_file.open (""base.in"", ios::in); + out_file.open (""base.out""); + + in_file >> ws >> old_cnum >> base_from >> base_to; + + while (!in_file.eof ()) + { + number = convert_to_10 (base_from, old_cnum); + valid = convert_to_base (base_to, number, new_cnum); + + if (valid) + out_file << setw (WSIZE) << new_cnum << endl; + else + out_file << setw (WSIZE) << ""ERROR"" << endl; + + in_file >> ws >> old_cnum >> base_from >> base_to; + } + + in_file.close (); + out_file.close (); + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +194,4344,easier-done-than-said, Easier Done than Said?,"Password security is a tricky thing. Users prefer simple passwords that are easy to remember (like buddy), but such passwords are often insecure. Some sites use random computer-generated passwords (like xvtpzyo), but users have a hard time remembering them and sometimes leave them written on notes stuck to their computer. One potential solution is to generate ""pronounceable"" passwords that are relatively secure but still easy to remember. + +FnordCom is developing such a password generator. You work in the quality control department, and it's your job to test the generator and make sure that the passwords are acceptable. To be acceptable, a password must satisfy these three rules: + +1. It must contain at least one vowel. +2. It cannot contain three consecutive vowels or three consecutive consonants +3. It cannot contain two consecutive occurrences of the same letter, except for 'ee' or 'oo'. + +(For the purposes of this problem, the vowels are 'a', 'e', 'i', 'o', and 'u'; all other +letters are consonants.) Note that these rules are not perfect; there are many +common/pronounceable words that are not acceptable. + +**Input Format:** +The input consists of one or more potential passwords, one per line, followed by a line +containing only the word 'end' that signals the end of input. Each password is at +least one and at most twenty letters long and consists only of lowercase letters. + +**Output Format:** +For each password, output whether or not it is acceptable, using the precise format shown in the example. + +**Example input:** + + a + tv + ptoui + bontres + zoggax + wiinq + eep + houctuh + end + +**Expected Output:** + + is acceptable. + is not acceptable. + is not acceptable. + is not acceptable. + is not acceptable. + is not acceptable. + is acceptable. + is acceptable. +",code,"Password security is a tricky thing. FnordCom is developing a password generator. You work in the quality control department, and it's your job to test the generator and make sure that the passwords are acceptable.",ai,2014-09-19T07:42:30,2016-09-09T09:52:55,,,,"Password security is a tricky thing. Users prefer simple passwords that are easy to remember (like buddy), but such passwords are often insecure. Some sites use random computer-generated passwords (like xvtpzyo), but users have a hard time remembering them and sometimes leave them written on notes stuck to their computer. One potential solution is to generate ""pronounceable"" passwords that are relatively secure but still easy to remember. + +FnordCom is developing such a password generator. You work in the quality control department, and it's your job to test the generator and make sure that the passwords are acceptable. To be acceptable, a password must satisfy these three rules: + +1. It must contain at least one vowel. +2. It cannot contain three consecutive vowels or three consecutive consonants +3. It cannot contain two consecutive occurrences of the same letter, except for 'ee' or 'oo'. + +(For the purposes of this problem, the vowels are 'a', 'e', 'i', 'o', and 'u'; all other +letters are consonants.) Note that these rules are not perfect; there are many +common/pronounceable words that are not acceptable. + +**Input Format:** +The input consists of one or more potential passwords, one per line, followed by a line +containing only the word 'end' that signals the end of input. Each password is at +least one and at most twenty letters long and consists only of lowercase letters. + +**Output Format:** +For each password, output whether or not it is acceptable, using the precise format shown in the example. + +**Example input:** + + a + tv + ptoui + bontres + zoggax + wiinq + eep + houctuh + end + +**Expected Output:** + + is acceptable. + is not acceptable. + is not acceptable. + is not acceptable. + is not acceptable. + is not acceptable. + is acceptable. + is acceptable. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T07:42:45,2016-05-12T23:56:31,setter," #include + #include + #include + + FILE *in; + FILE *out; + + char word[256]; + int n; + + + + int is_vowel(int ch) + { + return ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'; + } + + + + int contains_vowel(void) + { + int i; + + for (i = 0; i < n; ++i) { + if (is_vowel(word[i])) + return 1; + } + + return 0; + } + + + + int three_consecutive_vowels(void) + { + int i; + + for (i = 0; i < (n - 2); ++i) { + if (is_vowel(word[i]) && is_vowel(word[i+1]) && is_vowel(word[i+2])) + return 1; + } + + return 0; + } + + + + int three_consecutive_consonants(void) + { + int i; + + for (i = 0; i < (n - 2); ++i) { + if (!is_vowel(word[i]) && !is_vowel(word[i+1]) && !is_vowel(word[i+2])) + return 1; + } + + return 0; + } + + + + int repeated_letter(void) + { + int i; + + for (i = 0; i < (n - 1); ++i) { + if (word[i] == word[i+1] && word[i] != 'e' && word[i] != 'o') + return 1; + } + + return 0; + } + + + + + int can_say_it(void) + { + return contains_vowel() + && ! three_consecutive_vowels() + && ! three_consecutive_consonants() + && ! repeated_letter(); + } + + + + int main(void) + { + in = fopen(""say.in"", ""r""); + out = fopen(""say.out"", ""w""); + + while (strcmp(fgets(word, sizeof(word), in), ""end\n"") != 0) { + n = strlen(word) - 1; + word[n] = '\0'; + + fprintf(out, ""<%s> is "", word); + + if (! can_say_it()) fprintf(out, ""not ""); + + fprintf(out, ""acceptable.\n""); + } + + fclose(in); + fclose(out); + + return 0; + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +195,4346,instruens-fabulam,Instruens Fabulam,"*Instruens Fabulam means drawing a chart (or table) in Latin. That's what you will do for this problem.* + +The input consists of one or more table descriptions, followed by a line whose first character is `'*'`, which signals the end of the input. Each description begins with a header line containing one or more characters that define the number and alignment of columns in the table. Each character in the header line is either `'<'`, `'='`, or `'>'`, and indicates a left-justified, centered, or right-justified column. Following the header are at least two and at most 21 data lines that contain the entries for each row. Each data line consists of one or more nonempty entries separated by an ampersand (`'&'`), where the number of entries is equal to the number of columns defined in the header line. The first data line contains entries for the column titles, and the remaining data lines contain entries for the body of the table. Spaces may appear within an entry, but never at the beginning or end of an entry. The characters `'<'`, `'='`, `'>'`, `'&'`, and `'*'` will not appear in the input except where indicated above. + +For each table description, output the table using the exact format shown in the examples. Note that: + +* The total width of the table will never exceed 79 characters (not counting end-of-line). +* Dashes ('-') are used to draw horizontal lines, not underscores ('_'). 'At' signs ('@') appear at each of the four outer corners. Plus signs ('+') appear at intersections within the line separating the title from the body. +* The largest entry in a column is always separated from the enclosing bars ('|') by exactly one space. +* If a centered entry cannot be exactly centered within a column, the extra space goes on the right of the entry. + + +**Example Input:** + + <>=> + TITLE&VERSION&OPERATING SYSTEM&PRICE + Slug Farm&2.0&FreeBSD&49.99 + Figs of Doom&1.7&Linux&9.98 + Smiley Goes to Happy Town&11.0&Windows&129.25 + Wheelbarrow Motocross&1.0&BeOS&34.97 + > + What is the answer? + 42 + <> + Tweedledum&Tweedledee + ""Knock, knock.""&""Who's there?"" + ""Boo.""&""Boo who?"" + ""Don't cry, it's only me.""&(groan) + * + +**Expected Output:** + + @-----------------------------------------------------------------@ + | TITLE | VERSION | OPERATING SYSTEM | PRICE | + |---------------------------+---------+------------------+--------| + | Slug Farm | 2.0 | FreeBSD | 49.99 | + | Figs of Doom | 1.7 | Linux | 9.98 | + | Smiley Goes to Happy Town | 11.0 | Windows | 129.25 | + | Wheelbarrow Motocross | 1.0 | BeOS | 34.97 | + @-----------------------------------------------------------------@ + @---------------------@ + | What is the answer? | + |---------------------| + | 42 | + @---------------------@ + @---------------------------------------------@ + | Tweedledum | Tweedledee | + |----------------------------+----------------| + | ""Knock, knock."" | ""Who's there?"" | + | ""Boo."" | ""Boo who?"" | + | ""Don't cry, it's only me."" | (groan) | + @---------------------------------------------@",code,'Instruens Fabulam' means drawing a chart (or table) in Latin. That's what you will do for this problem.,ai,2014-09-19T08:10:57,2016-09-09T09:52:55,,,,"*Instruens Fabulam means drawing a chart (or table) in Latin. That's what you will do for this problem.* + +The input consists of one or more table descriptions, followed by a line whose first character is `'*'`, which signals the end of the input. Each description begins with a header line containing one or more characters that define the number and alignment of columns in the table. Each character in the header line is either `'<'`, `'='`, or `'>'`, and indicates a left-justified, centered, or right-justified column. Following the header are at least two and at most 21 data lines that contain the entries for each row. Each data line consists of one or more nonempty entries separated by an ampersand (`'&'`), where the number of entries is equal to the number of columns defined in the header line. The first data line contains entries for the column titles, and the remaining data lines contain entries for the body of the table. Spaces may appear within an entry, but never at the beginning or end of an entry. The characters `'<'`, `'='`, `'>'`, `'&'`, and `'*'` will not appear in the input except where indicated above. + +For each table description, output the table using the exact format shown in the examples. Note that: + +* The total width of the table will never exceed 79 characters (not counting end-of-line). +* Dashes ('-') are used to draw horizontal lines, not underscores ('_'). 'At' signs ('@') appear at each of the four outer corners. Plus signs ('+') appear at intersections within the line separating the title from the body. +* The largest entry in a column is always separated from the enclosing bars ('|') by exactly one space. +* If a centered entry cannot be exactly centered within a column, the extra space goes on the right of the entry. + + +**Example Input:** + + <>=> + TITLE&VERSION&OPERATING SYSTEM&PRICE + Slug Farm&2.0&FreeBSD&49.99 + Figs of Doom&1.7&Linux&9.98 + Smiley Goes to Happy Town&11.0&Windows&129.25 + Wheelbarrow Motocross&1.0&BeOS&34.97 + > + What is the answer? + 42 + <> + Tweedledum&Tweedledee + ""Knock, knock.""&""Who's there?"" + ""Boo.""&""Boo who?"" + ""Don't cry, it's only me.""&(groan) + * + +**Expected Output:** + + @-----------------------------------------------------------------@ + | TITLE | VERSION | OPERATING SYSTEM | PRICE | + |---------------------------+---------+------------------+--------| + | Slug Farm | 2.0 | FreeBSD | 49.99 | + | Figs of Doom | 1.7 | Linux | 9.98 | + | Smiley Goes to Happy Town | 11.0 | Windows | 129.25 | + | Wheelbarrow Motocross | 1.0 | BeOS | 34.97 | + @-----------------------------------------------------------------@ + @---------------------@ + | What is the answer? | + |---------------------| + | 42 | + @---------------------@ + @---------------------------------------------@ + | Tweedledum | Tweedledee | + |----------------------------+----------------| + | ""Knock, knock."" | ""Who's there?"" | + | ""Boo."" | ""Boo who?"" | + | ""Don't cry, it's only me."" | (groan) | + @---------------------------------------------@",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T08:11:14,2016-05-12T23:56:31,setter," #include + #include + #include + + #define LEFT '<' + #define RIGHT '>' + #define CENTER '=' + + enum {MAX_ROWS = 21, MAX_COLS = 19}; + enum {HEADER, ROW, END}; + + FILE *in; + FILE *out; + + int rows; /* number of rows in the table */ + int columns; /* number of columns in the table */ + + char align[MAX_COLS + 1]; /* alignment of each column */ + int max_width[MAX_COLS]; /* maximum width of column */ + + char *entry[MAX_ROWS][MAX_COLS]; /* text of each entry */ + int width[MAX_ROWS][MAX_COLS]; /* width of each entry */ + + char line[80 + 1]; /* the last line read from the file */ + int line_type; /* HEADER, ROW, or END */ + + + + int read_line(void) + { + fgets(line, sizeof(line), in); + line[strlen(line) - 1] = '\0'; + + if (line[0] == '*') + line_type = END; + else if (line[0]==LEFT || line[0]==RIGHT || line[0]==CENTER) + line_type = HEADER; + else + line_type = ROW; + + return line_type; + } + + + + void process_header(void) + { + int c; + + columns = strlen(line); + strcpy(align, line); + + for (c = 0; c < columns; ++c) + max_width[c] = 0; + } + + + + void read_rows(void) + { + rows = 0; + + while (read_line() == ROW) { + char *s; + int c = 0; + + for (s = strtok(line, ""&""); s != NULL; s = strtok(NULL, ""&"")) { + int n = strlen(s); + + entry[rows][c] = strdup(s); + width[rows][c] = n; + + if (n > max_width[c]) max_width[c] = n; + + ++c; + } + + ++rows; + } + } + + + + void print_char(int ch, int n) + { + int i; + + for (i = 0; i < n; ++i) fputc(ch, out); + } + + + + void print_row(int r) + { + int c; + + for (c = 0; c < columns; ++c) { + int n = width[r][c]; + int pad = max_width[c] - n; + + fprintf(out, ""| ""); + switch (align[c]) { + case LEFT: + fprintf(out, ""%s"", entry[r][c]); + print_char(' ', pad); + break; + case RIGHT: + print_char(' ', pad); + fprintf(out, ""%s"", entry[r][c]); + break; + case CENTER: + print_char(' ', pad / 2); + fprintf(out, ""%s"", entry[r][c]); + print_char(' ', pad - (pad/2)); + } + fprintf(out, "" ""); + } + + fprintf(out, ""|\n""); + } + + + + void print_separator(int outer_char, int inner_char) + { + int c; + + print_char(outer_char, 1); + print_char('-', max_width[0] + 2); + + for (c = 1; c < columns; ++c) { + print_char(inner_char, 1); + print_char('-', max_width[c] + 2); + } + + print_char(outer_char, 1); + fputc('\n', out); + } + + + + int main(void) + { + in = fopen(""fab.in"", ""r""); + out = fopen(""fab.out"", ""w""); + + read_line(); + while (line_type != END) { + int r; + + process_header(); + read_rows(); + + print_separator('@', '-'); + print_row(0); + print_separator('|', '+'); + + for (r = 1; r < rows; ++r) print_row(r); + + print_separator('@', '-'); + } + + fclose(in); + fclose(out); + + return 0; + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +196,4355,mapping-the-swaps,Mapping the Swaps,"Sorting an array can be done by swapping certain pairs of adjacent entries in the array. This is the fundamental technique used in the well-known bubble sort. If we list the identities of the pairs to be swapped, in the sequence they are to be swapped, we obtain what might be called a swap map. For example, suppose we wish to sort the array A whose elements are 3, 2, and 1 in that order. If the subscripts for this array are 1, 2, and 3, sorting the array can be accomplished by swapping A2 and A3, then swapping A1 and A2, and finally swapping A2 and A3. If a pair is identified in a swap map by indicating the subscript of the first element of the pair to be swapped, then this sorting process would be characterized with the swap map 2 1 2. + +It is instructive to note that there may be many ways in which swapping of adjacent array entries can be used to sort an array. The previous array, containing 3 2 1, could also be sorted by swapping A1 and A2, then swapping A2 and A3, and finally swapping A1 and A2 again. The swap map that describes this sorting sequence is 1 2 1. + +For a given array, how many different swap maps exist? A little thought will show that there are an infinite number of swap maps, since sequential swapping of an arbitrary pair of elements will not change the order of the elements. Thus the swap map 1 1 1 2 1 will also leave our array elements in ascending order. But how many swap maps of minimum size will place a given array in order? That is the question you are to answer in this problem. + +**Input Format:** The input data will contain an arbitrary number of test cases, followed by a single 0. Each test case will have a integer n that gives the size of an array, and will be followed by the n integer values in the array. + +**Output Format:** For each test case, print a message similar to those shown in the sample output below. In no test case will n be larger than 5. + +**Sample Input:** + +2 9 7 +2 12 50 +3 3 2 1 +3 9 1 5 +0 + +**Expected Output:** + +There are 1 swap maps for input data set 1. +There are 0 swap maps for input data set 2. +There are 2 swap maps for input data set 3. +There are 1 swap maps for input data set 4. +",code,"Sorting an array can be done by swapping certain pairs of adjacent entries in the array. But, how many swap maps of minimum size will place a given array in order? That is the question you are to answer in this problem.",ai,2014-09-19T15:42:43,2016-09-09T09:53:00,,,,"Sorting an array can be done by swapping certain pairs of adjacent entries in the array. This is the fundamental technique used in the well-known bubble sort. If we list the identities of the pairs to be swapped, in the sequence they are to be swapped, we obtain what might be called a swap map. For example, suppose we wish to sort the array A whose elements are 3, 2, and 1 in that order. If the subscripts for this array are 1, 2, and 3, sorting the array can be accomplished by swapping A2 and A3, then swapping A1 and A2, and finally swapping A2 and A3. If a pair is identified in a swap map by indicating the subscript of the first element of the pair to be swapped, then this sorting process would be characterized with the swap map 2 1 2. + +It is instructive to note that there may be many ways in which swapping of adjacent array entries can be used to sort an array. The previous array, containing 3 2 1, could also be sorted by swapping A1 and A2, then swapping A2 and A3, and finally swapping A1 and A2 again. The swap map that describes this sorting sequence is 1 2 1. + +For a given array, how many different swap maps exist? A little thought will show that there are an infinite number of swap maps, since sequential swapping of an arbitrary pair of elements will not change the order of the elements. Thus the swap map 1 1 1 2 1 will also leave our array elements in ascending order. But how many swap maps of minimum size will place a given array in order? That is the question you are to answer in this problem. + +**Input Format:** The input data will contain an arbitrary number of test cases, followed by a single 0. Each test case will have a integer n that gives the size of an array, and will be followed by the n integer values in the array. + +**Output Format:** For each test case, print a message similar to those shown in the sample output below. In no test case will n be larger than 5. + +**Sample Input:** + +2 9 7 +2 12 50 +3 3 2 1 +3 9 1 5 +0 + +**Expected Output:** + +There are 1 swap maps for input data set 1. +There are 0 swap maps for input data set 2. +There are 2 swap maps for input data set 3. +There are 1 swap maps for input data set 4. +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T15:43:15,2016-05-12T23:56:29,setter," #include + #include + + void swap(int *a, int i) { + int t; + t = a[i]; + a[i] = a[i+1]; + a[i+1] = t; + } + + int bub_srt(int n, int b[]) { + int *a, ns=0, i, j; + + a = (int*)malloc(sizeof(int) * n); + for (i=0; i0; i--) { + for (j=0; j a[j+1]) { + swap(a, j); + ns++; + } + } + } + + return ns; + } + + + int try1(int n, int *a, int depth) { + int i, ns=0; + + if (!depth) { + for (i=0; i a[i+1]) return 0; + } + return 1; + } + + for (i=0; ie2. Note that the precedes relation is transitive, as expected. Thus if e1->e2 and e2->e3, then we can also note that e1->e3. + +Sequential events in a single computation are not concurrent. For example, if a particular computation performs the operations identified by events e1, e2 and e3 in that order, then clearly and e1->e2 and e2->e3. + +Computations in a distributed system communicate by sending messages. If event esend corresponds to the sending of a message by one computation, and event erecv corresponds to the reception of that message by a different computation, then we can always note that esend->erecv, since a message cannot be received before it is sent. + +In this problem you will be supplied with lists of sequential events for an arbitrary number of computations, and the identification of an arbitrary number of messages sent between these computations. Your task is to identify those pairs of events that are concurrent. + +**Input and Output Specification:** + +A number of test cases will be supplied. For each test case the input will include first an integer, NC, specifying the number of computations in the test case. For each of these NC computations there will be a single line containing an integer NEi that specifies the number of sequential events in the computation followed by NEi event names. Event names will always contain one to five alphanumeric characters, and will be separated from each other by at least one blank. Following the specification of the events in the last computation there will be a line with a single integer, NM, that specifies the number of messages that are sent between computations. Finally, on each of the following NM lines there will be a pair of event names specifying the name of the event associated with the sending of a message, and the event associated with the reception of the message. These names will have previously appeared in the lists of events associated with computations, and will be separated by at least one blank. The last test case will be followed by the single integer 0 on a line by itself. + +For each test case, print the test case number (they are numbered sequentially starting with 1), the number of pairs of concurrent events for the test case, and any two pair of the concurrent event names. If there is only one concurrent pair of events, just print it. And if there are no concurrent events, then state that fact. + +**Example:** + +Consider the following input data: + +2 +2 e1 e2 +2 e3 e4 +1 +e3 e1 +0 + +There are two computations. In the first e1->e2 and in the second e3->e4. A single message is sent from e3 to e1, which means e3->e1. Using the transitive property of the precedes relation we can additionally determine that e3->e2. This leaves the pairs (e1,e4) and (e2,e4) as concurrent events. + +**Sample Input:** + +2 +2 e1 e2 +2 e3 e4 +1 +e3 e1 +3 +3 one two three +2 four five +3 six seven eight +2 +one four +five six +1 +3 x y zee +0 +2 +2 alpha beta +1 gamma +1 +gamma beta +0 + +**Expected Output:** + +Case 1, 2 concurrent events: +(e1,e4) (e2,e4) +Case 2, 10 concurrent events: +(two,four) (two,five) +Case 3, no concurrent events. +Case 4, 1 concurrent events: +(alpha,gamma) +",code,"In this problem you will be supplied with lists of sequential events for an arbitrary number of computations, and the identification of an arbitrary number of messages sent between these computations. Your task is to identify those pairs of events that are concurrent.",ai,2014-09-19T15:58:54,2016-09-09T09:53:00,,,,"It is important in distributed computer systems to identify those events (at identifiable points in time) that are concurrent, or not related to each other in time. A group of concurrent events may sometimes attempt to simultaneously use the same resource, and this could cause problems. + +Events that are not concurrent can be ordered in time. For example, if event e1 can be shown to always precede event e2 in time, then e1 and e2 are obviously not concurrent. Notationally we indicate that e1 precedes e2 by writing e1->e2. Note that the precedes relation is transitive, as expected. Thus if e1->e2 and e2->e3, then we can also note that e1->e3. + +Sequential events in a single computation are not concurrent. For example, if a particular computation performs the operations identified by events e1, e2 and e3 in that order, then clearly and e1->e2 and e2->e3. + +Computations in a distributed system communicate by sending messages. If event esend corresponds to the sending of a message by one computation, and event erecv corresponds to the reception of that message by a different computation, then we can always note that esend->erecv, since a message cannot be received before it is sent. + +In this problem you will be supplied with lists of sequential events for an arbitrary number of computations, and the identification of an arbitrary number of messages sent between these computations. Your task is to identify those pairs of events that are concurrent. + +**Input and Output Specification:** + +A number of test cases will be supplied. For each test case the input will include first an integer, NC, specifying the number of computations in the test case. For each of these NC computations there will be a single line containing an integer NEi that specifies the number of sequential events in the computation followed by NEi event names. Event names will always contain one to five alphanumeric characters, and will be separated from each other by at least one blank. Following the specification of the events in the last computation there will be a line with a single integer, NM, that specifies the number of messages that are sent between computations. Finally, on each of the following NM lines there will be a pair of event names specifying the name of the event associated with the sending of a message, and the event associated with the reception of the message. These names will have previously appeared in the lists of events associated with computations, and will be separated by at least one blank. The last test case will be followed by the single integer 0 on a line by itself. + +For each test case, print the test case number (they are numbered sequentially starting with 1), the number of pairs of concurrent events for the test case, and any two pair of the concurrent event names. If there is only one concurrent pair of events, just print it. And if there are no concurrent events, then state that fact. + +**Example:** + +Consider the following input data: + +2 +2 e1 e2 +2 e3 e4 +1 +e3 e1 +0 + +There are two computations. In the first e1->e2 and in the second e3->e4. A single message is sent from e3 to e1, which means e3->e1. Using the transitive property of the precedes relation we can additionally determine that e3->e2. This leaves the pairs (e1,e4) and (e2,e4) as concurrent events. + +**Sample Input:** + +2 +2 e1 e2 +2 e3 e4 +1 +e3 e1 +3 +3 one two three +2 four five +3 six seven eight +2 +one four +five six +1 +3 x y zee +0 +2 +2 alpha beta +1 gamma +1 +gamma beta +0 + +**Expected Output:** + +Case 1, 2 concurrent events: +(e1,e4) (e2,e4) +Case 2, 10 concurrent events: +(two,four) (two,five) +Case 3, no concurrent events. +Case 4, 1 concurrent events: +(alpha,gamma) +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T15:59:07,2016-05-12T23:56:29,setter," #include + #include + #include + + typedef struct Node { + int idx; + char *name; + struct Node *next, *child, *sibling; + } Node; + + Node *head=0, *tail=0; + int n_nodes = 0; + + Node *FindNode(char *str) { + Node *p; + p = head; + while (p && strcmp(p->name, str)) p = p->next; + if (!p) { + fprintf(stderr, ""name '%s' not found.\n"", str); + exit(1); + } + return p; + } + + Node *IndNode(int i) { + Node *p; + p = head; + while (i--) p = p->next; + return p; + } + + + void FreeNodes() { + Node *node; + node = head; + while (node) { + head = node->next; + free((char*)node); + node = head; + } + head = tail = 0; + n_nodes = 0; + } + + void AddChild(Node *par, Node *child) { + Node *node; + if (par->child) { + node = par->child; + while (node->sibling) node = node->sibling; + node->sibling = child; + } else { + par->child = child; + } + } + + Node *NewNode(char *name, Node *parent) { + Node *node; + + node = (Node*)malloc(sizeof(Node)); + node->idx = n_nodes++; + node->name = strdup(name); + if (parent) AddChild(parent, node); + if (tail) { + tail->next = node; + tail = tail->next; + } else { + head = tail = node; + } + node->next = node->child = node->sibling = 0; + + return node; + } + + #define REL(i, j) rel[i*n_nodes + j] + + void MarkKids(Node *node, Node *child, int *rel) { + if (child) { + REL(node->idx, child->idx) = 1; + REL(child->idx, node->idx) = 1; + MarkKids(node, child->child, rel); + MarkKids(node, child->sibling, rel); + } + } + + void Print(int *rel) { + Node *node; + int i, j; + + node = head; + while (node) { + printf(""%2d: %s, next=%s, child=%s, sibling=%s\n"", + node->idx, node->name, node->next ? node->next->name : ""<>"", + node->child ? node->child->name : ""<>"", + node->sibling ? node->sibling->name : ""<>""); + node = node->next; + } + + for (i=0; iname, node2->name); */ + AddChild(node1, node2); + } + + node1 = head; + while (node1) { + MarkKids(node1, node1->child, rel); + node1 = node1->next; + } + + /* Print(rel); */ + + b = 0; + for (i=0; iname, IndNode(j)->name); */ + b++; + } + } + } + if (b) { + printf(""Case %d, %d concurrent events: \n"", c++, b); + if (b>2) b=2; + for (i=0; iname, IndNode(j)->name); + b--; + } + } + } + putchar('\n'); + } else { + printf(""Case %d, no concurrent events.\n"", c++); + } + + FreeNodes(); + free((char*)rel); + + scanf(""%d"", &a); + } + + return 0; + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +198,4357,roman-digititis,Roman Digititis,"Many persons are familiar with the Roman numerals for relatively small numbers. The symbols ""i"", ""v"", ""x"", ""l"", and ""c"" represent the decimal values 1, 5, 10, 50, and 100 respectively. To represent other values, these symbols, and multiples where necessary, are concatenated, with the smaller-valued symbols written further to the right. For example, the number 3 is represented as ""iii"", and the value 73 is represented as ""lxxiii"". The exceptions to this rule occur for numbers having units values of 4 or 9, and for tens values of 40 or 90. For these cases, the Roman numeral representations are ""iv"" (4), ""ix"" (9), ""xl"" (40), and ""xc"" (90). So the Roman numeral representations for 24, 39, 44, 49, and 94 are ""xxiv"", ""xxxix"", ""xliv"", ""xlix"", and ""xciv"", respectively. + +The preface of many books has pages numbered with Roman numerals, starting with ""i"" for the first page of the preface, and continuing in sequence. Assume books with pages having 100 or fewer pages of preface. How many ""i"", ""v"", ""x"", ""l"", and ""c"" characters are required to number the pages in the preface? For example, in a five page preface we’ll use the Roman numerals ""i"", ""ii"", ""iii"", ""iv"", and ""v"", meaning we need 7 ""i"" characters and 2 ""v"" characters. + +**Input Format:** +The input will consist of a sequence of integers in the range 1 to 100, terminated by a zero. For each such integer, except the final zero, determine the number of different types of characters needed to number the prefix pages with Roman numerals. + +**Output Format:** +For each integer in the input, write one line containing the input integer and the number of characters of each type required. The examples shown below illustrate an acceptable format. + +**Example Input:** + +1 +2 +20 +99 +0 + +**Expected Output:** + +1: 1 i, 0 v, 0 x, 0 l, 0 c +2: 3 i, 0 v, 0 x, 0 l, 0 c +20: 28 i, 10 v, 14 x, 0 l, 0 c +99: 140 i, 50 v, 150 x, 50 l, 10 c ",code,"The preface of many books has pages numbered with Roman numerals, starting with ""i"" for the first page of the preface, and continuing. Assume books with pages having 100 or fewer pages of preface. How many ""i"", ""v"", ""x"", ""l"", and ""c"" characters are required to number the pages in the preface?",ai,2014-09-19T16:20:27,2016-09-09T09:53:01,,,,"Many persons are familiar with the Roman numerals for relatively small numbers. The symbols ""i"", ""v"", ""x"", ""l"", and ""c"" represent the decimal values 1, 5, 10, 50, and 100 respectively. To represent other values, these symbols, and multiples where necessary, are concatenated, with the smaller-valued symbols written further to the right. For example, the number 3 is represented as ""iii"", and the value 73 is represented as ""lxxiii"". The exceptions to this rule occur for numbers having units values of 4 or 9, and for tens values of 40 or 90. For these cases, the Roman numeral representations are ""iv"" (4), ""ix"" (9), ""xl"" (40), and ""xc"" (90). So the Roman numeral representations for 24, 39, 44, 49, and 94 are ""xxiv"", ""xxxix"", ""xliv"", ""xlix"", and ""xciv"", respectively. + +The preface of many books has pages numbered with Roman numerals, starting with ""i"" for the first page of the preface, and continuing in sequence. Assume books with pages having 100 or fewer pages of preface. How many ""i"", ""v"", ""x"", ""l"", and ""c"" characters are required to number the pages in the preface? For example, in a five page preface we’ll use the Roman numerals ""i"", ""ii"", ""iii"", ""iv"", and ""v"", meaning we need 7 ""i"" characters and 2 ""v"" characters. + +**Input Format:** +The input will consist of a sequence of integers in the range 1 to 100, terminated by a zero. For each such integer, except the final zero, determine the number of different types of characters needed to number the prefix pages with Roman numerals. + +**Output Format:** +For each integer in the input, write one line containing the input integer and the number of characters of each type required. The examples shown below illustrate an acceptable format. + +**Example Input:** + +1 +2 +20 +99 +0 + +**Expected Output:** + +1: 1 i, 0 v, 0 x, 0 l, 0 c +2: 3 i, 0 v, 0 x, 0 l, 0 c +20: 28 i, 10 v, 14 x, 0 l, 0 c +99: 140 i, 50 v, 150 x, 50 l, 10 c ",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T16:20:35,2016-05-12T23:56:29,setter," #include + #include + + int ni, nv, nx, nl, nc; + + void units(int n) + { + switch(n) { + case 0: break; + case 1: ni += 1; break; + case 2: ni += 2; break; + case 3: ni += 3; break; + case 4: ni += 1; nv += 1; break; + case 5: nv += 1; break; + case 6: ni += 1; nv += 1; break; + case 7: ni += 2; nv += 1; break; + case 8: ni += 3; nv += 1; break; + case 9: ni += 1; nx += 1; break; + default: printf(""bomb!\n""); exit(0); + } + } + + void tens(int n) + { + switch(n) { + case 0: break; + case 1: nx += 1; break; + case 2: nx += 2; break; + case 3: nx += 3; break; + case 4: nx += 1; nl += 1; break; + case 5: nl += 1; break; + case 6: nx += 1; nl += 1; break; + case 7: nx += 2; nl += 1; break; + case 8: nx += 3; nl += 1; break; + case 9: nx += 1; nc += 1; break; + case 10: nc += 1; break; + default: printf(""tens bomb!\n""); exit(0); + } + } + + main() + { + int i, n; + + while(1) { + scanf(""%d"",&n); + if (n == 0) exit(0); + ni = nv = nx = nl = nc = 0; + for (i=1;i<=n;i++) { + units(i % 10); + tens(i / 10); + } + printf(""%d: %d i, %d v, %d x %d l, %d c\n"", n, ni, nv, nx, nl, nc); + } + } +",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +199,4358,master-mind-hints,Master-Mind Hints,"MasterMind is a game for two players. One of them, Designer, selects a secret code. The other, Breaker, tries to break it. A code is no more than a row of colored dots. At the beginning of a game, the players agree upon the length N that a code must have and upon the colors that may occur in a code. + +In order to break the code, Breaker makes a number of guesses, each guess itself being a code. After each guess Designer gives a hint, stating to what extent the guess matches his secret code. +In this problem you will be given a secret code s1...sn and a guess g1...gn, and are to determine the hint. A hint consists of a pair of numbers determined as follows. + +A match is a pair (i,j), 1<=i<=n and 1<=j<=n, such that si = gj. Match (i,j) is called strong when i = j, and is called weak otherwise. Two matches (i,j) and (p,q) are called independent when i = p if and only if j = q. A set of matches is called independent when all of its members are pairwise independent. + +Designer chooses an independent set M of matches for which the total number of matches and the number of strong matches are both maximal. The hint then consists of the number of strong followed by the number of weak matches in M. Note that these numbers are uniquely determined by the secret code and the guess. If the hint turns out to be (n,0), then the guess is identical to the secret code. + +**Input Format:** + +The input will consist of data for a number of games. The input for each game begins with an integer specifying N (the length of the code). Following these will be the secret code, represented as N integers, which we will limit to the range 1 to 9. There will then follow an arbitrary number of guesses, each also represented as N integers, each in the range 1 to 9. Following the last guess in each game will be N zeroes; these zeroes are not to be considered as a guess. +Following the data for the first game will appear data for the second game (if any) beginning with a new value for N. The last game in the input will be followed by a single zero (when a value for N would normally be specified). The maximum value for N will be 1000. + +**Output Format:** + +The output for each game should list the hints that would be generated for each guess, in order, one hint per line. Each hint should be represented as a pair of integers enclosed in parentheses and separated by a comma. The entire list of hints for each game should be prefixed by a heading indicating the game number; games are numbered sequentially starting with 1. Separate the output for successive games using a blank line. + +**Example Input:** + +4 +1 3 5 5 +1 1 2 3 +4 3 3 5 +6 5 5 1 +6 1 3 5 +1 3 5 5 +0 0 0 0 + +10 +1 2 2 2 4 5 6 6 6 9 +1 2 3 4 5 6 7 8 9 1 +1 1 2 2 3 3 4 4 5 5 +1 2 1 3 1 5 1 6 1 9 +1 2 2 5 5 5 6 6 6 7 +0 0 0 0 0 0 0 0 0 0 + +0 + +**Expected Output:** + +Game 1: + (1,1) + (2,0) + (1,2) + (1,2) + (4,0) + +Game 2: + (2,4) + (3,2) + (5,0) + (7,0) +",code,"MasterMind is a game for two players. In this problem you will be given a secret code s1...sn and a guess g1...gn, and are to determine the hint.",ai,2014-09-19T16:31:43,2016-09-09T09:53:01,,,,"MasterMind is a game for two players. One of them, Designer, selects a secret code. The other, Breaker, tries to break it. A code is no more than a row of colored dots. At the beginning of a game, the players agree upon the length N that a code must have and upon the colors that may occur in a code. + +In order to break the code, Breaker makes a number of guesses, each guess itself being a code. After each guess Designer gives a hint, stating to what extent the guess matches his secret code. +In this problem you will be given a secret code s1...sn and a guess g1...gn, and are to determine the hint. A hint consists of a pair of numbers determined as follows. + +A match is a pair (i,j), 1<=i<=n and 1<=j<=n, such that si = gj. Match (i,j) is called strong when i = j, and is called weak otherwise. Two matches (i,j) and (p,q) are called independent when i = p if and only if j = q. A set of matches is called independent when all of its members are pairwise independent. + +Designer chooses an independent set M of matches for which the total number of matches and the number of strong matches are both maximal. The hint then consists of the number of strong followed by the number of weak matches in M. Note that these numbers are uniquely determined by the secret code and the guess. If the hint turns out to be (n,0), then the guess is identical to the secret code. + +**Input Format:** + +The input will consist of data for a number of games. The input for each game begins with an integer specifying N (the length of the code). Following these will be the secret code, represented as N integers, which we will limit to the range 1 to 9. There will then follow an arbitrary number of guesses, each also represented as N integers, each in the range 1 to 9. Following the last guess in each game will be N zeroes; these zeroes are not to be considered as a guess. +Following the data for the first game will appear data for the second game (if any) beginning with a new value for N. The last game in the input will be followed by a single zero (when a value for N would normally be specified). The maximum value for N will be 1000. + +**Output Format:** + +The output for each game should list the hints that would be generated for each guess, in order, one hint per line. Each hint should be represented as a pair of integers enclosed in parentheses and separated by a comma. The entire list of hints for each game should be prefixed by a heading indicating the game number; games are numbered sequentially starting with 1. Separate the output for successive games using a blank line. + +**Example Input:** + +4 +1 3 5 5 +1 1 2 3 +4 3 3 5 +6 5 5 1 +6 1 3 5 +1 3 5 5 +0 0 0 0 + +10 +1 2 2 2 4 5 6 6 6 9 +1 2 3 4 5 6 7 8 9 1 +1 1 2 2 3 3 4 4 5 5 +1 2 1 3 1 5 1 6 1 9 +1 2 2 5 5 5 6 6 6 7 +0 0 0 0 0 0 0 0 0 0 + +0 + +**Expected Output:** + +Game 1: + (1,1) + (2,0) + (1,2) + (1,2) + (4,0) + +Game 2: + (2,4) + (3,2) + (5,0) + (7,0) +",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-19T16:31:50,2016-05-12T23:56:28,setter," #include + #include + + #define MAXN 1000 + + int code[MAXN]; /* the current secret code */ + char match[MAXN]; /* match type (w/respect to code) */ + int guess[MAXN]; /* the current guess */ + int hint[2]; /* the hint */ + int n; /* length of the code */ + + void generate_hint() + { + int i, j; + + /* First identify all strong matches */ + for(i=0;i + #include + + #define min(a,b) (((a)<(b)) ? (a) : (b) ) + + typedef struct queueItem + { + unsigned long element; + struct queueItem *next; + } queueItem; + + typedef struct Queue + { + queueItem *first, *last; + } Queue; + + void queueinit(Queue* q) + { + queueItem *dummy = (queueItem*) malloc(sizeof(*dummy)); + q->first = q->last = dummy; + dummy->next = dummy; + } + + void enqueue(Queue* q, unsigned long elem) + { + queueItem *nu = (queueItem*) malloc(sizeof(*nu)); + nu->element = elem; + nu->next = q->last->next; + q->last = q->last->next = nu; + } + + unsigned long dequeue(Queue* q) + { + queueItem *old = q->first->next; + unsigned long elem = old->element; + q->first->next = old->next; + if (q->last == old) + { + q->last = q->first; + q->first->next = q->first; + } + free((char*) old); + return elem; + } + + void queueelim(Queue* q) + { + queueItem* curr = q->first->next; + while (curr != q->first) + { + queueItem* old = curr; + curr = curr->next; + free((char*) old); + } + free((char*) curr); + } + + #define FILL_A 0 + #define FILL_B 1 + #define EMPTY_A 2 + #define EMPTY_B 3 + #define POUR_A_B 4 + #define POUR_B_A 5 + + #define UNVISITED (unsigned long)(-1) + + unsigned long *initialize(unsigned a, unsigned b) + { + unsigned long sz = (a+1)*(b+1); + unsigned long* p = (unsigned long*) malloc(sz*sizeof(*p)); + while (sz--) + p[sz] = UNVISITED; + return p; + } + + int compute_soln(unsigned a, unsigned b, unsigned n, unsigned long *parent) + { + Queue q; + unsigned long stat; + if (n == 0) + return 0; + + queueinit(&q); + enqueue(&q,0); + parent[0] = 0; + while (1) + { + unsigned long jugStat = dequeue(&q); + int action; + for (action = FILL_A; action <= POUR_B_A; ++action) + { + unsigned long cb = jugStat % (b+1); + unsigned long ca = jugStat / (b+1); + switch (action) + { + case FILL_A: + ca = a; + break; + case FILL_B: + cb = b; + break; + case EMPTY_A: + ca = 0; + break; + case EMPTY_B: + cb = 0; + break; + case POUR_A_B: + { + unsigned sum = ca + cb; + cb = min(sum,b); + ca = sum - cb; + } break; + case POUR_B_A: + { + unsigned sum = ca + cb; + ca = min(sum,a); + cb = sum - ca; + } break; + } + stat = ca * (b+1) + cb; + if (parent[stat] == UNVISITED) + { + parent[stat] = jugStat; + if (stat%(b+1) == n) + { + queueelim(&q); + return stat; + } + enqueue(&q, stat); + } + } + } + } + + void print_soln(FILE *outfp, unsigned long stat, + unsigned a, unsigned b, + unsigned long *parent) + { + if (stat == 0) + return; + print_soln(outfp, parent[stat], a, b, parent); + + { + unsigned long jugStat = parent[stat]; + unsigned long cb = jugStat % (b+1); + unsigned long ca = jugStat / (b+1); + unsigned long nb = stat % (b+1); + unsigned long na = stat / (b+1); + + if (na + nb == ca + cb) + { + if (na > ca) + fprintf(outfp, ""pour B A\n""); + else + fprintf(outfp, ""pour A B\n""); + } + else if (na != ca) + { + if (na == 0) + fprintf(outfp, ""empty A\n""); + else + fprintf(outfp, ""fill A\n""); + } + else if (nb != cb) + { + if (nb == 0) + fprintf(outfp, ""empty B\n""); + else + fprintf(outfp, ""fill B\n""); + } + } + } + + int main(void) + { + FILE *infp = fopen(""jugs.dat"", ""r""); + FILE *outfp= fopen(""jugs.out"", ""w""); + + while (!feof(infp)) + { + unsigned long* parent; + unsigned long stat; + unsigned a,b,n; + fscanf(infp, ""%d %d %d\n"", &a, &b, &n); + parent = initialize(a,b); + stat = compute_soln(a,b,n,parent); + print_soln(outfp, stat, a, b, parent); + fprintf(outfp, ""success\n""); + free((char*) parent); + } + fclose(infp); + fclose(outfp); + return(0); + }",not-set,2016-04-24T02:03:06,2016-04-24T02:03:06,C++ +201,4375,justtrial,JustTrial,Take a number. Print hello world.,code,,ai,2014-09-20T12:48:31,2016-09-09T09:53:06,,,,Take a number. Print hello world.,0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]",,,,,Hard,,,,,,,2014-09-20T12:49:46,2016-05-12T23:56:26,setter,hi,not-set,2016-04-24T02:03:07,2016-04-24T02:03:07,Unknown +202,4429,sherlock-and-square,Sherlock and Square,"Watson gives a square of side length 1 to Sherlock. Now, after each second, each square of side $L$ will break into four squares each of side $L/2$(as shown in the image below). + +![img][123] + +Now, Watson asks Sherlock: What will be the sum of length of solid lines after $N$ seconds? + +As the number can be large print result mod $(10^9 + 7)$. + +For example, after 0 seconds, the length is 4. +After 1 second, the length is 6. + +**Input Format** +First line contains $T$, the number of testcases. Each testcase contains $N$ in one line. + +**Output Format** + +For each testcase, print the required answer in a new line. + +**Constraints** +$1 \le T \le 10^5$ +$0 \le N \le 10^9$ + +**Sample input** + + 2 + 0 + 1 + +**Sample output** + + 4 + 6 + +[123]: http://i.imgur.com/yXME9kL.png",code,Help Sherlock in finding the total side lengths of squares.,ai,2014-09-24T02:15:22,2022-09-02T09:55:08,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts INTEGER n as parameter. +# + +def solve(n): + # 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): + n = int(input().strip()) + + result = solve(n) + + fptr.write(str(result) + '\n') + + fptr.close() +","Watson gives a square of side length 1 to Sherlock. Now, after each second, each square of some arbitrary side $L$ will break into four squares each of side $L/2$(as shown in the image below). + +![img][123] + +Now, Watson asks Sherlock: What will be the sum of length of solid lines after $N$ seconds? + +As the number can be large print result mod $(10^9 + 7)$. + +For example, after 0 seconds, the length is 4. +After 1 second, the length is 6. + +**Input Format** +First line contains $T$, the number of testcases. Each testcase contains $N$ in one line. + +**Output Format** + +For each testcase, print the required answer in a new line. + +**Constraints** +$1 \le T \le 10^5$ +$0 \le N \le 10^9$ + +**Sample input** + + 3 + 0 + 1 + 5 + +**Sample output** + + 4 + 6 + 66 + +[123]: http://i.imgur.com/yXME9kL.png",0.5581395348837209,"[""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,,,,,,,2014-09-24T02:15:28,2016-12-06T15:12:39,setter,"###Python 2 +```python +MOD=10**9+7 +def mpow(a,n): + if n==0: return 1 + elif n==1: return a + p=mpow(a,n/2) + if (n&1): + return (p*p*a)%MOD + else: return (p*p)%MOD +t=input() +while t: + n=input() + print (4+2*(mpow(2,n)-1))%MOD + t-=1 +``` +",not-set,2016-04-24T02:03:07,2016-07-23T18:57:34,Python +203,3082,strange-numbers,Strange numbers,"Let $length(A)$ denote the count of digits of a number $A$ in its decimal representation. +John is looking for new methods of determining which numbers are strange all day long. +All non-negative numbers of length 1 are strange. Further, a number $X$ with $length(X) \ge1$ can also be considered strange if and only if + +* $X$ is evenly divisible by $length(X)$ +* the number $X/length(X)$ is recursively strange + +Your task is to calculate how many strange numbers belong to an interval $[L, R]$. + +**Input Format** +The first line contains single integer $T$ - the number of test cases. Next $T$ lines contain two integers separated by single space $L$ and $R$. + +**Output Format** +In $T$ lines, print $T$ integers - count of strange numbers belonging to the interval $[L, R]$. + +**Constraints** +$1 \le T \le 200$ +$0 \le L < R \le 10^{18}$ + +**Sample Input** + + 5 + 7 25 + 45 50 + 1 100 + 99 103 + 0 1000000 + +**Sample Output** + + 10 + 1 + 26 + 0 + 96 + +**Explanation** +First testcase: There are $10$ strange numbers that belong to the interval $[7,25]$. They are $7,8,9,10,12,14,16,18,20,24$. +Second testcase: Only $48$ satisfies the given constraints. ",code,"How many strange numbers belong to interval [L, R]?",ai,2014-06-18T20:01:55,2022-09-02T09:54:34,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. LONG_INTEGER l +# 2. LONG_INTEGER r +# + +def solve(l, r): + # 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() + + l = int(first_multiple_input[0]) + + r = int(first_multiple_input[1]) + + result = solve(l, r) + + fptr.write(str(result) + '\n') + + fptr.close() +","Let $length(A)$ denote the count of digits of a number $A$ in its decimal representation. +John is looking for new methods of determining which numbers are strange all day long. +All non-negative numbers of length 1 are strange. Further, a number $X$ with $length(X) \ge1$ can also be considered strange if and only if + +* $X$ is evenly divisible by $length(X)$ +* the number $X/length(X)$ is recursively strange + +Your task is to calculate how many strange numbers belong to an interval $[L, R]$. + +**Input Format** +The first line contains single integer $T$ - the number of test cases. Next $T$ lines contain two integers separated by single space $L$ and $R$. + +**Output Format** +In $T$ lines, print $T$ integers - count of strange numbers belonging to the interval $[L, R]$. + +**Constraints** +$1 \le T \le 200$ +$0 \le L < R \le 10^{18}$ + +**Sample Input** + + 5 + 7 25 + 45 50 + 1 100 + 99 103 + 0 1000000 + +**Sample Output** + + 10 + 1 + 26 + 0 + 96 + +**Explanation** +First testcase: There are $10$ strange numbers that belong to the interval $[7,25]$. They are $7,8,9,10,12,14,16,18,20,24$. +Second testcase: Only $48$ satisfies the given constraints. ",0.492063492,"[""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,,,,,,,2014-09-25T07:39:33,2016-12-01T23:56:26,setter,"###C++ +```cpp +#include +#include + +using namespace std; + +int t; +long long l,r; +vector V; +const unsigned long long MAX=1e+18; + +int length(long long X) +{ + int sol=1; + while (X>9){ + ++sol; + X/=10; + } + return sol; +} + +void precalc() +{ + V.clear(); + for(int i=0; i<10; ++i) + V.push_back(i); + + for(int i=1; iMAX) break; + int L=length(next); + if (L>1 && length(next)==new_len) + V.push_back(next); + next+=V[i]; + } + + } +} + +int solve(long long L, long long R) +{ + int res=0; + for(int i=0; i> t; + while (t--) + { + cin >> l >> r; + cout << solve(l,r) << endl; + } + + return 0; +} +``` +",not-set,2016-04-24T02:03:07,2016-07-23T17:56:58,C++ +204,2692,euler066,Project Euler #66: Diophantine equation," +

+ Consider quadratic Diophantine equations of the form: +

+

+ + x + + + 2 + + – D + + y + + + 2 + + = 1 +

+

+ For example, when D=13, the minimal solution in + + x + + is 649 + + 2 + + – 13×180 + + 2 + + = 1. +

+

+ It can be assumed that there are no solutions in positive integers when D is square. +

+

+ By finding minimal solutions in + + x + + for D = {2, 3, 5, 6, 7}, we obtain the following: +

+

+ 3 + + 2 + + – 2×2 + + 2 + + = 1 +
+ 2 + + 2 + + – 3×1 + + 2 + + = 1 +
+ + 9 + + + 2 + + – 5×4 + + 2 + + = 1 +
+ 5 + + 2 + + – 6×2 + + 2 + + = 1 +
+ 8 + + 2 + + – 7×3 + + 2 + + = 1 +

+

+ Hence, by considering minimal solutions in + + x + + for D ≤ 7, the largest + + x + + is obtained when D=5. +

+

+ Find the value of D ≤ 1000 in minimal solutions of + + x + + for which the largest value of + + x + + is obtained. +

",code,,ai,2014-06-16T12:28:31,2022-09-02T10:36:42,,,,"This problem is a programming version of [Problem 66](https://projecteuler.net/problem=66) from [projecteuler.net](https://projecteuler.net/) + +Consider quadratic Diophantine equations of the form: + +$$x^2 - Dy^2 = 1$$ + +For example, when $D=13$, the minimal solution in $x$ is $649^2 - 13×180^2 = 1$. It can be assumed that there are no solutions in positive integers when D is square. + +By finding minimal solutions in $x$ for $D = {2, 3, 5, 6, 7}$, we obtain the following: + +$$3^2 - 2\times2^2 = 1 \\\ + 2^2 - 3 \times 1^2 = 1 \\\ + \textbf{9}^2 - 5 \times 4^2 = 1 \\\ + 5^2 - 6 \times 2^2 = 1 \\\ + 8^2 - 7 \times 3^2 = 1 \\\ + $$ + +Hence, by considering minimal solutions in $x$ for $D \le 7$, the largest $x$ is obtained when $D=5$. + +Find the value of $D \le N$ in minimal solutions of $x$ for which the largest value of $x$ is obtained. +",0.5,"[""ada"",""bash"",""c"",""clojure"",""coffeescript"",""cpp"",""cpp14"",""csharp"",""d"",""elixir"",""erlang"",""fortran"",""fsharp"",""go"",""groovy"",""haskell"",""java"",""java8"",""javascript"",""julia"",""kotlin"",""lolcode"",""lua"",""objectivec"",""ocaml"",""octave"",""pascal"",""perl"",""php"",""pypy3"",""python3"",""r"",""racket"",""ruby"",""rust"",""sbcl"",""scala"",""smalltalk"",""swift"",""tcl"",""visualbasic"",""whitespace"",""cpp20"",""java15"",""typescript""]","Input contains an integer $N$. + +**Constraints** +$7 \le N \le 10^4$",Print the answer corresponding to the test case.,"```raw +7 +```","```raw +5 +```",Hard,,,,,,,2014-09-25T16:12:17,2016-05-12T23:56:18,tester,"```python +import math + + +def gen(n): + n2 = int(math.sqrt(n)) + num = 1 + den = n2 + yield n2 + while True: + x = num + num = den + den = (n - den * den) / x + p = int(n2 + 0.5 + num) / den + yield p + num = p * den - num + num, den = den, num + + +def solve_x(d): + h0, h1 = 0, 1 + k0, k1 = 1, 0 + g = gen(d) + for a in g: + h0, h1 = h1, a*h1+h0 + k0, k1 = k1, a*k1+k0 + # print h1, k1, h1*h1 - d*k1*k1 + if h1*h1 - d*k1*k1 == 1: + return h1 + + +N = int(raw_input()) +sq = 1 +best_x, best_d = 0, 0 +for d in xrange(1, N+1): + while sq*sq < d: sq += 1 + if sq*sq == d: continue + act_x = solve_x(d) + if act_x > best_x: + best_x = act_x + best_d = d +print best_d +```",not-set,2016-04-24T02:03:08,2016-04-24T02:03:08,Python +205,4503,fibonacci-gcd,Fibonacci GCD,"Fibonacci numbers have the following form: +$$Fib_1 = 1 \\\ +Fib_2 = 1 \\\ +Fib_3 = 2 \\\ +\vdots \\\ +Fib_n = Fib_{n-2}+Fib_{n-1}$$ + +We have an array which contains $N$ elements. +We want to find $gcd(Fib_{a_1},Fib_{a_2},Fib_{a_3}, \cdots ,Fib_{a_n} )$ + +**Input Format** +First line contains $N$, where $N$ denotes size of the array. +Each of the next $N$ lines contains a number: $i^{th}$ line contains $a_i$. + +**Output Format** +Print a single integer — remainder of division of the resulting number by $10^9+7$. + +**Constraints** +$1 \le N \le 2 \times 10^5$ +$1 \le a_i \le 10^{12}$ + + +**Sample Input#00** + + 3 + 2 + 3 + 5 + +**Sample Output#00** + + 1 + +**Explanation#00:** +$Fib_2 = 1$ +$Fib_3 = 2$ +$Fib_5 = 5$ +$gcd(1,2,5)=1$ + + +**Sample Input#01** + + 2 + 3 + 6 + +**Sample Output#01** + + 2 + +**Explanation#01:** +$Fib_3 = 2$ +$Fib_6 = 8$ +$gcd(2,8)=2$ + + + +",code,Find gcd for n fibonacci numbers.,ai,2014-09-29T13:09:27,2022-09-02T09:54:42,"# +# Complete the 'solve' function below. +# +# The function is expected to return an INTEGER. +# The function accepts LONG_INTEGER a as parameter. +# + +def solve(a): + # 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()) + + for n_itr in range(n): + a = int(input().strip()) + + result = solve(a) + + fptr.write(str(result) + '\n') + + fptr.close() +","Fibonacci numbers have the following form: +$$F_1 = 1 \\\ +F_2 = 1 \\\ +F_3 = 2 \\\ +\vdots \\\ +F_n = F_{n-2}+F_{n-1}$$ + +We have an array $a_1, a_2, \ldots, a_N$ which contains $N$ elements. + +We want to find $\gcd(F_{a_1},F_{a_2},F_{a_3}, \cdots ,F_{a_N} )$. + +**Input Format** +The first line contains $N$, where $N$ denotes size of the array. +Each of the next $N$ lines contains a number: the $i^{\text{th}}$ line contains $a_i$. + +**Output Format** +Print a single integer — the remainder of the division of the resulting number by $10^9+7$. + +**Constraints** +$1 \le N \le 2 \times 10^5$ +$1 \le a_i \le 10^{12}$ + + +**Sample Input 1** + + 3 + 2 + 3 + 5 + +**Sample Output 1** + + 1 + +**Explanation 1** +$F_2 = 1$ +$F_3 = 2$ +$F_5 = 5$ +$\gcd(1,2,5)=1$ + + +**Sample Input 2** + + 2 + 3 + 6 + +**Sample Output 2** + + 2 + +**Explanation 2** +$F_3 = 2$ +$F_6 = 8$ +$\gcd(2,8)=2$ + + + +",0.5,"[""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,,,,,,,2014-09-29T13:37:55,2016-12-04T15:20:14,tester,"###Python 2 +```python +from fractions import gcd +mod = 10**9+7 +class _: + def __init__(a, x=0, y=0): a.x, a.y = x, y + __add__ = lambda a, b: _((a.x+b.x)%mod, (a.y+b.y)%mod) + __mul__ = lambda a, b: _((a.x*b.x+5*a.y*b.y)%mod, (a.x*b.y+a.y*b.x)%mod) + __pow__ = lambda a, b: a if b == 1 else a*a**(b-1) if b&1 else (a*a)**(b>>1) +print(_(mod+1>>1,mod+1>>1)**reduce(gcd,(input() for i in xrange(input())))).y*2%mod +``` +",not-set,2016-04-24T02:03:08,2016-07-23T18:13:25,Python +206,4516,huskar-tuskar-and-balls,"Huskar, Tuskar, and Balls","Huskar and Tuskar are playing a game with balls. There is a tree with $N$ nodes numbered from $1$ to $N$ respectively (Root is $1$). There is a ball on each node. If a node has only one child, the ball on this node will drop onto child node. But if a node has more than one child, Huskar and Tuskar can't decide the way that the ball will follow. So they start deleting edges one by one(Huskar start first) until every ball has exactly one way to go. Every ball must be able to reach a leaf node.(A leaf node is a node which has no children.) + +In this game each player has a node. When a ball drops onto a player's node, this player gets one point and this ball is removed from the tree. + +Both of them are *just* trying to maximize their own points. They are not jealous friends. So if one can not affect his own points, he would like to help increasing his friends points. + +You are given a graph, and you need to determine Huskar and Tuskar's points when they delete edges optimally for themselves. + +###Input Format +Line 1 : Two integers : $N$ and $Q$ , the number of the nodes in the tree and number of the queries. + +Lines $2...N$ : line $i$, one integer : the parent of node $i$. + +Lines $N+1...N+Q$ : line $(N+i)$ , two integers : Huskar's node and Tuskar's node. + +###Constraints +$1 \le N \le 500\,000$ + +$1 \le Q \le 500\,000$ + +###Output Format +You must print $Q$ lines. In each line, two integers for each query : Huskar's points and Tuskar's points. + +###Sample Input 1 + 6 1 + 4 + 1 + 1 + 3 + 3 + 3 6 +###Sample Output 1 + 2 1 + +###Explanation 1 +Test Case 1 : First Huskar deletes the edge between 1 and 4. Second Tuskar deletes the edge between 3 and 5. + +Huskar removes a ball from node 3 and receives a point. Then a ball from node 1 drops onto node 3 and Huskar receive one more point removing this ball. The ball in node 6 gives one point to Tuskar. Two balls from nodes 4 and 2 stay at node 2 and do not affect Huskar or Tuskar's points. + +###Sample Input 2 + 9 2 + 4 + 5 + 1 + 4 + 2 + 2 + 5 + 3 + 6 8 + 4 9 +###Sample Output 2 + 4 2 + 2 3 + + + +",code,"There is a tree with N nodes. Each node has a ball in it. Two kids are playing a game. Eeach kid has a node. They delete some edges. After deleting, balls drop down in that tree. If a ball drops into a kid's nodes, they get points. We are trying to maximize the points that they have. ",ai,2014-09-30T18:47:23,2019-07-02T13:58:53,,,,"Huskar and Tuskar are playing a game with balls. There is a tree with $N$ nodes numbered from $1$ to $N$ respectively (root is $1$). There is a ball on each node. If a node has only one child, the ball on this node will drop onto the child node. But if a node has more than one child, Huskar and Tuskar can't decide the way that the ball will follow. So they start deleting edges one by one (Huskar goes first) until every ball has exactly one way to go. Every ball must be able to reach a leaf node. (A leaf node is a node which has no children.) + +In this game each player has a node. When a ball drops onto a player's node, this player gets one point and the ball is removed from the tree. + +Both of them are *just* trying to maximize their own points. They are not jealous friends. So if one cannot affect his own points, he would like to help increase his friend's points. + +You are given a graph, and you need to determine Huskar and Tuskar's points when they delete edges optimally for themselves.",0.5,"[""bash"",""c"",""cpp"",""java"",""csharp"",""php"",""ruby"",""python"",""perl"",""haskell"",""clojure"",""scala"",""lua"",""go"",""javascript"",""erlang"",""sbcl"",""d"",""ocaml"",""pascal"",""python3"",""groovy"",""objectivec"",""fsharp"",""visualbasic"",""lolcode"",""smalltalk"",""tcl"",""java8"",""r"",""racket"",""rust"",""swift"",""cpp14""]","Line 1 : Two integers : $N$ and $Q$, the number of the nodes in the tree and the number of queries. +Lines $2...N$ : line $i$, one integer : the parent of node $i$. +Lines $N+1...N+Q$ : line $(N+i)$ , two integers : Huskar's node and Tuskar's node. + + +**Constraints** +$2 \le N \le 2 \times 10^5$ +$1 \le Q \le 2 \times 10^5$ +Huskar and Tuskar can't be on same node. ","You must print $Q$ lines. In each line, two integers for each query : Huskar's points and Tuskar's points."," 6 1 + 4 + 1 + 1 + 3 + 3 + 3 6", 2 1,Hard,,,,,,,2014-10-02T05:25:02,2016-12-04T09:00:09,setter," #include + + using namespace std; + + const int MAXN = 500010; + const int LogN = 21; + + int dad[MAXN][LogN]; + + int N,Q; + + stack st; + + vector v[MAXN]; + + int wh[MAXN]; + int depth[MAXN]; + + void iterative( int k ){ + + st.push(k); + + while ( !st.empty() ){ + + k = st.top(); + st.pop(); + + if ( wh[k] < v[k].size() ){ + st.push(k); + st.push( v[k][ wh[k] ] ); + + depth[ v[k][wh[k]] ] = depth[k]+1; + + wh[k]++; + } + } + + } + + int LCA( int a , int b ){ + + if ( depth[a] > depth[b] ){ + for ( int i=LogN-1 ; i>=0 ; i-- ) + if ( depth[dad[a][i]] >= depth[b] ) + a=dad[a][i]; + } + else if ( depth[b] > depth[a] ){ + for ( int i=LogN-1 ; i>=0 ; i-- ) + if ( depth[dad[b][i]] >= depth[a] ) + b=dad[b][i]; + } + + if ( a==b ) return a; + + for ( int i=LogN-1 ; i>=0 ; i-- ) + if ( dad[a][i]!=dad[b][i] ){ + a=dad[a][i]; + b=dad[b][i]; + } + + return dad[a][0]; + } + + int main(){ + + scanf("" %d %d"",&N,&Q); + + for ( int i=2 ; i<=N ; i++ ){ + scanf("" %d"",&dad[i][0]); + v[ dad[i][0] ].push_back(i); + } + + depth[1] = 1; + + iterative(1); + + for ( int i=1 ; i 0 ) do + begin + dfs( e[i].v, d + 1 ); + + inc( id ); + dfs_order[id] := v; + + i := e[i].next; + end; + end; + + procedure nonRecursiveDFS( v: longInt ); + var i, r, id: longInt; + begin + id := 0; + depth[v] := 1; + parent[v] := 0; + r := 1; + stack[1] := v; + + while ( r > 0 ) do + begin + v := stack[r]; + dec( r ); + + while ( depth[ dfs_order[id] ] >= depth[v] ) do + begin + inc( id ); + dfs_order[id] := parent[ dfs_order[id - 1] ]; + end; + + inc( id ); + dfs_order[id] := v; + dfs_id[v] := id; + + i := first[v]; + while ( i > 0 ) do + begin + if ( parent[v] <> e[i].v ) then + begin + depth[ e[i].v ] := depth[v] + 1; + parent[ e[i].v ] := v; + inc( r ); + stack[r] := e[i].v; + end; + + i := e[i].next; + end; + end; + end; + + function minNode( u, v: longInt ): longInt; + begin + if ( depth[u] < depth[v] ) then + exit( u ) + else + exit( v ); + end; + + procedure prepareSparseTable( sz: longInt ); + var i, j: longInt; + begin + max2pow[1] := 0; + for i := 2 to sz do + begin + max2pow[i] := max2pow[i - 1]; + + if ( i = 2 shl max2pow[i] ) then + inc( max2pow[i] ); + end; + + for i := 1 to sz do + st[i][0] := dfs_order[i]; + + for j := 0 to 19 do + for i := 1 to sz - (2 shl j) + 1 do + st[i][j + 1] := minNode( st[i][j], st[i + 1 shl j][j] ); + end; + + function lca( u, v: longInt ): longInt; + var l, r, p: longInt; + begin + l := min( dfs_id[u], dfs_id[v] ); + r := max( dfs_id[u], dfs_id[v] ); + p := max2pow[r - l + 1]; + + exit( minNode( st[l][p], st[r - 1 shl p + 1][p] ) ); + end; + + var n, q, i, p, u, v: longInt; + + begin + readln( n, q ); + for i := 2 to n do + begin + readln( p ); + + addEdge( p, i ); + end; + + // dfs( 1, 1 ); + // recursive dfs may cause RTE due to low stack memory (8 MB) + + nonRecursiveDFS( 1 ); + + prepareSparseTable( 2 * n ); + + for i := 1 to q do + begin + readln( u, v ); + + writeln( depth[u], ' ', depth[v] - depth[ lca(u, v) ] ); + end; + end. +",not-set,2016-04-24T02:03:09,2016-04-24T02:03:09,JavaScript +208,4529,white-falcon-and-tree,White Falcon And Tree,"White falcon has a tree with $N$ nodes. Each node contains a linear function. And $f_u(x)$ is function of a node $u$. +Let us denote the path from node $u$ to node $v$ like this : $""p_1,p_2,p_3,...,p_k""$ where $p_1 = u$ and $p_k = v$. + +White falcon also has $Q$ queries. They are in the following format : + +1. ""$1$ $u$ $v$ $a$ $b$"" Assign $ax + b$ to functions of all the nodes on the path from $u$ to $v$, i.e., $f_u(x)$ is changed to $ax+b$ where x is a node denoted by one of the k indices $""p_1,p_2,p_3,...,p_k""$. + +2. ""$2$ $u$ $v$ $x$"" Calculate this : $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(... f_{p_1}(x))))$ at modulo $(10^9 + 7)$ + + +**Input Format** +The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. + +Following $N - 1$ lines contain edges of the tree. + +The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above. + +**Output Format** +For each second query, print one line containing an integer that denotes value of function at modulo $(10^9 + 7)$. + +**Constraints** +$1 \leq N \leq 50000$ (Number of nodes) +$1 \leq Q \leq 50000$ (Number of queries) +$0 \leq a, b, x < 10^9 + 7$ + +**Sample Input** + + 2 + 1 1 + 1 2 + 1 2 + 2 + 1 2 2 1 1 + 2 1 2 1 + + + + +**Sample Output** + + 3 + +**Explanation** + +$f_1(1) = 2$ +$f_2(2) = 3$ +",code,"Given a tree with N nodes and two queries, maintain the tree under these two queries.",ai,2014-10-02T18:29:55,2022-08-31T08:33:17,,,,"White Falcon has a tree with $N$ nodes. Each node contains a linear function. Let's denote by $f_u(x)$ the linear function contained in the node $u$. + +Let's denote the path from node $u$ to node $v$ like this: $p_1,p_2,p_3,\ldots,p_k$, where $p_1 = u$ and $p_k = v$, and $p_i$ and $p_{i+1}$ are connected. + +White Falcon also has $Q$ queries. They are in the following format: + +1. $1$ $u$ $v$ $a$ $b$. Assign $ax + b$ as the function of all the nodes on the path from $u$ to $v$, i.e., $f_{p_i}(x)$ is changed to $ax+b$ where $p_1,p_2,p_3,\ldots,p_k$ is the path from $u$ to $v$. + +2. $2$ $u$ $v$ $x$. Calculate $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(\ldots f_{p_1}(x))))$ modulo $(10^9 + 7)$ +",0.5,"[""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""]","The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. + +Following $N - 1$ lines contain edges of the tree. + +The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above.","For every query of the second kind, print one line containing an integer, the answer for that query. + +**Constraints** +$1 \leq N \leq 50000$ (Number of nodes) +$1 \leq Q \leq 50000$ (Number of queries) +$0 \leq a, b, x < 10^9 + 7$ +"," 2 + 1 1 + 1 2 + 1 2 + 2 + 1 2 2 1 1 + 2 1 2 1",3,Hard,,,,,,,2014-10-02T18:34:19,2016-05-12T23:56:08,setter," #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + + #define all(x) (x).begin(), (x).end() + #define type(x) __typeof((x).begin()) + #define foreach(it, x) for(type(x) it = (x).begin(); it != (x).end(); it++) + + //!! debug purposes + #ifdef KAZAR + #define eprintf(...) fprintf(stderr,__VA_ARGS__) + #else + #define eprintf(...) 0 + #endif + + using namespace std; + + template inline void umax(T &a,T b){if(a inline void umin(T &a,T b){if(a>b) a = b ; } + template inline T abs(T a){return a>0 ? a : -a;} + template inline T gcd(T a,T b){return __gcd(a, b);} + template inline T lcm(T a,T b){return a/gcd(a,b)*b;} + + const int inf = 1e9 + 143; + const long long longinf = 1e18 + 143; + + inline int read(){int x;scanf("" %d"",&x);return x;} + + const bool CHECK_SOLUTION = true; + + const int N = 1 << 18; + + const int mod = 1e9 + 7; + + inline int add(int x,int y){return (x + y >= mod)? x + y - mod : x + y;} + inline int mul(int x,int y){return (long long)x * y % mod;} + + inline int power(int x,int n){ + int res = 1; + while(n > 0){ + if(n & 1) + res = mul(res, x); + n >>= 1; + x = mul(x, x); + } + return res; + } + + struct func{ + int a, b; + func() : a(-1), b(-1) {}; + func(int _a,int _b) : a(_a), b(_b) {} + void debug(){ + eprintf(""%d %d\n"",a,b); + } + }; + + func merge(const func &g,const func &f){ + if(f.a == -1) return g; + if(g.a == -1) return f; + return func(mul(f.a, g.a), add(mul(f.a, g.b), f.b)); + } + + inline int sums(int x,int n){ + int p = power(x, n) - 1; + if(p < 0) p += mod; + return mul(p, power(x - 1, mod - 2)); + } + + func calc(const func &f,int n){ + int s = (f.a == 0)? 1 : ((f.a == 1)? n : sums(f.a, n)); + return func(power(f.a, n), mul(s, f.b)); + } + + int tree_sz[N << 1]; + + namespace treeLR{ + + func tree[N << 1], lazy[N << 1]; + + inline void push(int x){ + if(lazy[x].a != -1){ + lazy[x + x] = lazy[x]; + lazy[x + x + 1] = lazy[x]; + lazy[x].a = -1; + } + } + + func applied(int x){ + if(lazy[x].a != -1) + return calc(lazy[x], tree_sz[x]); + return tree[x]; + } + + inline void relax(int x){ + tree[x] = merge(applied(x + x), applied(x + x + 1));// order matters + } + + void upd(int x,int l,int r,int x1,int x2,func by){ + if(l > x2 || r < x1) return; + if(l >= x1 && r <= x2){ + lazy[x] = by; + return; + } + push(x); + int m = (l + r) >> 1; + upd(x + x, l, m, x1, x2, by); + upd(x + x + 1, m + 1, r, x1, x2, by); + relax(x); + } + + func get(int x,int l,int r,int x1,int x2){ + if(l > x2 || r < x1) return func(-1,-1); + if(l >= x1 && r <= x2) return applied(x); + push(x); + int m = (l + r) >> 1; + func L = get(x + x, l, m, x1, x2); + func R = get(x + x + 1, m + 1, r, x1, x2); + relax(x); + return merge(L, R); // order matters + } + + }; + + namespace treeRL{ + + func tree[N << 1], lazy[N << 1]; + + inline void push(int x){ + if(lazy[x].a != -1){ + lazy[x + x] = lazy[x]; + lazy[x + x + 1] = lazy[x]; + lazy[x].a = -1; + } + } + + func applied(int x){ + if(lazy[x].a != -1) + return calc(lazy[x], tree_sz[x]); + return tree[x]; + } + + inline void relax(int x){ + tree[x] = merge(applied(x + x + 1), applied(x + x)); + } + + void upd(int x,int l,int r,int x1,int x2,func by){ + if(l > x2 || r < x1) return; + if(l >= x1 && r <= x2){ + lazy[x] = by; + return; + } + push(x); + int m = (l + r) >> 1; + upd(x + x, l, m, x1, x2, by); + upd(x + x + 1, m + 1, r, x1, x2, by); + relax(x); + } + + func get(int x,int l,int r,int x1,int x2){ + if(l > x2 || r < x1) return func(-1,-1); + if(l >= x1 && r <= x2) return applied(x); + push(x); + int m = (l + r) >> 1; + func L = get(x + x, l, m, x1, x2); + func R = get(x + x + 1, m + 1, r, x1, x2); + relax(x); + return merge(R, L);//order matters again + } + + }; + + int fa[N], fb[N]; + vector g[N]; + int sz[N], d[N], par[N]; + int id[N], ptr = 0; + int inv_id[N]; + int up[N]; // for heavy chain + + void dfs1(int u,int p){ + sz[u] = 1; + foreach(it, g[u]){ + int v = *it; + if(v != p){ + d[v] = d[u] + 1; + par[v] = u; + dfs1(v, u); + sz[u] += sz[v]; + } + } + } + + void dfs2(int u,int p){ + id[u] = ++ptr; + inv_id[ptr] = u; + int bigid = -1; + foreach(it, g[u]){ + int v = *it; + if(v != p && (bigid == -1 || sz[bigid] < sz[v])) + bigid = v; + } + if(bigid != -1){ + up[bigid] = up[u]? up[u] : u; + dfs2(bigid, u); + } + foreach(it, g[u]){ + int v = *it; + if(v != bigid && v != p){ + up[v] = 0; + dfs2(v, u); + } + } + } + + int get_lca(int u,int v){// calculate lca with H-L decs. + for(;;){ + int nu = up[u]? up[u] : u; + int nv = up[v]? up[v] : v; + if(nu == nv){ + return (d[u] < d[v])? u : v; + }else{ + if(d[nu] > d[nv]){ + u = par[nu]; + }else{ + v = par[nv]; + } + } + } + } + + void upd_path(int u,int p,func f){// update all the nodes for both LR and RL + eprintf(""Updating %d %d with %d %d\n"",u,p,f.a,f.b); + while(d[u] > d[p]){ + if(!up[u]){ + treeLR::upd(1, 1, N, id[u], id[u], f); + treeRL::upd(1, 1, N, id[u], id[u], f); + eprintf(""upd : %d\n"",u); + u = par[u]; + }else{ + int next = up[u]; + if(d[next] < d[p]){ + next = p; + } + eprintf(""upd : (%d to %d]\n"",next,u); + treeLR::upd(1, 1, N, id[next] + 1, id[u], f); + treeRL::upd(1, 1, N, id[next] + 1, id[u], f); + u = next; + } + } + eprintf(""upd : %d\n"",p); + treeLR::upd(1, 1, N, id[p], id[p], f); + treeRL::upd(1, 1, N, id[p], id[p], f); + eprintf(""End of update\n""); + } + + func get_left(int u,int p){ // including p, travelling from u to p., remember order matters!!!! + eprintf(""Start get_left %d %d\n"",u,p); + func cur; + while(d[u] > d[p]){ + if(!up[u]){ + eprintf(""append [%d, %d]\n"", id[u], id[u]); + treeRL::get(1, 1, N, id[u], id[u]).debug(); + cur = merge(cur, treeRL::get(1, 1, N, id[u], id[u])); + u = par[u]; + }else{ + int next = up[u]; + if(d[next] < d[p]){ + next = p; + } + eprintf(""append [%d, %d]\n"", id[next] + 1, id[u]); + treeRL::get(1, 1, N, id[next] + 1, id[u]).debug(); + cur = merge(cur, treeRL::get(1, 1, N, id[next] + 1, id[u])); + u = next; + } + } + eprintf(""cur\n""); + cur.debug(); + eprintf(""append [%d, %d]\n"",id[p],id[p]); + treeLR::get(1, 1, N, id[p], id[p]).debug(); + cur = merge(cur, treeRL::get(1, 1, N, id[p], id[p])); + eprintf(""final func : %d %d\n"",cur.a,cur.b); + eprintf(""End of get_left\n""); + return cur; + } + + func get_right(int u,int p,bool add_damn_parent){ // p is not including, travelling from p to u + eprintf(""Introduce bloddy get_right\n""); + func cur; + while(d[u] > d[p]){ + if(!up[u]){ + cur = merge(treeLR::get(1, 1, N, id[u], id[u]), cur); + u = par[u]; + }else{ + int next = up[u]; + if(d[next] < d[p]){ + next = p; + } + eprintf(""fuck fuck fuck append this : [%d,%d]\n"",id[next] + 1,id[u]); + treeRL::get(1, 1, N, id[next] + 1, id[u]).debug(); + cur = merge(treeLR::get(1, 1, N, id[next] + 1, id[u]), cur); + u = next; + } + } + if(add_damn_parent){ + eprintf(""damn parent coming : [%d,%d]\n"",id[p],id[p]); + cur = merge(treeLR::get(1, 1, N, id[p], id[p]), cur); + } + eprintf(""The End bloddy get_right\n""); + return cur; + } + + func get_path(int u,int v){ + int lca = get_lca(u, v); + if(lca == u){ + return get_right(v, u, true); + } + if(lca == v){ + eprintf(""left\n""); + get_left(u, v).debug(); + return get_left(u, v); + } + eprintf(""-----------left\n""); + get_left(u, lca).debug(); + eprintf(""----------right\n""); + get_right(v, lca, false).debug(); + return merge(get_left(u, lca), get_right(v, lca, false)); + } + + namespace naive{ + void upd_path(int u,int p,int a,int b){ + for(;;){ + fa[u] = a; + fb[u] = b; + if(u == p) + break; + u = par[u]; + } + } + int calc(int u,int x,int dest,int p){ + if(u == dest) return x; + foreach(it, g[u]){ + int v = *it; + if(v == p) continue; + int t = calc(v, add(mul(fa[v], x), fb[v]), dest, u); + if(t != -1) + return t; + } + return -1; + } + int get_path(int u,int v,int x){ + return calc(u, add(mul(fa[u], x), fb[u]), v, 0); + } + }; + + int main(){ + + #ifdef KAZAR + freopen(""f.input"",""r"",stdin); + freopen(""f.output"",""w"",stdout); + freopen(""error"",""w"",stderr); + #endif + + for(int i = N; i < N + N; i++) + tree_sz[i] = 1; + for(int i = N - 1; i > 0; i--) + tree_sz[i] = tree_sz[i + i] + tree_sz[i + i + 1]; + + int n = read(); + + for(int i = 1; i <= n; i++){ + fa[i] = read(); + fb[i] = read(); + assert(fa[i] >= 0 && fa[i] < mod); + assert(fb[i] >= 0 && fb[i] < mod); + } + + for(int i = 1; i < n; i++){ + int u = read(); + int v = read(); + g[u].push_back(v); + g[v].push_back(u); + } + + dfs1(1, 0); + dfs2(1, 0); + + for(int i = 1; i <= n; i++){ + eprintf(""id[%d] = %d\n"",i,id[i]); + treeLR::upd(1, 1, N, id[i], id[i], func(fa[i], fb[i])); + treeRL::upd(1, 1, N, id[i], id[i], func(fa[i], fb[i])); + } + + int q = read(); + for(int i = 0; i < q; i++){ + int t = read(); + if(t == 1){ + int u = read(), v = read(); + int a = read(), b = read(); + int lca = get_lca(u, v); + eprintf(""lca : %d\n"",lca); + upd_path(u, lca, func(a, b)); + upd_path(v, lca, func(a, b)); + if(CHECK_SOLUTION){ + naive::upd_path(u, lca, a, b); + naive::upd_path(v, lca, a, b); + } + }else{ + int u = read(), v = read(), x = read(); + func f = get_path(u, v); + printf(""%d\n"",add(mul(f.a, x), f.b)); + if(CHECK_SOLUTION){ + if(naive::get_path(u, v, x) != add(mul(f.a, x), f.b)){ + eprintf(""Lca : %d\n"",get_lca(u, v)); + eprintf(""on the %d -> %d with %d\n"",u,v,x); + eprintf(""naive : %d\n"",naive::get_path(u, v, x)); + eprintf(""fastt : %d\n"",add(mul(f.a, x), f.b)); + exit(123); + } + } + } + } + + return 0; + } + +",not-set,2016-04-24T02:03:09,2016-04-24T02:03:09,C++ +209,4529,white-falcon-and-tree,White Falcon And Tree,"White falcon has a tree with $N$ nodes. Each node contains a linear function. And $f_u(x)$ is function of a node $u$. +Let us denote the path from node $u$ to node $v$ like this : $""p_1,p_2,p_3,...,p_k""$ where $p_1 = u$ and $p_k = v$. + +White falcon also has $Q$ queries. They are in the following format : + +1. ""$1$ $u$ $v$ $a$ $b$"" Assign $ax + b$ to functions of all the nodes on the path from $u$ to $v$, i.e., $f_u(x)$ is changed to $ax+b$ where x is a node denoted by one of the k indices $""p_1,p_2,p_3,...,p_k""$. + +2. ""$2$ $u$ $v$ $x$"" Calculate this : $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(... f_{p_1}(x))))$ at modulo $(10^9 + 7)$ + + +**Input Format** +The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. + +Following $N - 1$ lines contain edges of the tree. + +The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above. + +**Output Format** +For each second query, print one line containing an integer that denotes value of function at modulo $(10^9 + 7)$. + +**Constraints** +$1 \leq N \leq 50000$ (Number of nodes) +$1 \leq Q \leq 50000$ (Number of queries) +$0 \leq a, b, x < 10^9 + 7$ + +**Sample Input** + + 2 + 1 1 + 1 2 + 1 2 + 2 + 1 2 2 1 1 + 2 1 2 1 + + + + +**Sample Output** + + 3 + +**Explanation** + +$f_1(1) = 2$ +$f_2(2) = 3$ +",code,"Given a tree with N nodes and two queries, maintain the tree under these two queries.",ai,2014-10-02T18:29:55,2022-08-31T08:33:17,,,,"White Falcon has a tree with $N$ nodes. Each node contains a linear function. Let's denote by $f_u(x)$ the linear function contained in the node $u$. + +Let's denote the path from node $u$ to node $v$ like this: $p_1,p_2,p_3,\ldots,p_k$, where $p_1 = u$ and $p_k = v$, and $p_i$ and $p_{i+1}$ are connected. + +White Falcon also has $Q$ queries. They are in the following format: + +1. $1$ $u$ $v$ $a$ $b$. Assign $ax + b$ as the function of all the nodes on the path from $u$ to $v$, i.e., $f_{p_i}(x)$ is changed to $ax+b$ where $p_1,p_2,p_3,\ldots,p_k$ is the path from $u$ to $v$. + +2. $2$ $u$ $v$ $x$. Calculate $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(\ldots f_{p_1}(x))))$ modulo $(10^9 + 7)$ +",0.5,"[""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""]","The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. + +Following $N - 1$ lines contain edges of the tree. + +The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above.","For every query of the second kind, print one line containing an integer, the answer for that query. + +**Constraints** +$1 \leq N \leq 50000$ (Number of nodes) +$1 \leq Q \leq 50000$ (Number of queries) +$0 \leq a, b, x < 10^9 + 7$ +"," 2 + 1 1 + 1 2 + 1 2 + 2 + 1 2 2 1 1 + 2 1 2 1",3,Hard,,,,,,,2014-10-02T18:34:19,2016-05-12T23:56:08,tester," #include + #include + #include + #include + #include + #define fo(i,a,b) dfo(int,i,a,b) + #define fr(i,n) dfr(int,i,n) + #define fe(i,a,b) dfe(int,i,a,b) + #define fq(i,n) dfq(int,i,n) + #define nfo(i,a,b) dfo(,i,a,b) + #define nfr(i,n) dfr(,i,n) + #define nfe(i,a,b) dfe(,i,a,b) + #define nfq(i,n) dfq(,i,n) + #define dfo(d,i,a,b) for (d i = (a); i < (b); i++) + #define dfr(d,i,n) dfo(d,i,0,n) + #define dfe(d,i,a,b) for (d i = (a); i <= (b); i++) + #define dfq(d,i,n) dfe(d,i,1,n) + #define ffo(i,a,b) dffo(int,i,a,b) + #define ffr(i,n) dffr(int,i,n) + #define ffe(i,a,b) dffe(int,i,a,b) + #define ffq(i,n) dffq(int,i,n) + #define nffo(i,a,b) dffo(,i,a,b) + #define nffr(i,n) dffr(,i,n) + #define nffe(i,a,b) dffe(,i,a,b) + #define nffq(i,n) dffq(,i,n) + #define dffo(d,i,a,b) for (d i = (b)-1; i >= (a); i--) + #define dffr(d,i,n) dffo(d,i,0,n) + #define dffe(d,i,a,b) for (d i = (b); i >= (a); i--) + #define dffq(d,i,n) dffe(d,i,1,n) + #define ll long long + #define alok(n,t) ((t*)malloc((n)*sizeof(t))) + #define pf printf + #define sf scanf + #define pln pf(""\n"") + #define flsh fflush(stdout) + #include + #include + #include + #include + #include + using namespace std; + + #define mod 1000000007 + + // linear operator x -> ax+b + struct op { + int a, b; + op(int a = 1, int b = 0) : a(a), b(b) {} + + // compose this and v + op operator*(op v) { + return op(a * (ll)v.a % mod, (a * (ll)v.b + b) % mod); + } + + // evaluate this operator at x + int operator() (int x) { + return (a * (ll)x + b) % mod; + } + }; + + // identity operator + op one = op(); + + // tree node + struct node { + vector adj; // neighbors + op o; + int parent; + int size; + int hson; + int hindex; // index of heavy path + int hpos; // position in heavy path + + node(): parent(-1), size(0), hson(-1), hindex(-1) {} + }; + + vector pre; + vector nodes(111111); + vector ops(111111); + + // segment tree node + struct snode { + int i, j, k; + op val; + op *setv; + snode *lft; + snode *ryt; + + // make a segment tree in [i,j) + snode (int i, int j, int k): i(i), j(j), k(k), setv(NULL) { + if (j - i == 1) { + val = ops[i]; + lft = ryt = NULL; + } else { + int l = i + j >> 1; + lft = new snode(i, l, k-1); + ryt = new snode(l, j, k-1); + val = lft->val * ryt->val; + } + } + + // visit a node (propagate downwards if necessary) + #define visit() do {\ + if (setv) {\ + if (lft) {\ + lft->setv = setv;\ + ryt->setv = setv;\ + }\ + val = setv[k];\ + setv = NULL;\ + }\ + } while (0) + + // get product in [I,J) in this node + op get(int I, int J) { + visit(); + if (I <= i and j <= J) { + return val; + } else if (J <= i or j <= I) { + return one; + } else { + return lft->get(I, J) * ryt->get(I, J); + } + } + + // set values in [I,J) in this node to v + void set(int I, int J, op *v) { + if (I <= i and j <= J) { + setv = v; + visit(); + } else { + visit(); + if (!(J <= i or j <= I)) { + lft->set(I, J, v); + ryt->set(I, J, v); + val = lft->val * ryt->val; + } + } + } + }; + + struct path { + vector inds; + int size; + int parent; // parent node of top of heavy path + snode *uptree; + snode *dntree; + void initialize() { + size = inds.size(); + int k = 0; + while (1 << k < size) k++; + fr(i,size) ops[i] = nodes[inds[i]].o; + dntree = new snode(0, 1<set(i, j+1, v); + uptree->set(size-1-j, size-i, v); + } else { + dntree->set(j, i+1, v); + uptree->set(size-1-i, size-j, v); + } + } + op get(int i, int j) { + // smart enough to know up and down + if (i <= j) { + return dntree->get(i, j+1); + } else { + return uptree->get(size-1-i, size-j); + } + } + }; + + vector paths(111111); + + int main() { + int n; + sf(""%d"", &n); + + // collect ops + fr(i,n) { + int a, b; + sf(""%d%d"", &a, &b); + nodes[i].o = op(a, b); + } + + // collect edges + fr(i,n-1) { + int a, b; + sf(""%d%d"", &a, &b); + a--, b--; + nodes[a].adj.push_back(b); + nodes[b].adj.push_back(a); + } + + // calculate preorder and parents + #define add(i,p) (nodes[i].parent = p, pre.push_back(i)) + add(0,-1); + fr(f,n) { + int i = pre[f]; + fr(nb,nodes[i].adj.size()) { + int j = nodes[i].adj[nb]; + if (nodes[i].parent == j) continue; + add(j,i); + } + } + #undef add + + // calculate subtree sizes + ffo(f,1,n) { + int i = pre[f]; + int p = nodes[i].parent; + nodes[p].size += ++nodes[i].size; + nodes[p].hson = i; + } + nodes[0].size++; + + // calculate heavy sons + ffo(f,1,n) { + int i = pre[f]; + int p = nodes[i].parent; + if (nodes[nodes[p].hson].size < nodes[i].size) { + nodes[p].hson = i; + } + } + + // calculate heavy index + int hcount = 0; + fr(f,n) { + int i = pre[f]; + int idx = nodes[i].hindex; + if (!~idx) { + idx = nodes[i].hindex = hcount++; + paths[idx].parent = nodes[i].parent; + } + nodes[i].hpos = paths[idx].inds.size(); + paths[idx].inds.push_back(i); + int s = nodes[i].hson; + if (~s) nodes[s].hindex = idx; + } + + // initialize segment trees + fr(h,hcount) paths[h].initialize(); + + // calculate power of two for n + int k = 0; + while (1 << k < n) k++; + k++; + + // process queries + int q; + sf(""%d"", &q); + while (q--) { + int t; + sf(""%d"", &t); + if (t == 1) { + // update query + int u, v, a, b; + sf(""%d%d%d%d"", &u, &v, &a, &b); + u--, v--; + + // allocate powers of operator + op *o = alok(k, op); + o[0] = op(a, b); + fo(i,1,k) o[i] = o[i-1] * o[i-1]; + + // ascend and set in paths + #define ascend(i) do {\ + int h = nodes[i].hindex;\ + paths[h].set(0, nodes[i].hpos, o);\ + i = paths[h].parent;\ + } while (0) + while (nodes[u].hindex != nodes[v].hindex) { + if (nodes[u].hindex > nodes[v].hindex) { + ascend(u); + } else { + ascend(v); + } + } + #undef ascend + + // set in topmost path + int h = nodes[u].hindex; + paths[h].set(nodes[u].hpos, nodes[v].hpos, o); + } else { + // get query + int u, v, x; + sf(""%d%d%d"", &u, &v, &x); + u--, v--; + + // ascend and calculate operator in paths + op l = one; + while (nodes[u].hindex != nodes[v].hindex) { + if (nodes[u].hindex > nodes[v].hindex) { + int h = nodes[u].hindex; + x = paths[h].get(0, nodes[u].hpos)(x); + u = paths[h].parent; + } else { + int h = nodes[v].hindex; + l = l * paths[h].get(nodes[v].hpos, 0); + v = paths[h].parent; + } + } + + // operator in topmost path + int h = nodes[u].hindex; + x = paths[h].get(nodes[v].hpos, nodes[u].hpos)(x); + + // calculate and print the answer + int ans = l(x); + if (ans < 0) ans += mod; + pf(""%d\n"", ans); + } + } + } +",not-set,2016-04-24T02:03:09,2016-04-24T02:03:09,C++ +210,4545,assassins-steps,Assassin's Steps,"Training to be an assassin is not easy, especially when training under someone as accomplished as Master
Al-Manav. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. + +Altair is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? + +There are three possible choices for him at any time: + +1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. + +2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. + +3. Start from the beginning again. He knows he will perform the steps correctly this time. + +Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. + +See the example below for explanation. + +**Example** + +Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: + +_Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. + +_Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. + +_Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. + +_Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. + +Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: + + Case 1 Case 2 Case 3 Case 4 Expected + Probability 0.49 0.21 0.21 0.09 - + Additional steps if he keeps on walking 5 12 12 12 8.57 + Additional steps if he jumped back once 7 7 14 14 9.1 + Additional steps if he jumped back twice 9 9 9 9 9 + Additional steps if restarted immediately 7 7 7 7 7 + +
If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. + +**Input Format** + +The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. + +The next line contains _A_ real numbers: _P_1, _P_2, ..., _P_A. _P__i_ is the probability that Altair correctly took the ith step in the exercise. + +**Output Format** + +Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10-6. + +**Constraints** + +1 ≤ _T_ ≤ 20 +1 ≤ _A_ < _B_ ≤ 105 +0 ≤ _P__i_ ≤ 1 + +**Sample Input** + + 3 + 2 7 + 0.7 0.7 + 1 25 + 1 + 4 4 + 1 0.95 0.1 0.15 + +**Sample Output** + + 7.000000 + 24.000000 + 3.943000 +",code,,ai,2014-10-05T09:09:55,2016-09-09T09:54:14,,,,"Training to be an assassin is not easy, especially when training under someone as accomplished as Master Al-Manav. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. + +Altair is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? + +There are three possible choices for him at any time: + +1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. + +2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. + +3. Start from the beginning again. He knows he will perform the steps correctly this time. + +Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. + +See the example below for explanation. + +**Example** + +Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: + +_Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. + +_Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. + +_Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. + +_Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. + +Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: + + Case 1 Case 2 Case 3 Case 4 Expected + Probability 0.49 0.21 0.21 0.09 - + Additional steps if he keeps on walking 5 12 12 12 8.57 + Additional steps if he jumped back once 7 7 14 14 9.1 + Additional steps if he jumped back twice 9 9 9 9 9 + Additional steps if restarted immediately 7 7 7 7 7 + +
If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. + +**Input Format** + +The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. + +The next line contains _A_ real numbers: _P_1, _P_2, ..., _P_A. _P__i_ is the probability that Altair correctly took the ith step in the exercise. + +**Output Format** + +Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10-6. + +**Constraints** + +1 ≤ _T_ ≤ 20 +1 ≤ _A_ < _B_ ≤ 105 +0 ≤ _P__i_ ≤ 1 + +**Sample Input** + + 3 + 2 7 + 0.7 0.7 + 1 25 + 1 + 4 4 + 1 0.95 0.1 0.15 + +**Sample Output** + + 7.000000 + 24.000000 + 3.943000 +",0.5,"[""bash"",""c"",""cpp"",""java"",""cpp14""]",,,,,Hard,,,,,,,2014-10-05T09:11:21,2018-08-11T06:11:38,setter," #include + + using namespace std; + + int main () + { + int t,A,B,i; + double p[100002],product,expected,min; + + scanf(""%d"",&t); + + while(t--) + { + scanf(""%d%d"",&A,&B); + + for (int j=0;jAl-Manav. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. + +Altair is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? + +There are three possible choices for him at any time: + +1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. + +2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. + +3. Start from the beginning again. He knows he will perform the steps correctly this time. + +Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. + +See the example below for explanation. + +**Example** + +Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: + +_Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. + +_Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. + +_Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. + +_Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. + +Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: + + Case 1 Case 2 Case 3 Case 4 Expected + Probability 0.49 0.21 0.21 0.09 - + Additional steps if he keeps on walking 5 12 12 12 8.57 + Additional steps if he jumped back once 7 7 14 14 9.1 + Additional steps if he jumped back twice 9 9 9 9 9 + Additional steps if restarted immediately 7 7 7 7 7 + +
If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. + +**Input Format** + +The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. + +The next line contains _A_ real numbers: _P_1, _P_2, ..., _P_A. _P__i_ is the probability that Altair correctly took the ith step in the exercise. + +**Output Format** + +Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10-6. + +**Constraints** + +1 ≤ _T_ ≤ 20 +1 ≤ _A_ < _B_ ≤ 105 +0 ≤ _P__i_ ≤ 1 + +**Sample Input** + + 3 + 2 7 + 0.7 0.7 + 1 25 + 1 + 4 4 + 1 0.95 0.1 0.15 + +**Sample Output** + + 7.000000 + 24.000000 + 3.943000 +",code,,ai,2014-10-05T09:09:55,2016-09-09T09:54:14,,,,"Training to be an assassin is not easy, especially when training under someone as accomplished as Master Al-Manav. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. + +Altair is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? + +There are three possible choices for him at any time: + +1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. + +2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. + +3. Start from the beginning again. He knows he will perform the steps correctly this time. + +Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. + +See the example below for explanation. + +**Example** + +Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: + +_Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. + +_Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. + +_Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. + +_Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. + +Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: + + Case 1 Case 2 Case 3 Case 4 Expected + Probability 0.49 0.21 0.21 0.09 - + Additional steps if he keeps on walking 5 12 12 12 8.57 + Additional steps if he jumped back once 7 7 14 14 9.1 + Additional steps if he jumped back twice 9 9 9 9 9 + Additional steps if restarted immediately 7 7 7 7 7 + +
If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. + +**Input Format** + +The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. + +The next line contains _A_ real numbers: _P_1, _P_2, ..., _P_A. _P__i_ is the probability that Altair correctly took the ith step in the exercise. + +**Output Format** + +Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10-6. + +**Constraints** + +1 ≤ _T_ ≤ 20 +1 ≤ _A_ < _B_ ≤ 105 +0 ≤ _P__i_ ≤ 1 + +**Sample Input** + + 3 + 2 7 + 0.7 0.7 + 1 25 + 1 + 4 4 + 1 0.95 0.1 0.15 + +**Sample Output** + + 7.000000 + 24.000000 + 3.943000 +",0.5,"[""bash"",""c"",""cpp"",""java"",""cpp14""]",,,,,Hard,,,,,,,2014-10-05T09:11:21,2018-08-11T06:11:38,tester," import java.util.Scanner; + + public class AssassinSteps { + + public static double calculateMinSteps(int A, int B, double prob[]) { + + double sol = Double.MAX_VALUE; + + double p = 1; + for (int c = 1; c<=A; c++) { + p *= prob[c-1]; + int D = A-c; + sol = Math.min(sol, p*(2*D+B-A) + (1-p) * (2*D+2*B-A)); + } + + sol = Math.min(sol, B); + return sol; + } + + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int numTests = in.nextInt(); + int a,b; + double p[] = new double[100002]; + + for(int i=0; i< numTests; i++) + { + a = in.nextInt(); + b = in.nextInt(); + + for(int j=0; j + using namespace std; + int mod=1000000007; + int main() + { + static int t,i,j,way[1001][1001],n; + char c[1001][1001]; + cin>>t; + while (t--) + { + cin>>n; + for (i=0;i>c[i]; + } + way[0][0]=1; + for (i=1;i