Unnamed: 0
int64 0
269
| challenge_id
int64 104
5.95k
| challenge_slug
stringlengths 4
38
| challenge_name
stringlengths 5
57
| challenge_body
stringlengths 9
4.55k
⌀ | challenge_kind
stringclasses 2
values | challenge_preview
stringlengths 9
300
⌀ | challenge_category
stringclasses 2
values | challenge_created_at
stringdate 2013-01-04 20:28:56
2015-01-19 21:40:20
| challenge_updated_at
stringdate 2016-09-01 16:22:55
2022-09-02 10:36:47
| python3_template
stringlengths 2
303
⌀ | python3_template_head
stringclasses 2
values | python3_template_tail
stringclasses 52
values | problem_statement
stringlengths 9
4.55k
| difficulty
float64 0.4
0.6
| allowed_languages
stringclasses 28
values | input_format
stringlengths 1
987
⌀ | output_format
stringlengths 1
1.92k
⌀ | sample_input
stringlengths 1
284
⌀ | sample_output
stringclasses 52
values | difficulty_tag
stringclasses 1
value | editorial_title
stringclasses 32
values | editorial_content
stringclasses 32
values | editorial_draft
float64 0
0
⌀ | editorial_slug
stringclasses 32
values | editorial_published_at
stringdate 2013-03-04 16:26:12
2014-04-24 18:24:07
⌀ | editorial_statistics
stringclasses 45
values | editorial_created_at
stringdate 2013-03-04 16:26:12
2015-01-19 21:44:31
| editorial_updated_at
stringdate 2016-05-12 23:56:02
2020-09-08 16:59:12
| editorial_solution_kind
stringclasses 2
values | editorial_solution_code
stringlengths 2
13k
| editorial_solution_language
stringclasses 1
value | editorial_solution_created_at
stringdate 2016-04-24 02:02:11
2016-04-24 02:03:27
| editorial_solution_updated_at
stringdate 2016-04-24 02:02:11
2020-09-08 16:59:12
| language
stringclasses 7
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
100 | 3,167 | 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 (10<sup>9</sup>+9).
__Input Format__ <br>
The first line contains an integer __T__, the number of test cases.
This is followed by __T__ lines each containing 1 integer __n__.
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 600000
__Sample Input__ <br>
<pre>
2
2
5
</pre>
__Sample Output__ <br>
<pre>
1
11
</pre>
__Explanation__ <br>
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 | null | null | null | 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 (10<sup>9</sup>+9).
__Input Format__ <br>
The first line contains an integer __T__, the number of test cases.
This is followed by __T__ lines each containing 1 integer __n__.
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 600000
__Sample Input__ <br>
<pre>
2
2
5
</pre>
__Sample Output__ <br>
<pre>
1
11
</pre>
__Explanation__ <br>
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-06-27T07:12:06 | 2016-12-03T04:02:42 | setter | #include <iostream>
#include <vector>
#include <algorithm>
#include <string.h>
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 | 3,167 | 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 (10<sup>9</sup>+9).
__Input Format__ <br>
The first line contains an integer __T__, the number of test cases.
This is followed by __T__ lines each containing 1 integer __n__.
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 600000
__Sample Input__ <br>
<pre>
2
2
5
</pre>
__Sample Output__ <br>
<pre>
1
11
</pre>
__Explanation__ <br>
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 | null | null | null | 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 (10<sup>9</sup>+9).
__Input Format__ <br>
The first line contains an integer __T__, the number of test cases.
This is followed by __T__ lines each containing 1 integer __n__.
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 600000
__Sample Input__ <br>
<pre>
2
2
5
</pre>
__Sample Output__ <br>
<pre>
1
11
</pre>
__Explanation__ <br>
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-06-27T07:12:06 | 2016-12-03T04:02:42 | tester | #include<bits/stdc++.h>
using namespace std;
vector<int> prime;
vector<int> minFactor;
vector<bool> isp;
vector<int> non_prime;
vector<int> dp;
vector<int> sum_prime;
vector<int> 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 | 2,590 | 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_.
<br>
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 _i<sup>th</sup>_ 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 _k<sup>th</sup>_ lowest salary *among her subordinates*. Help them in solving their query.
**Note**
1. _1<sup>st</sup>_ lowest salary is equivalent to lowest salary, _2<sup>nd</sup>_ lowest means lowest salary which is greater that _1<sup>st</sup>_ 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 _i<sup>th</sup>_ 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 _k<sup>th</sup>_ lowest salary among the subordinates of _v_.
For the subsequent queries, we need to find the _k<sup>th</sup>_ lowest salary of the subordinates of _v+d_, where _d_ is the answer of previous query.
**Constraints**
1 ≤ _N_ ≤ 3*10<sup>4</sup>
1 ≤ _Q_ ≤ 3*10<sup>4</sup>
1 ≤ _s[i]_ ≤ 10<sup>9</sup>, _i_ ∈ _[1..N]_
_s[i]_ ≠ s[j], 1 ≤ i < j ≤ _N_
1 ≤ _u, p_ ≤ _N_, _u_ ≠ _p_
_-N_ ≤ _d_ ≤ _N_
For _1<sup>st</sup>_ 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 _1<sup>st</sup>_ 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)_ . _8<sup>th</sup>_ employee has the _5<sup>th</sup>_ 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)_. _6<sup>th</sup>_ 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 | null | null | null |
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_.
<br>
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 _i<sup>th</sup>_ 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 _k<sup>th</sup>_ lowest salary *among her subordinates*. Help them in solving their query.
**Note**
1. _1<sup>st</sup>_ lowest salary is equivalent to lowest salary, _2<sup>nd</sup>_ lowest means lowest salary which is greater that _1<sup>st</sup>_ 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 _i<sup>th</sup>_ 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 _k<sup>th</sup>_ lowest salary among the subordinates of _v_.
For the subsequent queries, we need to find the _k<sup>th</sup>_ lowest salary of the subordinates of _v+d_, where _d_ is the answer of previous query.
**Constraints**
1 ≤ _N_ ≤ 3*10<sup>4</sup>
1 ≤ _Q_ ≤ 3*10<sup>4</sup>
1 ≤ _s[i]_ ≤ 10<sup>9</sup>, _i_ ∈ _[1..N]_
_s[i]_ ≠ s[j], 1 ≤ i < j ≤ _N_
1 ≤ _u, p_ ≤ _N_, _u_ ≠ _p_
_-N_ ≤ _d_ ≤ _N_
For _1<sup>st</sup>_ 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 _1<sup>st</sup>_ 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)_ . _8<sup>th</sup>_ employee has the _5<sup>th</sup>_ 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)_. _6<sup>th</sup>_ 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.576923 | ["haskell","clojure","scala","erlang","sbcl","ocaml","fsharp","racket","elixir"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 2,500 | 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 | null | null | null | 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$)*.<br>
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 | null | null | null | null | null | null | 2014-06-27T20:02:46 | 2016-12-22T00:39:56 | setter | #include <cstdio>
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<x2 && y1<y2 && z1<z2)
{
//Again, we use the formula we have got from the inclusion-exclusion principle.
res = a[x2][y2][z2]
- a[x1-1][y2][z2] - a[x2][y1-1][z2] - a[x2][y2][z1-1]
+ a[x1-1][y1-1][z2] + a[x1-1][y2][z1-1] + a[x2][y1-1][z1-1]
- a[x1-1][y1-1][z1-1];
}
printf("%d\n", res);
}
return 0;
} | not-set | 2016-04-24T02:02:45 | 2016-04-24T02:02:45 | C++ |
||||
104 | 2,501 | jim-beam | Jim Beam | Jim likes to play with laser beams.
Jim stays at point $(0,0)$.
There is a mirror at point $(X_m, Y_m)$ and a wall between points $(X_1, Y_1)$ and $(X_2, Y_2)$.
Jim wants to find out if he can point the laser beam on the mirror.
**Input Format**
First line contains the number of test cases, $T$.
Each subsequent line contains one test case: space separated integers that denote endpoints of the wall $X_1, Y_1$, $X_2, Y_2$ and position of the mirror $X_m, Y_m$.
**Output Format**
The answer for each test case: Display `YES` if Jim can point the laser beam to the mirror, otherwise display `NO` .
**Constraints**
$1 \le T \le 100$
$0 \le |X_1|,|Y_1|,|X_2|,|Y_2|,|X_m|,|Y_m| \le 10^6$
Mirror doesn't have common points with wall.
Wall doesn't pass through the point $(0,0)$.
**Sample Input**
5
1 2 2 1 2 2
-1 1 1 1 1 -1
1 1 2 2 3 3
2 2 3 3 1 1
0 1 1 1 0 2
**Sample Output**
NO
YES
NO
YES
NO
| code | Help Jim determine if he can play with laser beam. | ai | 2014-05-10T02:21:57 | 2022-09-02T09:55:19 | #
# Complete the 'solve' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. INTEGER x1
# 2. INTEGER y1
# 3. INTEGER x2
# 4. INTEGER y2
# 5. INTEGER xm
# 6. INTEGER ym
#
def solve(x1, y1, x2, y2, xm, ym):
# 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()
x1 = int(first_multiple_input[0])
y1 = int(first_multiple_input[1])
x2 = int(first_multiple_input[2])
y2 = int(first_multiple_input[3])
xm = int(first_multiple_input[4])
ym = int(first_multiple_input[5])
result = solve(x1, y1, x2, y2, xm, ym)
fptr.write(result + '\n')
fptr.close()
| Jim likes to play with laser beams.
Jim stays at point $(0,0)$.
There is a mirror at point $(X_m, Y_m)$ and a wall between points $(X_1, Y_1)$ and $(X_2, Y_2)$.
Jim wants to find out if he can point the laser beam on the mirror.
**Input Format**
First line contains the number of test cases, $T$.
Each subsequent line contains one test case: space separated integers that denote endpoints of the wall $X_1, Y_1$, $X_2, Y_2$ and position of the mirror $X_m, Y_m$.
**Output Format**
The answer for each test case: Display `YES` if Jim can point the laser beam to the mirror, otherwise display `NO` .
**Constraints**
$1 \le T \le 100$
$0 \le |X_1|,|Y_1|,|X_2|,|Y_2|,|X_m|,|Y_m| \le 10^6$
Mirror doesn't have common points with wall.
Wall doesn't pass through the point $(0,0)$.
**Sample Input**
5
1 2 2 1 2 2
-1 1 1 1 1 -1
1 1 2 2 3 3
2 2 3 3 1 1
0 1 1 1 0 2
**Sample Output**
NO
YES
NO
YES
NO
| 0.557692 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-06-27T21:04:06 | 2016-12-08T14:20:50 | setter | ###C++
```cpp
#include <iostream>
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 | 2,535 | 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 <code>a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup></code> 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_ ≤ 10<sup>18</sup>
**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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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
<sub>**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).
</sub> | 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 | null | null | null | 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 <code>a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup></code> 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_ ≤ 10<sup>18</sup>
**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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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
<sub>**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).
</sub> | 0.478723 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-06-28T17:37:26 | 2016-12-02T06:26:04 | setter | #include<stdio.h>
#include<assert.h>
#include<string.h>
#include<vector>
#include<algorithm>
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 ( index<MaxVal){
tree[index] = tree[index] + val;
index = (index + (index&(-index)));
}
}
void UPDATE(ll a,ll g,int x,int y)
{
if(x>y) 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<int> 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<<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];
}
int lca(int p,int q)
{
int temp;
if(depth[p]<depth[q]) return 1;
int steps=store[depth[p]];
for(int i=steps;i>=0;i--)
if(depth[p]-(1<<i) >= 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<int>::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 | 2,535 | 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 <code>a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup></code> 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_ ≤ 10<sup>18</sup>
**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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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
<sub>**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).
</sub> | 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 | null | null | null | 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 <code>a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup></code> 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_ ≤ 10<sup>18</sup>
**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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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 a<sup>b</sup> + (a+1)<sup>b</sup> + (b+1)<sup>a</sup> = 2<sup>2</sup> + 3<sup>2</sup> + 3<sup>2</sup> = 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
<sub>**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).
</sub> | 0.478723 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-06-28T17:37:26 | 2016-12-02T06:26:04 | tester | #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 vector<int> VI;
typedef vector<LL> VL;
typedef vector<PII> 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<<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 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 A, class B> ostream& operator<<(ostream &o, pair<A, B> t) {o << "(" << t.x << ", " << t.y << ")"; return o;}
template<class T> void PV(T a, T b) {while(a != b)cout << *a++, cout << (a != b ? "\n" : "\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;}
const int inf = 0x3f3f3f3f;
const long long linf = 0x3f3f3f3f3f3f3f3fLL;
const int mod = int(1e9) + 7;
const int N = 111111;
template <class T>
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<int> 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<int> 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<int> 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<int, int> 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 | 2,141 | 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 i<sup>th</sup> line contains two space separated numbers T<sub>i</sub> and L<sub>i</sub>. T<sub>i</sub> is the time when i<sup>th</sup> customer order a pizza, and L<sub>i</sub> is the time required to cook that pizza.
**Output Format**
* Display the integer part of the minimum average waiting time.
**Constraints**
* 1 ≤ N ≤ 10<sup>5</sup>
* 0 ≤ T<sub>i</sub> ≤ 10<sup>9</sup>
* 1 ≤ L<sub>i</sub> ≤ 10<sup>9</sup>
**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 i<sup>th</sup> line contains two space separated numbers T<sub>i</sub> and L<sub>i</sub>. T<sub>i</sub> is the time when i<sup>th</sup> customer order a pizza, and L<sub>i</sub> 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 ≤ 10<sup>5</sup>
* 0 ≤ T<sub>i</sub> ≤ 10<sup>9</sup>
* 1 ≤ L<sub>i</sub> ≤ 10<sup>9</sup>
**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.418269 | ["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 | null | null | null | null | null | null | 2014-06-30T16:02:37 | 2016-12-02T02:59:41 | setter | /*
Solution: pick the order that takes shortest time to cook.
*/
#include <cstdio>
#include <iostream>
#include <fstream>
#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>
#include <climits>
#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
using namespace std;
#define maxn 100111
int n;
pair<int, int> order[maxn];
multiset<pair<int, int> > 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<int, int> 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 | 2,141 | 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 i<sup>th</sup> line contains two space separated numbers T<sub>i</sub> and L<sub>i</sub>. T<sub>i</sub> is the time when i<sup>th</sup> customer order a pizza, and L<sub>i</sub> is the time required to cook that pizza.
**Output Format**
* Display the integer part of the minimum average waiting time.
**Constraints**
* 1 ≤ N ≤ 10<sup>5</sup>
* 0 ≤ T<sub>i</sub> ≤ 10<sup>9</sup>
* 1 ≤ L<sub>i</sub> ≤ 10<sup>9</sup>
**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 i<sup>th</sup> line contains two space separated numbers T<sub>i</sub> and L<sub>i</sub>. T<sub>i</sub> is the time when i<sup>th</sup> customer order a pizza, and L<sub>i</sub> 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 ≤ 10<sup>5</sup>
* 0 ≤ T<sub>i</sub> ≤ 10<sup>9</sup>
* 1 ≤ L<sub>i</sub> ≤ 10<sup>9</sup>
**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.418269 | ["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 | null | null | null | null | null | null | 2014-06-30T16:02:37 | 2016-12-02T02:59:41 | tester | #include<bits/stdc++.h>
#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<n; i++)
{
cin >> 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<n)
{
while(i<n && ar[i].F<=cur)
{
mheap.push(mp(ar[i].S,ar[i].F));
i++;
}
if(mheap.empty() && i<n)
{
cur=ar[i].F;
mheap.push(mp(ar[i].S,ar[i].F));
i++;
}
pair < int, int > 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 | 3,090 | 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 | null | null | null | <img src="https://s3.amazonaws.com/hr-challenge-images/3090/1472582116-bf126e51f6-lunctimesurprise.jpg" title="lunctimesurprise.jpg" />
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 | null | null | null | null | null | null | 2014-06-30T17:14:35 | 2016-12-13T12:55:58 | setter | #include <stdio.h>
#include <stdlib.h>
#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 | 3,090 | 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 | null | null | null | <img src="https://s3.amazonaws.com/hr-challenge-images/3090/1472582116-bf126e51f6-lunctimesurprise.jpg" title="lunctimesurprise.jpg" />
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 | null | null | null | null | null | null | 2014-06-30T17:14:35 | 2016-12-13T12:55:58 | tester | #include <cstdio>
#include <cstring>
#include <string>
#include <cassert>
#include <cctype>
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 | 2,534 | 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.572165 | ["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 | null | null | null | null | null | null | 2014-07-01T08:20:40 | 2016-12-06T00:10:42 | setter | ###C++
```cpp
#include<bits/stdc++.h>
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 pdn(n) printf("%d\n",n)
#define sl(n) scanf("%lld",&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 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 | 2,461 | 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 | null | null | null | 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.465753 | ["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 | null | null | null | null | null | null | 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<n) 2^(k-1)/(k+1)
p2 = 0.5
for i in xrange(1,LIM):
S[i] = S[i-1] + p2/i
p2 *= 2
def bit_length(n):
''' Length of the binary representation of n '''
return len(bin(n)[2:])
def bit_count(n):
''' Number of 1 bits of n '''
return sum(map(int, bin(n)[2:]))
def bit_sum(n):
''' sum of bit_count(k) for 0<=k<n '''
return b1(n, bit_count(n)) + b2(n)
def b1(n,b):
if n == 0: return 0
if n & 1: return b1(n-1, b-1) + b-1
return b1(n>>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 | 2,619 | 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 ≤ 10<sup>5</sup>
1 ≤ M ≤ 10<sup>14</sup>
1 ≤ elements of the array ≤ 10<sup>18</sup>
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]$. | <pre>
STDIN Function
----- --------
1 q = 1
5 7 a[] size n = 5, m = 7
3 3 9 9 5
</pre> | 6 | Hard | null | null | null | null | null | null | 2014-07-01T08:52:28 | 2018-06-06T20:37:56 | setter | ###C++
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
void solve()
{
ll N,M;
ll x,prefix=0,maxim=0;
cin>>N>>M;
set<ll> S;
S.insert(0);
for(int i=1;i<=N;i++){
cin>>x;
prefix = (prefix + x)%M;
maxim = max(maxim,prefix);
set<ll>::iterator it = S.lower_bound(prefix+1);
if( it != S.end() ){
maxim = max(maxim,prefix - (*it) + M );
}
S.insert(prefix);
}
cout<<maxim<<endl;
}
int main()
{
int T;
scanf("%d",&T);
while(T--) solve();
return 0;
}
```
| not-set | 2016-04-24T02:02:47 | 2016-07-23T13:35:09 | C++ |
|
114 | 2,596 | order-of-prime-in-factorial | Order of Prime in Factorial | [Download Pdf version](https://hr-filepicker.s3.amazonaws.com/infinitum-jul14/2596-order-of-prime-in-factorial.pdf)
For a given prime $p$, define $\operatorname{ord}_p(k)$ as the multiplicity of $p$ in $k$, i.e. the number of times $p$ appears in the prime factorization of $k$.
For a given $p$ (prime) and $L$, let $F(p,L)$ be the number of integers $n$ such that $1 \le n \le L$ and $\operatorname{ord}_p(n!)$ is divisible by $p$. Here $n!$ denotes the factorial of $n$.
Your job is to calculate $F(p,L)$ given $p$ and $L$.
**Input Format**
The first line contains the number of test cases $T$.
Each of the next $T$ lines contains two integers $p$ and $L$ separated by a space.
**Output Format**
For each test case, output one line containing $F(p,L)$.
**Constraints**
$1 \le T \le 100000$
$2 \le p \le 10^{18}$
$1 \le L \le 10^{18}$
$p$ is prime
**Sample input**
2
2 6
3 6
**Sample Output**
2
2
**Explanation**
Here are the first 6 factorials: 1, 2, 6, 24, 120, 720.
The multiplicities of 2 in these numbers are: 0, 1, 1, 3, 3, 4.
Exactly two of these are divisible by 2 (0 and 4), so $F(2,6) = 2$.
The multiplicities of 3 in these numbers are: 0, 0, 1, 1, 1, 2.
Exactly two of these are divisible by 3 (0 and 0), so $F(3,6) = 2$.
| code | How many factorials have order divisible by that prime? | ai | 2014-06-11T18:24:21 | 2022-09-02T09:54:46 | #
# Complete the 'solve' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
# 1. LONG_INTEGER p
# 2. LONG_INTEGER l
#
def solve(p, l):
# 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()
p = int(first_multiple_input[0])
l = int(first_multiple_input[1])
result = solve(p, l)
fptr.write(str(result) + '\n')
fptr.close()
| For a given prime $p$, define $\operatorname{ord}_p(k)$ as the multiplicity of $p$ in $k$, i.e. the number of times $p$ appears in the prime factorization of $k$.
For a given $p$ (prime) and $L$, let $F(p,L)$ be the number of integers $n$ such that $1 \le n \le L$ and $\operatorname{ord}_p(n!)$ is divisible by $p$. Here $n!$ denotes the factorial of $n$.
Your job is to calculate $F(p,L)$ given $p$ and $L$.
**Input Format**
The first line contains the number of test cases $T$.
Each of the next $T$ lines contains two integers $p$ and $L$ separated by a space.
**Output Format**
For each test case, output one line containing $F(p,L)$.
**Constraints**
$1 \le T \le 100000$
$2 \le p \le 10^{18}$
$1 \le L \le 10^{18}$
$p$ is prime
**Sample input**
2
2 6
3 6
**Sample Output**
2
2
**Explanation**
Here are the first 6 factorials: 1, 2, 6, 24, 120, 720.
The multiplicities of 2 in these numbers are: 0, 1, 1, 3, 3, 4.
Exactly two of these are divisible by 2 (0 and 4), so $F(2,6) = 2$.
The multiplicities of 3 in these numbers are: 0, 0, 1, 1, 1, 2.
Exactly two of these are divisible by 3 (0 and 0), so $F(3,6) = 2$.
| 0.575 | ["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 | null | null | null | null | null | null | 2014-07-01T09:00:54 | 2016-12-08T11:22:20 | setter | ###Python 2
```python
def S(p,n):
return 0 if n == 0 else (n%p) + S(p,n/p)
def G(p,L):
Q,R = divmod(L,p)
return Q + ((-S(p,Q)) % p < R)
def F_(p,L):
Q,R = divmod(L,p)
return p*G(p,Q) + R*(S(p,Q) % p == 0)
def F(p,L):
return F_(p,L+1) - 1
for cas in xrange(input()):
p,L = map(int, raw_input().strip().split())
print F(p,L)
```
| not-set | 2016-04-24T02:02:47 | 2016-07-23T18:19:32 | Python |
||||
115 | 3,193 | 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. <br>
The salary given to the person i follows this formula: <br>
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.<br><br>
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.<br>
If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees?
__Input Format__ <br>
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__ <br>
For each test case, output the minimum total salary Baba'ee has to pay to the employees?
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 10<sup>5</sup> <br>
1 ≤ extra[i] ≤ 10<sup>6</sup> <br>
__Sample Input__ <br>
1
3
1 1
7 12 13
__Sample Output__ <br>
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 | null | null | null | 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. <br>
The salary given to the person i follows this formula: <br>
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.<br><br>
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.<br>
If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees?
__Input Format__ <br>
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__ <br>
For each test case, output the minimum total salary Baba'ee has to pay to the employees?
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 10<sup>5</sup> <br>
1 ≤ extra[i] ≤ 10<sup>6</sup> <br>
__Sample Input__ <br>
1
3
1 1
7 12 13
__Sample Output__ <br>
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-02T09:06:45 | 2017-01-02T06:15:11 | setter | #include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
typedef long long ll;
const ll N = 100000+10;
ll extra[N];
ll depth[N];
vector <int> adj[N];
queue <int> 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<int>());
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 | 3,193 | 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. <br>
The salary given to the person i follows this formula: <br>
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.<br><br>
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.<br>
If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees?
__Input Format__ <br>
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__ <br>
For each test case, output the minimum total salary Baba'ee has to pay to the employees?
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 10<sup>5</sup> <br>
1 ≤ extra[i] ≤ 10<sup>6</sup> <br>
__Sample Input__ <br>
1
3
1 1
7 12 13
__Sample Output__ <br>
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 | null | null | null | 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. <br>
The salary given to the person i follows this formula: <br>
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.<br><br>
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.<br>
If Baba'ee makes the swaps optimally, what is the minimum total salary Baba'ee has to pay to the employees?
__Input Format__ <br>
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__ <br>
For each test case, output the minimum total salary Baba'ee has to pay to the employees?
__Constraints__ <br>
1 ≤ T ≤ 20 <br>
1 ≤ n ≤ 10<sup>5</sup> <br>
1 ≤ extra[i] ≤ 10<sup>6</sup> <br>
__Sample Input__ <br>
1
3
1 1
7 12 13
__Sample Output__ <br>
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-02T09:06:45 | 2017-01-02T06:15:11 | tester | #include<bits/stdc++.h>
using namespace std;
int main()
{
int t, n, temp;
cin >> t;
map<int, int> parent;
map<int, int> height;
map<int, int> height_count;
vector<int> 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 | 3,200 | 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 | null | null | null | **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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<j;k++)
dp[i][j] = min(dp[i][k] + dp[i][j-k],dp[i][j]);
for(int k = 1;k<i;k++)
dp[i][j] = min(dp[k][j] + dp[i-k][j],dp[i][j]);
}
dp[j][i] = dp[i][j];
}
}
}
int main() {
int tt;
precalc();
cin>>tt;
while(tt--)
{
cin>>n>>m;
cout<<dp[n][m]<<endl;
}
return 0;
} | not-set | 2016-04-24T02:02:47 | 2016-04-24T02:02:47 | C++ |
118 | 3,200 | 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 | null | null | null | **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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-03T01:38:40 | 2017-04-12T09:10:12 | tester | #include<bits/stdc++.h>
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 | 3,215 | crazy-country | Crazy country | <p>
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.
</p>
<br>Input format</br>
<br>
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.
</br>
<br>Output format</br>
<br>
For every '2' query output one line containing the closer city to the capital in the path between the two cities provided.
</br>
<br>Sample input</br>
<br>10
<br>1 8
<br>8 9
<br>9 4
<br>4 2
<br>9 5
<br>9 6
<br>6 7
<br>6 10
<br>10 3
<br>6
<br>1 5
<br>2 10 1
<br>1 4
<br>1 8
<br>1 10
<br>2 7 10
</br>
<br>Sample output</br>
<br>9
<br>10 | code | Can you solve this queries? | ai | 2014-07-04T20:45:41 | 2016-09-09T09:47:40 | null | null | null | <p>
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.
</p>
<br>Input format</br>
<br>
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.
</br>
<br>Output format</br>
<br>
For every '2' query output one line containing the closer city to the capital in the path between the two cities provided.
</br>
<br>Sample input</br>
<br>10
<br>1 8
<br>8 9
<br>9 4
<br>4 2
<br>9 5
<br>9 6
<br>6 7
<br>6 10
<br>10 3
<br>6
<br>1 5
<br>2 10 1
<br>1 4
<br>1 8
<br>1 10
<br>2 7 10
</br>
<br>Sample output</br>
<br>9
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-04T20:46:40 | 2016-05-13T00:00:36 | setter | <pre>
#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <queue>
#include <cctype>
#include <climits>
#include <complex>
#include <set>
#include <stack>
#include <map>
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<n;i++) {
int u,v;
scanf("%d%d", &u, &v);
link(tree[u], tree[v]);
}
scanf("%d", &q);
evert(tree[1]);
while(q--) {
scanf("%d", &op);
if(op == 1) {
scanf("%d", &a);
evert(tree[a]);
} else {
scanf("%d%d", &a, &b);
printf("%d\n", lca(tree[a], tree[b]));
}
}
return 0;
}
</pre> | not-set | 2016-04-24T02:02:48 | 2016-04-24T02:02:48 | C++ |
120 | 3,232 | 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 | null | null | null | 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 | null | null | null | null | null | null | 2014-07-06T14:03:58 | 2016-05-13T00:00:34 | setter | #include<bits/stdc++.h>
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 pdn(n) printf("%d\n",n)
#define sl(n) scanf("%lld",&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 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<n; i++)
cin >> arr[i];
prntl[0]=INF;
prntr[n-1]=INF;
for(i=1; i<n; i++)
{
if(arr[i]<=arr[i-1])prntl[i]=i-1;
else
{
j=prntl[i-1];
while(1)
{
if(j==INF || arr[j]>=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; i<n; i++)
{
if(prntl[i]==INF)p=i+1;
else p=i-prntl[i];
if(prntr[i]==INF)q=n-i;
else q=prntr[i]-i;
ans += (LL)p*(LL)q;
}
cout << ans << endl;
}
return 0;
}
| not-set | 2016-04-24T02:02:48 | 2016-04-24T02:02:48 | C++ |
||||
121 | 3,242 | savita-and-friends | Savita And Friends | 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$'<sup>th</sup> 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$<sup>th</sup> 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$'<sup>th</sup> 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$<sup>th</sup> 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 | null | null | null | null | null | null | 2014-07-08T10:47:24 | 2016-12-02T16:44:29 | tester | ###C++
```cpp
#include<bits/stdc++.h>
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<PII> VPII;
typedef vector<LL> VI;
const LL INF = 1000000000000000000ll;
vector<PII> edges[100009];
VI dijk(int N, int s)
{
priority_queue<PII, vector<PII>, greater<PII> > 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<PII>::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<M; i++)
{
scanf("%lld %lld %lld",&a,&b,&c);
a--,b--;
edges[a].push_back(make_pair(c,b));
edges[b].push_back(make_pair(c,a));
if(i==K-1)
s1=a,s2=b,l=c;
}
vector < LL > dist1=dijk(N,s1);
vector < LL > dist2=dijk(N,s2);
/* for(int i=0; i<N; i++)
printf("%lld ",dist1[i]);
cout << endl;
for(int i=0; i<N; i++)
printf("%lld ",dist2[i]);
cout << endl;*/
VPII fin;
for(int i=0; i<N; i++)
fin.pb(mp(dist1[i],dist2[i]));
sort(fin.begin(),fin.end());
LL prevx=-1,prevy=-1;
VPII w;
for(int i=N-1; 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; i<P-1; i++)
{
double tmp = (w[i].second - w[i+1].first + l) / 2.0;
double val= w[i+1].first+tmp;
if(val<ans)ans=val,finans=tmp;
else if(val==ans)finans=min(finans,tmp);
}
printf("%.5lf %.5lf\n",(double)finans,(double)ans);
}
return 0;
}
```
| not-set | 2016-04-24T02:02:49 | 2016-07-23T14:07:21 | C++ |
122 | 2,517 | 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).

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* <= 10<sup>9</sup>
min(_M, N_) % 2 == 0
1 <= _a<sub>ij</sub>_ <= 10<sup>8</sup>, 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 | null | null | null | <sup><strong>[Here](https://www.hackerrank.com/challenges/matrix-rotation-algo) is the non-FP version of this challenge, with all languages enabled.</strong></sup>
---
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).

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* <= 10<sup>9</sup>
min(_M, N_) % 2 == 0
1 <= _a<sub>ij</sub>_ <= 10<sup>8</sup>, 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 | null | null | null | null | null | null | 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 | 2,517 | 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).

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* <= 10<sup>9</sup>
min(_M, N_) % 2 == 0
1 <= _a<sub>ij</sub>_ <= 10<sup>8</sup>, 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 | null | null | null | <sup><strong>[Here](https://www.hackerrank.com/challenges/matrix-rotation-algo) is the non-FP version of this challenge, with all languages enabled.</strong></sup>
---
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).

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* <= 10<sup>9</sup>
min(_M, N_) % 2 == 0
1 <= _a<sub>ij</sub>_ <= 10<sup>8</sup>, 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 | null | null | null | null | null | null | 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 | 3,244 | 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.
<b>Input format</b>
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
<br>5 5
<br>1 4 5 1
<br>1 5 5 2
<br>2 2 5
<br>1 5 5 1
<br>2 5 5
Sample output
<br>6
<br>4
| code | Can you solve this queries? | ai | 2014-07-09T02:01:17 | 2016-09-09T09:47:48 | null | null | null | 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.
<b>Input format</b>
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
<br>5 5
<br>1 4 5 1
<br>1 5 5 2
<br>2 2 5
<br>1 5 5 1
<br>2 5 5
Sample output
<br>6
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-09T02:01:31 | 2016-05-13T00:00:13 | setter | <pre>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#include <cmath>
#include <set>
#include <cassert>
#include <algorithm>
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 | 3,259 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-11T18:59:43 | 2016-05-13T00:00:06 | setter | <pre>
#include<iostream>
#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<int> ady[MAXV];
int D[MAXV1], Mx[MAXV], My[MAXV];
bool BFS() {
int u, v, i, e;
queue<int> 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<double, pair<double, double> > cubes[1005];
pair<double, double> holes[1005];
int main() {
scanf("%d%d", &N, &M);
assert(N > 0 && N <= 1000 && M > 0 && M <= 1000);
for(int i = 0;i<N;i++) {
scanf("%lf%lf%lf", &x, &y, &z);
assert(x>0 && x <= 10 && y>0 && y <= 10 && z>0 && z <= 10);
cubes[i] = make_pair(x, make_pair(y,z));
}
for(int i = 0;i<M;i++) {
scanf("%lf%lf", &x, &y);
assert(x>0 && x <= 10 && y>0 && y <= 10);
holes[i] = make_pair(x,y);
}
for(int i = 0;i<N;i++)
for(int j = 0;j<M;j++)
if(check(cubes[i].first,cubes[i].second.first,cubes[i].second.second, holes[j].first, holes[j].second)) {
ady[i].push_back(j);
}
printf("%d\n", hopcroft_karp());
return 0;
} | not-set | 2016-04-24T02:02:50 | 2016-04-24T02:02:50 | C++ |
126 | 3,262 | two-pictures | Two pictures | 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**
<br>3 3
<br>1 2 3
<br>4 5 6
<br>7 8 9
<br>2 2
<br>2 1
<br>3 4
**Sample output**
<br>1 1 4 | code | Just match the pictures!! | ai | 2014-07-12T02:40:46 | 2016-09-09T09:47:54 | null | null | null | 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**
<br>3 3
<br>1 2 3
<br>4 5 6
<br>7 8 9
<br>2 2
<br>2 1
<br>3 4
**Sample output**
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-12T02:40:55 | 2016-05-13T00:00:04 | setter | <pre>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <queue>
#include <cmath>
#include <set>
#include <map>
#include <stack>
#include <cassert>
#include <algorithm>
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;i<R;i++)
for(int j = 0;j<C;j++) {
scanf("%d", &F[i][j]);
A[i * C + j].x = F[i][j];
SumSumF[i+1][j+1] = F[i][j] * F[i][j];
SumSumF[i+1][j+1] += SumSumF[i][j+1] + SumSumF[i+1][j] - SumSumF[i][j];
}
scanf("%d%d", &H, &W);
for(int i = 0;i<H;i++)
for(int j = 0;j<W;j++) {
scanf("%d", &Pa[i][j]);
B[i * C + j].x = Pa[i][j];
SumSumP += Pa[i][j] * Pa[i][j];
}
int nn = 1;
while((1<<nn) <= R * C) ++nn;
nn = 1<<nn;
fft(A, nn, false);
fft(B, nn, false);
for(int i = 0;i<nn;i++)
A[i] = A[i] * B[-i & (nn-1)];
fft(A, nn, true);
for(int i = 0;i<R-H+1;i++)
for(int j = 0;j<C-W+1;j++) {
score = SumSumP;
score += SumSumF[i+H][j+W] - SumSumF[i][j+W] - SumSumF[i+H][j] + SumSumF[i][j];
score -= 2 * correct(A[ i * C + j ].x);
if(score < sol) {
sol = score;
rs = i + 1;
cs = j + 1;
}
}
printf("%d %d %lld\n", rs, cs, sol);
return 0;
} | not-set | 2016-04-24T02:02:50 | 2016-04-24T02:02:50 | C++ |
127 | 3,269 | gneck | Girlfriend & Necklace | 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 ≤ 10<sup>4</sup>
2 ≤ N ≤ 10<sup>18</sup>
**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 10<sup>9</sup>+7, print the answer modulo ( % ) 10<sup>9</sup>+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 | null | null | null | 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 ≤ 10<sup>4</sup>
2 ≤ N ≤ 10<sup>18</sup>
**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 10<sup>9</sup>+7, print the answer modulo ( % ) 10<sup>9</sup>+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.591837 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-14T09:08:57 | 2016-12-05T16:43:28 | setter | ###C++
```cpp
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<cstdio>
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"<<endl;
else
cout<<func(N+2)<<endl;
}
return 0;
}
```
| not-set | 2016-04-24T02:02:50 | 2016-07-23T18:59:09 | C++ |
128 | 3,269 | gneck | Girlfriend & Necklace | 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 ≤ 10<sup>4</sup>
2 ≤ N ≤ 10<sup>18</sup>
**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 10<sup>9</sup>+7, print the answer modulo ( % ) 10<sup>9</sup>+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 | null | null | null | 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 ≤ 10<sup>4</sup>
2 ≤ N ≤ 10<sup>18</sup>
**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 10<sup>9</sup>+7, print the answer modulo ( % ) 10<sup>9</sup>+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.591837 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-14T09:08:57 | 2016-12-05T16:43:28 | tester | ###C++
```cpp
#include<bits/stdc++.h>
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 | 3,081 | 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.594595 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-18T17:51:42 | 2016-12-05T11:56:17 | setter | ###C++
```cpp
/*******************
Akash Agrawall
IIIT HYDERABAD
akash.agrawall094@gmail.com
***********************/
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<math.h>
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<int> v;rep(i,n){ int j;si(j);v.pb(j);}
#define mod (int)(1e9 + 7)
int isprime[1000006];
vector<int> 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 | 3,327 | 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.<br>
Second line will contain N (total number of rooms) and K(maximum sum IQ level that director can take)<br>
Third line will contain number N numbers 'ai' that will be IQ level of students in ith room<br>
__CONSTRAINTS__
1<=t<=10<br>
1<=N<=100000<br>
-10^15<=K<=10^15<br>
-10^9<=ai<=10^9<br>
__OUTPUT__
Single integer per line denoting the maximum IQ level sum that director can pick according to condition.
__Sample Input__<br>
2<br>
6 8<br>
3 -2 1 3 2 0<br>
8 -3<br>
-1 0 -2 -2 3 4 5 1<br>
__OUTPUT__<br>
7<br>
-4<br>
###Explanation<br>
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 | null | null | null | 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.<br>
Second line will contain N (total number of rooms) and K(maximum sum IQ level that director can take)<br>
Third line will contain number N numbers 'ai' that will be IQ level of students in ith room<br>
__CONSTRAINTS__
1<=t<=10<br>
1<=N<=100000<br>
-10^15<=K<=10^15<br>
-10^9<=ai<=10^9<br>
__OUTPUT__
Single integer per line denoting the maximum IQ level sum that director can pick according to condition.
__Sample Input__<br>
2<br>
6 8<br>
3 -2 1 3 2 0<br>
8 -3<br>
-1 0 -2 -2 3 4 5 1<br>
__OUTPUT__<br>
7<br>
-4<br>
###Explanation<br>
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-19T13:59:27 | 2016-05-12T23:59:43 | setter | #include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<set>
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<n;i++)
cin>>a[i];
set<long long int> myset;
myset.clear();
myset.insert(0);
for(i=0;i<n;i++)
{
cum=cum+a[i];
set<long long int>::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<<endl;
else
cout<<maxi<<endl;
}
return 0;
} | not-set | 2016-04-24T02:02:52 | 2016-04-24T02:02:52 | C++ |
131 | 3,334 | little-chammys-huge-donation | Little Ashish's Huge Donation | Little Ashish is doing internship at multiple places. Instead of giving parties to his friends he decided to donate candies to children. He likes solving puzzles and playing games. Hence he plays a small game. Suppose there are $N$ children. The rules of the game are:
1. The $i^{th}$ child gets $i^{2}$ candies ($1 \le i \le N$).
2. The $y^{th}$ child cannot get a candy until and unless all the children before him ($1 \le i \lt y$) gets candies according to rule number $1$.
One of his jealous friends, Pipi, asks him "Given $X$ (the number of candies) how many children will you be able to serve?". Little Ashish fears calculations and cannot solve this problem so he leaves this problem to the worthy programmers of the world. Help little Ashish in finding the solution.
**Input Format**
The first line contains $T$ i.e. number of test cases.
$T$ lines follow, each line containing an integer $X$.
**Output Format**
For each testcase, print the output that little Ashish wants in one line.
**Constraints**
$1 \le T \le 10000$
$1 \le X \le 10^{16}$
**Note: If the $i^{th}$ child doesn't get $i^{2}$ number of candies then it's not counted as a successful donation**
**Sample Input**
3
1
5
13
**Sample Output**
1
2
2
**Explanation**
1. For $X = 1$. Only the $1^{st}$ child can get the candy (i.e. $1^{2}$ candy) and no other child.
2. For $X = 5$. Both the $1^{st}$($1^{2}$ candies) and the $2^{nd}$($2^{2}$ candies) children can get the candies.
3. For $X = 13$. Since the $3^{rd}$ child will get only 8 candies following the rule it won't be counted as a successful donation. Only the $1^{st}$ and the $2^{nd}$ children can get 1 and 4 candies respectively.
| code | Help Ashish calculate donations. | ai | 2014-07-20T20:41:41 | 2022-09-02T09:54:30 | #
# 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()
| Little Ashish is doing internship at multiple places. Instead of giving parties to his friends he decided to donate candies to children. He likes solving puzzles and playing games. Hence he plays a small game. Suppose there are $N$ children. The rules of the game are:
1. The $i^{th}$ child gets $i^{2}$ candies ($1 \le i \le N$).
2. The $y^{th}$ child cannot get a candy until and unless all the children before him ($1 \le i \lt y$) gets candies according to rule number $1$.
One of his jealous friends, Pipi, asks him "Given $X$ (the number of candies) how many children will you be able to serve?". Little Ashish fears calculations and cannot solve this problem so he leaves this problem to the worthy programmers of the world. Help little Ashish in finding the solution.
**Input Format**
The first line contains $T$ i.e. number of test cases.
$T$ lines follow, each line containing an integer $X$.
**Output Format**
For each testcase, print the output that little Ashish wants in one line.
**Constraints**
$1 \le T \le 10000$
$1 \le X \le 10^{16}$
**Note: If the $i^{th}$ child doesn't get $i^{2}$ number of candies then it's not counted as a successful donation**
**Sample Input**
3
1
5
13
**Sample Output**
1
2
2
**Explanation**
1. For $X = 1$. Only the $1^{st}$ child can get the candy (i.e. $1^{2}$ candy) and no other child.
2. For $X = 5$. Both the $1^{st}$($1^{2}$ candies) and the $2^{nd}$($2^{2}$ candies) children can get the candies.
3. For $X = 13$. Since the $3^{rd}$ child will get only 8 candies following the rule it won't be counted as a successful donation. Only the $1^{st}$ and the $2^{nd}$ children can get 1 and 4 candies respectively.
| 0.59622 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-20T20:41:56 | 2016-12-06T14:35:59 | setter | ###C++
```cpp
/*******************
Akash Agrawall
IIIT HYDERABAD
akash.agrawall094@gmail.com
***********************/
#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<stdio.h>
#include<math.h>
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<x)
{
low=mid+1;
}
else
high=mid-1;
}
}
return 0;
}
```
| not-set | 2016-04-24T02:02:52 | 2016-07-23T17:34:05 | C++ |
132 | 3,340 | value-of-all-permutations | Value of all Permutations | You are given an array $A$ of size $N$. You are asked to answer $Q$ queries.
Each query contains a number $M$.
For each *distinct* permutation of the array $A$, you need to print the sum of the values returned by the `find` function.
As the sum can be too large, output it modulo $P$, which is a prime and given in input.
find(int permutation_A[], int M)
{
x = Length(permutation_A)
sum = 0
for(i = 0; i < x; i++) {
if (permutation_A[i] <= M)
sum = sum + permutation_A[i]
else
break
}
return sum
}
**Input Format**
The first line of input contains $P$.
The second line of input contains $N$. The next line contains $N$ numbers $A[0] \ldots A[N-1]$ separated by single spaces.
The next line contains $Q$, the number of queries to follow. Each subsequent line contains one positive integer $M$.
**Output Format**
For each query, output as asked above.
**Constraints**
$1000000 \le P \le 2000003$
$1 \le N \le 10^5$
$1 \le Q \le 10^5$
$1 \le A[i], M \le 10^9$
**Sample Input**
2000003
5
4 2 3 1 4
2
1
2
**Sample Output**
12
45
**Explanation**
*Query 1*:
Consider all permutations. if the first number is greater than 1, then the loop will break in the beginning itself. There are a total of 60 distinct permutations out of which 48 will give 0. The remaining 12 will fetch 1 each from the function. Thus the answer is 12.
| code | For each distinct permutation of the array A, you need to print the sum of the values returned by the described function. | ai | 2014-07-21T17:27:10 | 2022-09-02T09:54:59 | null | null | null | You are given an array $A$ of size $N$. You are asked to answer $Q$ queries.
Each query contains a number $M$.
For each *distinct* permutation of the array $A$, you need to print the sum of the values returned by the `find` function.
As the sum can be too large, output it modulo $P$, which is a prime and given in input.
find(int permutation_A[], int M)
{
x = Length(permutation_A)
sum = 0
for(i = 0; i < x; i++) {
if (permutation_A[i] <= M)
sum = sum + permutation_A[i]
else
break
}
return sum
}
**Input Format**
The first line of input contains $P$.
The second line of input contains $N$. The next line contains $N$ numbers $A[0] \ldots A[N-1]$ separated by single spaces.
The next line contains $Q$, the number of queries to follow. Each subsequent line contains one positive integer $M$.
**Output Format**
For each query, output as asked above.
**Constraints**
$1000000 \le P \le 2000003$
$1 \le N \le 10^5$
$1 \le Q \le 10^5$
$1 \le A[i], M \le 10^9$
**Sample Input**
2000003
5
4 2 3 1 4
2
1
2
**Sample Output**
12
45
**Explanation**
*Query 1*:
Consider all permutations. if the first number is greater than 1, then the loop will break in the beginning itself. There are a total of 60 distinct permutations out of which 48 will give 0. The remaining 12 will fetch 1 each from the function. Thus the answer is 12.
| 0.444444 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-21T17:56:07 | 2016-12-03T12:49:09 | setter | ###C++
```cpp
#include<stdio.h>
#include<iostream>
#include<vector>
#include<string>
#include<stdlib.h>
#include<algorithm>
#include<set>
#include<stack>
#include<queue>
#include<math.h>
#include<assert.h>
#include<utility>
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<size/2;k++){
even = output[k];
odd = output[k+size/2];
store = ((ll)var2*(ll)odd)%M;
output[k] = (even + store)%M;
output[k+size/2] = (even - store)%M; //same as even - store
if ( output[k+size/2] < 0 ) output[k+size/2] += M;
var2 = ((ll)var2*(ll)var1)%M;
}
}
ll CA[(1<<18)+1],CB[(1<<18)+1];
void multiply( ll A[] , ll B[] ,ll result[] ,int y)
{
integral_fft(A,CA,1,y,0);
integral_fft(B,CB,1,y,0);
ll inverse_of_y = powmod(y,M-2,M);
for(int i=0;i<y;i++) CA[i] = ( ( (CA[i]*CB[i])%M )*inverse_of_y )%M;
integral_fft(CA,result,1,y,0);
swap(result[0],result[y]);
reverse(result,result+y+1);
//for(int i=0;i<y;i++) printf("%d ",result[i]);
//complex_fft(CA,result,1,y,false);
}
void get_poly(ll A[] ,ll B[],ll N)
{
//A[i] = (N-i-1)! , B[i] = 1/i!
A[N-1] = 1;
for(int i=N-2;i>=0;i--) A[i] = (A[i+1]*(N-1-i))%M;
B[0]= 1;
for(int i=1;i<N;i++) B[i] = (B[i-1]*(ll)powmod(i,M-2,M))%M;
for(int i=N;i<(1<<18);i++) A[i]=B[i]=0;
}
ll poly1[1<<18],poly2[1<<18],result1[1<<18],result2[1<<18],fact[100001],result[1<<18];
ll mulmod (ll a,ll b , ll m )
{
ll ans = 0;
while( b)
{
if ( b&1){
ans = (ans + a);
if ( ans > 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<t;i++) M1 = M1*mod[i];
ll ans = 0;
for(int i=0;i<t;i++){
ans = (ans + mulmod(((rem[i]*powmod(M1/mod[i],mod[i]-2,mod[i]))%M1),(M1/mod[i]),M1) )%M1;
}
return ans;
}
void mixing()
{
for(int i=0;i<(1<<18);i++){
ll rem[] = { result1[i] , result2[i] };
ll mod[] = { mod0 , mod1 };
result[i] = CRT ( rem ,mod,2 )%M;
}
}
int main()
{
scanf("%lld",&modulo);
integral_fft_constant();
int t,n,x,index;
ll factor,constant_factor=1;
vector<int> A,B;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&x);
A.push_back(x);
}
sort(A.begin(),A.end());
B.push_back(A[0]%modulo);
for(int i=1;i<n;i++) B.push_back((B[i-1]+A[i])%modulo);
M = modulo;
get_poly(poly1,poly2,n);
flag = 0;
M = mod0;
multiply(poly1,poly2,result1,(1<<18));
flag = 1;
M = mod1;
multiply(poly1,poly2,result2,(1<<18));
M = modulo;
mixing();
fact[0]=1;
for(int i=1;i<=100000;i++) fact[i]=(fact[i-1]*(ll)i)%modulo;
factor= 0;
for(int i=0;i<A.size();i++){
if ( i+1==A.size() ){
factor++;
constant_factor = (constant_factor*fact[factor])%modulo;
break;
}
if ( A[i]!=A[i+1]){
factor++;
constant_factor = (constant_factor*fact[factor])%modulo;
factor=0;
}
else factor++;
}
constant_factor = powmod(constant_factor,M-2,M);
scanf("%d",&t);
while(t--){
scanf("%d",&x);
index = upper_bound(A.begin(),A.end(),x) - A.begin();
index--;
ll answer = (fact[index]*((ll)B[index]*(ll)result[index])%M)%M;
answer = (answer*constant_factor)%M;
printf("%lld\n",answer);
}
return 0;
}
```
| not-set | 2016-04-24T02:02:52 | 2016-07-23T18:42:05 | C++ |
133 | 3,340 | value-of-all-permutations | Value of all Permutations | You are given an array $A$ of size $N$. You are asked to answer $Q$ queries.
Each query contains a number $M$.
For each *distinct* permutation of the array $A$, you need to print the sum of the values returned by the `find` function.
As the sum can be too large, output it modulo $P$, which is a prime and given in input.
find(int permutation_A[], int M)
{
x = Length(permutation_A)
sum = 0
for(i = 0; i < x; i++) {
if (permutation_A[i] <= M)
sum = sum + permutation_A[i]
else
break
}
return sum
}
**Input Format**
The first line of input contains $P$.
The second line of input contains $N$. The next line contains $N$ numbers $A[0] \ldots A[N-1]$ separated by single spaces.
The next line contains $Q$, the number of queries to follow. Each subsequent line contains one positive integer $M$.
**Output Format**
For each query, output as asked above.
**Constraints**
$1000000 \le P \le 2000003$
$1 \le N \le 10^5$
$1 \le Q \le 10^5$
$1 \le A[i], M \le 10^9$
**Sample Input**
2000003
5
4 2 3 1 4
2
1
2
**Sample Output**
12
45
**Explanation**
*Query 1*:
Consider all permutations. if the first number is greater than 1, then the loop will break in the beginning itself. There are a total of 60 distinct permutations out of which 48 will give 0. The remaining 12 will fetch 1 each from the function. Thus the answer is 12.
| code | For each distinct permutation of the array A, you need to print the sum of the values returned by the described function. | ai | 2014-07-21T17:27:10 | 2022-09-02T09:54:59 | null | null | null | You are given an array $A$ of size $N$. You are asked to answer $Q$ queries.
Each query contains a number $M$.
For each *distinct* permutation of the array $A$, you need to print the sum of the values returned by the `find` function.
As the sum can be too large, output it modulo $P$, which is a prime and given in input.
find(int permutation_A[], int M)
{
x = Length(permutation_A)
sum = 0
for(i = 0; i < x; i++) {
if (permutation_A[i] <= M)
sum = sum + permutation_A[i]
else
break
}
return sum
}
**Input Format**
The first line of input contains $P$.
The second line of input contains $N$. The next line contains $N$ numbers $A[0] \ldots A[N-1]$ separated by single spaces.
The next line contains $Q$, the number of queries to follow. Each subsequent line contains one positive integer $M$.
**Output Format**
For each query, output as asked above.
**Constraints**
$1000000 \le P \le 2000003$
$1 \le N \le 10^5$
$1 \le Q \le 10^5$
$1 \le A[i], M \le 10^9$
**Sample Input**
2000003
5
4 2 3 1 4
2
1
2
**Sample Output**
12
45
**Explanation**
*Query 1*:
Consider all permutations. if the first number is greater than 1, then the loop will break in the beginning itself. There are a total of 60 distinct permutations out of which 48 will give 0. The remaining 12 will fetch 1 each from the function. Thus the answer is 12.
| 0.444444 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-21T17:56:07 | 2016-12-03T12:49:09 | tester | ###Python 2
```python
P = input()
# collect and sort A
N = input()
A = map(int, raw_input().strip().split())
A.sort()
# calculate partial sums S
S = [0]*(N+1)
for i in xrange(N):
S[i+1] = (S[i] + A[i]) % P
# inverses mod P
inv = [1]*(N+2)
for i in xrange(2,N+2):
inv[i] = -(P/i) * inv[P%i] % P
# calculate number of distinct permutations
perms = 1
count = 1
for i in xrange(1,N):
if A[i] != A[i-1]:
count = 0
count += 1
perms *= inv[count] * (i+1)
perms %= P
# process queries
Q = input()
for cas in xrange(Q):
M = input()
# binary search
h, i = -1, N
while i - h > 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 | 2,324 | 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.493976 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-29T10:04:09 | 2016-12-01T20:29:14 | setter | ###C++
```cpp
#include<bits/stdc++.h>
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<<func(n,m)<<endl;
}
return 0;
}
```
| not-set | 2016-04-24T02:02:53 | 2016-07-23T17:55:55 | C++ |
135 | 2,609 | emma-and-sum-of-products | Emma and sum of products | Emma is really fond of integers and loves playing with them. Her friends were jealous, and to test her, one of them gave her a problem.
Emma is given a list $A$ of $N$ integers and is asked a set of $Q$ queries. Each query is denoted by an integer $K$, for which you have to return the sum of product of all possible sublists having exactly $K$ elements.
Emma has got stuck in this problem and you being her best friend have decided to help her write a code to solve it. Since the answers can be very large, print the answers modulo $100003$.
**Input Format**
First line has an integer $N$, denoting the number of integers in list $A$. Next line contains $N$ space separated integers. The third line contains integer $Q$, and next $Q$ lines have a single integer $K$.
**Output Format**
For each of the queries, print the corresponding answer in a new line.
**NOTE** Sublist here refers to selecting $K$ elements from a list of $N$ elements. There will be $N \choose K$ ways to do that, it doesn't matter if two elements are same.
**Constraints**
$1 \le N \le 3\times10^4$
$1 \le A_i \le 10^5$
$1 \le Q \le N$
$1 \le K \le N$
**Sample Input #00**
3
1 2 3
2
1
2
**Sample Output #00**
6
11
**Sample Input #01**
3
1 2 2
1
2
**Sample Output #01**
8
**Explanation**
Sample #00:
For $K=1$ possible sublists are $\{1\},\{2\},\{3\}$ so answer is $1+2+3 = 6$.
For $K=2$ possible sublists are $\{1,2\},\{2,3\},\{3,1\}$ so answer is $(1\times2) + (2\times3) + (3\times1) = 2+6+3 = 11$.
Sample #01:
For $K=2$ possible sublists are $\{1,2\},\{2,2\},\{2,1\}$ so answer is $(1\times 2) + (2\times2) + (2\times 1) = 2+4+2 = 8$. | code | Help Emma find sum of product of all K size sublists. | ai | 2014-06-13T18:12:02 | 2022-09-02T09:55:12 | #
# Complete the 'solve' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER_ARRAY A
# 2. INTEGER_ARRAY queries
#
def solve(A, 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')
A_count = int(input().strip())
A = list(map(int, input().rstrip().split()))
queries_count = int(input().strip())
queries = []
for _ in range(queries_count):
queries_item = int(input().strip())
queries.append(queries_item)
result = solve(A, queries)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| Emma is really fond of integers and loves playing with them. Her friends were jealous, and to test her, one of them gave her a problem.
Emma is given a list $A$ of $N$ integers and is asked a set of $Q$ queries. Each query is denoted by an integer $K$, for which you have to return the sum of product of all possible sublists having exactly $K$ elements.
Emma has got stuck in this problem and you being her best friend have decided to help her write a code to solve it. Since the answers can be very large, print the answers modulo $100003$.
**Input Format**
First line has an integer $N$, denoting the number of integers in list $A$. Next line contains $N$ space separated integers. The third line contains integer $Q$, and next $Q$ lines have a single integer $K$.
**Output Format**
For each of the queries, print the corresponding answer in a new line.
**NOTE** Sublist here refers to selecting $K$ elements from a list of $N$ elements. There will be $N \choose K$ ways to do that, it doesn't matter if two elements are same.
**Constraints**
$1 \le N \le 3\times10^4$
$1 \le A_i \le 10^5$
$1 \le Q \le N$
$1 \le K \le N$
**Sample Input #00**
3
1 2 3
2
1
2
**Sample Output #00**
6
11
**Sample Input #01**
3
1 2 2
1
2
**Sample Output #01**
8
**Explanation**
Sample #00:
For $K=1$ possible sublists are $\{1\},\{2\},\{3\}$ so answer is $1+2+3 = 6$.
For $K=2$ possible sublists are $\{1,2\},\{2,3\},\{3,1\}$ so answer is $(1\times2) + (2\times3) + (3\times1) = 2+6+3 = 11$.
Sample #01:
For $K=2$ possible sublists are $\{1,2\},\{2,2\},\{2,1\}$ so answer is $(1\times 2) + (2\times2) + (2\times 1) = 2+4+2 = 8$. | 0.576923 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-29T13:34:12 | 2016-07-23T18:59:58 | setter | ###C++
```cpp
#include<iostream>
#include<vector>
#include<cmath>
#include<complex>
using namespace std;
#define PB push_back
const double PI = 4*atan(1);
typedef complex<double> base;
vector<base> 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<base> & a)
{
long long n = (long long) a.size();
if (n == 1) return;
long long half = n >> 1;
vector<base> even (half), odd (half);
for (int i=0, j=0; i<n; i+=2, ++j)
{
even[j] = a[i];
odd[j] = a[i+1];
}
fft (even), fft (odd);
for (int i=0, fact = FFT_N/n; i < half; ++i)
{
base twiddle = odd[i] * omega[i * fact] ;
a[i] = even[i] + twiddle;
a[i+half] = even[i] - twiddle;
}
}
void multiply (const vector<long long> & a, const vector<long long> & b, vector<long long> & res)
{
vector<base> 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<n; ++i)
fa[i] = conj( fa[i] * fb[i]);
fft (fa);
res.resize (n);
for (size_t i=0; i<n; ++i)
{
res[i] = (long long) (fa[i].real() / n + 0.5);
res[i]%=mod;
}
}
int main()
{
int t,n,i,p,l,k,q;
long long x;
vector<long long> inp,res;
vector<vector<long long> > calc[20];
cin>>n;
p=0;l=n;
for(i=0;i<n;i++)
{
inp.clear();
cin>>x;
inp.PB(1);
inp.PB(x);
calc[0].PB(inp);
}
while(l>1)
{
p++;
for(i=0;i<l/2;i++)
{
calc[p].PB(res);
multiply(calc[p-1][2*i],calc[p-1][2*i+1],calc[p][i]);
}
if(l%2)
calc[p].PB(calc[p-1][l-1]);
l=calc[p].size();
}
cin>>q;
while(q--)
{
cin>>k;
cout<<calc[p][0][k]<<endl;
}
return 0;
}
```
| not-set | 2016-04-24T02:02:53 | 2016-07-23T18:59:48 | C++ |
136 | 2,609 | emma-and-sum-of-products | Emma and sum of products | Emma is really fond of integers and loves playing with them. Her friends were jealous, and to test her, one of them gave her a problem.
Emma is given a list $A$ of $N$ integers and is asked a set of $Q$ queries. Each query is denoted by an integer $K$, for which you have to return the sum of product of all possible sublists having exactly $K$ elements.
Emma has got stuck in this problem and you being her best friend have decided to help her write a code to solve it. Since the answers can be very large, print the answers modulo $100003$.
**Input Format**
First line has an integer $N$, denoting the number of integers in list $A$. Next line contains $N$ space separated integers. The third line contains integer $Q$, and next $Q$ lines have a single integer $K$.
**Output Format**
For each of the queries, print the corresponding answer in a new line.
**NOTE** Sublist here refers to selecting $K$ elements from a list of $N$ elements. There will be $N \choose K$ ways to do that, it doesn't matter if two elements are same.
**Constraints**
$1 \le N \le 3\times10^4$
$1 \le A_i \le 10^5$
$1 \le Q \le N$
$1 \le K \le N$
**Sample Input #00**
3
1 2 3
2
1
2
**Sample Output #00**
6
11
**Sample Input #01**
3
1 2 2
1
2
**Sample Output #01**
8
**Explanation**
Sample #00:
For $K=1$ possible sublists are $\{1\},\{2\},\{3\}$ so answer is $1+2+3 = 6$.
For $K=2$ possible sublists are $\{1,2\},\{2,3\},\{3,1\}$ so answer is $(1\times2) + (2\times3) + (3\times1) = 2+6+3 = 11$.
Sample #01:
For $K=2$ possible sublists are $\{1,2\},\{2,2\},\{2,1\}$ so answer is $(1\times 2) + (2\times2) + (2\times 1) = 2+4+2 = 8$. | code | Help Emma find sum of product of all K size sublists. | ai | 2014-06-13T18:12:02 | 2022-09-02T09:55:12 | #
# Complete the 'solve' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
# 1. INTEGER_ARRAY A
# 2. INTEGER_ARRAY queries
#
def solve(A, 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')
A_count = int(input().strip())
A = list(map(int, input().rstrip().split()))
queries_count = int(input().strip())
queries = []
for _ in range(queries_count):
queries_item = int(input().strip())
queries.append(queries_item)
result = solve(A, queries)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
| Emma is really fond of integers and loves playing with them. Her friends were jealous, and to test her, one of them gave her a problem.
Emma is given a list $A$ of $N$ integers and is asked a set of $Q$ queries. Each query is denoted by an integer $K$, for which you have to return the sum of product of all possible sublists having exactly $K$ elements.
Emma has got stuck in this problem and you being her best friend have decided to help her write a code to solve it. Since the answers can be very large, print the answers modulo $100003$.
**Input Format**
First line has an integer $N$, denoting the number of integers in list $A$. Next line contains $N$ space separated integers. The third line contains integer $Q$, and next $Q$ lines have a single integer $K$.
**Output Format**
For each of the queries, print the corresponding answer in a new line.
**NOTE** Sublist here refers to selecting $K$ elements from a list of $N$ elements. There will be $N \choose K$ ways to do that, it doesn't matter if two elements are same.
**Constraints**
$1 \le N \le 3\times10^4$
$1 \le A_i \le 10^5$
$1 \le Q \le N$
$1 \le K \le N$
**Sample Input #00**
3
1 2 3
2
1
2
**Sample Output #00**
6
11
**Sample Input #01**
3
1 2 2
1
2
**Sample Output #01**
8
**Explanation**
Sample #00:
For $K=1$ possible sublists are $\{1\},\{2\},\{3\}$ so answer is $1+2+3 = 6$.
For $K=2$ possible sublists are $\{1,2\},\{2,3\},\{3,1\}$ so answer is $(1\times2) + (2\times3) + (3\times1) = 2+6+3 = 11$.
Sample #01:
For $K=2$ possible sublists are $\{1,2\},\{2,2\},\{2,1\}$ so answer is $(1\times 2) + (2\times2) + (2\times 1) = 2+4+2 = 8$. | 0.576923 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-07-29T13:34:12 | 2016-07-23T18:59:58 | tester | ###C++
```cpp
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#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 | 3,436 | 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 | null | null | null | **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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 3,437 | 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 | null | null | null | 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.545455 | ["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 | null | null | null | null | null | null | 2014-08-01T00:35:56 | 2016-07-23T14:07:35 | setter | ###C++
```cpp
#include<stdio.h>
#include<math.h>
#include<complex>
#include<iostream>
#include<queue>
#include<stack>
#include<algorithm>
#include<string.h>
#include<cstring>
#include<cassert>
#include<map>
#include<vector>
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(ini<end && level[dest]==-1)
{
u = Q[ini++];
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;
}
int DFS(int u,int auxflow)
{
int res,v;
if(u == dest) return auxflow;
for(int i = now[u];i!=-1;now[u] = i = next[i])
{
v = ady[i];
if(level[v]>level[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<cc;j++) {
scanf("%d", &v);
assert(v>= 1 && v <= n);
ADD(v, n + i, 1);
}
scanf("%d", &cc);
assert(cc >= 0 && cc <= 50);
for(int j = 0;j<cc;j++) {
scanf("%d", &v);
assert(v>= 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 | 3,465 | 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.
<br>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.
<br>0 < T <= 10^6
<br>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
<br>2
<br>1
###Sample Output:
1
<br>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.
<br>For the second case, there is no way Goku can satisfy the condition. No superpower for Goku. :( | code | null | ai | 2014-08-02T05:17:43 | 2016-09-09T09:48:54 | null | null | null | 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.
<br>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.
<br>0 < T <= 10^6
<br>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
<br>2
<br>1
###Sample Output:
1
<br>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.
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-02T05:19:44 | 2016-12-22T22:43:16 | setter | #include <cstdio>
#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 | 3,511 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 3,542 | 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 | null | ai | 2014-08-10T08:21:34 | 2016-09-09T09:49:21 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-10T08:36:09 | 2016-05-12T23:58:51 | setter |
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<bitset>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<stdio.h>
#include<queue>
#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<int,int> pii;
typedef vector<int> vec;
typedef vector<pii> 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;}
stack<pii>S;
int main(){
int n;
scanf("%d",&n);
ll ret = 0;
for(int i=0;i<n;++i){
int h;
scanf("%d",&h);
pii p(h,1);
for(;!S.empty() && S.top().first<=h;S.pop()){
ret += S.top().second;
if(S.top().first==h)p.second+=S.top().second;
}
if(!S.empty())++ret;
S.push(p);
}
cout<<ret<<endl;
return 0;
}
| not-set | 2016-04-24T02:02:55 | 2016-04-24T02:02:55 | C++ |
142 | 3,545 | kevin-and-expected-value-2 | Kevin and Expected Value 2 | When students solved the first problem quickly, Kevinsogo gave them a harder problem. Students need your help in solving this problem.<br>
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.<br>
Next $T$ lines contain an integer $N$.<br>
**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 | null | null | null | When students solved the first problem quickly, Kevinsogo gave them a harder problem. Students need your help in solving this problem.<br>
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.<br>
Next $T$ lines contain an integer $N$.<br>
**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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-10T20:06:54 | 2016-05-12T23:58:49 | tester | #include <math.h>
#include <stdio.h>
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 | 3,547 | 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.473684 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-11T10:39:05 | 2016-12-06T10:15:06 | setter | ###C++
```cpp
#include<bits/stdc++.h>
using namespace std;
pair <int,int> 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 | 3,547 | 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.473684 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 3,548 | 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 *i<sup>th</sup>* line contains $A[i]$, the value of Mehta's *i<sup>th</sup>* 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 *i<sup>th</sup>* line contains $A[i]$, the value of Mehta's *i<sup>th</sup>* 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.421053 | ["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 | null | null | null | null | null | null | 2014-08-11T11:00:18 | 2016-12-04T05:30:50 | setter | ###C++
```cpp
#include<bits/stdc++.h>
using namespace std;
pair<long long,int> 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<<N;
limit--;
for(int i = 1;i <= limit;i++)
{
long long lcm = 1;
pre[i].second = __builtin_popcount(i);
int k = 1;
for(int j = N-1;j>=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<<N;
limit--;
int Q;
cin >> 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 | 3,548 | 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 *i<sup>th</sup>* line contains $A[i]$, the value of Mehta's *i<sup>th</sup>* 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 *i<sup>th</sup>* line contains $A[i]$, the value of Mehta's *i<sup>th</sup>* 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.421053 | ["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 | null | null | null | null | null | null | 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<<n)
lcms = [1]*(1<<n)
for i in xrange(n):
a = input()
for j in xrange(1<<i):
lcms[(1<<i)|j] = lcm(a, lcms[j])
bitcount[(1<<i)|j] = bitcount[j] + 1
def count(k):
t = 0
for s in xrange(1,1<<n):
t -= k / lcms[s] * (-1)**bitcount[s]
return t
for i in xrange(input()):
l, r = map(int, raw_input().strip().split())
print count(r) - count(l-1)
```
| not-set | 2016-04-24T02:02:56 | 2016-07-23T18:32:46 | Python |
||||
147 | 3,585 | jim-and-his-lan-party | Jim and his LAN Party | 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$<sup>th</sup> 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: i<sup>th</sup> line denotes i<sup>th</sup> wire and is denoted by $u_i$ and $v_i$ pairs each separated by a single space.
**Output Format**
Print on the $i$<sup>th</sup> line the answer for the $i$<sup>th</sup> 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 3<sup>rd</sup> wire is added. The group with game 2 can play only after the 4<sup>th</sup> wire has been added because after adding the 4<sup>th</sup> 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$<sup>th</sup> 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: i<sup>th</sup> line denotes i<sup>th</sup> wire and is denoted by $u_i$ and $v_i$ pairs each separated by a single space.
| Print on the $i$<sup>th</sup> line the answer for the $i$<sup>th</sup> game.
| 5 2 4
1 2 2 2 1
1 2
2 3
1 5
4 5
| 3
4
| Hard | null | null | null | null | null | null | 2014-08-15T10:42:46 | 2016-12-02T11:12:23 | setter | ###C++
```cpp
#include <iostream>
#include <vector>
using namespace std;
#define SZ(x) ( (int) (x).size() )
const int MAX_N = 100000 + 1;
int N, M, Q;
int color[MAX_N];
vector<int> cpos[MAX_N];
vector<int> 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 | 3,666 | 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.592593 | ["c","clojure","cpp","cpp14","csharp","erlang","go","haskell","java","java8","javascript","kotlin","lua","objectivec","perl","php","pypy3","python3","ruby","scala","swift"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-17T03:33:24 | 2016-12-02T14:47:34 | setter | ###C++
```cpp
#include <iostream>
#include <vector>
#define pb push_back
using namespace std;
long long mod=1000000007;
vector<long long> 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<n;i++)
{
cin>>inp;
for(int i=0;i<fibo.size();i++)
{
if(fibo[i]>inp)
{
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<<ans<<endl;
return 0;
}
```
| not-set | 2016-04-24T02:02:57 | 2016-07-23T17:59:37 | C++ |
149 | 2,056 | pmix | Mixing proteins | Some scientists are working on protein recombination, and during their research, they have found a remarkable fact: there are 4 proteins in the protein ring that mutate after every second according to a fixed pattern. For simplicity, proteins are called $A, B, C, D$ (you know, protein names can be very complicated). A protein mutates into another one depending on itself and the protein right after it. Scientists determined that the mutation table goes like this:
A B C D
_ _ _ _
A| A B C D
B| B A D C
C| C D A B
D| D C B A
Here rows denote the protein at current position, while columns denote the protein at the next position. And the corresponding value in the table denotes the new protein that will emerge. So for example, **if protein i is A, and protein i + 1 is B, protein i will change to B**. All mutations take place simultaneously. The protein ring is seen as a circular list, so last protein of the list mutates depending on the first protein.
Using this data, they have written a small simulation software to get mutations second by second. The problem is that the protein rings can be very long (up to 1 million proteins in a single ring) and they want to know the state of the ring after upto $10^9$ seconds. Thus their software takes too long to report the results. They ask you for your help.
**Input Format**
Input contains 2 lines.
First line has 2 integers $N$ and $K$, $N$ being the length of the protein ring and $K$ the desired number of seconds.
Second line contains a string of length $N$ containing uppercase letters $A$,$ B$, $C$ or $D$ only, describing the ring.
**Output Format**
Output a single line with a string of length $N$, describing the state of the ring after $K$ seconds.
**Constraints**
$1 \le N \le 10^6$
$1 \le K \le 10^9$
**Sample Input:**
5 15
AAAAD
**Sample Output:**
DDDDA
**Explanation**
The complete sequence of mutations is:
AAADD
AADAD
ADDDD
DAAAD
DAADA
DADDD
DDAAA
ADAAD
DDADD
ADDAA
DADAA
DDDAD
AADDA
ADADA
DDDDA
| code | Your help is required for mutation prediction... | ai | 2014-03-07T01:25:46 | 2022-08-31T08:15:01 | #
# Complete the 'pmix' function below.
#
# The function is expected to return a STRING.
# The function accepts following parameters:
# 1. STRING s
# 2. INTEGER k
#
def pmix(s, 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')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
k = int(first_multiple_input[1])
s = input()
result = pmix(s, k)
fptr.write(result + '\n')
fptr.close()
| Some scientists are working on protein recombination, and during their research, they have found a remarkable fact: there are 4 proteins in the protein ring that mutate after every second according to a fixed pattern. For simplicity, proteins are called $A, B, C, D$ (you know, protein names can be very complicated). A protein mutates into another one depending on itself and the protein right after it. Scientists determined that the mutation table goes like this:
A B C D
_ _ _ _
A| A B C D
B| B A D C
C| C D A B
D| D C B A
Here rows denote the protein at current position, while columns denote the protein at the next position. And the corresponding value in the table denotes the new protein that will emerge. So for example, **if protein i is A, and protein i + 1 is B, protein i will change to B**. All mutations take place simultaneously. The protein ring is seen as a circular list, so last protein of the list mutates depending on the first protein.
Using this data, they have written a small simulation software to get mutations second by second. The problem is that the protein rings can be very long (up to 1 million proteins in a single ring) and they want to know the state of the ring after upto $10^9$ seconds. Thus their software takes too long to report the results. They ask you for your help. | 0.421053 | ["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"] | Input contains 2 lines.
First line has 2 integers $N$ and $K$, $N$ being the length of the protein ring and $K$ the desired number of seconds.
Second line contains a string of length $N$ containing uppercase letters $A$,$ B$, $C$ or $D$ only, describing the ring. | Output a single line with a string of length $N$, describing the state of the ring after $K$ seconds. | Hard | null | null | null | null | null | null | 2014-08-18T16:57:49 | 2016-12-08T11:30:19 | setter | ###C++
```cpp
//============================================================================
// Name : PMIX.cpp
// Author : Shaka
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <cstdio>
#include <cassert>
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 | 3,900 | 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 | null | ai | 2014-08-22T07:05:17 | 2016-09-09T09:50:28 | null | null | null |
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-22T07:08:29 | 2016-05-12T23:58:07 | setter | #include<stdio.h>
int treegrowth(int s)
{int a,c=1,i;
a=s/2;
if(s%2==0)
{
for(i=0;i<a;i++)
{
c=c*2;
c=c+1;
}
}
else{
for(i=0;i<a;i++)
{
c=c*2;
c=c+1;
} c=c*2;
}
return c;
}
int main()
{
int a,i,n[10];
scanf("%d",&a);
for(i=0;i<a;i++)
{
scanf("%d",&n[i]);
}
for(i=0;i<a;i++)
{
printf("%d\n",treegrowth(n[i]));
}
return 0;
} | not-set | 2016-04-24T02:02:58 | 2016-04-24T02:02:58 | C++ |
151 | 3,902 | weird-queries | Two Array Problem | In this problem you operate on two arrays of $N$ integers. We will call them the $0^{th}$ and the $1^{st}$ respectively.
Your goal is just to maintain them under the modification operations, such as:
+ 1 $id$ $l$ $r$: Reverse the subarray of the $id^{th}$ array, starting at the $l^{th}$ number, ending at the $r^{th}$ number, inclusively;
+ 2 $id$ $l_1$ $r_1$ $l_2$ $r_2$: Swap two consecutive fragments of the $id^{th}$ array, the first is from the $l_1^{th}$ number to the $r_1^{th}$, the second is from the $l_2^{th}$ number to the $r_2^{th}$;
+ 3 $l$ $r$: Swap the piece that starts at the $l^{th}$ number and end at the $r^{th}$ one between the $0^{th}$ and the $1^{st}$ array;
+ 4 $l$ $r$: We consider only the piece from the $l^{th}$ number to the $r^{th}$ one. The numbers in the $0^{th}$ array are $X$-coordinates of some set of points and the numbers in the $1^{st}$ array are $Y$-coordinates of them. For the obtained set of points we would like to place such a circle on a plane that would contain all the points in it and would have the minimal radius. Find this minimal radius.
**Input Format**
The first line of input contains two space separated integers $N$ and $M$ denoting the number of integers in arrays and the number of queries respectively.
The second line contains $N$ space separated integers: the initial elements of the $0^{th}$ array.
The third line contains $N$ space separated integers: the initial elements of the $1^{th}$ array.
Then there are $M$ lines containing queries in the format listed above.
**Output Format**
For each type-**4** query output the sought minimal radius with **exactly** two symbols after the decimal point precision.
**Constraints**
$1 \le N, M \le 10^5$
All the numbers in arrays are non-negative and don't exceed $10^6$.
The sum of $R-L$ over the type-**4** queries won't exceed $10^6$.
In the query of the type 2, $1 \le l_1 \le r_1 < l_2 \le r_2 \le N$.
In the queries of the types 1, 3, 4, $1 \le l \le r \le N$; $0 \le id < 2$.
**Sample Input**
10 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
3 2 6
1 0 9 9
4 6 9
2 0 2 7 9 9
1 0 3 6
2 1 2 3 4 5
1 1 7 10
2 1 8 8 9 10
4 6 9
2 0 2 2 4 6
**Example Output**
2.12
2.50
| code | Given 2 arrays, you have to maitain them, given 4 types of queries. | ai | 2014-08-22T13:35:42 | 2022-08-31T08:33:19 | null | null | null | In this problem you operate on two arrays of $N$ integers. We will call them the $0^{th}$ and the $1^{st}$ respectively.
Your goal is just to maintain them under the modification operations, such as:
+ 1 $id$ $l$ $r$: Reverse the subarray of the $id^{th}$ array, starting at the $l^{th}$ number, ending at the $r^{th}$ number, inclusively;
+ 2 $id$ $l_1$ $r_1$ $l_2$ $r_2$: Swap two consecutive fragments of the $id^{th}$ array, the first is from the $l_1^{th}$ number to the $r_1^{th}$, the second is from the $l_2^{th}$ number to the $r_2^{th}$;
+ 3 $l$ $r$: Swap the piece that starts at the $l^{th}$ number and end at the $r^{th}$ one between the $0^{th}$ and the $1^{st}$ array;
+ 4 $l$ $r$: We consider only the piece from the $l^{th}$ number to the $r^{th}$ one. The numbers in the $0^{th}$ array are $X$-coordinates of some set of points and the numbers in the $1^{st}$ array are $Y$-coordinates of them. For the obtained set of points we would like to place such a circle on a plane that would contain all the points in it and would have the minimal radius. Find this minimal radius.
**Input Format**
The first line of input contains two space separated integers $N$ and $M$ denoting the number of integers in arrays and the number of queries respectively.
The second line contains $N$ space separated integers: the initial elements of the $0^{th}$ array.
The third line contains $N$ space separated integers: the initial elements of the $1^{th}$ array.
Then there are $M$ lines containing queries in the format listed above.
**Output Format**
For each type-**4** query output the sought minimal radius with **exactly** two symbols after the decimal point precision.
**Constraints**
$1 \le N, M \le 10^5$
All the numbers in arrays are non-negative and don't exceed $10^6$.
The sum of $R-L$ over the type-**4** queries won't exceed $10^6$.
In the query of the type 2, $1 \le l_1 \le r_1 < l_2 \le r_2 \le N$.
In the queries of the types 1, 3, 4, $1 \le l \le r \le N$; $0 \le id < 2$.
**Sample Input**
10 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
3 2 6
1 0 9 9
4 6 9
2 0 2 7 9 9
1 0 3 6
2 1 2 3 4 5
1 1 7 10
2 1 8 8 9 10
4 6 9
2 0 2 2 4 6
**Example Output**
2.12
2.50
| 0.458333 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-22T13:35:54 | 2016-12-03T07:48:01 | tester | #ifdef ssu1
#define _GLIBCXX_DEBUG
#endif
#undef NDEBUG
#include <algorithm>
#include <functional>
#include <numeric>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <bitset>
#include <sstream>
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<int, int> pt;
template<typename T> T abs(T a) { return a < 0 ? -a : a; }
template<typename T> 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<typename T>
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<int>& 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<int>& 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<int> 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<point, ld> 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<point, ld> min_circle(vector<point> p, point q, point w){
pair<point, ld> 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<point, ld> min_circle(vector<point> p, point q){
pair<point, ld> 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<point>(p.begin(), p.begin() + i), p[i], q);
}
}
return ans;
}
pair<point, ld> min_circle(vector<point> p){
if(p.empty())
return pair<point, ld>();
if(sz(p) == 1)
return make_pair(p[0], 0);
random_shuffle(all(p));
pair<point, ld> 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<point>(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<int> 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<point> 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 | 3,957 | 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).
<br>
Below is the sample representation of number keys present in the keyboard.
<br>

<br>
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_ ≤ 10<sup>4</sup>
**Input #00**
2
1 2
**Output #00**
2
**Input #01**
3
1 0 3
**Output #01**
5
**Explanations**
<br>
*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.
<br>
*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 | null | null | null | 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).
<br>
Below is the sample representation of number keys present in the keyboard.
<br>

<br>
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_ ≤ 10<sup>4</sup>
**Input #00**
2
1 2
**Output #00**
2
**Input #01**
3
1 0 3
**Output #01**
5
**Explanations**
<br>
*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.
<br>
*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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 3,985 | testproblem | testProblem | Print 100 | code | Print 100 | ai | 2014-08-26T16:56:45 | 2016-09-09T09:50:57 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-26T16:58:49 | 2016-05-12T23:57:55 | setter | include <stdio.h>
int main()
{
printf("100");
return 0;
} | not-set | 2016-04-24T02:02:59 | 2016-04-24T02:02:59 | Unknown |
154 | 3,993 | 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 **i<sup>th</sup> level** only till the **(i+1)<sup>th</sup> 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 j<sup>th</sup> integer in the i<sup>th</sup> line denotes the power of j<sup>th</sup> enemy on the i<sup>th</sup> level. Each of next N lines of a test case contains M space separated integers, where j<sup>th</sup> integer in the i<sup>th</sup> line denotes the number of bullets j<sup>th</sup> enemy of i<sup>th</sup> 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 5x10<sup>5</sup>.
**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 | null | null | null | null | null | null | 2014-08-27T12:25:04 | 2016-12-07T15:45:23 | setter | ###C++
```cpp
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define all(x) x.begin(),x.end()
#define PII pair<int,int>
#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<n;i++){
for(int j=0;j<m;j++){
cin>>P[i][j];
MW[i][j]=inf;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>W[i][j];
}
}
int ans;
vector <pair<int,int> > MS;
for(int i=0;i<m;i++)
{
MW[0][i]=P[0][i];
MS.push_back(mp(W[0][i],MW[0][i]));
}
sort(all(MS));
for(int i=1;i<n;i++){
vector<PII > t;
for(int j=0;j<m;j++){
t.push_back(mp(P[i][j],j));
}
sort(all(t));
int k=0,l=0,maxx=inf;
while(l<m){
while(k<m&&MS[k].ft<=t[l].ft){
maxx=min(maxx,MS[k].sd-MS[k].ft);
k++;
}
MW[i][t[l].sd]=min(MW[i][t[l].sd],maxx+P[i][t[l].sd]);
l++;
}
k=m-1;
l=m-1;
maxx=inf;
while(l>=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<m;j++){
MS.push_back(mp(W[i][j],MW[i][j]));
}
sort(all(MS));
}
ans=inf;
for(int i=0;i<m;i++)
ans=min(ans,MW[n-1][i]);
cout << ans << endl;
}
return 0;
}
```
| not-set | 2016-04-24T02:03:00 | 2016-07-23T15:16:54 | C++ |
155 | 3,994 | 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.485714 | ["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 | null | null | null | null | null | null | 2014-08-27T17:06:14 | 2016-12-02T08:39:51 | setter | ###C++
```cpp
/*
* Bidhan Roy
* University of Dhaka
*/
using namespace std;
#include <bits/stdc++.h>
#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 | 3,994 | 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.485714 | ["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 | null | null | null | null | null | null | 2014-08-27T17:06:14 | 2016-12-02T08:39:51 | tester | ###C++
```cpp
#ifdef ssu1
#define _GLIBCXX_DEBUG
#endif
#undef NDEBUG
#include <algorithm>
#include <functional>
#include <numeric>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <bitset>
#include <sstream>
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<int, int> pt;
template<typename T> T abs(T a) { return a < 0 ? -a : a; }
template<typename T> 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<line>& 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<line>& 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<line> 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 | 3,997 | 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<=i<N-1). The first of these two lines describes the pathes to the left. It starts with a
number L(0<=L<=N-i-1). Next, follow L integers Li(i<Li<N), the checkpoints are going to be reached following these
pathes. The second of these two lines describes the pathes to the right. It starts with a number R(0<=R<=N-i-1).
Next, follow R integers Ri(i<Ri<N), the checkpoints are going to be reached following these pathes.
**Output specification:**
Output just a simple line, the maximum score can be obtained.
**Sample input**
<br>5 1
<br>421 990 160 473 333
<br>4 2 1 2 3
<br>0
<br>1 2
<br>2 4 4
<br>1 4
<br>2 4 4
<br>1 4
<br>0
**Sample output**
<br>1904 | code | Let's count! | ai | 2014-08-27T19:11:28 | 2016-09-09T09:51:01 | null | null | null | 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<=i<N-1). The first of these two lines describes the pathes to the left. It starts with a
number L(0<=L<=N-i-1). Next, follow L integers Li(i<Li<N), the checkpoints are going to be reached following these
pathes. The second of these two lines describes the pathes to the right. It starts with a number R(0<=R<=N-i-1).
Next, follow R integers Ri(i<Ri<N), the checkpoints are going to be reached following these pathes.
**Output specification:**
Output just a simple line, the maximum score can be obtained.
**Sample input**
<br>5 1
<br>421 990 160 473 333
<br>4 2 1 2 3
<br>0
<br>1 2
<br>2 4 4
<br>1 4
<br>2 4 4
<br>1 4
<br>0
**Sample output**
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<Integer> 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[x][0].size();i++) {
int y = G[x][0].get(i);
if(s == 0) {
maxx = Math.max(maxx, solve(y, 0, kk));
} else {
maxx = Math.max(maxx, solve(y, 1, kk + 1));
}
}
for(int i = 0;i<G[x][1].size();i++) {
int y = G[x][1].get(i);
if(s == 1) {
maxx = Math.max(maxx, solve(y, 1, kk));
} else {
maxx = Math.max(maxx, solve(y, 0, kk + 1));
}
}
return DP[x][s][kk] = maxx + points[x];
}
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]);
DP = new int[N+1][2][K+1];
for(int i = 0;i<N;i++)
for(int j = 0;j<=K;j++) {
DP[i][0][j] = -1;
DP[i][1][j] = -1;
}
points = new int[N+1];
cad = br.readLine().split(" ");
G = new Vector[N+1][2];
for (int i = 0; i < N; i++) {
points[i] = Integer.parseInt(cad[i]);
G[i][0] = new Vector<Integer>();
G[i][1] = new Vector<Integer>();
}
for(int i = 0;i<N-1;i++) {
cad = br.readLine().split(" ");
L = Integer.parseInt(cad[0]);
for(int j=1;j<=L;j++) {
G[i][0].add( Integer.parseInt(cad[j]) );
}
cad = br.readLine().split(" ");
R = Integer.parseInt(cad[0]);
for(int j=1;j<=R;j++) {
G[i][1].add( Integer.parseInt(cad[j]) );
}
}
System.out.println(solve(0,0,0));
}
} | not-set | 2016-04-24T02:03:00 | 2016-04-24T02:03:00 | Python |
158 | 3,998 | another-increasing-subsequence-problem | Another increasing subsequence problem | 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**
<br>5 5 3
<br>1 5 4 4 1
**Sample output**
<br>7 | code | How many special subsequence! | ai | 2014-08-27T19:26:55 | 2016-09-09T09:51:01 | null | null | null | 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**
<br>5 5 3
<br>1 5 4 4 1
**Sample output**
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<N;i++) {
arr[i] = Integer.parseInt(cad[i]);
DP[1][i] = 1;
}
for(int i = 2;i<=K;i++) {
BIT = new int[100001];
for(int j = 0;j<N;j++) {
if(j + 1 >= 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;j<N;j++)
sol = (sol + DP[i][j]) % MOD;
System.out.println(sol);
}
} | not-set | 2016-04-24T02:03:00 | 2016-04-24T02:03:00 | Python |
159 | 4,001 | business-business | Business, business | 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**
<br>1 1 1
<br>10
<br>15
<br>1 1
**Sample output**
<br>15 | code | Can you help the company to earn money? | ai | 2014-08-27T19:54:53 | 2016-09-09T09:51:02 | null | null | null | 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**
<br>1 1 1
<br>10
<br>15
<br>1 1
**Sample output**
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 4,002 | 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 | null | null | null | null | null | null | 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<<j);
}
arr[i] = mask;
}
DP = new int[K+2][N+2][18];
for(int j = 1;j<=N;j++) {
DP[1][j][ arr[j] ] = 1;
for(int k = 0;k<16;k++){
DP[1][j][k] += DP[1][j-1][k];
}
}
for(int i=1;i<K;i++) {
for(int j = i;j<N;j++) {
for(int k = 0;k<16;k++){
DP[i+1][j+1][k | arr[j+1]] = (DP[i+1][j+1][k | arr[j+1]] + DP[i][j][k] ) % MOD;
DP[i+1][j+1][k] = (DP[i+1][j+1][k] + DP[i+1][j][k] ) % MOD;
}
}
}
int sol = 0;
for(int k = 0;k<15;k++)
sol = (sol + DP[K][N][k]) % MOD;
System.out.println(sol);
}
}
```
| not-set | 2016-04-24T02:03:00 | 2016-07-23T15:14:36 | Java |
161 | 4,022 | puzzle-and-pc | Puzzle and PC | Mom has to go to work and she doesn't want little Johnny to get bored. So she gives him a simple puzzle to solve. She also tells him that he can play a PC game only if he solves this problem. Johnny loves PC games and wants to solve this puzzle quickly. So he asks you for help.
You are given a square _NxN_ board divided into single cells, where _N_ is always a power of 2. You are also given an infinite number of L-shaped trominoes:

Note that each tromino can covers three cells.
The board has one special cell _S_ on which you are not allowed to place any tromino. Your task is to cover the whole board with trominoes in such a way that any two trominoes don't overlap, and every cell (except cell _S_) is covered by some tromino.
Indexing starts from 1, and top-left cell is indexed (1, 1).
**Input**
In the first line, there is an integer $M$. $N = 2^M$ denotes the size of the board.
In the second line, there are two integers, _r c_, denoting the row and the column of cell _S_.
**Output**
For every tromino placed, print one line containing 6 space separated numbers, denoting the coordinates (in row major form) of 3 cells covered by this block.
**Constraints**
- $1 \le M \le 9$
- $1 \le r, c \le 2^M$
**Note**
- You are also allowed to rotate the trominoes.
- There may be multiple solution for a case. All valid solutions will be considered correct.
**Sample Input #00**
1
2 2
**Sample Output #00**
1 1 1 2 2 1
**Sample Input #01**
2
1 1
**Sample Output #01**
2 3 3 2 3 3
1 2 2 1 2 2
1 3 1 4 2 4
3 1 4 1 4 2
3 4 4 3 4 4
**Explanation #00**
*Sample Case #00:* Since you are not allowed to cover bottom-right cell, you will cover points (1,1), (1,2) & (2,1) with a single tromino.
1 2
1 | 1 | 1 |
2 | 1 | x |
*Sample Case #01:* Since $N = 2^2 = 4$, board is of size $4x4$ and you are not allowed cover top-left cell. You will need 5 trominoes to cover whole board, except cell (1, 1).
1. `2 3 3 2 3 3`: This tromino will cover points (2, 3), (3, 2), (3, 3).
2. `1 2 2 1 2 2`: This tromino will cover points (1, 2), (2, 1), (2, 2).
3. `1 3 1 4 2 4`: This tromino will cover points (1, 3), (1, 4), (2, 4).
4. `3 1 4 1 4 2`: This tromino will cover points (3, 1), (4, 1), (4, 2).
5. `3 4 4 3 4 4`: This tromino will cover ponits (3, 4), (4, 3), (4, 4).
.
1 2 3 4
1 | x | 2 | 3 | 3 |
2 | 2 | 2 | 1 | 3 |
3 | 4 | 1 | 1 | 5 |
4 | 4 | 4 | 5 | 5 |
Note that there can be multiple configurations to this input, and all will be considered correct
---
**Tested by** [Wanbo](/wanbo)
| code | Help little Johnny with the puzzle. | ai | 2014-08-29T19:51:24 | 2016-09-01T16:34:30 | null | null | null | Mom has to go to work and she doesn't want little Johnny to get bored. So she gives him a simple puzzle to solve. She also tells him that he can play a PC game only if he solves this problem. Johnny loves PC games and wants to solve this puzzle quickly. So he asks you for help.
You are given a square _NxN_ board divided into single cells, where _N_ is always a power of 2. You are also given an infinite number of L-shaped trominoes:

Note that each tromino can covers three cells.
The board has one special cell _S_ on which you are not allowed to place any tromino. Your task is to cover the whole board with trominoes in such a way that any two trominoes don't overlap, and every cell (except cell _S_) is covered by some tromino.
Indexing starts from 1, and top-left cell is indexed (1, 1).
**Input**
In the first line, there is an integer $M$. $N = 2^M$ denotes the size of the board.
In the second line, there are two integers, _r c_, denoting the row and the column of cell _S_.
**Output**
For every tromino placed, print one line containing 6 space separated numbers, denoting the coordinates (in row major form) of 3 cells covered by this block.
**Constraints**
- $1 \le M \le 9$
- $1 \le r, c \le 2^M$
**Note**
- You are also allowed to rotate the trominoes.
- There may be multiple solution for a case. All valid solutions will be considered correct.
**Sample Input #00**
1
2 2
**Sample Output #00**
1 1 1 2 2 1
**Sample Input #01**
2
1 1
**Sample Output #01**
2 3 3 2 3 3
1 2 2 1 2 2
1 3 1 4 2 4
3 1 4 1 4 2
3 4 4 3 4 4
**Explanation #00**
*Sample Case #00:* Since you are not allowed to cover bottom-right cell, you will cover points (1,1), (1,2) & (2,1) with a single tromino.
1 2
1 | 1 | 1 |
2 | 1 | x |
*Sample Case #01:* Since $N = 2^2 = 4$, board is of size $4x4$ and you are not allowed cover top-left cell. You will need 5 trominoes to cover whole board, except cell (1, 1).
1. `2 3 3 2 3 3`: This tromino will cover points (2, 3), (3, 2), (3, 3).
2. `1 2 2 1 2 2`: This tromino will cover points (1, 2), (2, 1), (2, 2).
3. `1 3 1 4 2 4`: This tromino will cover points (1, 3), (1, 4), (2, 4).
4. `3 1 4 1 4 2`: This tromino will cover points (3, 1), (4, 1), (4, 2).
5. `3 4 4 3 4 4`: This tromino will cover ponits (3, 4), (4, 3), (4, 4).
.
1 2 3 4
1 | x | 2 | 3 | 3 |
2 | 2 | 2 | 1 | 3 |
3 | 4 | 1 | 1 | 5 |
4 | 4 | 4 | 5 | 5 |
Note that there can be multiple configurations to this input, and all will be considered correct
---
**Tested by** [Wanbo](/wanbo)
| 0.5 | ["haskell","clojure","scala","erlang","sbcl","ocaml","fsharp","racket","elixir"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-29T19:51:55 | 2016-05-12T23:57:44 | tester | -- Translated by abhiranjan
-- Haskell
import Data.List
main :: IO ()
main =
getContents >>=
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 | 4,032 | 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**
<br>for C = 0:
<br>The optimal way to make a singe stack:
<br>**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:
<br>**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 | null | null | null | 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**
<br>for C = 0:
<br>The optimal way to make a singe stack:
<br>**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:
<br>**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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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;i<end;i++) {
minn = Math.min(minn, Math.max(0, (long)(i-beg+1) * (arr[i]-arr[beg-1]) +
(long)(end-i) * (arr[end]-arr[i]) +
solve(beg, i) + solve(i+1, end)-M));
}
return DP[beg][end] = minn;
}
static boolean check() {
for(int i = 1;i<=N;i++)
for(int j = i;j<=N;j++)
DP[i][j] = -1;
long val = solve(1,N);
return val <= T;
}
public static void main(String[] args) throws IOException {
InputStreamReader sr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(sr);
String cad[] = br.readLine().split(" ");
N = Integer.parseInt(cad[0]);
T = Long.parseLong(cad[1]);
arr = new long[N+2];
DP = new long[N+2][N+2];
cad = br.readLine().split(" ");
for(int i = 1;i<=N;i++)
arr[i] = arr[i-1] + Long.parseLong(cad[i-1]);
L=0;
R=(long) 1e15;
M=0;
while(R-L>5){
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 | 4,032 | 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**
<br>for C = 0:
<br>The optimal way to make a singe stack:
<br>**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:
<br>**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 | null | null | null | 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**
<br>for C = 0:
<br>The optimal way to make a singe stack:
<br>**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:
<br>**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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-08-31T07:51:44 | 2016-12-05T00:09:48 | tester | #include <map>
#include <set>
#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<PLL> VPLL;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<PII> VPII;
typedef vector<VI> VVI;
typedef vector<VPII> VVPII;
#define MM(a,x) memset(a,x,sizeof(a));
#define ALL(x) (x).begin(), (x).end()
#define P(x) cerr<<"["#x<<" = "<<(x)<<"]"<<endl;
#define P2(x,y) cerr<<"["#x" = "<<(x)<<", "#y" = "<<(y)<<"]"<<endl;
#define P3(x,y,z)cerr<<"["#x" = "<<(x)<<", "#y" = "<<(y)<<", "#z" = "<<(z)<<"]"<<endl;
#define PP(x,i) cerr<<"["#x<<i<<" = "<<x[i]<<"]"<<endl;
#define TM(a,b) cerr<<"["#a" -> "#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<class A, class B> ostream& operator<<(ostream &o, pair<A, B> t) {o << "(" << t.x << ", " << t.y << ")"; return o;}
template<class T> 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<class T> 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<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;}
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 | 4,036 | 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**
<br>2
<br>1 2
<br>34 66
<br>29 71
**Sample output**
<br>3.45 | code | You have been challenged by the colony!! | ai | 2014-08-31T09:06:13 | 2016-09-09T09:51:13 | null | null | null | 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**
<br>2
<br>1 2
<br>34 66
<br>29 71
**Sample output**
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 <n;col++)
M[row][n] -= M[row][col] * M[col][n];
M[row][n] /= M[row][row];
}
}
public static void main(String[] args) throws IOException {
InputStreamReader sr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(sr);
N = Integer.parseInt(br.readLine());
cad = br.readLine().split(" ");
A = Integer.parseInt(cad[0]);
for(int i = 1;i<=A;i++) {
INITIAL |= 1<<(Integer.parseInt(cad[i])-1);
}
P = new double[N+1][N+1];
for(int i = 0;i<N;i++) {
cad = br.readLine().split(" ");
for(int j = 0;j<N;j++) {
P[i][j] = Double.parseDouble(cad[j]) / 100.0;
}
}
M = new double[(1<<N)+5][(1<<N)+5];
for(int i = 1;i<(1<<N)-1;i++) {
int cc = 0;
for(int j = 0;j<N;j++)
if((i & (1<<j))>0)
++cc;
for(int j = 0;j<N;j++)
if((i & (1<<j))>0) {
double rep = (cc == 1 ? 1.0 : 0.5);
for(int k = 0;k<N;k++){
M[i-1][ (i | (1<<k)) - 1] -= (1.0/(double)cc) * rep * P[j][k];
}
if(cc>1)
M[i-1][ (i ^ (1<<j)) - 1] -= (1.0/(double)cc) * 0.5;
}
M[i-1][i-1] += 1.0;
M[i-1][(1<<N)-1] = 1;
}
M[(1<<N)-2][(1<<N)-2] = 1;
M[(1<<N)-2][(1<<N)-1] = 0;
Gauss((1<<N)-1);
System.out.println(Round(M[INITIAL-1][(1<<N)-1]));
}
} | not-set | 2016-04-24T02:03:01 | 2016-04-24T02:03:01 | Python |
165 | 4,048 | snipers | Snipers | 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**
<br>5 1
<br>8 1 9 5 6
**Sample output**
<br>4
Hint:
<br>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 | null | null | null | 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**
<br>5 1
<br>8 1 9 5 6
**Sample output**
<br>4
Hint:
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<N;i++) {
remove = i - D - 1;
if(remove >= 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 | 4,050 | 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**
<br>50 1000
**Sample output**
<br>0.712 | code | Find the odds for the people! | ai | 2014-08-31T22:06:16 | 2016-09-09T09:51:20 | null | null | null | 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**
<br>50 1000
**Sample output**
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<N;i++) {
sol *= (1.0 - (double) i /(double)K);
}
System.out.println(Round(1.0 - sol));
}
}
} | not-set | 2016-04-24T02:03:01 | 2016-04-24T02:03:01 | Python |
167 | 4,052 | playing-with-stacks | Playing with stacks | 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**
<br>4 3
<br>1 0 1
**Sample output**
<br>2
**Hint:**
<br>3 1 4 2
<br>3 2 4 1 | code | If you like permutations solve this challenge! | ai | 2014-08-31T22:52:42 | 2016-09-09T09:51:20 | null | null | null | 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**
<br>4 3
<br>1 0 1
**Sample output**
<br>2
**Hint:**
<br>3 1 4 2
<br>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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<N-1;i++)
P[i] = Integer.parseInt(cad[i]);
DP[N-1][1] = 1;
for(int i=N-2;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 | 4,059 | 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. <br><br>
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$.<br>
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$ <br>
**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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-01T17:05:23 | 2016-12-02T17:55:45 | setter | #include<bits/stdc++.h>
using namespace std;
int a[510000];
int b[510000];
int arr[510000];
int MaxInSeq(int N)
{
int i;
set<int> s;
set<int>::iterator k;
for (i=0; i<N; i++)
{
if (s.insert(arr[i]).second)
{
k = s.find(arr[i]);
k++;
if (k!=s.end()) s.erase(k);
}
}
return s.size();
}
int main()
{
int n;
cin>>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 ; i<n ; i++)
{
arr[i] = n+5 - a[i+1];
}
cout<<MaxInSeq(n)<<endl;
return 0;
}
| not-set | 2016-04-24T02:03:01 | 2016-04-24T02:03:01 | C++ |
169 | 4,084 | floor | Magical floor | Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of them. Consider a cell with number x written on it, if this cell is attacked by one of the bishops Gargari will get x dollars for it. Tell Gargari, how to place bishops on the chessboard to get maximum amount of money.
We assume a cell is attacked by a bishop, if the cell is located on the same diagonal with the bishop (the cell, where the bishop is, also considered attacked by it).
__Input__
The first line contains a single integer n (2 ≤ n ≤ 1000). Each of the next n lines contains n integers a[i][j] (0 ≤ a[i][j] ≤ 100) — description of the chessboard.
__Output__
Print the maximal number of dollars Gargari will get.
__Sample Cases__
__input__
4
1 1 1 1
2 1 1 0
1 1 1 0
1 0 0 1
__output__
12 | code | null | ai | 2014-09-02T20:20:48 | 2016-09-09T09:51:30 | null | null | null | Rajarshee has few friends. As you see, not all of them are beneficial. Some are selfish while some of them are too proud. However, he is leading his own life, not much problem to worry about yet. One thing you should know about him : he is very fond of adventure!
However, as you all now, a peaceful life is enviable.
Rajarshee is much weak in solving problems and doesn't care much about challenges and avoids them. However a jealous friend tries to disrupt his peace and throws an unsolved challenge to him and says, "Solve your love for adventure!"
Rajarshee gets angry and takes this threat seriously!
His friend gives him information about a strange house with a magical floor on which a __n x n__ grid is drawn with square cells and a number written on each cell. The magical part lies in the fact that whenever any two people stands on two cells each, all the numbers in either diagonal of a cell gets added (including the cell on which you stand) and you get a total reward in gold with value of the sum. The same thing happens for both the cell.
"Easy!", Rajarshee lies!
"Let me add more to your pain. If there is a cell which lies in a diagonal common to both the cell, you wont get any gold. Instead, you will visit hell straight down!"
Rajarshee gets afraid yet he is ashamed to show his fear to the jealous friend. Instead, he comes to you, his best friend and a remarkable programmer.
You visit the house with your laptop along with him. After seeing the grid and all the numbered cells, you start writing a program that will solve the problem and make the gold inevitable for you two! | 0.5 | ["c","cpp","java","java8","python3","ruby","python","cpp14"] | The first line contains a integer n (2 ≤ n ≤ 2000). The __ith__ line of the next n lines contains n integers where __jth__ integer denotes __a[i][j]__ (0 ≤ a[i][j] ≤ 10^9) where __a__ is the matrix representation of the grid. | Print the maximum total reward that you can achieve. | 4
1 1 1 1
2 1 1 0
1 1 1 0
1 0 0 1
| 12 | Hard | null | null | null | null | null | null | 2014-09-02T20:29:25 | 2016-05-12T23:57:24 | setter | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int i,j,n = Integer.parseInt(br.readLine());
long a[][] = new long[n][n];
int x1=0,y1=0,x2=0,y2=1;
long max1=0,max2=0;
cell c[][] = new cell[n][n];
for(i=0;i<n;i++)
{
j=0;
String t[] = br.readLine().split(" ");
while(j<n)
{
a[i][j] = Integer.parseInt(t[j]);
int x = i, y = j;
if(x<y)
{
y -= (x-0);
x = 0;
}
else
{
x -= (y-0);
y = 0;
}
if(c[x][y]==null)
c[x][y] = new cell();
c[x][y].dia1+= a[i][j];
x= i; y = j;
if(x-0>n-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;i<n; i++)
{
for(j=0;j<n; j++)
{
if(c[i][j]==null)
c[i][j] = new cell();
int x = i, y = j;
if(x<y)
{
y -= (x-0);
x = 0;
}
else
{
x -= (y-0);
y = 0;
}
c[i][j].dia1 = c[x][y].dia1;
x= i; y = j;
if(x-0>n-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 | 4,094 | 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.<br>
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. <br>
Assign mice to holes so that the time required for all the mice to move inside the holes is minimized.
__Input Format__ <br>
The first line contains an integer __T__, the number of test cases. This is followed by __T__ blocks of input: <br>
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__ <br>
For each testcase, print the minimum time taken by all the mice to reach inside the holes.
__Constraints__ <br>
1 ≤ T ≤ 17 <br>
1 ≤ n ≤ 131072 <br>
1 ≤ m ≤ 131072 <br>
n ≤ m <br>
-10<sup>8</sup> ≤ mouse[i] ≤ 10<sup>8</sup> <br>
-10<sup>8</sup> ≤ hole[j] ≤ 10<sup>8</sup> <br>
__Sample Input__ <br>
<pre>
1
3 4
2 0 -4
3 1 2 -1
</pre>
__Sample Output__ <br>
<pre>
3
</pre>
**Explanation**
One possible solution is : <br>
Assign mouse at position x=-4 to hole at position x=-1 -> 3 minutes <br>
Assign mouse at postion x=2 to hole at position x=2 -> 0 minutes <br>
Assign mouse at postion x=0 to hole at postion x=3 -> 3 minutes <br>
So the answer is 3, after 3 minutes all of the mice are in the holes. | code | null | ai | 2014-09-03T11:26:43 | 2016-09-09T09:51:34 | null | null | null | __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.<br>
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. <br>
Assign mice to holes so that the time required for all the mice to move inside the holes is minimized.
__Input Format__ <br>
The first line contains an integer __T__, the number of test cases. This is followed by __T__ blocks of input: <br>
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__ <br>
For each testcase, print the minimum time taken by all the mice to reach inside the holes.
__Constraints__ <br>
1 ≤ T ≤ 17 <br>
1 ≤ n ≤ 131072 <br>
1 ≤ m ≤ 131072 <br>
n ≤ m <br>
-10<sup>8</sup> ≤ mouse[i] ≤ 10<sup>8</sup> <br>
-10<sup>8</sup> ≤ hole[j] ≤ 10<sup>8</sup> <br>
__Sample Input__ <br>
<pre>
1
3 4
2 0 -4
3 1 2 -1
</pre>
__Sample Output__ <br>
<pre>
3
</pre>
**Explanation**
One possible solution is : <br>
Assign mouse at position x=-4 to hole at position x=-1 -> 3 minutes <br>
Assign mouse at postion x=2 to hole at position x=2 -> 0 minutes <br>
Assign mouse at postion x=0 to hole at postion x=3 -> 3 minutes <br>
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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 4,101 | 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.<br>
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$ <br>
$ 1\le N \le 10^5$ <br>
$ 1\le K \le 10^5$ <br>
**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.<br>
$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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-04T05:17:07 | 2016-12-08T10:35:17 | setter | ###C++
```cpp
#include<bits/stdc++.h>
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<<func(3,2)<<endl;
while(t--)
{
long long int n,k;
cin>>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<<ans<<endl;
}
return 0;
}
```
| not-set | 2016-04-24T02:03:02 | 2016-07-23T18:21:13 | C++ |
172 | 2,676 | euler050 | Project Euler #50: Consecutive prime sum | <sub>This problem is a programming version of [Problem 50](https://projecteuler.net/problem=50) from [projecteuler.net](https://projecteuler.net/)</sub>
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 | null | null | null | <sub>This problem is a programming version of [Problem 50](https://projecteuler.net/problem=50) from [projecteuler.net](https://projecteuler.net/)</sub>
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 | null | null | null | null | null | null | 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<int> primes = new List<int>(); // 664579 number of primes < MAX
static List<long> psum = new List<long>();
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 | 3,517 | 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.
<br>
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.
<br>
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.
<br>
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.
<br>
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.535714 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-07T15:08:06 | 2016-12-07T22:23:36 | setter | ###C++
```cpp
--C++
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
#define FOR(i,n) for(int (i)=0;(i)<(n);++(i))
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<vector<ull> > 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 | 1,739 | 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<br/>
All numbers in the list will fit in a **32-bit signed integer** and greater than 0.<br/>
**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 | null | null | null | **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<br/>
All numbers in the list will fit in a **32-bit signed integer** and greater than 0.<br/>
**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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 <cstdio>
#include <cassert>
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 | 1,739 | 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<br/>
All numbers in the list will fit in a **32-bit signed integer** and greater than 0.<br/>
**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 | null | null | null | **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<br/>
All numbers in the list will fit in a **32-bit signed integer** and greater than 0.<br/>
**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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-12T16:39:32 | 2016-12-30T04:48:50 | tester | #include<iostream>
#include<cassert>
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 | 4,291 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-17T17:53:08 | 2016-05-12T23:56:41 | setter | #include <vector>
#include <algorithm>
#include <cstdio>
#include <cassert>
using namespace std;
int perimeter(vector<int>);
int ways(int);
int fact(int);
int main()
{
int n;
while(1)
{
scanf("%d",&n);
if(!n)
break;
vector<int> v(n);
int i;
for(i=0;i<n;++i)
scanf("%d",&v[i]);
printf("%d %d\n",perimeter(v),ways((int)v.size()));
}
return 0;
}
int perimeter(vector<int> 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 | 4,293 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-17T18:21:00 | 2016-05-12T23:56:41 | setter | #include <stdio.h>
/*
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; i<n_nodes; i++) {
n_edges_to = NumEdgesTo(edge_list, i);
// if there are no edges to this, it's a root node
if (n_edges_to == 0) {
if (root_node == -1) {
root_node = i;
} else {
// if a root node has already been found, die--
// can't have more than one root
return 0;
}
} else if (n_edges_to != 1) {
// can't have more than one edge to any node
return 0;
}
}
// if no root exists, is not a tree
if (root_node == -1) return 0;
// create an array that will note how many times each
// node was visited
int *visited = new int[n_nodes];
for (i=0; i<n_nodes; i++) visited[i] = 0;
// starting at the root, visit every node recursively
Visit(edge_list, root_node, visited);
// make sure every node was visited exactly once
for (i=0; i<n_nodes; i++) {
if (visited[i] != 1) {
delete[]visited;
return 0;
}
}
delete[]visited;
return 1;
}
int main() {
int case_no = 1;
int from, to;
// FILE *inf = fopen("prob_2.in", "r");
FILE *inf = stdin;
while (fscanf(inf, "%d %d", &from, &to), from != -1 || to != -1) {
// reset the lists
edge_list = 0;
ClearNodeNumList();
// read in the edge list
while (from || to) {
Edge *new_edge = new Edge(from, to);
new_edge->next = 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 | 4,294 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-17T18:48:47 | 2016-05-12T23:56:40 | setter | #include <stdio.h>
#include <math.h>
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<n; i++) {
fscanf(inf, "%lf %d %d %d", &f, &lights[i].g,
&lights[i].y, &lights[i].r);
lights[i].dist = f;
}
any = 0;
speeds[61] = 0; /* put a terminator at the end so
the exit condition is easier */
/* try each possible speed */
for (speed=30; speed <= 60; speed++) {
speeds[speed] = MustGoFaster_MustGoFaster(lights, n, speed);
any = any || speeds[speed];
}
printf("Case %d: ", c++);
if (!any) {
printf("No acceptable speeds.\n");
} else {
int span_start, span_end, first = 1;
speed = 30;
/* find all the spans of valid speeds */
while (speed <= 60) {
while (!speeds[speed] && speed <= 60) speed++;
if (speed > 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 | 4,302 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T09:48:35 | 2016-05-12T23:56:39 | setter | #include <stdlib.h>
#include <iostream.h>
#include <assert.h>
#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<padsize; i++) { // read in pad
cin >> 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 | 4,303 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T09:57:09 | 2016-05-12T23:56:39 | setter | #include <stdlib.h>
#include <iostream.h>
#include <assert.h>
// 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 | 2,591 | 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 | null | null | null | 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.545455 | ["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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 4,305 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T10:15:20 | 2016-05-12T23:56:37 | setter | #include <stdio.h>
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<participants; i++)
{ if (positions[i])
fprintf(outp, "%1d ", i+1);
}
fprintf(outp, "\n");
}
void main(void)
{ int i;
inp = fopen("mash.in", "r");
outp = fopen("mash.out", "w");
sim_count = 0;
while (!feof(inp))
{ fscanf(inp, "%d %d", &participants, &lucky);
for (i=0; i<20; i++)
{ fscanf(inp, "%d", &cards[i]); }
fscanf(inp, "\n");
find_positions();
}
fclose(inp);
fclose(outp);
}
| not-set | 2016-04-24T02:03:05 | 2016-04-24T02:03:05 | C++ |
183 | 4,307 | coconuts-1 | Coconuts 1 | The short story titled Coconuts, by Ben Ames Williams, tells about five men and a monkey who were shipwrecked on an island. They spent the first night gathering coconuts. During the night, one man woke up and decided to take his share of the coconuts. He divided them into five piles. One coconut was left over so he gave it to the monkey, then hid his share and went back to sheep.
Soon a second man woke up and did the same thing. After dividing the coconuts into five piles, one coconut was left over which he gave to the monkey. He then hid his share and went back to bed. The third, fourth, and fifth man followed exactly the same procedure. The next morning, after they all woke up, they divided the remaining coconuts into five equal shares. This time no coconuts were left over.
An obvious question is "how many coconuts did they originally gather?" There are an infinite number of answers, but the lowest of these is 3,121. But that's not our problem here.
Suppose we turn the problem around. If we know the number of coconuts that were gathered, what is the maximum number of persons (and one monkey) that could have been shipwrecked if the same procedure could occur?
**Input Format:**
The input will consist of a sequence of integers, each representing the number of coconuts gathered by a group of persons (and a monkey) that were shipwrecked. The sequence will be followed by a negative number.
**Output Format:**
For each number of coconuts, determine the largest number of persons who could have participated in the procedure described above. Display the results similar to the manner shown below, in the Expected Output. There may be no solution for some of the input cases; if so, state that observation.
**Sample Input:**
25
30
3121
-1
**Expected Input:**
25 coconuts, 3 persons and 1 monkey
30 coconuts, no solution
3121 coconuts, 5 persons and 1 monkey
| code | Based on a short story titled 'Coconuts', by Ben Ames Williams,which tells about five men and a monkey who were shipwrecked on an island. | ai | 2014-09-18T10:22:08 | 2016-09-09T09:52:42 | null | null | null | The short story titled Coconuts, by Ben Ames Williams, tells about five men and a monkey who were shipwrecked on an island. They spent the first night gathering coconuts. During the night, one man woke up and decided to take his share of the coconuts. He divided them into five piles. One coconut was left over so he gave it to the monkey, then hid his share and went back to sheep.
Soon a second man woke up and did the same thing. After dividing the coconuts into five piles, one coconut was left over which he gave to the monkey. He then hid his share and went back to bed. The third, fourth, and fifth man followed exactly the same procedure. The next morning, after they all woke up, they divided the remaining coconuts into five equal shares. This time no coconuts were left over.
An obvious question is "how many coconuts did they originally gather?" There are an infinite number of answers, but the lowest of these is 3,121. But that's not our problem here.
Suppose we turn the problem around. If we know the number of coconuts that were gathered, what is the maximum number of persons (and one monkey) that could have been shipwrecked if the same procedure could occur?
**Input Format:**
The input will consist of a sequence of integers, each representing the number of coconuts gathered by a group of persons (and a monkey) that were shipwrecked. The sequence will be followed by a negative number.
**Output Format:**
For each number of coconuts, determine the largest number of persons who could have participated in the procedure described above. Display the results similar to the manner shown below, in the Expected Output. There may be no solution for some of the input cases; if so, state that observation.
**Sample Input:**
25
30
3121
-1
**Expected Input:**
25 coconuts, 3 persons and 1 monkey
30 coconuts, no solution
3121 coconuts, 5 persons and 1 monkey
| 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T10:22:24 | 2016-05-12T23:56:37 | setter | #include <stdio.h>
/* 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<n_people; i++) {
/* check that the coconuts divide by the number of people
plus one remainder */
if (n_coco % n_people != 1) return 0;
/* remove 1 for the monkey, and one person's share */
n_coco = n_coco - 1 - (n_coco / n_people);
}
/* check that the remaining coconuts divide evenly among
the people */
return (n_coco % n_people) == 0;
}
int main() {
long n_coco;
long n_people;
long i, j, k;
/* FILE *inf = fopen("prob_3.in", "r"); */
FILE *inf = stdin;
while (fscanf(inf, "%ld", &n_coco), n_coco!=-1) {
/* starting at the # of coconuts-1, count down until
a number of people is found that works */
for (n_people=n_coco-1; n_people > 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 | 4,310 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 | 4,311 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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<puzzleTiles ; i++) {
String leadingSpace = "";
if (p[i] < 10)
leadingSpace = " ";
else if (p[i] < 100)
leadingSpace = " ";
System.out.print(leadingSpace + p[i] + " ");
if (((i+1) % puzzleSize) == 0)
System.out.println();
}
}
} | not-set | 2016-04-24T02:03:05 | 2016-04-24T02:03:05 | Python |
186 | 4,316 | pyramid-trap | Pyramid Trap | A team called Archaeologists of the Central Mountains (ACM) is interested in the famous Helmut's Pyramid (HP) in Egypt. In the Pyramid, there is a Sarcophagus of Umbertiti Nefrites (SUN). According to the legend, the Sarcophagus contains (besides the pharaoh's body, of course) a priceless treasure: air-tickets to Orlando, FL, with the magic date March 2000. The ACM decided to locate this treasure and retrieve it from the Pyramid before it is too late. The problem is that the Pyramid is equipped with many varied traps to protect the tickets from being stolen. Many years of intensive study have been spent monitoring activities inside the Pyramid and discovering all the traps. Finally, the archaeologists are ready to enter the Pyramid. They have a very powerful notebook to help them finish their task. And your task is to provide the software for them.
There is a large room in the Pyramid called Room-of-No-Return. Its floor is covered by rectangular tiles of equal size. The name of the room was chosen because of the very high number of traps and mechanisms in it. The ACM group has spent several years studying the secret plan of this room. It has made a clever plan to avoid all the traps. A specially trained mechanic was sent to deactivate the most feared trap called Shattered Bones. After deactivating the trap the mechanic had to escape from the room. It is very important to step on the center of the tiles only; he must not touch the edges. One wrong step and a large rock falls from the ceiling squashing the mechanic like a pancake. After deactivating the trap, he realized a horrible thing: the ACM plan did not take his equipment box into consideration. The box must be laid onto the ground because the mechanic must have both hands free to prevent contact with other traps. But when the box is laid on the ground, it could touch the line separating the tiles. And this is the main problem you are to solve.
**Input Specification:**
The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case consists of a single line. The line contains exactly four integer numbers separated by spaces: A, B, X and Y. A and Bindicate the dimensions of the tiles, X and Y are the dimensions of the equipment box (1 <= A,B,X,Y <= 50000).
**Output Specification:**
Your task is to determine whether it is possible to put the box on a single tile -- that is, if the whole box fits on a single tile without touching its border. If so, you are to print one line with the sentence "Escape is possible.". Otherwise print the sentence "Box cannot be dropped.".
**Sample Input:**
2
10 10 8 8
8 8 10 10
**Output for the Sample Input:**
Escape is possible.
Box cannot be dropped.
| code | A team called Archaeologists of the Central Mountains (ACM) is interested in the famous Helmut's Pyramid (HP) in Egypt. They have a very powerful notebook to help them finish their task. Your task is to provide the software for them. | ai | 2014-09-18T16:47:04 | 2016-09-09T09:52:44 | null | null | null | A team called Archaeologists of the Central Mountains (ACM) is interested in the famous Helmut's Pyramid (HP) in Egypt. In the Pyramid, there is a Sarcophagus of Umbertiti Nefrites (SUN). According to the legend, the Sarcophagus contains (besides the pharaoh's body, of course) a priceless treasure: air-tickets to Orlando, FL, with the magic date March 2000. The ACM decided to locate this treasure and retrieve it from the Pyramid before it is too late. The problem is that the Pyramid is equipped with many varied traps to protect the tickets from being stolen. Many years of intensive study have been spent monitoring activities inside the Pyramid and discovering all the traps. Finally, the archaeologists are ready to enter the Pyramid. They have a very powerful notebook to help them finish their task. And your task is to provide the software for them.
There is a large room in the Pyramid called Room-of-No-Return. Its floor is covered by rectangular tiles of equal size. The name of the room was chosen because of the very high number of traps and mechanisms in it. The ACM group has spent several years studying the secret plan of this room. It has made a clever plan to avoid all the traps. A specially trained mechanic was sent to deactivate the most feared trap called Shattered Bones. After deactivating the trap the mechanic had to escape from the room. It is very important to step on the center of the tiles only; he must not touch the edges. One wrong step and a large rock falls from the ceiling squashing the mechanic like a pancake. After deactivating the trap, he realized a horrible thing: the ACM plan did not take his equipment box into consideration. The box must be laid onto the ground because the mechanic must have both hands free to prevent contact with other traps. But when the box is laid on the ground, it could touch the line separating the tiles. And this is the main problem you are to solve.
**Input Specification:**
The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case consists of a single line. The line contains exactly four integer numbers separated by spaces: A, B, X and Y. A and Bindicate the dimensions of the tiles, X and Y are the dimensions of the equipment box (1 <= A,B,X,Y <= 50000).
**Output Specification:**
Your task is to determine whether it is possible to put the box on a single tile -- that is, if the whole box fits on a single tile without touching its border. If so, you are to print one line with the sentence "Escape is possible.". Otherwise print the sentence "Box cannot be dropped.".
**Sample Input:**
2
10 10 8 8
8 8 10 10
**Output for the Sample Input:**
Escape is possible.
Box cannot be dropped.
| 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T16:50:04 | 2016-05-12T23:56:35 | setter | #define TEXT_YES "Escape is possible.\n"
#define TEXT_NO "Box cannot be dropped.\n"
#include <stdio.h>
#include <math.h>
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 | 4,320 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include<conio.h>
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 | 4,322 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T17:52:34 | 2016-05-12T23:56:35 | setter | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
template<class T> 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 | 4,325 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T18:16:49 | 2016-05-12T23:56:34 | setter | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
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 | 4,327 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-18T18:48:46 | 2016-05-12T23:56:34 | setter | #include <stdio.h>
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<n_digits || overflow; j++) {
if (j<n_digits) {
digits[j] = digits[j] * i + overflow;
} else {
digits[j] = overflow;
}
overflow = digits[j] / 10;
digits[j] = digits[j] % 10;
}
n_digits = j;
}
printf("%d! --\n", n);
for (i=0; i<n_digits; i++) {
digit_counts[digits[i]]++;
}
for (i=0; i<10; i++) {
printf(" (%d) %3d ", i, digit_counts[i]);
digit_counts[i] = 0;
if (i==4 || i==9) putchar('\n');
}
scanf("%d", &n);
}
return 0;
} | not-set | 2016-04-24T02:03:06 | 2016-04-24T02:03:06 | C++ |
191 | 4,335 | galactic-import | Galactic Import | With the introduction of the new ThrustoZoom gigadimensional drive, it has become possible for HyperCommodities, the import/export conglomerate from New Jersey, to begin trading with even the most remote galaxies in the universe. HyperCommodities wants to import goods from some of the galaxies in the Plural Z sector. Planets within these galaxies export valuable products and raw materials like vacuuseal, transparent aluminum, digraphite, and quantum steel. Preliminary reports have revealed the following facts:
* Each galaxy contains at least one and at most 26 planets. Each planet within a galaxy is identified by a unique letter from A to Z.
* Each planet specializes in the production and export of one good. Different planets within the same galaxy export different goods.
* Some pairs of planets are connected by hyperspace shipping lines. If planets A and B are connected, they can trade goods freely. If planet C is connected to B but not to A, then A and C can still trade goods with each other through B, but B keeps 5% of the shipment as a shipping fee. (Thus A only receives 95% of what C shipped, and C receives only 95% of what A shipped.) In general, any two planets can trade goods as long as they are connected by some set of shipping lines, but each intermediate planet along the shipping route keeps 5% of what it shipped (which is not necessarily equal to 5% of the original shipment).
* At least one planet in each galaxy is willing to open a ThrustoZoom shipping line to Earth. A ThrustoZoom line is the same as any other shipping line within the galaxy, as far as business is concerned. For example, if planet K opens a ThrustoZoom line to Earth, then the Earth can trade goods freely with K, or it can trade goods with any planet connected to K, subject to the usual shipping fees.
HyperCommodities has assigned a relative value (a positive real number less than 10) to each planet's chief export. The higher the number, the more valuable the product. More valuable products can be resold with a higher profit margin in domestic markets. The problem is to determine which planet has the most valuable export when shipping fees are taken into account.
**Input Format:**
The consists of one or more galaxy descriptions. Each galaxy description begins with a line containing an integer N which specifies the number of planets in the galaxy. The next N lines contain descriptions of each planet, which consist of:
1. The letter used to represent the planet.
2. A space.
3. The relative value of the planet's export, in the form d.dd.
4. A space.
5. A string containing letters and/or the character `'*'`; a letter indicates a shipping line to that planet, and a`'*'` indicates a willingness to open a ThrustoZoom shipping line to Earth.
**Output Format:**
For each galaxy description, output a single line which reads "Import from P" where P is the letter of the planet with the most valuable export, once shipping fees have been taken into account. (If more than one planet have the same most valuable export value then output the plant which is alphabetically first).
A **sample input** is shown here:
1
F 0.81 *
5
E 0.01 *A
D 0.01 A*
C 0.01 *A
A 1.00 EDCB
B 0.01 A*
10
S 2.23 Q*
A 9.76 C
K 5.88 MI
E 7.54 GC
M 5.01 OK
G 7.43 IE
I 6.09 KG
C 8.42 EA
O 4.55 QM
Q 3.21 SO
The following **output** should be produced from the above sample input:
Import from F
Import from A
Import from A | code | With the introduction of the new ThrustoZoom gigadimensional drive, it has become possible for HyperCommodities, the import/export conglomerate from New Jersey, to begin trading with even the most remote galaxies in the universe. HyperCommodities wants your help for this. | ai | 2014-09-19T04:22:14 | 2016-09-09T09:52:51 | null | null | null | With the introduction of the new ThrustoZoom gigadimensional drive, it has become possible for HyperCommodities, the import/export conglomerate from New Jersey, to begin trading with even the most remote galaxies in the universe. HyperCommodities wants to import goods from some of the galaxies in the Plural Z sector. Planets within these galaxies export valuable products and raw materials like vacuuseal, transparent aluminum, digraphite, and quantum steel. Preliminary reports have revealed the following facts:
* Each galaxy contains at least one and at most 26 planets. Each planet within a galaxy is identified by a unique letter from A to Z.
* Each planet specializes in the production and export of one good. Different planets within the same galaxy export different goods.
* Some pairs of planets are connected by hyperspace shipping lines. If planets A and B are connected, they can trade goods freely. If planet C is connected to B but not to A, then A and C can still trade goods with each other through B, but B keeps 5% of the shipment as a shipping fee. (Thus A only receives 95% of what C shipped, and C receives only 95% of what A shipped.) In general, any two planets can trade goods as long as they are connected by some set of shipping lines, but each intermediate planet along the shipping route keeps 5% of what it shipped (which is not necessarily equal to 5% of the original shipment).
* At least one planet in each galaxy is willing to open a ThrustoZoom shipping line to Earth. A ThrustoZoom line is the same as any other shipping line within the galaxy, as far as business is concerned. For example, if planet K opens a ThrustoZoom line to Earth, then the Earth can trade goods freely with K, or it can trade goods with any planet connected to K, subject to the usual shipping fees.
HyperCommodities has assigned a relative value (a positive real number less than 10) to each planet's chief export. The higher the number, the more valuable the product. More valuable products can be resold with a higher profit margin in domestic markets. The problem is to determine which planet has the most valuable export when shipping fees are taken into account.
**Input Format:**
The consists of one or more galaxy descriptions. Each galaxy description begins with a line containing an integer N which specifies the number of planets in the galaxy. The next N lines contain descriptions of each planet, which consist of:
1. The letter used to represent the planet.
2. A space.
3. The relative value of the planet's export, in the form d.dd.
4. A space.
5. A string containing letters and/or the character `'*'`; a letter indicates a shipping line to that planet, and a`'*'` indicates a willingness to open a ThrustoZoom shipping line to Earth.
**Output Format:**
For each galaxy description, output a single line which reads "Import from P" where P is the letter of the planet with the most valuable export, once shipping fees have been taken into account. (If more than one planet have the same most valuable export value then output the plant which is alphabetically first).
A **sample input** is shown here:
1
F 0.81 *
5
E 0.01 *A
D 0.01 A*
C 0.01 *A
A 1.00 EDCB
B 0.01 A*
10
S 2.23 Q*
A 9.76 C
K 5.88 MI
E 7.54 GC
M 5.01 OK
G 7.43 IE
I 6.09 KG
C 8.42 EA
O 4.55 QM
Q 3.21 SO
The following **output** should be produced from the above sample input:
Import from F
Import from A
Import from A | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T04:22:51 | 2016-05-12T23:56:33 | setter | //When the input is from a file and the output is to a file. (Logic remains the same.)
#include <stdio.h>
#include <string.h>
#include <math.h>
#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 | 4,339 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 <ctype.h>
#include <fstream.h>
#include <string.h>
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 | 4,342 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 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 <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <string.h>
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 | 4,344 | 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:**
<a> is acceptable.
<tv> is not acceptable.
<ptoui> is not acceptable.
<bontres> is not acceptable.
<zoggax> is not acceptable.
<wiinq> is not acceptable.
<eep> is acceptable.
<houctuh> 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 | null | null | null | 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:**
<a> is acceptable.
<tv> is not acceptable.
<ptoui> is not acceptable.
<bontres> is not acceptable.
<zoggax> is not acceptable.
<wiinq> is not acceptable.
<eep> is acceptable.
<houctuh> 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T07:42:45 | 2016-05-12T23:56:31 | setter | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
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 | 4,346 | 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 | null | null | null | *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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T08:11:14 | 2016-05-12T23:56:31 | setter | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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 | 4,355 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T15:43:15 | 2016-05-12T23:56:29 | setter | #include <stdio.h>
#include <stdlib.h>
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; i<n; i++) a[i] = b[i];
for (i=n-1; i>0; i--) {
for (j=0; j<i; j++) {
if (a[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<n-1; i++) {
if (a[i] > a[i+1]) return 0;
}
return 1;
}
for (i=0; i<n-1; i++) {
swap(a, i);
ns += try1(n, a, depth-1);
swap(a, i);
}
return ns;
}
int main() {
int set_no=1;
int n, *a, ns, min_ns, i;
scanf("%d", &n);
while (n) {
a = (int*)malloc(sizeof(int) * n);
for (i=0; i<n; i++) {
scanf("%d", a+i);
}
min_ns = bub_srt(n, a);
ns = min_ns ? try1(n, a, min_ns) : 0;
printf("There are %d swap maps for input data set %d.\n", ns, set_no++);
scanf("%d", &n);
}
return 0;
}
| not-set | 2016-04-24T02:03:06 | 2016-04-24T02:03:06 | C++ |
197 | 4,356 | concurrency-check | Concurrency Check | 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)
| 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T15:59:07 | 2016-05-12T23:56:29 | setter | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
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; i<n_nodes; i++) {
for (j=0; j<n_nodes; j++) {
printf("%d ", REL(i, j));
} putchar('\n');
}
putchar('\n');
}
int main() {
int a, b, c=1, i, j, *rel; /* rel == 'related' */
char str[100];
Node *node1, *node2;
scanf("%d", &a);
while (a) {
for (i=0; i<a; i++) {
scanf("%d", &b);
node1 = 0;
for (j=0; j<b; j++) {
scanf("%s", str);
node1 = NewNode(str, node1);
}
}
rel = (int*)malloc(sizeof(int) * n_nodes * n_nodes);
for (i=0; i<n_nodes; i++)
for (j=0; j<n_nodes; j++)
REL(i, j) = 0;
scanf("%d", &b);
for (j=0; j<b; j++) {
scanf("%s", str);
node1 = FindNode(str);
scanf("%s", str);
node2 = FindNode(str);
/* printf("message from %s to %s\n", node1->name, node2->name); */
AddChild(node1, node2);
}
node1 = head;
while (node1) {
MarkKids(node1, node1->child, rel);
node1 = node1->next;
}
/* Print(rel); */
b = 0;
for (i=0; i<n_nodes; i++) {
for (j=i+1; j<n_nodes; j++) {
if (!REL(i, j)) {
/* printf(" (%s, %s)\n", IndNode(i)->name, IndNode(j)->name); */
b++;
}
}
}
if (b) {
printf("Case %d, %d concurrent events: \n", c++, b);
if (b>2) b=2;
for (i=0; i<n_nodes && b; i++) {
for (j=i+1; j<n_nodes && b; j++) {
if (!REL(i, j)) {
printf("(%s,%s) ", IndNode(i)->name, 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 | 4,357 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T16:20:35 | 2016-05-12T23:56:29 | setter | #include <stdio.h>
#include<stdlib.h>
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 | 4,358 | 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 | null | null | null | 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"] | null | null | null | null | Hard | null | null | null | null | null | null | 2014-09-19T16:31:50 | 2016-05-12T23:56:28 | setter | #include <stdio.h>
#include<stdlib.h>
#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<n;i++)
if (guess[i] == code[i]) match[i] = 'S'; /* strong match */
else match[i] = ' '; /* no match yet */
/* Now identify the remaining weak matches */
for(i=0;i<n;i++) {
if (match[i] == 'S') continue; /* already a strong match */
for (j=0;j<n;j++) {
if (match[j] != ' ') continue; /* element matched already */
if (guess[i] != code[j]) continue; /* no match */
match[j] = 'W'; /* weak match */
break;
}
}
/* Now count the strong and weak matches */
hint[0] = hint[1] = 0;
for (i=0;i<n;i++) switch(match[i]) {
case 'S': hint[0]++; break;
case 'W': hint[1]++; break;
}
}
main()
{
int i, gameno = 0;
for(;;) {
scanf("%d",&n); /* get parameter for this game */
if (n == 0) exit(0); /* all done! */
printf("Game %d:\n", ++gameno);
for(i=0;i<n;i++) scanf("%d",code+i); /* get the secret code */
for(;;) {
for(i=0;i<n;i++) scanf("%d",guess+i); /* get a guess */
if (guess[0] == 0) break; /* end of game */
generate_hint();
printf(" (%d,%d)\n", hint[0], hint[1]);
}
putchar('\n');
}
}
| not-set | 2016-04-24T02:03:06 | 2016-04-24T02:03:06 | C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.