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
200
4,360
jugs-1
Jugs 1
In the movie "Die Hard 3", Bruce Willis and Samuel L. Jackson were confronted with the following puzzle. They were given a 3-gallon jug and a 5-gallon jug and were asked to fill the 5-gallon jug with exactly 4 gallons. This problem generalizes that puzzle. You have two jugs, A and B, and an infinite supply of water. There are three types of actions that you can use: (1) you can fill a jug, (2) you can empty a jug, and (3) you can pour from one jug to the other. Pouring from one jug to the other stops when the first jug is empty or the second jug is full, whichever comes first. For example, if A has 5 gallons and B has 6 gallons and a capacity of 8, then pouring from A to B leaves B full and 3 gallons in A. A problem is given by a triple (Ca,Cb,N), where Ca and Cb are the capacities of the jugs A and B, respectively, and N is the goal. A solution is a sequence of steps that leaves exactly N gallons in jug B. The possible steps are fill A fill B empty A empty B pour A B pour B A success where "pour A B" means "pour the contents of jug A into jug B", and "success" means that the goal has been accomplished. You may assume that the input you are given does have a solution. **Input Format:** Input to your program consists of a series of input lines each defining one puzzle. Input for each puzzle is a single line of three positive integers: Ca, Cb, and N. Ca and Cb are the capacities of jugs A and B, and N is the goal. You can assume 0 < Ca <= Cb and N <= Cb <=1000 and that A and B are relatively prime to one another. '-1' in a new line indicates end of input. **Required Output Format:** Output from your program will consist of a series of instructions from the list of the potential output lines which will result in either of the jugs containing exactly N gallons of water. The last line of output for each puzzle should be the line "success". Output lines start in column 1 and there should be no empty lines nor any trailing spaces. **Sample Input:** 3 5 4 5 7 3 -1 **Sample Output:** fill B pour B A empty A pour B A fill B pour B A success fill A pour A B fill A pour A B empty B pour A B success
code
In the movie "Die Hard 3", Bruce Willis and Samuel L. Jackson were confronted with the following puzzle. They were given a 3-gallon jug and a 5-gallon jug and were asked to fill the 5-gallon jug with exactly 4 gallons. This problem generalizes that puzzle.
ai
2014-09-19T17:16:21
2016-09-09T09:53:02
null
null
null
In the movie "Die Hard 3", Bruce Willis and Samuel L. Jackson were confronted with the following puzzle. They were given a 3-gallon jug and a 5-gallon jug and were asked to fill the 5-gallon jug with exactly 4 gallons. This problem generalizes that puzzle. You have two jugs, A and B, and an infinite supply of water. There are three types of actions that you can use: (1) you can fill a jug, (2) you can empty a jug, and (3) you can pour from one jug to the other. Pouring from one jug to the other stops when the first jug is empty or the second jug is full, whichever comes first. For example, if A has 5 gallons and B has 6 gallons and a capacity of 8, then pouring from A to B leaves B full and 3 gallons in A. A problem is given by a triple (Ca,Cb,N), where Ca and Cb are the capacities of the jugs A and B, respectively, and N is the goal. A solution is a sequence of steps that leaves exactly N gallons in jug B. The possible steps are fill A fill B empty A empty B pour A B pour B A success where "pour A B" means "pour the contents of jug A into jug B", and "success" means that the goal has been accomplished. You may assume that the input you are given does have a solution. **Input Format:** Input to your program consists of a series of input lines each defining one puzzle. Input for each puzzle is a single line of three positive integers: Ca, Cb, and N. Ca and Cb are the capacities of jugs A and B, and N is the goal. You can assume 0 < Ca <= Cb and N <= Cb <=1000 and that A and B are relatively prime to one another. '-1' in a new line indicates end of input. **Required Output Format:** Output from your program will consist of a series of instructions from the list of the potential output lines which will result in either of the jugs containing exactly N gallons of water. The last line of output for each puzzle should be the line "success". Output lines start in column 1 and there should be no empty lines nor any trailing spaces. **Sample Input:** 3 5 4 5 7 3 -1 **Sample Output:** fill B pour B A empty A pour B A fill B pour B A success fill A pour A B fill A pour A B empty B pour A B success
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-19T17:16:36
2016-05-12T23:56:27
setter
#include <stdio.h> #include <stdlib.h> #define min(a,b) (((a)<(b)) ? (a) : (b) ) typedef struct queueItem { unsigned long element; struct queueItem *next; } queueItem; typedef struct Queue { queueItem *first, *last; } Queue; void queueinit(Queue* q) { queueItem *dummy = (queueItem*) malloc(sizeof(*dummy)); q->first = q->last = dummy; dummy->next = dummy; } void enqueue(Queue* q, unsigned long elem) { queueItem *nu = (queueItem*) malloc(sizeof(*nu)); nu->element = elem; nu->next = q->last->next; q->last = q->last->next = nu; } unsigned long dequeue(Queue* q) { queueItem *old = q->first->next; unsigned long elem = old->element; q->first->next = old->next; if (q->last == old) { q->last = q->first; q->first->next = q->first; } free((char*) old); return elem; } void queueelim(Queue* q) { queueItem* curr = q->first->next; while (curr != q->first) { queueItem* old = curr; curr = curr->next; free((char*) old); } free((char*) curr); } #define FILL_A 0 #define FILL_B 1 #define EMPTY_A 2 #define EMPTY_B 3 #define POUR_A_B 4 #define POUR_B_A 5 #define UNVISITED (unsigned long)(-1) unsigned long *initialize(unsigned a, unsigned b) { unsigned long sz = (a+1)*(b+1); unsigned long* p = (unsigned long*) malloc(sz*sizeof(*p)); while (sz--) p[sz] = UNVISITED; return p; } int compute_soln(unsigned a, unsigned b, unsigned n, unsigned long *parent) { Queue q; unsigned long stat; if (n == 0) return 0; queueinit(&q); enqueue(&q,0); parent[0] = 0; while (1) { unsigned long jugStat = dequeue(&q); int action; for (action = FILL_A; action <= POUR_B_A; ++action) { unsigned long cb = jugStat % (b+1); unsigned long ca = jugStat / (b+1); switch (action) { case FILL_A: ca = a; break; case FILL_B: cb = b; break; case EMPTY_A: ca = 0; break; case EMPTY_B: cb = 0; break; case POUR_A_B: { unsigned sum = ca + cb; cb = min(sum,b); ca = sum - cb; } break; case POUR_B_A: { unsigned sum = ca + cb; ca = min(sum,a); cb = sum - ca; } break; } stat = ca * (b+1) + cb; if (parent[stat] == UNVISITED) { parent[stat] = jugStat; if (stat%(b+1) == n) { queueelim(&q); return stat; } enqueue(&q, stat); } } } } void print_soln(FILE *outfp, unsigned long stat, unsigned a, unsigned b, unsigned long *parent) { if (stat == 0) return; print_soln(outfp, parent[stat], a, b, parent); { unsigned long jugStat = parent[stat]; unsigned long cb = jugStat % (b+1); unsigned long ca = jugStat / (b+1); unsigned long nb = stat % (b+1); unsigned long na = stat / (b+1); if (na + nb == ca + cb) { if (na > ca) fprintf(outfp, "pour B A\n"); else fprintf(outfp, "pour A B\n"); } else if (na != ca) { if (na == 0) fprintf(outfp, "empty A\n"); else fprintf(outfp, "fill A\n"); } else if (nb != cb) { if (nb == 0) fprintf(outfp, "empty B\n"); else fprintf(outfp, "fill B\n"); } } } int main(void) { FILE *infp = fopen("jugs.dat", "r"); FILE *outfp= fopen("jugs.out", "w"); while (!feof(infp)) { unsigned long* parent; unsigned long stat; unsigned a,b,n; fscanf(infp, "%d %d %d\n", &a, &b, &n); parent = initialize(a,b); stat = compute_soln(a,b,n,parent); print_soln(outfp, stat, a, b, parent); fprintf(outfp, "success\n"); free((char*) parent); } fclose(infp); fclose(outfp); return(0); }
not-set
2016-04-24T02:03:06
2016-04-24T02:03:06
C++
201
4,375
justtrial
JustTrial
Take a number. Print hello world.
code
null
ai
2014-09-20T12:48:31
2016-09-09T09:53:06
null
null
null
Take a number. Print hello world.
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-09-20T12:49:46
2016-05-12T23:56:26
setter
hi
not-set
2016-04-24T02:03:07
2016-04-24T02:03:07
Unknown
202
4,429
sherlock-and-square
Sherlock and Square
Watson gives a square of side length 1 to Sherlock. Now, after each second, each square of side $L$ will break into four squares each of side $L/2$(as shown in the image below). ![img][123] Now, Watson asks Sherlock: What will be the sum of length of solid lines after $N$ seconds? As the number can be large print result mod $(10^9 + 7)$. For example, after 0 seconds, the length is 4. After 1 second, the length is 6. **Input Format** First line contains $T$, the number of testcases. Each testcase contains $N$ in one line. **Output Format** For each testcase, print the required answer in a new line. **Constraints** $1 \le T \le 10^5$ $0 \le N \le 10^9$ **Sample input** 2 0 1 **Sample output** 4 6 [123]: http://i.imgur.com/yXME9kL.png
code
Help Sherlock in finding the total side lengths of squares.
ai
2014-09-24T02:15:22
2022-09-02T09:55:08
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER n as parameter. # def solve(n): # Write your code here
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): n = int(input().strip()) result = solve(n) fptr.write(str(result) + '\n') fptr.close()
Watson gives a square of side length 1 to Sherlock. Now, after each second, each square of some arbitrary side $L$ will break into four squares each of side $L/2$(as shown in the image below). ![img][123] Now, Watson asks Sherlock: What will be the sum of length of solid lines after $N$ seconds? As the number can be large print result mod $(10^9 + 7)$. For example, after 0 seconds, the length is 4. After 1 second, the length is 6. **Input Format** First line contains $T$, the number of testcases. Each testcase contains $N$ in one line. **Output Format** For each testcase, print the required answer in a new line. **Constraints** $1 \le T \le 10^5$ $0 \le N \le 10^9$ **Sample input** 3 0 1 5 **Sample output** 4 6 66 [123]: http://i.imgur.com/yXME9kL.png
0.55814
["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-24T02:15:28
2016-12-06T15:12:39
setter
###Python 2 ```python MOD=10**9+7 def mpow(a,n): if n==0: return 1 elif n==1: return a p=mpow(a,n/2) if (n&1): return (p*p*a)%MOD else: return (p*p)%MOD t=input() while t: n=input() print (4+2*(mpow(2,n)-1))%MOD t-=1 ```
not-set
2016-04-24T02:03:07
2016-07-23T18:57:34
Python
203
3,082
strange-numbers
Strange numbers
Let $length(A)$ denote the count of digits of a number $A$ in its decimal representation. John is looking for new methods of determining which numbers are strange all day long. All non-negative numbers of length 1 are strange. Further, a number $X$ with $length(X) \ge1$ can also be considered strange if and only if * $X$ is evenly divisible by $length(X)$ * the number $X/length(X)$ is recursively strange Your task is to calculate how many strange numbers belong to an interval $[L, R]$. **Input Format** The first line contains single integer $T$ - the number of test cases. Next $T$ lines contain two integers separated by single space $L$ and $R$. **Output Format** In $T$ lines, print $T$ integers - count of strange numbers belonging to the interval $[L, R]$. **Constraints** $1 \le T \le 200$ $0 \le L < R \le 10^{18}$ **Sample Input** 5 7 25 45 50 1 100 99 103 0 1000000 **Sample Output** 10 1 26 0 96 **Explanation** First testcase: There are $10$ strange numbers that belong to the interval $[7,25]$. They are $7,8,9,10,12,14,16,18,20,24$. Second testcase: Only $48$ satisfies the given constraints.
code
How many strange numbers belong to interval [L, R]?
ai
2014-06-18T20:01:55
2022-09-02T09:54:34
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. LONG_INTEGER l # 2. LONG_INTEGER r # def solve(l, r): # Write your code here
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): first_multiple_input = input().rstrip().split() l = int(first_multiple_input[0]) r = int(first_multiple_input[1]) result = solve(l, r) fptr.write(str(result) + '\n') fptr.close()
Let $length(A)$ denote the count of digits of a number $A$ in its decimal representation. John is looking for new methods of determining which numbers are strange all day long. All non-negative numbers of length 1 are strange. Further, a number $X$ with $length(X) \ge1$ can also be considered strange if and only if * $X$ is evenly divisible by $length(X)$ * the number $X/length(X)$ is recursively strange Your task is to calculate how many strange numbers belong to an interval $[L, R]$. **Input Format** The first line contains single integer $T$ - the number of test cases. Next $T$ lines contain two integers separated by single space $L$ and $R$. **Output Format** In $T$ lines, print $T$ integers - count of strange numbers belonging to the interval $[L, R]$. **Constraints** $1 \le T \le 200$ $0 \le L < R \le 10^{18}$ **Sample Input** 5 7 25 45 50 1 100 99 103 0 1000000 **Sample Output** 10 1 26 0 96 **Explanation** First testcase: There are $10$ strange numbers that belong to the interval $[7,25]$. They are $7,8,9,10,12,14,16,18,20,24$. Second testcase: Only $48$ satisfies the given constraints.
0.492063
["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-25T07:39:33
2016-12-01T23:56:26
setter
###C++ ```cpp #include <iostream> #include <vector> using namespace std; int t; long long l,r; vector<long long> V; const unsigned long long MAX=1e+18; int length(long long X) { int sol=1; while (X>9){ ++sol; X/=10; } return sol; } void precalc() { V.clear(); for(int i=0; i<10; ++i) V.push_back(i); for(int i=1; i<V.size(); ++i) { int len=length(V[i]); unsigned long long next=V[i]*len; for(int new_len=len; new_len<=len+2; ++new_len) { if (next>MAX) break; int L=length(next); if (L>1 && length(next)==new_len) V.push_back(next); next+=V[i]; } } } int solve(long long L, long long R) { int res=0; for(int i=0; i<V.size(); ++i) if (L<=V[i] && V[i]<=R) ++res; return res; } int main() { precalc(); cin >> t; while (t--) { cin >> l >> r; cout << solve(l,r) << endl; } return 0; } ```
not-set
2016-04-24T02:03:07
2016-07-23T17:56:58
C++
204
2,692
euler066
Project Euler #66: Diophantine equation
<p> Consider quadratic Diophantine equations of the form: </p> <p style="text-align:center;"> <i> x </i> <sup> 2 </sup> – D <i> y </i> <sup> 2 </sup> = 1 </p> <p> For example, when D=13, the minimal solution in <i> x </i> is 649 <sup> 2 </sup> – 13×180 <sup> 2 </sup> = 1. </p> <p> It can be assumed that there are no solutions in positive integers when D is square. </p> <p> By finding minimal solutions in <i> x </i> for D = {2, 3, 5, 6, 7}, we obtain the following: </p> <p style="margin-left:20px;"> 3 <sup> 2 </sup> – 2×2 <sup> 2 </sup> = 1 <br> 2 <sup> 2 </sup> – 3×1 <sup> 2 </sup> = 1 <br> <span style="color:#dd0000;font-weight:bold;"> 9 </span> <sup> 2 </sup> – 5×4 <sup> 2 </sup> = 1 <br> 5 <sup> 2 </sup> – 6×2 <sup> 2 </sup> = 1 <br> 8 <sup> 2 </sup> – 7×3 <sup> 2 </sup> = 1 </p> <p> Hence, by considering minimal solutions in <i> x </i> for D ≤ 7, the largest <i> x </i> is obtained when D=5. </p> <p> Find the value of D ≤ 1000 in minimal solutions of <i> x </i> for which the largest value of <i> x </i> is obtained. </p>
code
null
ai
2014-06-16T12:28:31
2022-09-02T10:36:42
null
null
null
<sub>This problem is a programming version of [Problem 66](https://projecteuler.net/problem=66) from [projecteuler.net](https://projecteuler.net/)</sub> Consider quadratic Diophantine equations of the form: $$x^2 - Dy^2 = 1$$ For example, when $D=13$, the minimal solution in $x$ is $649^2 - 13×180^2 = 1$. It can be assumed that there are no solutions in positive integers when D is square. By finding minimal solutions in $x$ for $D = {2, 3, 5, 6, 7}$, we obtain the following: $$3^2 - 2\times2^2 = 1 \\\ 2^2 - 3 \times 1^2 = 1 \\\ \textbf{9}^2 - 5 \times 4^2 = 1 \\\ 5^2 - 6 \times 2^2 = 1 \\\ 8^2 - 7 \times 3^2 = 1 \\\ $$ Hence, by considering minimal solutions in $x$ for $D \le 7$, the largest $x$ is obtained when $D=5$. Find the value of $D \le N$ in minimal solutions of $x$ for which the largest value of $x$ is obtained.
0.5
["ada","bash","c","clojure","coffeescript","cpp","cpp14","csharp","d","elixir","erlang","fortran","fsharp","go","groovy","haskell","java","java8","javascript","julia","kotlin","lolcode","lua","objectivec","ocaml","octave","pascal","perl","php","pypy3","python3","r","racket","ruby","rust","sbcl","scala","smalltalk","swift","tcl","visualbasic","whitespace","cpp20","java15","typescript"]
Input contains an integer $N$. **Constraints** $7 \le N \le 10^4$
Print the answer corresponding to the test case.
```raw 7 ```
```raw 5 ```
Hard
null
null
null
null
null
null
2014-09-25T16:12:17
2016-05-12T23:56:18
tester
```python import math def gen(n): n2 = int(math.sqrt(n)) num = 1 den = n2 yield n2 while True: x = num num = den den = (n - den * den) / x p = int(n2 + 0.5 + num) / den yield p num = p * den - num num, den = den, num def solve_x(d): h0, h1 = 0, 1 k0, k1 = 1, 0 g = gen(d) for a in g: h0, h1 = h1, a*h1+h0 k0, k1 = k1, a*k1+k0 # print h1, k1, h1*h1 - d*k1*k1 if h1*h1 - d*k1*k1 == 1: return h1 N = int(raw_input()) sq = 1 best_x, best_d = 0, 0 for d in xrange(1, N+1): while sq*sq < d: sq += 1 if sq*sq == d: continue act_x = solve_x(d) if act_x > best_x: best_x = act_x best_d = d print best_d ```
not-set
2016-04-24T02:03:08
2016-04-24T02:03:08
Python
205
4,503
fibonacci-gcd
Fibonacci GCD
Fibonacci numbers have the following form: $$Fib_1 = 1 \\\ Fib_2 = 1 \\\ Fib_3 = 2 \\\ \vdots \\\ Fib_n = Fib_{n-2}+Fib_{n-1}$$ We have an array which contains $N$ elements. We want to find $gcd(Fib_{a_1},Fib_{a_2},Fib_{a_3}, \cdots ,Fib_{a_n} )$ **Input Format** First line contains $N$, where $N$ denotes size of the array. Each of the next $N$ lines contains a number: $i^{th}$ line contains $a_i$. **Output Format** Print a single integer — remainder of division of the resulting number by $10^9+7$. **Constraints** $1 \le N \le 2 \times 10^5$ $1 \le a_i \le 10^{12}$ **Sample Input#00** 3 2 3 5 **Sample Output#00** 1 **Explanation#00:** $Fib_2 = 1$ $Fib_3 = 2$ $Fib_5 = 5$ $gcd(1,2,5)=1$ **Sample Input#01** 2 3 6 **Sample Output#01** 2 **Explanation#01:** $Fib_3 = 2$ $Fib_6 = 8$ $gcd(2,8)=2$
code
Find gcd for n fibonacci numbers.
ai
2014-09-29T13:09:27
2022-09-02T09:54:42
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts LONG_INTEGER a as parameter. # def solve(a): # Write your code here
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) for n_itr in range(n): a = int(input().strip()) result = solve(a) fptr.write(str(result) + '\n') fptr.close()
Fibonacci numbers have the following form: $$F_1 = 1 \\\ F_2 = 1 \\\ F_3 = 2 \\\ \vdots \\\ F_n = F_{n-2}+F_{n-1}$$ We have an array $a_1, a_2, \ldots, a_N$ which contains $N$ elements. We want to find $\gcd(F_{a_1},F_{a_2},F_{a_3}, \cdots ,F_{a_N} )$. **Input Format** The first line contains $N$, where $N$ denotes size of the array. Each of the next $N$ lines contains a number: the $i^{\text{th}}$ line contains $a_i$. **Output Format** Print a single integer — the remainder of the division of the resulting number by $10^9+7$. **Constraints** $1 \le N \le 2 \times 10^5$ $1 \le a_i \le 10^{12}$ **Sample Input 1** 3 2 3 5 **Sample Output 1** 1 **Explanation 1** $F_2 = 1$ $F_3 = 2$ $F_5 = 5$ $\gcd(1,2,5)=1$ **Sample Input 2** 2 3 6 **Sample Output 2** 2 **Explanation 2** $F_3 = 2$ $F_6 = 8$ $\gcd(2,8)=2$
0.5
["c","clojure","cpp","cpp14","cpp20","csharp","erlang","go","haskell","java","java8","java15","javascript","julia","kotlin","lua","objectivec","perl","php","pypy3","python3","ruby","rust","scala","swift","typescript","r"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-09-29T13:37:55
2016-12-04T15:20:14
tester
###Python 2 ```python from fractions import gcd mod = 10**9+7 class _: def __init__(a, x=0, y=0): a.x, a.y = x, y __add__ = lambda a, b: _((a.x+b.x)%mod, (a.y+b.y)%mod) __mul__ = lambda a, b: _((a.x*b.x+5*a.y*b.y)%mod, (a.x*b.y+a.y*b.x)%mod) __pow__ = lambda a, b: a if b == 1 else a*a**(b-1) if b&1 else (a*a)**(b>>1) print(_(mod+1>>1,mod+1>>1)**reduce(gcd,(input() for i in xrange(input())))).y*2%mod ```
not-set
2016-04-24T02:03:08
2016-07-23T18:13:25
Python
206
4,516
huskar-tuskar-and-balls
Huskar, Tuskar, and Balls
Huskar and Tuskar are playing a game with balls. There is a tree with $N$ nodes numbered from $1$ to $N$ respectively (Root is $1$). There is a ball on each node. If a node has only one child, the ball on this node will drop onto child node. But if a node has more than one child, Huskar and Tuskar can't decide the way that the ball will follow. So they start deleting edges one by one(Huskar start first) until every ball has exactly one way to go. Every ball must be able to reach a leaf node.(A leaf node is a node which has no children.) In this game each player has a node. When a ball drops onto a player's node, this player gets one point and this ball is removed from the tree. Both of them are *just* trying to maximize their own points. They are not jealous friends. So if one can not affect his own points, he would like to help increasing his friends points. You are given a graph, and you need to determine Huskar and Tuskar's points when they delete edges optimally for themselves. ###Input Format Line 1 : Two integers : $N$ and $Q$ , the number of the nodes in the tree and number of the queries. Lines $2...N$ : line $i$, one integer : the parent of node $i$. Lines $N+1...N+Q$ : line $(N+i)$ , two integers : Huskar's node and Tuskar's node. ###Constraints $1 \le N \le 500\,000$ $1 \le Q \le 500\,000$ ###Output Format You must print $Q$ lines. In each line, two integers for each query : Huskar's points and Tuskar's points. ###Sample Input 1 6 1 4 1 1 3 3 3 6 ###Sample Output 1 2 1 ###Explanation 1 Test Case 1 : First Huskar deletes the edge between 1 and 4. Second Tuskar deletes the edge between 3 and 5. Huskar removes a ball from node 3 and receives a point. Then a ball from node 1 drops onto node 3 and Huskar receive one more point removing this ball. The ball in node 6 gives one point to Tuskar. Two balls from nodes 4 and 2 stay at node 2 and do not affect Huskar or Tuskar's points. ###Sample Input 2 9 2 4 5 1 4 2 2 5 3 6 8 4 9 ###Sample Output 2 4 2 2 3
code
There is a tree with N nodes. Each node has a ball in it. Two kids are playing a game. Eeach kid has a node. They delete some edges. After deleting, balls drop down in that tree. If a ball drops into a kid's nodes, they get points. We are trying to maximize the points that they have.
ai
2014-09-30T18:47:23
2019-07-02T13:58:53
null
null
null
Huskar and Tuskar are playing a game with balls. There is a tree with $N$ nodes numbered from $1$ to $N$ respectively (root is $1$). There is a ball on each node. If a node has only one child, the ball on this node will drop onto the child node. But if a node has more than one child, Huskar and Tuskar can't decide the way that the ball will follow. So they start deleting edges one by one (Huskar goes first) until every ball has exactly one way to go. Every ball must be able to reach a leaf node. (A leaf node is a node which has no children.) In this game each player has a node. When a ball drops onto a player's node, this player gets one point and the ball is removed from the tree. Both of them are *just* trying to maximize their own points. They are not jealous friends. So if one cannot affect his own points, he would like to help increase his friend's points. You are given a graph, and you need to determine Huskar and Tuskar's points when they delete edges optimally for themselves.
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
Line 1 : Two integers : $N$ and $Q$, the number of the nodes in the tree and the number of queries. Lines $2...N$ : line $i$, one integer : the parent of node $i$. Lines $N+1...N+Q$ : line $(N+i)$ , two integers : Huskar's node and Tuskar's node. **Constraints** $2 \le N \le 2 \times 10^5$ $1 \le Q \le 2 \times 10^5$ Huskar and Tuskar can't be on same node.
You must print $Q$ lines. In each line, two integers for each query : Huskar's points and Tuskar's points.
6 1 4 1 1 3 3 3 6
2 1
Hard
null
null
null
null
null
null
2014-10-02T05:25:02
2016-12-04T09:00:09
setter
#include <bits/stdc++.h> using namespace std; const int MAXN = 500010; const int LogN = 21; int dad[MAXN][LogN]; int N,Q; stack<int> st; vector<int> v[MAXN]; int wh[MAXN]; int depth[MAXN]; void iterative( int k ){ st.push(k); while ( !st.empty() ){ k = st.top(); st.pop(); if ( wh[k] < v[k].size() ){ st.push(k); st.push( v[k][ wh[k] ] ); depth[ v[k][wh[k]] ] = depth[k]+1; wh[k]++; } } } int LCA( int a , int b ){ if ( depth[a] > depth[b] ){ for ( int i=LogN-1 ; i>=0 ; i-- ) if ( depth[dad[a][i]] >= depth[b] ) a=dad[a][i]; } else if ( depth[b] > depth[a] ){ for ( int i=LogN-1 ; i>=0 ; i-- ) if ( depth[dad[b][i]] >= depth[a] ) b=dad[b][i]; } if ( a==b ) return a; for ( int i=LogN-1 ; i>=0 ; i-- ) if ( dad[a][i]!=dad[b][i] ){ a=dad[a][i]; b=dad[b][i]; } return dad[a][0]; } int main(){ scanf(" %d %d",&N,&Q); for ( int i=2 ; i<=N ; i++ ){ scanf(" %d",&dad[i][0]); v[ dad[i][0] ].push_back(i); } depth[1] = 1; iterative(1); for ( int i=1 ; i<LogN ; i++ ) for ( int j=1 ; j<=N ; j++ ) dad[j][i] = dad[dad[j][i-1]][i-1]; int a,b,lca; for ( int i=1 ; i<=Q ; i++ ){ scanf(" %d %d",&a,&b); lca = LCA(a,b); printf("%d %d\n",depth[a],depth[b]-depth[lca]); } return 0; }
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
C++
207
4,516
huskar-tuskar-and-balls
Huskar, Tuskar, and Balls
Huskar and Tuskar are playing a game with balls. There is a tree with $N$ nodes numbered from $1$ to $N$ respectively (Root is $1$). There is a ball on each node. If a node has only one child, the ball on this node will drop onto child node. But if a node has more than one child, Huskar and Tuskar can't decide the way that the ball will follow. So they start deleting edges one by one(Huskar start first) until every ball has exactly one way to go. Every ball must be able to reach a leaf node.(A leaf node is a node which has no children.) In this game each player has a node. When a ball drops onto a player's node, this player gets one point and this ball is removed from the tree. Both of them are *just* trying to maximize their own points. They are not jealous friends. So if one can not affect his own points, he would like to help increasing his friends points. You are given a graph, and you need to determine Huskar and Tuskar's points when they delete edges optimally for themselves. ###Input Format Line 1 : Two integers : $N$ and $Q$ , the number of the nodes in the tree and number of the queries. Lines $2...N$ : line $i$, one integer : the parent of node $i$. Lines $N+1...N+Q$ : line $(N+i)$ , two integers : Huskar's node and Tuskar's node. ###Constraints $1 \le N \le 500\,000$ $1 \le Q \le 500\,000$ ###Output Format You must print $Q$ lines. In each line, two integers for each query : Huskar's points and Tuskar's points. ###Sample Input 1 6 1 4 1 1 3 3 3 6 ###Sample Output 1 2 1 ###Explanation 1 Test Case 1 : First Huskar deletes the edge between 1 and 4. Second Tuskar deletes the edge between 3 and 5. Huskar removes a ball from node 3 and receives a point. Then a ball from node 1 drops onto node 3 and Huskar receive one more point removing this ball. The ball in node 6 gives one point to Tuskar. Two balls from nodes 4 and 2 stay at node 2 and do not affect Huskar or Tuskar's points. ###Sample Input 2 9 2 4 5 1 4 2 2 5 3 6 8 4 9 ###Sample Output 2 4 2 2 3
code
There is a tree with N nodes. Each node has a ball in it. Two kids are playing a game. Eeach kid has a node. They delete some edges. After deleting, balls drop down in that tree. If a ball drops into a kid's nodes, they get points. We are trying to maximize the points that they have.
ai
2014-09-30T18:47:23
2019-07-02T13:58:53
null
null
null
Huskar and Tuskar are playing a game with balls. There is a tree with $N$ nodes numbered from $1$ to $N$ respectively (root is $1$). There is a ball on each node. If a node has only one child, the ball on this node will drop onto the child node. But if a node has more than one child, Huskar and Tuskar can't decide the way that the ball will follow. So they start deleting edges one by one (Huskar goes first) until every ball has exactly one way to go. Every ball must be able to reach a leaf node. (A leaf node is a node which has no children.) In this game each player has a node. When a ball drops onto a player's node, this player gets one point and the ball is removed from the tree. Both of them are *just* trying to maximize their own points. They are not jealous friends. So if one cannot affect his own points, he would like to help increase his friend's points. You are given a graph, and you need to determine Huskar and Tuskar's points when they delete edges optimally for themselves.
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
Line 1 : Two integers : $N$ and $Q$, the number of the nodes in the tree and the number of queries. Lines $2...N$ : line $i$, one integer : the parent of node $i$. Lines $N+1...N+Q$ : line $(N+i)$ , two integers : Huskar's node and Tuskar's node. **Constraints** $2 \le N \le 2 \times 10^5$ $1 \le Q \le 2 \times 10^5$ Huskar and Tuskar can't be on same node.
You must print $Q$ lines. In each line, two integers for each query : Huskar's points and Tuskar's points.
6 1 4 1 1 3 3 3 6
2 1
Hard
null
null
null
null
null
null
2014-10-02T05:25:02
2016-12-04T09:00:09
tester
program sparseTableSolution; // Complexity - O(N log N + Q) uses math; const MAXN = 500000; type tEdge = record v, next: longInt; end; var first, depth, dfs_id, dfs_order, max2pow, stack, parent: array[ 1..2 * MAXN ] of longInt; e: array[ 1..MAXN ] of tEdge; st: array[ 1..2 * MAXN, 0..20 ] of longInt; procedure addEdge( u, v: longInt ); const ee: longInt = 0; begin inc( ee ); e[ee].v := v; e[ee].next := first[u]; first[u] := ee; end; procedure dfs( v, d: longInt ); const id: longInt = 0; var i: longInt; begin inc( id ); depth[v] := d; dfs_id[v] := id; dfs_order[id] := v; i := first[v]; while ( i > 0 ) do begin dfs( e[i].v, d + 1 ); inc( id ); dfs_order[id] := v; i := e[i].next; end; end; procedure nonRecursiveDFS( v: longInt ); var i, r, id: longInt; begin id := 0; depth[v] := 1; parent[v] := 0; r := 1; stack[1] := v; while ( r > 0 ) do begin v := stack[r]; dec( r ); while ( depth[ dfs_order[id] ] >= depth[v] ) do begin inc( id ); dfs_order[id] := parent[ dfs_order[id - 1] ]; end; inc( id ); dfs_order[id] := v; dfs_id[v] := id; i := first[v]; while ( i > 0 ) do begin if ( parent[v] <> e[i].v ) then begin depth[ e[i].v ] := depth[v] + 1; parent[ e[i].v ] := v; inc( r ); stack[r] := e[i].v; end; i := e[i].next; end; end; end; function minNode( u, v: longInt ): longInt; begin if ( depth[u] < depth[v] ) then exit( u ) else exit( v ); end; procedure prepareSparseTable( sz: longInt ); var i, j: longInt; begin max2pow[1] := 0; for i := 2 to sz do begin max2pow[i] := max2pow[i - 1]; if ( i = 2 shl max2pow[i] ) then inc( max2pow[i] ); end; for i := 1 to sz do st[i][0] := dfs_order[i]; for j := 0 to 19 do for i := 1 to sz - (2 shl j) + 1 do st[i][j + 1] := minNode( st[i][j], st[i + 1 shl j][j] ); end; function lca( u, v: longInt ): longInt; var l, r, p: longInt; begin l := min( dfs_id[u], dfs_id[v] ); r := max( dfs_id[u], dfs_id[v] ); p := max2pow[r - l + 1]; exit( minNode( st[l][p], st[r - 1 shl p + 1][p] ) ); end; var n, q, i, p, u, v: longInt; begin readln( n, q ); for i := 2 to n do begin readln( p ); addEdge( p, i ); end; // dfs( 1, 1 ); // recursive dfs may cause RTE due to low stack memory (8 MB) nonRecursiveDFS( 1 ); prepareSparseTable( 2 * n ); for i := 1 to q do begin readln( u, v ); writeln( depth[u], ' ', depth[v] - depth[ lca(u, v) ] ); end; end.
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
JavaScript
208
4,529
white-falcon-and-tree
White Falcon And Tree
White falcon has a tree with $N$ nodes. Each node contains a linear function. And $f_u(x)$ is function of a node $u$. Let us denote the path from node $u$ to node $v$ like this : $"p_1,p_2,p_3,...,p_k"$ where $p_1 = u$ and $p_k = v$. White falcon also has $Q$ queries. They are in the following format : 1. "$1$ $u$ $v$ $a$ $b$" Assign $ax + b$ to functions of all the nodes on the path from $u$ to $v$, i.e., $f_u(x)$ is changed to $ax+b$ where x is a node denoted by one of the k indices $"p_1,p_2,p_3,...,p_k"$. 2. "$2$ $u$ $v$ $x$" Calculate this : $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(... f_{p_1}(x))))$ at modulo $(10^9 + 7)$ **Input Format** The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. Following $N - 1$ lines contain edges of the tree. The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above. **Output Format** For each second query, print one line containing an integer that denotes value of function at modulo $(10^9 + 7)$. **Constraints** $1 \leq N \leq 50000$ (Number of nodes) $1 \leq Q \leq 50000$ (Number of queries) $0 \leq a, b, x < 10^9 + 7$ **Sample Input** 2 1 1 1 2 1 2 2 1 2 2 1 1 2 1 2 1 **Sample Output** 3 **Explanation** $f_1(1) = 2$ $f_2(2) = 3$
code
Given a tree with N nodes and two queries, maintain the tree under these two queries.
ai
2014-10-02T18:29:55
2022-08-31T08:33:17
null
null
null
White Falcon has a tree with $N$ nodes. Each node contains a linear function. Let's denote by $f_u(x)$ the linear function contained in the node $u$. Let's denote the path from node $u$ to node $v$ like this: $p_1,p_2,p_3,\ldots,p_k$, where $p_1 = u$ and $p_k = v$, and $p_i$ and $p_{i+1}$ are connected. White Falcon also has $Q$ queries. They are in the following format: 1. $1$ $u$ $v$ $a$ $b$. Assign $ax + b$ as the function of all the nodes on the path from $u$ to $v$, i.e., $f_{p_i}(x)$ is changed to $ax+b$ where $p_1,p_2,p_3,\ldots,p_k$ is the path from $u$ to $v$. 2. $2$ $u$ $v$ $x$. Calculate $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(\ldots f_{p_1}(x))))$ modulo $(10^9 + 7)$
0.5
["ada","bash","c","clojure","coffeescript","cpp","cpp14","cpp20","csharp","d","elixir","erlang","fortran","fsharp","go","groovy","haskell","java","java8","java15","javascript","julia","kotlin","lolcode","lua","objectivec","ocaml","octave","pascal","perl","php","pypy3","python3","r","racket","ruby","rust","sbcl","scala","smalltalk","swift","tcl","typescript","visualbasic","whitespace"]
The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. Following $N - 1$ lines contain edges of the tree. The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above.
For every query of the second kind, print one line containing an integer, the answer for that query. **Constraints** $1 \leq N \leq 50000$ (Number of nodes) $1 \leq Q \leq 50000$ (Number of queries) $0 \leq a, b, x < 10^9 + 7$
2 1 1 1 2 1 2 2 1 2 2 1 1 2 1 2 1
3
Hard
null
null
null
null
null
null
2014-10-02T18:34:19
2016-05-12T23:56:08
setter
#include <algorithm> #include <iostream> #include <cstring> #include <complex> #include <cassert> #include <cstdlib> #include <cstdio> #include <bitset> #include <vector> #include <string> #include <cmath> #include <ctime> #include <queue> #include <list> #include <map> #include <set> #define all(x) (x).begin(), (x).end() #define type(x) __typeof((x).begin()) #define foreach(it, x) for(type(x) it = (x).begin(); it != (x).end(); it++) //!! debug purposes #ifdef KAZAR #define eprintf(...) fprintf(stderr,__VA_ARGS__) #else #define eprintf(...) 0 #endif using namespace std; template<class T> inline void umax(T &a,T b){if(a<b) a = b ; } template<class T> inline void umin(T &a,T b){if(a>b) a = b ; } template<class T> inline T abs(T a){return a>0 ? a : -a;} template<class T> inline T gcd(T a,T b){return __gcd(a, b);} template<class T> inline T lcm(T a,T b){return a/gcd(a,b)*b;} const int inf = 1e9 + 143; const long long longinf = 1e18 + 143; inline int read(){int x;scanf(" %d",&x);return x;} const bool CHECK_SOLUTION = true; const int N = 1 << 18; const int mod = 1e9 + 7; inline int add(int x,int y){return (x + y >= mod)? x + y - mod : x + y;} inline int mul(int x,int y){return (long long)x * y % mod;} inline int power(int x,int n){ int res = 1; while(n > 0){ if(n & 1) res = mul(res, x); n >>= 1; x = mul(x, x); } return res; } struct func{ int a, b; func() : a(-1), b(-1) {}; func(int _a,int _b) : a(_a), b(_b) {} void debug(){ eprintf("%d %d\n",a,b); } }; func merge(const func &g,const func &f){ if(f.a == -1) return g; if(g.a == -1) return f; return func(mul(f.a, g.a), add(mul(f.a, g.b), f.b)); } inline int sums(int x,int n){ int p = power(x, n) - 1; if(p < 0) p += mod; return mul(p, power(x - 1, mod - 2)); } func calc(const func &f,int n){ int s = (f.a == 0)? 1 : ((f.a == 1)? n : sums(f.a, n)); return func(power(f.a, n), mul(s, f.b)); } int tree_sz[N << 1]; namespace treeLR{ func tree[N << 1], lazy[N << 1]; inline void push(int x){ if(lazy[x].a != -1){ lazy[x + x] = lazy[x]; lazy[x + x + 1] = lazy[x]; lazy[x].a = -1; } } func applied(int x){ if(lazy[x].a != -1) return calc(lazy[x], tree_sz[x]); return tree[x]; } inline void relax(int x){ tree[x] = merge(applied(x + x), applied(x + x + 1));// order matters } void upd(int x,int l,int r,int x1,int x2,func by){ if(l > x2 || r < x1) return; if(l >= x1 && r <= x2){ lazy[x] = by; return; } push(x); int m = (l + r) >> 1; upd(x + x, l, m, x1, x2, by); upd(x + x + 1, m + 1, r, x1, x2, by); relax(x); } func get(int x,int l,int r,int x1,int x2){ if(l > x2 || r < x1) return func(-1,-1); if(l >= x1 && r <= x2) return applied(x); push(x); int m = (l + r) >> 1; func L = get(x + x, l, m, x1, x2); func R = get(x + x + 1, m + 1, r, x1, x2); relax(x); return merge(L, R); // order matters } }; namespace treeRL{ func tree[N << 1], lazy[N << 1]; inline void push(int x){ if(lazy[x].a != -1){ lazy[x + x] = lazy[x]; lazy[x + x + 1] = lazy[x]; lazy[x].a = -1; } } func applied(int x){ if(lazy[x].a != -1) return calc(lazy[x], tree_sz[x]); return tree[x]; } inline void relax(int x){ tree[x] = merge(applied(x + x + 1), applied(x + x)); } void upd(int x,int l,int r,int x1,int x2,func by){ if(l > x2 || r < x1) return; if(l >= x1 && r <= x2){ lazy[x] = by; return; } push(x); int m = (l + r) >> 1; upd(x + x, l, m, x1, x2, by); upd(x + x + 1, m + 1, r, x1, x2, by); relax(x); } func get(int x,int l,int r,int x1,int x2){ if(l > x2 || r < x1) return func(-1,-1); if(l >= x1 && r <= x2) return applied(x); push(x); int m = (l + r) >> 1; func L = get(x + x, l, m, x1, x2); func R = get(x + x + 1, m + 1, r, x1, x2); relax(x); return merge(R, L);//order matters again } }; int fa[N], fb[N]; vector<int> g[N]; int sz[N], d[N], par[N]; int id[N], ptr = 0; int inv_id[N]; int up[N]; // for heavy chain void dfs1(int u,int p){ sz[u] = 1; foreach(it, g[u]){ int v = *it; if(v != p){ d[v] = d[u] + 1; par[v] = u; dfs1(v, u); sz[u] += sz[v]; } } } void dfs2(int u,int p){ id[u] = ++ptr; inv_id[ptr] = u; int bigid = -1; foreach(it, g[u]){ int v = *it; if(v != p && (bigid == -1 || sz[bigid] < sz[v])) bigid = v; } if(bigid != -1){ up[bigid] = up[u]? up[u] : u; dfs2(bigid, u); } foreach(it, g[u]){ int v = *it; if(v != bigid && v != p){ up[v] = 0; dfs2(v, u); } } } int get_lca(int u,int v){// calculate lca with H-L decs. for(;;){ int nu = up[u]? up[u] : u; int nv = up[v]? up[v] : v; if(nu == nv){ return (d[u] < d[v])? u : v; }else{ if(d[nu] > d[nv]){ u = par[nu]; }else{ v = par[nv]; } } } } void upd_path(int u,int p,func f){// update all the nodes for both LR and RL eprintf("Updating %d %d with %d %d\n",u,p,f.a,f.b); while(d[u] > d[p]){ if(!up[u]){ treeLR::upd(1, 1, N, id[u], id[u], f); treeRL::upd(1, 1, N, id[u], id[u], f); eprintf("upd : %d\n",u); u = par[u]; }else{ int next = up[u]; if(d[next] < d[p]){ next = p; } eprintf("upd : (%d to %d]\n",next,u); treeLR::upd(1, 1, N, id[next] + 1, id[u], f); treeRL::upd(1, 1, N, id[next] + 1, id[u], f); u = next; } } eprintf("upd : %d\n",p); treeLR::upd(1, 1, N, id[p], id[p], f); treeRL::upd(1, 1, N, id[p], id[p], f); eprintf("End of update\n"); } func get_left(int u,int p){ // including p, travelling from u to p., remember order matters!!!! eprintf("Start get_left %d %d\n",u,p); func cur; while(d[u] > d[p]){ if(!up[u]){ eprintf("append [%d, %d]\n", id[u], id[u]); treeRL::get(1, 1, N, id[u], id[u]).debug(); cur = merge(cur, treeRL::get(1, 1, N, id[u], id[u])); u = par[u]; }else{ int next = up[u]; if(d[next] < d[p]){ next = p; } eprintf("append [%d, %d]\n", id[next] + 1, id[u]); treeRL::get(1, 1, N, id[next] + 1, id[u]).debug(); cur = merge(cur, treeRL::get(1, 1, N, id[next] + 1, id[u])); u = next; } } eprintf("cur\n"); cur.debug(); eprintf("append [%d, %d]\n",id[p],id[p]); treeLR::get(1, 1, N, id[p], id[p]).debug(); cur = merge(cur, treeRL::get(1, 1, N, id[p], id[p])); eprintf("final func : %d %d\n",cur.a,cur.b); eprintf("End of get_left\n"); return cur; } func get_right(int u,int p,bool add_damn_parent){ // p is not including, travelling from p to u eprintf("Introduce bloddy get_right\n"); func cur; while(d[u] > d[p]){ if(!up[u]){ cur = merge(treeLR::get(1, 1, N, id[u], id[u]), cur); u = par[u]; }else{ int next = up[u]; if(d[next] < d[p]){ next = p; } eprintf("fuck fuck fuck append this : [%d,%d]\n",id[next] + 1,id[u]); treeRL::get(1, 1, N, id[next] + 1, id[u]).debug(); cur = merge(treeLR::get(1, 1, N, id[next] + 1, id[u]), cur); u = next; } } if(add_damn_parent){ eprintf("damn parent coming : [%d,%d]\n",id[p],id[p]); cur = merge(treeLR::get(1, 1, N, id[p], id[p]), cur); } eprintf("The End bloddy get_right\n"); return cur; } func get_path(int u,int v){ int lca = get_lca(u, v); if(lca == u){ return get_right(v, u, true); } if(lca == v){ eprintf("left\n"); get_left(u, v).debug(); return get_left(u, v); } eprintf("-----------left\n"); get_left(u, lca).debug(); eprintf("----------right\n"); get_right(v, lca, false).debug(); return merge(get_left(u, lca), get_right(v, lca, false)); } namespace naive{ void upd_path(int u,int p,int a,int b){ for(;;){ fa[u] = a; fb[u] = b; if(u == p) break; u = par[u]; } } int calc(int u,int x,int dest,int p){ if(u == dest) return x; foreach(it, g[u]){ int v = *it; if(v == p) continue; int t = calc(v, add(mul(fa[v], x), fb[v]), dest, u); if(t != -1) return t; } return -1; } int get_path(int u,int v,int x){ return calc(u, add(mul(fa[u], x), fb[u]), v, 0); } }; int main(){ #ifdef KAZAR freopen("f.input","r",stdin); freopen("f.output","w",stdout); freopen("error","w",stderr); #endif for(int i = N; i < N + N; i++) tree_sz[i] = 1; for(int i = N - 1; i > 0; i--) tree_sz[i] = tree_sz[i + i] + tree_sz[i + i + 1]; int n = read(); for(int i = 1; i <= n; i++){ fa[i] = read(); fb[i] = read(); assert(fa[i] >= 0 && fa[i] < mod); assert(fb[i] >= 0 && fb[i] < mod); } for(int i = 1; i < n; i++){ int u = read(); int v = read(); g[u].push_back(v); g[v].push_back(u); } dfs1(1, 0); dfs2(1, 0); for(int i = 1; i <= n; i++){ eprintf("id[%d] = %d\n",i,id[i]); treeLR::upd(1, 1, N, id[i], id[i], func(fa[i], fb[i])); treeRL::upd(1, 1, N, id[i], id[i], func(fa[i], fb[i])); } int q = read(); for(int i = 0; i < q; i++){ int t = read(); if(t == 1){ int u = read(), v = read(); int a = read(), b = read(); int lca = get_lca(u, v); eprintf("lca : %d\n",lca); upd_path(u, lca, func(a, b)); upd_path(v, lca, func(a, b)); if(CHECK_SOLUTION){ naive::upd_path(u, lca, a, b); naive::upd_path(v, lca, a, b); } }else{ int u = read(), v = read(), x = read(); func f = get_path(u, v); printf("%d\n",add(mul(f.a, x), f.b)); if(CHECK_SOLUTION){ if(naive::get_path(u, v, x) != add(mul(f.a, x), f.b)){ eprintf("Lca : %d\n",get_lca(u, v)); eprintf("on the %d -> %d with %d\n",u,v,x); eprintf("naive : %d\n",naive::get_path(u, v, x)); eprintf("fastt : %d\n",add(mul(f.a, x), f.b)); exit(123); } } } } return 0; }
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
C++
209
4,529
white-falcon-and-tree
White Falcon And Tree
White falcon has a tree with $N$ nodes. Each node contains a linear function. And $f_u(x)$ is function of a node $u$. Let us denote the path from node $u$ to node $v$ like this : $"p_1,p_2,p_3,...,p_k"$ where $p_1 = u$ and $p_k = v$. White falcon also has $Q$ queries. They are in the following format : 1. "$1$ $u$ $v$ $a$ $b$" Assign $ax + b$ to functions of all the nodes on the path from $u$ to $v$, i.e., $f_u(x)$ is changed to $ax+b$ where x is a node denoted by one of the k indices $"p_1,p_2,p_3,...,p_k"$. 2. "$2$ $u$ $v$ $x$" Calculate this : $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(... f_{p_1}(x))))$ at modulo $(10^9 + 7)$ **Input Format** The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. Following $N - 1$ lines contain edges of the tree. The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above. **Output Format** For each second query, print one line containing an integer that denotes value of function at modulo $(10^9 + 7)$. **Constraints** $1 \leq N \leq 50000$ (Number of nodes) $1 \leq Q \leq 50000$ (Number of queries) $0 \leq a, b, x < 10^9 + 7$ **Sample Input** 2 1 1 1 2 1 2 2 1 2 2 1 1 2 1 2 1 **Sample Output** 3 **Explanation** $f_1(1) = 2$ $f_2(2) = 3$
code
Given a tree with N nodes and two queries, maintain the tree under these two queries.
ai
2014-10-02T18:29:55
2022-08-31T08:33:17
null
null
null
White Falcon has a tree with $N$ nodes. Each node contains a linear function. Let's denote by $f_u(x)$ the linear function contained in the node $u$. Let's denote the path from node $u$ to node $v$ like this: $p_1,p_2,p_3,\ldots,p_k$, where $p_1 = u$ and $p_k = v$, and $p_i$ and $p_{i+1}$ are connected. White Falcon also has $Q$ queries. They are in the following format: 1. $1$ $u$ $v$ $a$ $b$. Assign $ax + b$ as the function of all the nodes on the path from $u$ to $v$, i.e., $f_{p_i}(x)$ is changed to $ax+b$ where $p_1,p_2,p_3,\ldots,p_k$ is the path from $u$ to $v$. 2. $2$ $u$ $v$ $x$. Calculate $f_{p_k}(f_{p_{k-1}}(f_{p_{k-2}}(\ldots f_{p_1}(x))))$ modulo $(10^9 + 7)$
0.5
["ada","bash","c","clojure","coffeescript","cpp","cpp14","cpp20","csharp","d","elixir","erlang","fortran","fsharp","go","groovy","haskell","java","java8","java15","javascript","julia","kotlin","lolcode","lua","objectivec","ocaml","octave","pascal","perl","php","pypy3","python3","r","racket","ruby","rust","sbcl","scala","smalltalk","swift","tcl","typescript","visualbasic","whitespace"]
The first line contains $N$, the number of nodes. The following $N$ lines each contain two integers $a$ and $b$ that describe the function $ax + b$. Following $N - 1$ lines contain edges of the tree. The next line contains $Q$, the number of queries. Each subsequent line contains one of the queries described above.
For every query of the second kind, print one line containing an integer, the answer for that query. **Constraints** $1 \leq N \leq 50000$ (Number of nodes) $1 \leq Q \leq 50000$ (Number of queries) $0 \leq a, b, x < 10^9 + 7$
2 1 1 1 2 1 2 2 1 2 2 1 1 2 1 2 1
3
Hard
null
null
null
null
null
null
2014-10-02T18:34:19
2016-05-12T23:56:08
tester
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <time.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 flsh fflush(stdout) #include <map> #include <algorithm> #include <vector> #include <set> #include <iostream> using namespace std; #define mod 1000000007 // linear operator x -> ax+b struct op { int a, b; op(int a = 1, int b = 0) : a(a), b(b) {} // compose this and v op operator*(op v) { return op(a * (ll)v.a % mod, (a * (ll)v.b + b) % mod); } // evaluate this operator at x int operator() (int x) { return (a * (ll)x + b) % mod; } }; // identity operator op one = op(); // tree node struct node { vector<int> adj; // neighbors op o; int parent; int size; int hson; int hindex; // index of heavy path int hpos; // position in heavy path node(): parent(-1), size(0), hson(-1), hindex(-1) {} }; vector<int> pre; vector<node> nodes(111111); vector<op> ops(111111); // segment tree node struct snode { int i, j, k; op val; op *setv; snode *lft; snode *ryt; // make a segment tree in [i,j) snode (int i, int j, int k): i(i), j(j), k(k), setv(NULL) { if (j - i == 1) { val = ops[i]; lft = ryt = NULL; } else { int l = i + j >> 1; lft = new snode(i, l, k-1); ryt = new snode(l, j, k-1); val = lft->val * ryt->val; } } // visit a node (propagate downwards if necessary) #define visit() do {\ if (setv) {\ if (lft) {\ lft->setv = setv;\ ryt->setv = setv;\ }\ val = setv[k];\ setv = NULL;\ }\ } while (0) // get product in [I,J) in this node op get(int I, int J) { visit(); if (I <= i and j <= J) { return val; } else if (J <= i or j <= I) { return one; } else { return lft->get(I, J) * ryt->get(I, J); } } // set values in [I,J) in this node to v void set(int I, int J, op *v) { if (I <= i and j <= J) { setv = v; visit(); } else { visit(); if (!(J <= i or j <= I)) { lft->set(I, J, v); ryt->set(I, J, v); val = lft->val * ryt->val; } } } }; struct path { vector<int> inds; int size; int parent; // parent node of top of heavy path snode *uptree; snode *dntree; void initialize() { size = inds.size(); int k = 0; while (1 << k < size) k++; fr(i,size) ops[i] = nodes[inds[i]].o; dntree = new snode(0, 1<<k, k); fr(i,size) ops[i] = nodes[inds[size-1-i]].o; uptree = new snode(0, 1<<k, k); } void set(int i, int j, op *v) { // smart enough to know up and down if (i <= j) { dntree->set(i, j+1, v); uptree->set(size-1-j, size-i, v); } else { dntree->set(j, i+1, v); uptree->set(size-1-i, size-j, v); } } op get(int i, int j) { // smart enough to know up and down if (i <= j) { return dntree->get(i, j+1); } else { return uptree->get(size-1-i, size-j); } } }; vector<path> paths(111111); int main() { int n; sf("%d", &n); // collect ops fr(i,n) { int a, b; sf("%d%d", &a, &b); nodes[i].o = op(a, b); } // collect edges fr(i,n-1) { int a, b; sf("%d%d", &a, &b); a--, b--; nodes[a].adj.push_back(b); nodes[b].adj.push_back(a); } // calculate preorder and parents #define add(i,p) (nodes[i].parent = p, pre.push_back(i)) add(0,-1); fr(f,n) { int i = pre[f]; fr(nb,nodes[i].adj.size()) { int j = nodes[i].adj[nb]; if (nodes[i].parent == j) continue; add(j,i); } } #undef add // calculate subtree sizes ffo(f,1,n) { int i = pre[f]; int p = nodes[i].parent; nodes[p].size += ++nodes[i].size; nodes[p].hson = i; } nodes[0].size++; // calculate heavy sons ffo(f,1,n) { int i = pre[f]; int p = nodes[i].parent; if (nodes[nodes[p].hson].size < nodes[i].size) { nodes[p].hson = i; } } // calculate heavy index int hcount = 0; fr(f,n) { int i = pre[f]; int idx = nodes[i].hindex; if (!~idx) { idx = nodes[i].hindex = hcount++; paths[idx].parent = nodes[i].parent; } nodes[i].hpos = paths[idx].inds.size(); paths[idx].inds.push_back(i); int s = nodes[i].hson; if (~s) nodes[s].hindex = idx; } // initialize segment trees fr(h,hcount) paths[h].initialize(); // calculate power of two for n int k = 0; while (1 << k < n) k++; k++; // process queries int q; sf("%d", &q); while (q--) { int t; sf("%d", &t); if (t == 1) { // update query int u, v, a, b; sf("%d%d%d%d", &u, &v, &a, &b); u--, v--; // allocate powers of operator op *o = alok(k, op); o[0] = op(a, b); fo(i,1,k) o[i] = o[i-1] * o[i-1]; // ascend and set in paths #define ascend(i) do {\ int h = nodes[i].hindex;\ paths[h].set(0, nodes[i].hpos, o);\ i = paths[h].parent;\ } while (0) while (nodes[u].hindex != nodes[v].hindex) { if (nodes[u].hindex > nodes[v].hindex) { ascend(u); } else { ascend(v); } } #undef ascend // set in topmost path int h = nodes[u].hindex; paths[h].set(nodes[u].hpos, nodes[v].hpos, o); } else { // get query int u, v, x; sf("%d%d%d", &u, &v, &x); u--, v--; // ascend and calculate operator in paths op l = one; while (nodes[u].hindex != nodes[v].hindex) { if (nodes[u].hindex > nodes[v].hindex) { int h = nodes[u].hindex; x = paths[h].get(0, nodes[u].hpos)(x); u = paths[h].parent; } else { int h = nodes[v].hindex; l = l * paths[h].get(nodes[v].hpos, 0); v = paths[h].parent; } } // operator in topmost path int h = nodes[u].hindex; x = paths[h].get(nodes[v].hpos, nodes[u].hpos)(x); // calculate and print the answer int ans = l(x); if (ans < 0) ans += mod; pf("%d\n", ans); } } }
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
C++
210
4,545
assassins-steps
Assassin's Steps
Training to be an assassin is not easy, especially when training under someone as accomplished as Master <a href="https://www.facebook.com/manavcool.sethi">Al-Manav</a>. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. <a href="http://assassinscreed.wikia.com/wiki/Alta%C3%AFr_Ibn-La%27Ahad">Altair</a> is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? There are three possible choices for him at any time: 1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. 2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. 3. Start from the beginning again. He knows he will perform the steps correctly this time. Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. See the example below for explanation. **Example** Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: _Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. _Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. _Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. _Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: Case 1 Case 2 Case 3 Case 4 Expected Probability 0.49 0.21 0.21 0.09 - Additional steps if he keeps on walking 5 12 12 12 8.57 Additional steps if he jumped back once 7 7 14 14 9.1 Additional steps if he jumped back twice 9 9 9 9 9 Additional steps if restarted immediately 7 7 7 7 7 <br>If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. **Input Format** The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. The next line contains _A_ real numbers: _P_<sub>1</sub>, _P_<sub>2</sub>, ..., _P_<sub>A</sub>. _P_<sub>_i_</sub> is the probability that Altair correctly took the i<sup>th</sup> step in the exercise. **Output Format** Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10<sup>-6</sup>. **Constraints** 1 &le; _T_ &le; 20 1 &le; _A_ < _B_ &le; 10<sup>5</sup> 0 &le; _P_<sub>_i_</sub> &le; 1 **Sample Input** 3 2 7 0.7 0.7 1 25 1 4 4 1 0.95 0.1 0.15 **Sample Output** 7.000000 24.000000 3.943000
code
null
ai
2014-10-05T09:09:55
2016-09-09T09:54:14
null
null
null
Training to be an assassin is not easy, especially when training under someone as accomplished as Master <a href="https://www.facebook.com/manavcool.sethi">Al-Manav</a>. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. <a href="http://assassinscreed.wikia.com/wiki/Alta%C3%AFr_Ibn-La%27Ahad">Altair</a> is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? There are three possible choices for him at any time: 1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. 2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. 3. Start from the beginning again. He knows he will perform the steps correctly this time. Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. See the example below for explanation. **Example** Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: _Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. _Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. _Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. _Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: Case 1 Case 2 Case 3 Case 4 Expected Probability 0.49 0.21 0.21 0.09 - Additional steps if he keeps on walking 5 12 12 12 8.57 Additional steps if he jumped back once 7 7 14 14 9.1 Additional steps if he jumped back twice 9 9 9 9 9 Additional steps if restarted immediately 7 7 7 7 7 <br>If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. **Input Format** The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. The next line contains _A_ real numbers: _P_<sub>1</sub>, _P_<sub>2</sub>, ..., _P_<sub>A</sub>. _P_<sub>_i_</sub> is the probability that Altair correctly took the i<sup>th</sup> step in the exercise. **Output Format** Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10<sup>-6</sup>. **Constraints** 1 &le; _T_ &le; 20 1 &le; _A_ < _B_ &le; 10<sup>5</sup> 0 &le; _P_<sub>_i_</sub> &le; 1 **Sample Input** 3 2 7 0.7 0.7 1 25 1 4 4 1 0.95 0.1 0.15 **Sample Output** 7.000000 24.000000 3.943000
0.5
["bash","c","cpp","java","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-10-05T09:11:21
2018-08-11T06:11:38
setter
#include <cstdio> using namespace std; int main () { int t,A,B,i; double p[100002],product,expected,min; scanf("%d",&t); while(t--) { scanf("%d%d",&A,&B); for (int j=0;j<A;j++) { scanf("%lf",&p[j]); } min = B * 1.0; product = 1; for (int j=0; j<A; j++) { product *= p[j]; expected = product*(A+B-2*j-2)+(1-product)*(A+2*B-2*j-2); if (expected<min) { min=expected; } } printf("%.6lf\n",min); } return 0; }
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
C++
211
4,545
assassins-steps
Assassin's Steps
Training to be an assassin is not easy, especially when training under someone as accomplished as Master <a href="https://www.facebook.com/manavcool.sethi">Al-Manav</a>. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. <a href="http://assassinscreed.wikia.com/wiki/Alta%C3%AFr_Ibn-La%27Ahad">Altair</a> is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? There are three possible choices for him at any time: 1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. 2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. 3. Start from the beginning again. He knows he will perform the steps correctly this time. Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. See the example below for explanation. **Example** Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: _Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. _Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. _Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. _Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: Case 1 Case 2 Case 3 Case 4 Expected Probability 0.49 0.21 0.21 0.09 - Additional steps if he keeps on walking 5 12 12 12 8.57 Additional steps if he jumped back once 7 7 14 14 9.1 Additional steps if he jumped back twice 9 9 9 9 9 Additional steps if restarted immediately 7 7 7 7 7 <br>If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. **Input Format** The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. The next line contains _A_ real numbers: _P_<sub>1</sub>, _P_<sub>2</sub>, ..., _P_<sub>A</sub>. _P_<sub>_i_</sub> is the probability that Altair correctly took the i<sup>th</sup> step in the exercise. **Output Format** Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10<sup>-6</sup>. **Constraints** 1 &le; _T_ &le; 20 1 &le; _A_ < _B_ &le; 10<sup>5</sup> 0 &le; _P_<sub>_i_</sub> &le; 1 **Sample Input** 3 2 7 0.7 0.7 1 25 1 4 4 1 0.95 0.1 0.15 **Sample Output** 7.000000 24.000000 3.943000
code
null
ai
2014-10-05T09:09:55
2016-09-09T09:54:14
null
null
null
Training to be an assassin is not easy, especially when training under someone as accomplished as Master <a href="https://www.facebook.com/manavcool.sethi">Al-Manav</a>. An assassin must learn to how to take the correct steps while walking stealthily in order to become a master assassin. Therefore, a particular training exercise concentrates on making the novice assassin walk in a straight line, taking his steps in the complicated assassin manner. <a href="http://assassinscreed.wikia.com/wiki/Alta%C3%AFr_Ibn-La%27Ahad">Altair</a> is still in training, and makes mistakes when walking in a straight line. In one particular training instance, he has taken some steps, but may have committed some mistakes. That is, he may have taken some steps incorrectly in one or more of the previous steps. Given the probabilities of how likely he was to perform each step correctly, what should he do? There are three possible choices for him at any time: 1. Continue walking to the end. Altair knows he will take the rest of the steps correctly. If one of the earlier steps was wrong, Master Al-Manav will make him take all the steps again -- but he knows he will perform the steps correctly the second time. 2. Jump back some number of steps, and then complete the steps as in option 1. If one of the steps over which he did not jump back was wrong, he will have to walk all the steps again, knowing that he will perform the steps correctly the second time. 3. Start from the beginning again. He knows he will perform the steps correctly this time. Altair wishes to minimize the expected number of additional steps needed. Each forward step in the exercise costs 1 step; and each back jump also costs 1 step. See the example below for explanation. **Example** Suppose the training exercise has 7 steps, and Altair has already taken the first two steps, but had a 30% chance of committing a mistake when taking each one of them. Then there are four possible cases: _Case 1_: He took both the steps without error. This occurs with probability 0.7 * 0.7 = 0.49. _Case 2_: He took the first step correctly but made a mistake while taking the second step. This occurs with probability 0.7 * 0.3 = 0.21. _Case 3_: He took the second step correctly but made a mistake while taking the first step. This occurs with probability 0.3 * 0.7 = 0.21. _Case 4_: He made a mistake while taking both the steps. This occurs with probability 0.3 * 0.3 = 0.09. Altair does not know how many mistakes he actually committed, but for any possible strategy, he can compute the expected number of steps required for using the strategy. This is explained in the table given below: Case 1 Case 2 Case 3 Case 4 Expected Probability 0.49 0.21 0.21 0.09 - Additional steps if he keeps on walking 5 12 12 12 8.57 Additional steps if he jumped back once 7 7 14 14 9.1 Additional steps if he jumped back twice 9 9 9 9 9 Additional steps if restarted immediately 7 7 7 7 7 <br>If he keeps on walking, then there is a 0.49 probability that he will need 5 additional steps, and a 0.51 probability that he will need 12 additional steps. If he repeated the trial many times, then he would use 5 additional steps 49% of the time, and 12 additional steps the remaining 51% of the time, so the average number of additional steps needed would be 0.49 * 5 + 0.51 * 12 = 8.57. However in this case, it would be better for him to restart immediately, which requires 7 additional steps. **Input Format** The first line of the input contains _T_, the number of test cases. Each test case begins with a line containing two integers, _A_ and _B_. _A_ is the number of steps that Altair has already taken, and _B_ is the total number of steps in the exercise. The next line contains _A_ real numbers: _P_<sub>1</sub>, _P_<sub>2</sub>, ..., _P_<sub>A</sub>. _P_<sub>_i_</sub> is the probability that Altair correctly took the i<sup>th</sup> step in the exercise. **Output Format** Output one line corresponding to each test case, containing the expected number of additional steps Altair needs (i.e. not counting the steps he has taken so far), assuming that the optimal strategy is chosen. The error in the answer must not exceed 10<sup>-6</sup>. **Constraints** 1 &le; _T_ &le; 20 1 &le; _A_ < _B_ &le; 10<sup>5</sup> 0 &le; _P_<sub>_i_</sub> &le; 1 **Sample Input** 3 2 7 0.7 0.7 1 25 1 4 4 1 0.95 0.1 0.15 **Sample Output** 7.000000 24.000000 3.943000
0.5
["bash","c","cpp","java","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-10-05T09:11:21
2018-08-11T06:11:38
tester
import java.util.Scanner; public class AssassinSteps { public static double calculateMinSteps(int A, int B, double prob[]) { double sol = Double.MAX_VALUE; double p = 1; for (int c = 1; c<=A; c++) { p *= prob[c-1]; int D = A-c; sol = Math.min(sol, p*(2*D+B-A) + (1-p) * (2*D+2*B-A)); } sol = Math.min(sol, B); return sol; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int numTests = in.nextInt(); int a,b; double p[] = new double[100002]; for(int i=0; i< numTests; i++) { a = in.nextInt(); b = in.nextInt(); for(int j=0; j<a;j++) { p[j] = in.nextDouble(); } try { System.out.println(String.format("%.6f", calculateMinSteps(a,b,p))); } catch (Exception e) { e.printStackTrace(); } } in.close(); } }
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
Python
212
4,546
street-walk
Street Walk
Ram needs to cross the jungle, But in the jungle many paths are dangerous and cannot be taken. Consider the jungle as a n*n grid where, where grid positions are marked as '.' if it is safe else 'x'.Ram starts at the origin of the grid i.e. 0,0 and wants to reach the end of the grid i.e. n-1,n-1.He can only move down or right. Count the total number of ways in which he can reach put of the jungle safely. Since the answer can be large output ways mod 1000000007. If there is no way output -1. Note : Initial and Final position do not contain rock. **Constraints :** t<=10 n<=1000 **Input:** First Line contain **t** the number of test cases. Each test case consists of multiply lines. First line of each test case consist of a single integer **n**, the size of the jungle. n lines follow each consisting of **n characters**. Each character can be either **'x'** or **'.'** 'x' denotes danger. '.' denotes path. **Output:** Output **t** lines each consisting of the **number of ways mod 1000000007** to reach out of the jungle. If there is no way to reach out of the jungle output **-1**. **Sample Input** 2 2 .. .. 3 ..x ..x .x. **Sample Output** 2 -1 **To be eligible for prizes you have to register for Code-O-Mania at the Zeitgeist site. To register visit [Zeitgeist][1]. Only those candidates who have registered on the [Zeitgeist website][2] for the Code-O-Mania contest will be eligible to avail the Prizes.** [1]: http://www.zeitgeist.org.in/#/ [2]: http://zeitgeist.org.in/
code
null
ai
2014-10-05T09:42:29
2016-09-09T09:54:14
null
null
null
Ram needs to cross the jungle, But in the jungle many paths are dangerous and cannot be taken. Consider the jungle as a n*n grid where, where grid positions are marked as '.' if it is safe else 'x'.Ram starts at the origin of the grid i.e. 0,0 and wants to reach the end of the grid i.e. n-1,n-1.He can only move down or right. Count the total number of ways in which he can reach put of the jungle safely. Since the answer can be large output ways mod 1000000007. If there is no way output -1. Note : Initial and Final position do not contain rock. **Constraints :** t<=10 n<=1000 **Input:** First Line contain **t** the number of test cases. Each test case consists of multiply lines. First line of each test case consist of a single integer **n**, the size of the jungle. n lines follow each consisting of **n characters**. Each character can be either **'x'** or **'.'** 'x' denotes danger. '.' denotes path. **Output:** Output **t** lines each consisting of the **number of ways mod 1000000007** to reach out of the jungle. If there is no way to reach out of the jungle output **-1**. **Sample Input** 2 2 .. .. 3 ..x ..x .x. **Sample Output** 2 -1 **To be eligible for prizes you have to register for Code-O-Mania at the Zeitgeist site. To register visit [Zeitgeist][1]. Only those candidates who have registered on the [Zeitgeist website][2] for the Code-O-Mania contest will be eligible to avail the Prizes.** [1]: http://www.zeitgeist.org.in/#/ [2]: http://zeitgeist.org.in/
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-10-05T10:28:53
2017-01-05T15:58:24
setter
#include<iostream> using namespace std; int mod=1000000007; int main() { static int t,i,j,way[1001][1001],n; char c[1001][1001]; cin>>t; while (t--) { cin>>n; for (i=0;i<n;i++) { cin>>c[i]; } way[0][0]=1; for (i=1;i<n;i++) { if (c[0][i]!='x') { way[0][i]=way[0][i-1]; } else { way[0][i]=0; } } for (i=1;i<n;i++) { if (c[i][0]!='x') { way[i][0]=way[i-1][0]; } else { way[i][0]=0; } } for (i=1;i<n;i++) { for (j=1;j<n;j++) { if (c[i][j]!='x') { way[i][j]=way[i-1][j]+way[i][j-1]; way[i][j]%=mod; } else { way[i][j]=0; } } } if (way[n-1][n-1]) cout<<way[n-1][n-1]<<endl; else cout<<-1<<endl; } return 0; }
not-set
2016-04-24T02:03:09
2016-04-24T02:03:09
C++
213
4,571
the-dragon-warrior
The Dragon Warrior
Po has one last task to achieve ultimate glory and be termed The Dragon Warrior of Kung Fu. Po has Tigress, Crane, Mantis, Viper and Monkey to help him with this. Po needs to gain atleast Q calories of energy by the end of this task to defeat Tai Lung. Help us find out if he does ! There are K items hidden in the cells of a grid containing (A+1) rows and (Z+1) columns. Rows are number 0 through A and columns 0 through Z. These K items appear one at a time after the previous item is found. Po can choose which cell he wants to start on. In every round Po can move to any cell in the same row or the same column or stay in the previous cell. If Po is unable to get to an item in a round, it is assured that one of the remaining 5 will. Thus, there are K rounds in all. Po gains calories each time an item is found! Po's gain is A + Z, minus the Manhattan distance of his cell from the cell where the item was found. So if the item was found at cell (j,k) and Po is situated at (s,r), then his gain would be A + Z - | S - J | - | R - K |, where | | denotes absolute value. You are given the integers A, Z, Q and K. You are also given K pairs integers, (X, Y) where X(row) and Y(column) denote the location where the next item is hidden. Note that the items will appear in the same sequece. Calculate the maximum calories gained by Po when all the items have been found. If he gains atleast Q calories of energy print 1. Otherwise print 0. ###Input : The input consists of K+1 lines. The first line has A Z Q and K separated by spaces. The next K lines consist of two space separated integers denoting the X and Y coorinates of item respectively. ###Output : Your output should be **1** if Po gains atleast Q calories. If not, **0**. ###Constraints : - A and Z lie between 1 and 1,000,000. - Q lies between 1 and 1,000,000,000. - K lies between 0 and 50. ###Sample Input : 2 2 6 2 0 0 2 1 ###Sample Output : 1 ###Explanation : The grid consists of 3 rows and 3 columns. Since Po gets to choose where he wants to start he can start with 0,0 to gain a maximum strength of 4 for the first item. Then the second item is on 2,1. So Po moves to cell 2,0. He gains 2 + 2 - | 2 - 2 | - | 1 – 0 | = 3 calories. Thus his total gain would be 4 + 3 = 7. Since 7 > 6 the output is 1.
code
null
ai
2014-10-07T09:27:20
2016-09-09T09:54:23
null
null
null
Po has one last task to achieve ultimate glory and be termed The Dragon Warrior of Kung Fu. Po has Tigress, Crane, Mantis, Viper and Monkey to help him with this. Po needs to gain atleast Q calories of energy by the end of this task to defeat Tai Lung. Help us find out if he does ! There are K items hidden in the cells of a grid containing (A+1) rows and (Z+1) columns. Rows are number 0 through A and columns 0 through Z. These K items appear one at a time after the previous item is found. Po can choose which cell he wants to start on. In every round Po can move to any cell in the same row or the same column or stay in the previous cell. If Po is unable to get to an item in a round, it is assured that one of the remaining 5 will. Thus, there are K rounds in all. Po gains calories each time an item is found! Po's gain is A + Z, minus the Manhattan distance of his cell from the cell where the item was found. So if the item was found at cell (j,k) and Po is situated at (s,r), then his gain would be A + Z - | S - J | - | R - K |, where | | denotes absolute value. You are given the integers A, Z, Q and K. You are also given K pairs integers, (X, Y) where X(row) and Y(column) denote the location where the next item is hidden. Note that the items will appear in the same sequece. Calculate the maximum calories gained by Po when all the items have been found. If he gains atleast Q calories of energy print 1. Otherwise print 0. ###Input : The input consists of K+1 lines. The first line has A Z Q and K separated by spaces. The next K lines consist of two space separated integers denoting the X and Y coorinates of item respectively. ###Output : Your output should be **1** if Po gains atleast Q calories. If not, **0**. ###Constraints : - A and Z lie between 1 and 1,000,000. - Q lies between 1 and 1,000,000,000. - K lies between 0 and 50. ###Sample Input : 2 2 6 2 0 0 2 1 ###Sample Output : 1 ###Explanation : The grid consists of 3 rows and 3 columns. Since Po gets to choose where he wants to start he can start with 0,0 to gain a maximum strength of 4 for the first item. Then the second item is on 2,1. So Po moves to cell 2,0. He gains 2 + 2 - | 2 - 2 | - | 1 – 0 | = 3 calories. Thus his total gain would be 4 + 3 = 7. Since 7 > 6 the output is 1.
0.5
["bash","c","cpp","java","python","python3","java8","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-10-07T09:30:41
2016-05-12T23:56:02
setter
#include<stdio.h> #include<iostream> #include<algorithm> #include <cstring> #include <vector> using namespace std; int k, a, z, q; int dp[51][51][51]; vector <int> x; vector <int> y; int rec(int p, int r, int s) { int &res = dp[p][r][s]; if (res == -1) { if (s == k) { res = 0; } else { int dif = a + z - abs( x[p] - x[s]) - abs( y[r] - y[s]); res = 0; for (int na = 0; na < k; na++) { res = max(res, dif + rec(na,r,s + 1) ); } for (int nb = 0; nb < k; nb++) { res = max(res, dif + rec(p,nb,s + 1) ); } } } return res; } int main() { int row, col, q; scanf("%d %d %d %d", &a, &z, &q, &k); memset(dp, -1, sizeof(dp)); int ans=0; for(int i=0; i<k; i++) { scanf("%d %d", &row, &col); x.push_back(row); //add X coordinates to vector x y.push_back(col); //add Y coordinates to vector y } for(int i=0; i<k; i++) { for(int j=0; j<k; j++) { ans=max(ans, rec(i, j, 0)); } } if(ans>=q) printf("1"); else printf("0"); return 0; }
not-set
2016-04-24T02:03:10
2016-04-24T02:03:10
C++
214
4,582
devu-and-sub-sequence
Devu and Subsequence
Devu is newbie to the computer programming, So he wants your help in solving a problem. Problem can be described as below:<br> Given two lists $A$ and $B$ having same length, Find the largest subsequence of list $A$, whose sum is greater than or equal to corresponding subsequence of list $B$. Corresonding subsequence means indices choosen in both of the lists must be the same. **Input Format** The first line contains an integer $N$ i.e. length of the lists.<br> The second line contains $N$ integers corresponding to list $A$.<br> The second line contains $N$ integers corresponding to list $B$. **Output Format** Print the value of in a single line. **Constraints** $ 1\le N \le 10^5$ <br> $ 0\le A[i] \le 10^7$ <br> $ 0\le B[i] \le 10^7$ <br> **Sample Input** 3 100 100 5 2 2 1000 **Sample Output** 2 **Explanation**<br><br> Largest sub-sequence is when indices $1$ and $2$ are choosen i.e. $100+100 \ge 2+ 2$.
code
Help Devu find the largest subsequence.
ai
2014-10-07T17:06:44
2019-07-02T13:58:55
null
null
null
Devu is a newbie to computer programming, so he wants your help in solving a problem. The problem can be described as below:<br> Given two lists $A$ and $B$ having the same length, find the length of longest subsequence of list $A$, whose sum is greater than or equal to the corresponding subsequence of list $B$. Corresponding subsequence means indices chosen in both of the lists must be the same.
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"]
The first line contains an integer $N$, i.e. the length of the lists.<br> The second line contains $N$ integers corresponding to list $A$.<br> The second line contains $N$ integers corresponding to list $B$. **Constraints** $1 \le N \le 10^5$<br> $0 \le A[i] \le 10^7$<br> $0 \le B[i] \le 10^7$<br>
Print the answer in a single line.
3 100 100 5 2 2 1000
2
Hard
null
null
null
null
null
null
2014-10-07T17:06:54
2016-12-27T13:38:00
setter
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int N; cin>>N; int C[N]; for(int i = 0 ; i< N ; i++) cin>>C[i]; for(int i = 0 ; i< N ; i++) { int x; cin>>x; C[i] = C[i]-x; } sort(C,C+N); long long int s = 0; int ans = 0; for(int i= N-1 ; i >= 0 ; i--) { s = s+ C[i]; if(s >= 0) ans++; else break; } cout<<ans<<endl; return 0; }
not-set
2016-04-24T02:03:10
2016-04-24T02:03:10
C++
215
4,585
devu-and-lucky-numbers
Devu and Lucky Numbers
Devu believes in God, So he thinks that few numbers are lucky and while others are unlucky. Devu considers a number as lucky iff $4$,$5$ and $6$ are the only digits occuring in the number.To calculate his luck factor for today, he wants to add all the lucky numbers. So, your task is pretty simple. Given three numbers $x,y \hspace{2mm}\& \hspace{2mm} z$. You have to find sum of all lucky numbers, having atmax $x$ numbers of $4's$, $y$ numbers of $5's$ and $z$ numbers of $6's$. As summation can be very large, print it modulo $10^9+7$. **Input Format** TA line containing threeinteger $x$,$y$ and $z$.<br> **Output Format** Print the summation modulo $10^9+7$. **Constraints** $ 0\le x \le 100$ <br> $ 0\le y \le 100$ <br> $ 0\le z \le 100$ <br> **Sample Input** 1 1 1 **Sample Output** 3675 **Explanation**<br><br> For the given input: $$4 + 5 +6 + 45+ 54+56+65+46+64 + 456+465+546+564+645+654 = 3675$$
code
Help Devu in adding lucky numbers.
ai
2014-10-07T19:39:07
2016-09-09T09:54:28
null
null
null
You are given three integers $x$, $y$ and $z$. You have to find the sum of all numbers whose digits are made of only $4$, $5$ and $6$, that have at most $x$ fours in decimal representation, at most $y$ fives in decimal representation and at most $z$ sixes in decimal representation. As summation can be very large, print it modulo $10^9+7$. **Input Format** The only line containing three space-separated integers $x$, $y$ and $z$. **Constraints** $ 0\le x \le 100$ $ 0\le y \le 100$ $ 0\le z \le 100$ **Output Format** Output the summation modulo $10^9+7$. **Sample Input#0** 1 1 1 **Sample Output#0** 3675 **Sample Input#1** 1 2 3 **Sample Output#1** 39345806 **Explanation** For the given input: $$4 + 5 +6 + 45+ 54+56+65+46+64 + 456+465+546+564+645+654 = 3675$$
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-10-07T19:39:54
2016-12-19T22:04:42
setter
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7 ; int x , y , z ; int dp[101][101][101] ,cnt[101][101][101]; int solve1(int x,int y,int z){ if(x <= 0 && y <= 0 && z <= 0) return 1 ; int &ret = cnt[x][y][z] ; if(ret != -1) return ret ; ret = 0 ; if(x) ret += solve1(x-1,y,z) ; if(ret >= mod) ret -= mod ; if(y) ret += solve1(x,y-1,z) ; if(ret >= mod) ret -= mod ; if(z) ret += solve1(x,y,z-1) ; if(ret >= mod) ret -= mod ; return ret ; } int solve(int x,int y,int z){ if( x <= 0 && y <= 0 && z <= 0 ) return 0 ; int &ret = dp[x][y][z] ; if(ret != -1) return ret ; ret = 0 ; if(x) ret += (1LL* solve(x-1,y,z) * 10 + 1LL * 4 * solve1(x-1,y,z)) % mod ; if(ret >= mod) ret -= mod ; if(y) ret += (1LL* solve(x,y-1,z) * 10 + 1LL * 5 * solve1(x,y-1,z)) % mod ; if(ret >= mod) ret -= mod ; if(z) ret += (1LL* solve(x,y,z-1) * 10 + 1LL * 6 * solve1(x,y,z-1)) % mod ; if(ret >= mod) ret -= mod ; return ret ; } int main() { cin >> x >> y >> z ; memset(dp,-1,sizeof dp) ; memset(cnt,-1,sizeof cnt) ; int ans = 0 ; for(int i=0;i<=x;i++) for(int j=0;j<=y;j++) for(int k=0;k<=z;k++){ ans += solve(i,j,k) ; if(ans >= mod) ans -= mod ; } cout << ans << endl ; return 0; }
not-set
2016-04-24T02:03:10
2016-04-24T02:03:10
C++
216
4,595
furys-network
Fury's Network
**S.H.I.E.L.D** is an espionage and law-enforcement agency headed by Colonel Nick Fury. Over the years, HYDRA secretly infiltrated **S.H.I.E.L.D** and used the agency to their advantage in many ways. They recruited a large sum of all the agents and silently killed off anyone who got in their way. Soon, Nick Fury found out that **S.H.I.E.L.D** was compromised.<br/><br/> So, he decided to share highly confidential information among the other loyal members through a secret network. The network has **N** systems (numbered from **1 to N**) and there exists a unique communication pathway between any two systems in the network. The communication link between two adjacent systems has some cost **D**. Colonel Fury performs some covert operations in the network. For each operation, he chooses two systems from the network and then increase/decrease or replace the costs of all the links in the communication pathway between the chosen systems.<br/><br/> Agent Romanoff is worried about the utilities of the different pathways. The utility of a communication pathway is the sum of the cubes of the costs of all the links in the pathway. She keeps pinging Colonel Fury to determine the utility between two systems at any time. Fury, being the creator of this network, tells her about the utility instantaneously.<br/><br/> Now, the question that arises is how covert is the network actually? Can only Fury answer for the utilities or can you also? ###Input: The first line of the input contains the integer **N**, denoting the number of systems.<br/> The next **N-1** lines contain triples of the form **X Y D** with the meaning that there is a link between the **X-th** and the **Y-th** system having cost **D**.<br/> The next line contains a single integer **M**, denoting the number of queries.<br/> The next **M** lines contains queries in one of the following forms:<br/> **Q X Y:** utility between the systems **X** and **Y**.<br/> **I X Y Z:** Add **Z** to the cost of all the links between the systems **X** and **Y**<br/> **R X Y Z:** Replace the cost of each link with **Z** between systems **X** and **Y**. ###Output: For every query of type **Q**, print the utility on a separate line. It is assured that the answer will fit in long long int. ###Constraints 1<=**N, M**<=100000<br/> 1<=**X, Y**<=**N**<br/> 1<=**D**<=1000<br/> -1000<=**Z**<=1000<br/> ###Example **Input:**<br/> 5<br/> 1 2 1<br/> 2 3 2<br/> 1 4 3<br/> 4 5 4<br/> 10<br/> Q 1 3<br/> Q 2 4<br/> I 1 5 1<br/> Q 1 5<br/> R 3 4 4<br/> Q 3 4<br/> Q 2 5<br/> I 3 5 -1<br/> Q 3 5<br/> Q 4 1<br/><br/> **Output**<br/> 9<br/> 28<br/> 189<br/> 192<br/> 253<br/> 145<br/> 27
code
A problem for Inscription 2014 organised by NITK.
ai
2014-10-08T13:14:00
2016-09-09T09:54:31
null
null
null
**S.H.I.E.L.D** is an espionage and law-enforcement agency headed by Colonel Nick Fury. Over the years, HYDRA secretly infiltrated **S.H.I.E.L.D** and used the agency to their advantage in many ways. They recruited a large sum of all the agents and silently killed off anyone who got in their way. Soon, Nick Fury found out that **S.H.I.E.L.D** was compromised.<br/><br/> So, he decided to share highly confidential information among the other loyal members through a secret network. The network has **N** systems (numbered from **1 to N**) and there exists a unique communication pathway between any two systems in the network. The communication link between two adjacent systems has some cost **D**. Colonel Fury performs some covert operations in the network. For each operation, he chooses two systems from the network and then increase/decrease or replace the costs of all the links in the communication pathway between the chosen systems.<br/><br/> Agent Romanoff is worried about the utilities of the different pathways. The utility of a communication pathway is the sum of the cubes of the costs of all the links in the pathway. She keeps pinging Colonel Fury to determine the utility between two systems at any time. Fury, being the creator of this network, tells her about the utility instantaneously.<br/><br/> Now, the question that arises is how covert is the network actually? Can only Fury answer for the utilities or can you also? ###Input: The first line of the input contains the integer **N**, denoting the number of systems.<br/> The next **N-1** lines contain triples of the form **X Y D** with the meaning that there is a link between the **X-th** and the **Y-th** system having cost **D**.<br/> The next line contains a single integer **M**, denoting the number of queries.<br/> The next **M** lines contains queries in one of the following forms:<br/> **Q X Y:** utility between the systems **X** and **Y**.<br/> **I X Y Z:** Add **Z** to the cost of all the links between the systems **X** and **Y**<br/> **R X Y Z:** Replace the cost of each link with **Z** between systems **X** and **Y**. ###Output: For every query of type **Q**, print the utility on a separate line. It is assured that the answer will fit in long long int. ###Constraints 1<=**N, M**<=100000<br/> 1<=**X, Y**<=**N**<br/> 1<=**D**<=1000<br/> -1000<=**Z**<=1000<br/> ###Example **Input:**<br/> 5<br/> 1 2 1<br/> 2 3 2<br/> 1 4 3<br/> 4 5 4<br/> 10<br/> Q 1 3<br/> Q 2 4<br/> I 1 5 1<br/> Q 1 5<br/> R 3 4 4<br/> Q 3 4<br/> Q 2 5<br/> I 3 5 -1<br/> Q 3 5<br/> Q 4 1<br/><br/> **Output**<br/> 9<br/> 28<br/> 189<br/> 192<br/> 253<br/> 145<br/> 27
0.5
["bash","c","cpp","java","csharp","python","python3","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-10-08T13:16:40
2017-05-23T11:09:29
setter
#include<cstdio> #include<cstring> #include<vector> #include<algorithm> #define MAX 100001 #define DMAX 262145 using namespace std; struct node { int sum,u; long long sqsum; long long cubsum; bool ch,rep; }seg[DMAX]; struct rx { int s; long long sq; long long cu; }res[MAX]; struct vertex { int to,cost; }e; vector<vertex> v[MAX]; int arr[MAX],l[MAX],p[MAX][17],sub[MAX],pos[MAX],chainHead[MAX],chainInd[MAX]; int indx,z,logn,qs,qe,qn,chainNo,ptr=1; bool cht; void build_tree(int i,int j,int ind) { seg[ind].u=0; seg[ind].ch=false; seg[ind].rep=false; if(i==j) { seg[ind].sum=arr[i]; seg[ind].sqsum=arr[i]*arr[i]; seg[ind].cubsum=seg[ind].sqsum*arr[i]; return; } int mid,l,r; mid=(i+j)>>1; l=ind<<1; r=l+1; build_tree(i,mid,l); build_tree(mid+1,j,r); seg[ind].sum=seg[l].sum+seg[r].sum; seg[ind].sqsum=seg[l].sqsum+seg[r].sqsum; seg[ind].cubsum=seg[l].cubsum+seg[r].cubsum; } int update(int i,int j,int ind) { if(j<qs || i>qe) return 0; int mid,l,r; mid=(i+j)>>1; l=ind<<1; r=l+1; if(seg[ind].ch) { if(seg[ind].rep) { seg[ind].cubsum=0; seg[ind].sqsum=0; seg[ind].sum=0; if(i!=j) { seg[l].u=0; seg[r].u=0; } } if(i!=j) { seg[l].u+=seg[ind].u; seg[l].ch=true; seg[l].rep=seg[ind].rep|seg[l].rep; seg[r].u+=seg[ind].u; seg[r].ch=true; seg[r].rep=seg[ind].rep|seg[r].rep; } int u=seg[ind].u; seg[ind].cubsum+=(long long)(j-i+1)*u*u*u+(seg[ind].sqsum+seg[ind].sum*u)*3*u; seg[ind].sqsum+=(long long)(j-i+1)*u*u+seg[ind].sum*2*u; seg[ind].sum+=(j-i+1)*u; seg[ind].ch=false; seg[ind].rep=false; seg[ind].u=0; } if(i>=qs && j<=qe) { int diff=j-i+1; if(!qn) { seg[ind].u=0; seg[ind].rep=true; res[indx].s=diff*z-seg[ind].sum; res[indx].sq=(long long)diff*z*z-seg[ind].sqsum; res[indx].cu=(long long)diff*z*z*z - seg[ind].cubsum; } else { res[indx].s=diff*z; res[indx].sq=(long long)diff*z*z+2*z*seg[ind].sum; res[indx].cu=(long long)diff*z*z*z + (seg[ind].sqsum+seg[ind].sum*z)*3*z; } seg[ind].u+=z; seg[ind].ch=true; return indx++; } int left,right; left=update(i,mid,l); right=update(mid+1,j,r); if(!left) { seg[ind].sum+=res[right].s; seg[ind].sqsum+=res[right].sq; seg[ind].cubsum+=res[right].cu; return right; } if(!right) { seg[ind].sum+=res[left].s; seg[ind].sqsum+=res[left].sq; seg[ind].cubsum+=res[left].cu; return left; } res[left].s+=res[right].s; res[left].sq+=res[right].sq; res[left].cu+=res[right].cu; seg[ind].sum+=res[left].s; seg[ind].sqsum+=res[left].sq; seg[ind].cubsum+=res[left].cu; return left; } long long query(int i,int j,int ind) { if(j<qs || i>qe) return 0; int mid,l,r; mid=(i+j)>>1; l=ind<<1; r=l+1; if(seg[ind].ch) { if(seg[ind].rep) { seg[ind].sqsum=0; seg[ind].sum=0; seg[ind].cubsum=0; if(i!=j) { seg[l].u=0; seg[r].u=0; } } if(i!=j) { seg[l].u+=seg[ind].u; seg[l].ch=true; seg[l].rep=seg[ind].rep|seg[l].rep; seg[r].u+=seg[ind].u; seg[r].ch=true; seg[r].rep=seg[ind].rep|seg[r].rep; } int u=seg[ind].u; seg[ind].cubsum+=(long long)(j-i+1)*u*u*u+(seg[ind].sqsum+seg[ind].sum*u)*3*u; seg[ind].sqsum+=(long long)(j-i+1)*u*u+seg[ind].sum*2*u; seg[ind].sum+=(j-i+1)*u; seg[ind].ch=false; seg[ind].rep=false; seg[ind].u=0; } if(i>=qs&&j<=qe) return seg[ind].cubsum; return query(i,mid,l)+query(mid+1,j,r); } long long query_up(int i,int j) { if(i==j) return 0; int ichain=chainInd[i],jchain=chainInd[j]; long long ans=0; while(ichain!=jchain) { qs=pos[chainHead[ichain]]; qe=pos[i]; ans+=query(1,ptr,1); i=p[chainHead[ichain]][0]; ichain=chainInd[i]; } if(i!=j) { qs=pos[j]+1; qe=pos[i]; ans+=query(1,ptr,1); } return ans; } void update_up(int i,int j) { if(i==j) return; int ichain=chainInd[i],jchain=chainInd[j]; while(ichain!=jchain) { qs=pos[chainHead[ichain]]; qe=pos[i]; update(1,ptr,1); i=p[chainHead[ichain]][0]; ichain=chainInd[i]; } if(i!=j) { qs=pos[j]+1; qe=pos[i]; update(1,ptr,1); } } void HLD(int s,int cost,int pre) { if(!chainHead[chainNo]) chainHead[chainNo]=s; pos[s]=ptr; arr[ptr++]=cost; chainInd[s]=chainNo; int i,c,x,ind=0; for(i=0;i<v[s].size();i++) { x=v[s][i].to; if(x!=pre) { if(sub[x]>sub[ind]) { ind=x; c=v[s][i].cost; } } } if(ind) HLD(ind,c,s); for(i=0;i<v[s].size();i++) { x=v[s][i].to; if(x!=pre && x!=ind) { chainNo++; HLD(x,v[s][i].cost,s); } } } void dfs(int s,int pre) { int i,x; p[s][0]=pre; l[s]=l[pre]+1; sub[s]=1; for(i=0;i<v[s].size();i++) { x=v[s][i].to; if(x!=pre) { dfs(x,s); sub[s]+=sub[x]; } } } int LCA(int a,int b) { int i,lg; if(l[a]<l[b]) swap(a,b); for(lg=0;(1<<lg)<=l[a];lg++); lg--; if(l[a]!=l[b]) { for(i=lg;i>=0;i--) if(l[a]-(1<<i)>=l[b]) a=p[a][i]; } if(a==b) return a; for(i=lg;i>=0;i--) { if(p[a][i] && p[a][i]!=p[b][i]) { a=p[a][i]; b=p[b][i]; } } return p[a][0]; } long long q(int i,int j) { int lca=LCA(i,j); return query_up(i,lca)+query_up(j,lca); } void upd(int i,int j) { int lca=LCA(i,j); update_up(i,lca); update_up(j,lca); } int main() { int i,j,n,m,x,y; char ch[2]; int turn=20; scanf("%d",&n); for(i=1;i<n;i++) { scanf("%d%d%d",&x,&y,&e.cost); e.to=y; v[x].push_back(e); e.to=x; v[y].push_back(e); } l[0]=-1; dfs(1,0); for(logn=0;(1<<logn)<=n;logn++); /*DP for LCA*/ for(j=1;j<logn;j++) for(i=1;i<=n;i++) { x=p[p[i][j-1]][j-1]; if(x) p[i][j]=x; } HLD(1,-1,0); ptr--; build_tree(1,ptr,1); scanf("%d",&m); while(m--) { indx=1; scanf("%s",ch); scanf("%d%d",&i,&j); if(*ch=='Q') { printf("%lld\n",q(i,j)); } else { scanf("%d",&z); if(*ch=='I') qn=1; else qn=0; upd(i,j); } } return 0; }
not-set
2016-04-24T02:03:10
2016-04-24T02:03:10
C++
217
4,715
totient-until-the-end
Totient Until The End
Saito promises to stay by Louise's side until the end. Louise wants to test the strength of Saito's promise by having him calculate the *totient* until the end. The *totient of $N$*, written as $\phi(N)$, is the number of integers $K$ such that $1 \le K \le N$ and $\gcd(K,N) = 1$. It is clear that when the function $\phi$ is iterated starting from $N$, we will eventually reach $1$ (which we'll call *the end*). Given $N$, Louise asks Saito to find the number of iterations of $\phi$ that can be done until the end (i.e. the number of iterations until we reach $1$). Since $N$ is very large, it will be given in the form $N = a^b c^d e^f g^h$. If Saito is unable to do this, he will receive ten thousand lashes. Please help Saito accomplish this task and prove his worth to Louise! **Input Format** The first line of input contains a single integer $T$, which is the number of test cases. The following lines contain the test cases. Each test case consists of one line containing eight integers, $a$, $b$, $c$, $d$, $e$, $f$, $g$, and $h$. **Output Format** For each test case, output a single line containing the answer. **Constraints** $1 \le T \le 5\cdot 10^4$ $1 \le a, b, c, d, e, f, g, h \le 2\cdot 10^6$ **Sample Input** 2 2 2 3 1 3 1 6 1 1 1 1 1 1 1 1 1 **Sample Output** 6 0 **Explanation** In the first test case, $N = 2^2 3^1 3^1 6^1 = 216$, so iterating $\phi$, we get: $$216 \rightarrow 72 \rightarrow 24 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$$ Therefore, $6$ iterations are needed to reach $1$. In the second test case, since $N = 1$ already, we need $0$ iterations to reach $1$.
code
Find the totient until the end.
ai
2014-10-12T18:19:26
2019-07-02T13:58:55
null
null
null
Saito promises to stay by Louise's side until the end. Louise wants to test the strength of Saito's promise by having him calculate the *totient* until the end. The *totient of $N$*, written as $\phi(N)$, is the number of integers $K$ such that $1 \le K \le N$ and $\gcd(K,N) = 1$. It is clear that when the function $\phi$ is iterated starting from $N$, we will eventually reach $1$ (which we'll call *the end*). Given $N$, Louise asks Saito to find the number of iterations of $\phi$ that can be done until the end (i.e. the number of iterations until we reach $1$). Since $N$ is very large, it will be given in the form $N = a^b c^d e^f g^h$. If Saito is unable to do this, he will receive ten thousand lashes. Please help Saito accomplish this task and prove his worth to Louise! **Input Format** The first line of input contains a single integer, $T$, which is the number of test cases. The following lines contain the test cases. Each test case consists of one line containing eight integers, $a$, $b$, $c$, $d$, $e$, $f$, $g$, and $h$. **Output Format** For each test case output a single line containing the answer. **Constraints** $1 \le T \le 5\times 10^4$ $1 \le a, b, c, d, e, f, g, h \le 2\times 10^6$ **Sample Input** 2 2 2 3 1 3 1 6 1 1 1 1 1 1 1 1 1 **Sample Output** 6 0 **Explanation** In the first test case, $N = 2^2 3^1 3^1 6^1 = 216$, so iterating $\phi$, we get: $$216 \rightarrow 72 \rightarrow 24 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$$ Therefore, $6$ iterations are needed to reach $1$. In the second test case, since $N = 1$ already, we need $0$ iterations to reach $1$.
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
Hard
null
null
null
null
null
null
2014-10-12T22:20:22
2017-01-02T18:12:24
setter
#include <stdio.h> #define N 2000000 #define alok(n,t) ((t*)malloc((n)*sizeof(t))) #include <algorithm> using namespace std; int pf[N+1]; int ex[N+1]; int rm[N+1]; int *n = alok(1111, int); int *m = alok(1111, int); int pi[N+1]; int pis[11111]; int tk[N+1]; int pic, cas; void collect(int n) { while (!(n & 1)) n >>= 1; while (n > 1) { int p = pf[n]; n = rm[n]; if (tk[p] != cas) { tk[p] = cas; pis[pic++] = p; collect(p-1); } } } int main() { for (int i = 0; i <= N; i++) { pf[i] = i; ex[i] = rm[i] = tk[i] = 0; } for (int n = 2; n <= N; n++) { if (pf[n] == n) { for (int j = n; j <= N; j += n) { pf[j] = n; } } rm[n] = n / pf[n]; ex[n] = 1; if (rm[n] % pf[n] == 0) { ex[n] += ex[rm[n]]; rm[n] = rm[rm[n]]; } } int z; scanf("%d", &z); for (cas = 1; cas <= z; cas++) { int a, b, c, d, e, f, g, h; scanf("%d%d%d%d%d%d%d%d", &a, &b, &c, &d, &e, &f, &g, &h); pic = 0; collect(a); collect(c); collect(e); collect(g); if (a > 1 || c > 1 || e > 1 || g > 1) pis[pic++] = 2; if (pic == 0) { printf("0\n"); continue; } sort(pis, pis + pic); for (int i = 0; i < pic; i++) { pi[pis[i]] = i; n[i] = 0; } for (; a > 1; a = rm[a]) n[pi[pf[a]]] += ex[a]*b; for (; c > 1; c = rm[c]) n[pi[pf[c]]] += ex[c]*d; for (; e > 1; e = rm[e]) n[pi[pf[e]]] += ex[e]*f; for (; g > 1; g = rm[g]) n[pi[pf[g]]] += ex[g]*h; c = 0; while (1) { while (~--pic && !n[pic]); if (!++pic) break; for (int i = 0; i < pic; i++) { m[i] = 0; } for (int i = 0; i < pic; i++) { int e = n[i]; if (!e) continue; if (e > 1) m[i] += e-1; for (int f = pis[i]-1; f > 1; f = rm[f]) { m[pi[pf[f]]] += ex[f]; } } int eq = 1; for (int i = 0; i < pic; i++) { if (!m[i]^!n[i]) { eq = 0; break; } } if (eq) { int r = 2000000000; for (int i = 0; i < pic; i++) { int e = n[i]; if (!e) continue; if (e > m[i]) { if (r > e) r = e; } } for (int i = 0; i < pic; i++) { int e = n[i]; if (!e) continue; n[i] = e + (m[i] - e) * r; } c += r; } else { int *temp = n; n = m, m = temp; c++; } } printf("%d\n", c); } }
not-set
2016-04-24T02:03:11
2016-04-24T02:03:11
C++
218
4,715
totient-until-the-end
Totient Until The End
Saito promises to stay by Louise's side until the end. Louise wants to test the strength of Saito's promise by having him calculate the *totient* until the end. The *totient of $N$*, written as $\phi(N)$, is the number of integers $K$ such that $1 \le K \le N$ and $\gcd(K,N) = 1$. It is clear that when the function $\phi$ is iterated starting from $N$, we will eventually reach $1$ (which we'll call *the end*). Given $N$, Louise asks Saito to find the number of iterations of $\phi$ that can be done until the end (i.e. the number of iterations until we reach $1$). Since $N$ is very large, it will be given in the form $N = a^b c^d e^f g^h$. If Saito is unable to do this, he will receive ten thousand lashes. Please help Saito accomplish this task and prove his worth to Louise! **Input Format** The first line of input contains a single integer $T$, which is the number of test cases. The following lines contain the test cases. Each test case consists of one line containing eight integers, $a$, $b$, $c$, $d$, $e$, $f$, $g$, and $h$. **Output Format** For each test case, output a single line containing the answer. **Constraints** $1 \le T \le 5\cdot 10^4$ $1 \le a, b, c, d, e, f, g, h \le 2\cdot 10^6$ **Sample Input** 2 2 2 3 1 3 1 6 1 1 1 1 1 1 1 1 1 **Sample Output** 6 0 **Explanation** In the first test case, $N = 2^2 3^1 3^1 6^1 = 216$, so iterating $\phi$, we get: $$216 \rightarrow 72 \rightarrow 24 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$$ Therefore, $6$ iterations are needed to reach $1$. In the second test case, since $N = 1$ already, we need $0$ iterations to reach $1$.
code
Find the totient until the end.
ai
2014-10-12T18:19:26
2019-07-02T13:58:55
null
null
null
Saito promises to stay by Louise's side until the end. Louise wants to test the strength of Saito's promise by having him calculate the *totient* until the end. The *totient of $N$*, written as $\phi(N)$, is the number of integers $K$ such that $1 \le K \le N$ and $\gcd(K,N) = 1$. It is clear that when the function $\phi$ is iterated starting from $N$, we will eventually reach $1$ (which we'll call *the end*). Given $N$, Louise asks Saito to find the number of iterations of $\phi$ that can be done until the end (i.e. the number of iterations until we reach $1$). Since $N$ is very large, it will be given in the form $N = a^b c^d e^f g^h$. If Saito is unable to do this, he will receive ten thousand lashes. Please help Saito accomplish this task and prove his worth to Louise! **Input Format** The first line of input contains a single integer, $T$, which is the number of test cases. The following lines contain the test cases. Each test case consists of one line containing eight integers, $a$, $b$, $c$, $d$, $e$, $f$, $g$, and $h$. **Output Format** For each test case output a single line containing the answer. **Constraints** $1 \le T \le 5\times 10^4$ $1 \le a, b, c, d, e, f, g, h \le 2\times 10^6$ **Sample Input** 2 2 2 3 1 3 1 6 1 1 1 1 1 1 1 1 1 **Sample Output** 6 0 **Explanation** In the first test case, $N = 2^2 3^1 3^1 6^1 = 216$, so iterating $\phi$, we get: $$216 \rightarrow 72 \rightarrow 24 \rightarrow 8 \rightarrow 4 \rightarrow 2 \rightarrow 1$$ Therefore, $6$ iterations are needed to reach $1$. In the second test case, since $N = 1$ already, we need $0$ iterations to reach $1$.
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
Hard
null
null
null
null
null
null
2014-10-12T22:20:22
2017-01-02T18:12:24
tester
#include <unordered_map> using namespace std; unordered_map<int,int> d,updList; unordered_map<int,int>::iterator it; int p[2000001]; int toAdd[200],toDelete[200]; inline void addToDict(int key,int value) { value+=updList[key]; if(!value)updList.erase(key); else updList[key]=value; } inline void addPrime(int key,int value) { addToDict(key,-value); --key; while(p[key]) { addToDict(p[key],value); key/=p[key]; } } int main() { int T,i,n,ok; int mi,c,a,j; int ans,ts,m,k; for(i=2;i*i<=2000000;i++) if(!p[i]) { p[i]=i; for(j=i*i;j<=2000000;j+=i) p[j]=i; } for(;i<=2000000;i++) if(!p[i]) p[i]=i; scanf("%d",&T); for(ts=0;ts<T;ts++) { for(i=0;i<4;i++) { scanf("%d%d",&n,&a); while(p[n]) { d[p[n]]+=a; n/=p[n]; } } updList.clear(); for(it=d.begin();it!=d.end();++it) addPrime(it->first,1); ans=0; while(!d.empty()) { ok=0; mi=1999999999; for(it=updList.begin();it!=updList.end();++it) if(!d[it->first]) { ok=1; break; } else if(it->second<0) mi=min(mi,d[it->first]); if(ok)mi=1; ans+=mi; m=k=0; for(it=updList.begin();it!=updList.end();++it) { n=d[it->first]; if(!n) { toAdd[m++]=it->first; d[it->first]=it->second*mi; continue; } n+=it->second*mi; if(!n) { d.erase(it->first); toDelete[k++]=it->first; } else d[it->first]=n; } for(i=0;i<m;i++) addPrime(toAdd[i],1); for(i=0;i<k;i++) addPrime(toDelete[i],-1); } printf("%d\n",ans); } return 0; }
not-set
2016-04-24T02:03:11
2016-04-24T02:03:11
C++
219
4,732
pairwise-sum-and-divide
Pairwise Sum and Divide
You are given an array of numbers. Let us denote the array with $A[]$. Your task is very simple. You need to find the value returned by the function $\text{fun}(A)$. fun(A) sum = 0 for i = 1 to A.length for j = i+1 to A.length sum = sum + Floor((A[i]+A[j])/(A[i]*A[j])) return sum In short, this function takes all distinct pairs of indexes from the array and adds the value $ \left \lfloor \frac{A[i]+A[j]}{A[i]\times A[j]}\right \rfloor$ to the sum. Your task is to find the sum. **Note:** $\left \lfloor \frac{A}{B} \right\rfloor$ is the integer division function. **Input Format** The first line contains $T$, the number of test cases to follow. Each test case contains two lines: the first line contains $N$, the size of the array, and the second line contains $N$ integers separated by spaces. **Output Format** The output should contain exactly $T$ lines where the $i^{\text{th}}$ line contains the answer for the $i^{\text{th}}$ test case. **Constraints** $1 \le T \le 15$ $1 \le N \le 2 \times 10^5$ $1 \le \text{Sum of $N$ over all test cases } \le 2 \times 10^5$ $1 \le A[i] \le 10^9$ **Sample Input** 2 3 4 2 3 3 1 4 1 **Sample Output** 0 4 **Explanation** *First Test Case:* $\left \lfloor \frac{6}{8}\right \rfloor + \left \lfloor \frac{7}{12}\right \rfloor + \left \lfloor \frac{5}{6}\right \rfloor = 0$ *Second Test Case:* $\left \lfloor \frac{5}{4}\right \rfloor + \left \lfloor \frac{2}{1}\right \rfloor + \left \lfloor \frac{5}{4}\right \rfloor = 4$
code
Find the sum of ( a_i + a_j ) / (a_i * a_j)
ai
2014-10-13T21:22:42
2022-09-02T09:55:05
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY a as parameter. # def solve(a): # Write your code here
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input().strip()) for t_itr in range(t): a_count = int(input().strip()) a = list(map(int, input().rstrip().split())) result = solve(a) fptr.write(str(result) + '\n') fptr.close()
You are given an array of numbers. Let us denote the array with $A[]$. Your task is very simple. You need to find the value returned by the function $\text{fun}(A)$. fun(A) sum = 0 for i = 1 to A.length for j = i+1 to A.length sum = sum + Floor((A[i]+A[j])/(A[i]*A[j])) return sum In short, this function takes all distinct pairs of indexes from the array and adds the value $ \left \lfloor \frac{A[i]+A[j]}{A[i]\times A[j]}\right \rfloor$ to the sum. Your task is to find the sum. **Note:** $\left \lfloor \frac{A}{B} \right\rfloor$ is the integer division function. **Input Format** The first line contains $T$, the number of test cases to follow. Each test case contains two lines: the first line contains $N$, the size of the array, and the second line contains $N$ integers separated by spaces. **Output Format** The output should contain exactly $T$ lines where the $i^{\text{th}}$ line contains the answer for the $i^{\text{th}}$ test case. **Constraints** $1 \le T \le 15$ $1 \le N \le 2 \times 10^5$ $1 \le \text{Sum of $N$ over all test cases } \le 2 \times 10^5$ $1 \le A[i] \le 10^9$ **Sample Input** 2 3 4 2 3 3 1 4 1 **Sample Output** 0 4 **Explanation** *First Test Case:* $\left \lfloor \frac{6}{8}\right \rfloor + \left \lfloor \frac{7}{12}\right \rfloor + \left \lfloor \frac{5}{6}\right \rfloor = 0$ *Second Test Case:* $\left \lfloor \frac{5}{4}\right \rfloor + \left \lfloor \frac{2}{1}\right \rfloor + \left \lfloor \frac{5}{4}\right \rfloor = 4$
0.541985
["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-10-13T21:23:13
2016-12-13T17:10:36
setter
###C++ ```cpp #include<stdio.h> #include<assert.h> #include<algorithm> using namespace std; typedef long long int ll; ll A[210004]; void solve() { ll n; scanf("%lld",&n); assert(n>=1 && n<=200000); ll ones=0,twos=0,ans=0; for(int i=1;i<=n;i++){ scanf("%lld",&A[i]); assert(A[i]>=1 && A[i] <= 1000000000); if ( A[i] == 1) ones++; if ( A[i] == 2) twos++; } A[n+1] = (1<<30); ans = (twos*(twos-1))/2 + (ones*(n-ones)) + (ones*(ones-1)); printf("%lld\n",ans); } int main() { int T; scanf("%d",&T); while(T--){ solve(); } return 0; } ```
not-set
2016-04-24T02:03:11
2016-07-23T18:56:06
C++
220
4,736
line-segments
Line Segments
Adigha is in trouble with line segments. He can not do his homework and needs someones help. Can you help him? You are given $N$ line segments. All of them lie on the same line. We will describe $i$-*th* line segment with two integers, $A$<sub>$i$</sub> and $B$<sub>$i$</sub>. This means it starts at $A$<sub>$i$</sub> and ends at $B$<sub>$i$</sub>. It will be denoted as $(A$<sub>$i$</sub>$; B$<sub>$i$</sub>$)$. Let's say a pair of line segments is ***good***, if one of them is not covering other one. For example, the pair of $(1; 4)$ and $(2; 5)$ is ***good***. But the pair of $(1; 6)$ and $(2; 5)$ is ***bad*** because $(1; 6)$ covers $(2; 5)$. Let's assume that we have $i$-*th* and $j$-*th* line segments. If $A$<sub>$i$</sub> $ \le A$<sub>$j$</sub> and $B$<sub>$i$</sub> $ \ge $ $B$<sub>$j$</sub>, we can say "$i$-*th* line segment covers $j$-*th* line segment." You must find the size of the biggest subset of these line segments that contains __no__ ***bad*** pairs. ###Input Format Line 1: An integer $N$, the number of the line segments. Line 2...N+1: line $i+1$, two integers, $A$<sub>$i$</sub> and $B$<sub>$i$</sub>. ###Constraints $1 \le N \le 100\,000$ $1 \le $ $A$<sub>$i$</sub> $ \le $ $B$<sub>$i$</sub> $ \le $ $10$<sup>$9$</sup> ###Output Format You must print one integer in one line, the size of the biggest subset. ###Sample Input 1 4 2 5 1 4 1 6 3 8 ###Sample Output 1 3 ###Explanation 1 We can only choose first, second, and fourth line segments. We can not choose third line segment because it covers first and second line segments. ###Sample Input 2 5 5 8 3 7 4 10 12 15 1 7 ###Sample Output 2 3
code
We have N line segments in a plane and all of them are parallel to each other. We will pick a subset with K elements from these line segments. There must be no coincident pairs in that subset. We are trying to maximize K.
ai
2014-10-14T09:44:05
2019-07-02T13:58:56
null
null
null
You are given $N$ line segments. All of them lie on the same line. We will describe the $i^{th}$ line segment with two integers, $A_i$ and $B_i$. This means it starts at $A_i$ and ends at $B_i$. It will be denoted as $(A_i;B_i)$. Let's say a pair of line segments is ***good***, if one of them is not covering the other one. For example, the pair of $(1; 4)$ and $(2; 5)$ is ***good***. But the pair of $(1; 6)$ and $(2; 5)$ is ***bad*** because $(1; 6)$ covers $(2; 5)$. Let's assume that we have the $i^{th}$ and $j^{th}$ line segments. If $A_i \le A_j$ and $B_i \ge B_j$, we can say "the $i^{th}$ line segment covers $j^{th}$ line segment." You must find the size of the biggest subset of these line segments that contains __no__ ***bad*** pairs. **Input Format** In the first line you are given an integer $N$, the total number of line segments. The next $N$ lines contain two integers, $A_i ~and ~B_i$. **Constraints** $1 \le N \le 10^5$ $1 \le $ $A_i \le B_i \le 10^9$ **Output Format** You must print one integer denoting the size of the biggest subset. **Sample Input#0** 4 2 5 1 4 1 6 3 8 **Sample Output#0** 3 **Explanation#0** We can only choose the first, second, and fourth line segments. We can not choose the third line segment because it covers the first and second line segments. **Sample Input#1** 5 5 8 3 7 4 10 12 15 1 7 **Sample Output#1** 3
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
Hard
null
null
null
null
null
null
2014-10-14T10:25:27
2016-05-12T23:58:26
setter
#include <bits/stdc++.h> using namespace std; typedef pair<int,int> ii; const int MAXN = 100010; int seg[5*MAXN]; ii LineS[MAXN]; ii subseq[MAXN]; int N; int comparator( ii a , ii b ){ if ( a.first != b.first ) return a.first < b.first; return a.second > b.second; } int update( int k , int b , int e , int x , int y ){ int m = (b+e)/2; if ( b>x || e<x ) return seg[k]; if ( b==e ) return seg[k] = y; return seg[k] = max( update( 2*k , b , m , x , y ) , update( 2*k+1 , m+1 , e , x , y ) ); } int find( int k , int b , int e , int x , int y ){ int m = (b+e)/2; if ( b>y || e<x ) return 0; if ( b>=x && e<=y ) return seg[k]; return max( find( 2*k , b , m , x , y ) , find( 2*k+1 , m+1 , e , x , y ) ); } int main(){ scanf(" %d",&N); for ( int i=1 ; i<=N ; i++ ) scanf(" %d %d",&LineS[i].first , &LineS[i].second); sort( LineS + 1 , LineS + N + 1 ); for ( int i=1 ; i<=N ; i++ ){ subseq[i].first = LineS[i].second; subseq[i].second = i; } sort( subseq + 1 , subseq + N + 1 , comparator ); // CARE : INCREASING ORDER , NOT NON-DECREASING ORDER for ( int i=1 ; i<=N ; i++ ) update( 1 , 1 , N , subseq[i].second , find( 1 , 1 , N , 1 , subseq[i].second )+1 ); printf("%d\n",seg[1]); return 0; }
not-set
2016-04-24T02:03:11
2016-04-24T02:03:11
C++
221
4,736
line-segments
Line Segments
Adigha is in trouble with line segments. He can not do his homework and needs someones help. Can you help him? You are given $N$ line segments. All of them lie on the same line. We will describe $i$-*th* line segment with two integers, $A$<sub>$i$</sub> and $B$<sub>$i$</sub>. This means it starts at $A$<sub>$i$</sub> and ends at $B$<sub>$i$</sub>. It will be denoted as $(A$<sub>$i$</sub>$; B$<sub>$i$</sub>$)$. Let's say a pair of line segments is ***good***, if one of them is not covering other one. For example, the pair of $(1; 4)$ and $(2; 5)$ is ***good***. But the pair of $(1; 6)$ and $(2; 5)$ is ***bad*** because $(1; 6)$ covers $(2; 5)$. Let's assume that we have $i$-*th* and $j$-*th* line segments. If $A$<sub>$i$</sub> $ \le A$<sub>$j$</sub> and $B$<sub>$i$</sub> $ \ge $ $B$<sub>$j$</sub>, we can say "$i$-*th* line segment covers $j$-*th* line segment." You must find the size of the biggest subset of these line segments that contains __no__ ***bad*** pairs. ###Input Format Line 1: An integer $N$, the number of the line segments. Line 2...N+1: line $i+1$, two integers, $A$<sub>$i$</sub> and $B$<sub>$i$</sub>. ###Constraints $1 \le N \le 100\,000$ $1 \le $ $A$<sub>$i$</sub> $ \le $ $B$<sub>$i$</sub> $ \le $ $10$<sup>$9$</sup> ###Output Format You must print one integer in one line, the size of the biggest subset. ###Sample Input 1 4 2 5 1 4 1 6 3 8 ###Sample Output 1 3 ###Explanation 1 We can only choose first, second, and fourth line segments. We can not choose third line segment because it covers first and second line segments. ###Sample Input 2 5 5 8 3 7 4 10 12 15 1 7 ###Sample Output 2 3
code
We have N line segments in a plane and all of them are parallel to each other. We will pick a subset with K elements from these line segments. There must be no coincident pairs in that subset. We are trying to maximize K.
ai
2014-10-14T09:44:05
2019-07-02T13:58:56
null
null
null
You are given $N$ line segments. All of them lie on the same line. We will describe the $i^{th}$ line segment with two integers, $A_i$ and $B_i$. This means it starts at $A_i$ and ends at $B_i$. It will be denoted as $(A_i;B_i)$. Let's say a pair of line segments is ***good***, if one of them is not covering the other one. For example, the pair of $(1; 4)$ and $(2; 5)$ is ***good***. But the pair of $(1; 6)$ and $(2; 5)$ is ***bad*** because $(1; 6)$ covers $(2; 5)$. Let's assume that we have the $i^{th}$ and $j^{th}$ line segments. If $A_i \le A_j$ and $B_i \ge B_j$, we can say "the $i^{th}$ line segment covers $j^{th}$ line segment." You must find the size of the biggest subset of these line segments that contains __no__ ***bad*** pairs. **Input Format** In the first line you are given an integer $N$, the total number of line segments. The next $N$ lines contain two integers, $A_i ~and ~B_i$. **Constraints** $1 \le N \le 10^5$ $1 \le $ $A_i \le B_i \le 10^9$ **Output Format** You must print one integer denoting the size of the biggest subset. **Sample Input#0** 4 2 5 1 4 1 6 3 8 **Sample Output#0** 3 **Explanation#0** We can only choose the first, second, and fourth line segments. We can not choose the third line segment because it covers the first and second line segments. **Sample Input#1** 5 5 8 3 7 4 10 12 15 1 7 **Sample Output#1** 3
0.5
["bash","c","cpp","java","csharp","php","ruby","python","perl","haskell","clojure","scala","lua","go","javascript","erlang","sbcl","d","ocaml","pascal","python3","groovy","objectivec","fsharp","visualbasic","lolcode","smalltalk","tcl","java8","r","racket","rust","swift","cpp14"]
Hard
null
null
null
null
null
null
2014-10-14T10:25:27
2016-05-12T23:58:26
tester
program lineSegments; type tSegment = record l, r: longInt; end; var a: array[ 1..100000 ] of tSegment; function less( const a, b: tSegment ): boolean; begin if ( a.l <> b.l ) then exit( a.l < b.l ); exit( a.r > b.r ); end; procedure qsort( l, r: longInt ); var i, j: longInt; t, med: tSegment; begin if ( l < r ) then begin i := l; j := r; med := a[ l + random(r - l + 1) ]; while ( i <= j ) do begin while ( less( a[i], med ) ) do inc( i ); while ( less( med, a[j] ) ) do dec( j ); if ( i <= j ) then begin t := a[i]; a[i] := a[j]; a[j] := t; inc( i ); dec( j ); end; end; qsort( l, j ); qsort( i, r ); end; end; var n, i, x, l, r, c, ans: longInt; f: array[ 0..100000 ] of longInt; begin readln( n ); for i := 1 to n do readln( a[i].l, a[i].r ); qsort( 1, n ); ans := 0; f[0] := 0; for i := 1 to n do begin x := a[i].r; if ( x > f[ans] ) then begin inc( ans ); f[ans] := x; continue; end; l := 1; r := ans; while ( l < r ) do begin c := ( l + r ) div 2; if ( f[c] >= x ) then r := c else l := c + 1; end; f[l] := x; end; writeln( ans ); end.
not-set
2016-04-24T02:03:11
2016-04-24T02:03:11
JavaScript
222
4,879
chief-hopper
Chief Hopper
Chief's bot is playing an old DOS-based game. There are $N+1$ buildings in the game - indexed from $0$ to $N$ and are placed left-to-right. It is guaranteed that building with index $0$ will be of height $0$ unit. For buildings with index $i$ ($i \in [1, N]$) height will be $h_i$ units. <br> At beginning Chief's bot is at building with index $0$. At each step, bot jumps to next (right) building. Suppose bot is at $k^{th}$ building and his current energy is $botEnergy$, then in next step he will jump to $(k+1)^{th}$ building. He will gain/lose energy which is directly proportional to difference between $h_{k+1}$ and $botEnergy$ - If $h_{k+1} > botEnergy$, then he will lose $h_{k+1} - botEnergy$ units of energy. - Otherwise, he will gain $botEnergy - h_{k+1}$ units of energy. Goal is to reach $N^{th}$ building, and during the course bot should never have negative energy units. What should be the minimum units of energy with which bot should start to successfully complete the game? **Input Format** The first line contains integer $N$. Next line contains $N$ space separated integers $h_1, h_2, \cdots , h_N$ representing the heights of the buildings. **Output Format** Print a single number representing minimum units of energy required to complete the game. **Constraints** $1 \le N \le 10^5$ $1 \le h_i \le 10^5, i \in [1, N]$ **Sample Input** 5 3 4 3 2 4 **Sample Output** 4 **Explanation** **Sample Input** 3 4 4 4 **Sample Output** 4 **Explanation** In the second test case if bot has energy 4, it's energy is changed by (4 - 4 = 0) at every step and remains 4.
code
Find the minimum units of energy with which bot should start to successfully complete the game.
ai
2014-10-22T02:37:45
2022-08-31T08:14:38
# # Complete the 'chiefHopper' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY arr as parameter. # def chiefHopper(arr): # Write your code here
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) arr = list(map(int, input().rstrip().split())) result = chiefHopper(arr) fptr.write(str(result) + '\n') fptr.close()
Chief's bot is playing an old DOS based game. There is a row of buildings of different heights arranged at each index along a number line. The bot starts at building $0$ and at a height of $0$. You must determine the minimum energy his bot needs at the start so that he can jump to the top of each building without his energy going below zero. Units of height relate directly to units of energy. The bot's energy level is calculated as follows: - If the bot's $botEnergy$ is less than the height of the building, his $newEnergy = botEnergy - (height - botEnergy)$ - If the bot's $botEnergy$ is greater than the height of the building, his $newEnergy = botEnergy + (botEnergy - height)$ **Example** $arr = [2,3,4,3,2]$ Starting with $botEnergy = 4$, we get the following table: <pre> botEnergy height delta 4 2 +2 6 3 +3 9 4 +5 14 3 +11 25 2 +23 48 </pre> That allows the bot to complete the course, but may not be the minimum starting value. The minimum starting $botEnergy$ in this case is $3$. **Function Description** Complete the *chiefHopper* function in the editor below. chiefHopper has the following parameter(s): - *int arr[n]:* building heights **Returns** - *int:* the minimum starting $botEnergy$
0.588235
["ada","bash","c","clojure","coffeescript","cpp","cpp14","cpp20","csharp","d","elixir","erlang","fortran","fsharp","go","groovy","haskell","java","java8","java15","javascript","julia","kotlin","lolcode","lua","objectivec","ocaml","octave","pascal","perl","php","pypy3","python3","r","racket","ruby","rust","sbcl","scala","smalltalk","swift","tcl","typescript","visualbasic","whitespace"]
The first line contains an integer $n$, the number of buildings. The next line contains $n$ space-separated integers $arr[1]..arr[n]$, the heights of the buildings.
5 3 4 3 2 4 **sample Output** 4 **Sample Input** 3 4 4 4
4
Hard
null
null
null
null
null
null
2014-10-22T02:37:52
2018-05-07T19:45:45
setter
###C++ ```cpp #include <bits/stdc++.h> using namespace std; int main() { int n; cin>>n; vector <long long int> Arr(n); for (int i=0;i<n;i++) { cin>>Arr[i]; } long long int beg = Arr[n-1]/2 + Arr[n-1]%2; for (int i = n-2;i>=0;i--) { beg = (Arr[i] + beg)/2 + (Arr[i] + beg)%2; } cout<<beg<<endl; return 0; } ```
not-set
2016-04-24T02:03:13
2016-07-23T14:27:28
C++
223
4,879
chief-hopper
Chief Hopper
Chief's bot is playing an old DOS-based game. There are $N+1$ buildings in the game - indexed from $0$ to $N$ and are placed left-to-right. It is guaranteed that building with index $0$ will be of height $0$ unit. For buildings with index $i$ ($i \in [1, N]$) height will be $h_i$ units. <br> At beginning Chief's bot is at building with index $0$. At each step, bot jumps to next (right) building. Suppose bot is at $k^{th}$ building and his current energy is $botEnergy$, then in next step he will jump to $(k+1)^{th}$ building. He will gain/lose energy which is directly proportional to difference between $h_{k+1}$ and $botEnergy$ - If $h_{k+1} > botEnergy$, then he will lose $h_{k+1} - botEnergy$ units of energy. - Otherwise, he will gain $botEnergy - h_{k+1}$ units of energy. Goal is to reach $N^{th}$ building, and during the course bot should never have negative energy units. What should be the minimum units of energy with which bot should start to successfully complete the game? **Input Format** The first line contains integer $N$. Next line contains $N$ space separated integers $h_1, h_2, \cdots , h_N$ representing the heights of the buildings. **Output Format** Print a single number representing minimum units of energy required to complete the game. **Constraints** $1 \le N \le 10^5$ $1 \le h_i \le 10^5, i \in [1, N]$ **Sample Input** 5 3 4 3 2 4 **Sample Output** 4 **Explanation** **Sample Input** 3 4 4 4 **Sample Output** 4 **Explanation** In the second test case if bot has energy 4, it's energy is changed by (4 - 4 = 0) at every step and remains 4.
code
Find the minimum units of energy with which bot should start to successfully complete the game.
ai
2014-10-22T02:37:45
2022-08-31T08:14:38
# # Complete the 'chiefHopper' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY arr as parameter. # def chiefHopper(arr): # Write your code here
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) arr = list(map(int, input().rstrip().split())) result = chiefHopper(arr) fptr.write(str(result) + '\n') fptr.close()
Chief's bot is playing an old DOS based game. There is a row of buildings of different heights arranged at each index along a number line. The bot starts at building $0$ and at a height of $0$. You must determine the minimum energy his bot needs at the start so that he can jump to the top of each building without his energy going below zero. Units of height relate directly to units of energy. The bot's energy level is calculated as follows: - If the bot's $botEnergy$ is less than the height of the building, his $newEnergy = botEnergy - (height - botEnergy)$ - If the bot's $botEnergy$ is greater than the height of the building, his $newEnergy = botEnergy + (botEnergy - height)$ **Example** $arr = [2,3,4,3,2]$ Starting with $botEnergy = 4$, we get the following table: <pre> botEnergy height delta 4 2 +2 6 3 +3 9 4 +5 14 3 +11 25 2 +23 48 </pre> That allows the bot to complete the course, but may not be the minimum starting value. The minimum starting $botEnergy$ in this case is $3$. **Function Description** Complete the *chiefHopper* function in the editor below. chiefHopper has the following parameter(s): - *int arr[n]:* building heights **Returns** - *int:* the minimum starting $botEnergy$
0.588235
["ada","bash","c","clojure","coffeescript","cpp","cpp14","cpp20","csharp","d","elixir","erlang","fortran","fsharp","go","groovy","haskell","java","java8","java15","javascript","julia","kotlin","lolcode","lua","objectivec","ocaml","octave","pascal","perl","php","pypy3","python3","r","racket","ruby","rust","sbcl","scala","smalltalk","swift","tcl","typescript","visualbasic","whitespace"]
The first line contains an integer $n$, the number of buildings. The next line contains $n$ space-separated integers $arr[1]..arr[n]$, the heights of the buildings.
5 3 4 3 2 4 **sample Output** 4 **Sample Input** 3 4 4 4
4
Hard
null
null
null
null
null
null
2014-10-22T02:37:52
2018-05-07T19:45:45
tester
###C++ ```cpp #include <bits/stdc++.h> using namespace std; const long long linf = 0x3f3f3f3f3f3f3f3fLL; const int N = 111111; int n; int h[N]; int check(long long x) { long long energy = x; for(int i = 1; i <= n; i++) { energy += energy - h[i]; if(energy >= linf) return 1; if(energy < 0) return 0; } return 1; } int main() { cin >> n; for(int i = 1; i <= n; i++) { cin >> h[i]; } long long L = 0, R = linf; while(L < R) { long long M = (L + R) / 2; if(check(M)) { R = M; } else { L = M + 1; } } cout << L << endl; return 0; } ```
not-set
2016-04-24T02:03:13
2016-07-23T14:30:35
C++
224
4,912
receive-the-signal
Receive The Signal
Lagnajeet is standing at the position 0 on a number line. Sunil is sending a list of commands through Wi-Fi to Lagnajeet's smartphone and Lagnajeet follows them. Each command is one of the following two types: Go 1 unit towards the positive direction, denoted as '+' Go 1 unit towards the negative direction, denoted as '-' But the Wi-Fi condition is so poor that Lagnajeet's smartphone reports some of the commands can't be recognized and Lagnajeet knows that some of them might even be wrong though successfully recognized. Lagnajeet decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the 1 unit to the negative or positive direction with the same probability 0.5). You are given an original list of commands sent by Sunil and list received by Lagnajeet. What is the probability that Lagnajeet ends in the position originally supposed to be final by Sunil's commands? __Input__<br> The first line contains a string s1 — the commands Sunil sends to Lagnajeet, this string consists of only the characters in the set {'+', '-'}. The second line contains a string s2 — the commands Lagnajeet's smartphone recognizes, this string consists of only the characters in the set {'+', '-', '?'}. '?' denotes an unrecognized command. Lengths of two strings are equal and do not exceed 10. __Output__<br> Output a single real number corresponding to the probability. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. __Sample test(s)__<br> __input__<br> ++-+-<br> +-+-+ __output__<br> 1.000000000000 __input__<br> +-+-<br> +-?? __output__<br> 0.500000000000 __input__<br> +++<br> ??- __output__<br> 0.000000000000 __Note__<br> For the first sample, both s1 and s2 will lead Lagnajeet to finish at the same position  + 1. For the second sample, s1 will lead Lagnajeet to finish at position 0, while there are four possibilites for s2: {"+-++", "+-+-", "+--+", "+---"} with ending position {+2, 0, 0, -2} respectively. So there are 2 correct cases out of 4, so the probability of finishing at the correct position is 0.5. For the third sample, s2 could only lead us to finish at positions {+1, -1, -3}, so the probability to finish at the correct position  + 3 is 0.
code
null
ai
2014-10-24T19:30:33
2016-09-09T09:57:04
null
null
null
Lagnajeet is standing at the position 0 on a number line. Sunil is sending a list of commands through Wi-Fi to Lagnajeet's smartphone and Lagnajeet follows them. Each command is one of the following two types: Go 1 unit towards the positive direction, denoted as '+' Go 1 unit towards the negative direction, denoted as '-' But the Wi-Fi condition is so poor that Lagnajeet's smartphone reports some of the commands can't be recognized and Lagnajeet knows that some of them might even be wrong though successfully recognized. Lagnajeet decides to follow every recognized command and toss a fair coin to decide those unrecognized ones (that means, he moves to the 1 unit to the negative or positive direction with the same probability 0.5). You are given an original list of commands sent by Sunil and list received by Lagnajeet. What is the probability that Lagnajeet ends in the position originally supposed to be final by Sunil's commands? __Input__<br> The first line contains a string s1 — the commands Sunil sends to Lagnajeet, this string consists of only the characters in the set {'+', '-'}. The second line contains a string s2 — the commands Lagnajeet's smartphone recognizes, this string consists of only the characters in the set {'+', '-', '?'}. '?' denotes an unrecognized command. Lengths of two strings are equal and do not exceed 10. __Output__<br> Output a single real number corresponding to the probability. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. __Sample test(s)__<br> __input__<br> ++-+-<br> +-+-+ __output__<br> 1.000000000000 __input__<br> +-+-<br> +-?? __output__<br> 0.500000000000 __input__<br> +++<br> ??- __output__<br> 0.000000000000 __Note__<br> For the first sample, both s1 and s2 will lead Lagnajeet to finish at the same position  + 1. For the second sample, s1 will lead Lagnajeet to finish at position 0, while there are four possibilites for s2: {"+-++", "+-+-", "+--+", "+---"} with ending position {+2, 0, 0, -2} respectively. So there are 2 correct cases out of 4, so the probability of finishing at the correct position is 0.5. For the third sample, s2 could only lead us to finish at positions {+1, -1, -3}, so the probability to finish at the correct position  + 3 is 0.
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-10-24T19:30:48
2016-05-12T23:58:14
setter
http://ideone.com/MgyHDW
not-set
2016-04-24T02:03:13
2016-04-24T02:03:13
Unknown
225
4,932
burger-happiness
Burger Happiness
In Burger Town new burger restaurants will be opened! Concretely, $N$ restaurants will open in $N$ days, while restaurant $i$ will be opened on day $i$ and will be located at $X_i$. The town should be imagined as an one dimensional line in which every object's location can be described by the $x$ coordinate. Tim has just recently arrived the town after a very bad result in a programming contest. Thus he wants to cheer himself up by starting a trip to try out some new burgers. Every burger restaurant $i$ is associated with two integers $A_i$ and $B_i$. If Tim eats a burger from $i$, then his happiness will increase by $A_i$, which can also be negative, depending on the deliciousness of the burger. On the other hand, if Tim looks through the window of an opened restaurant $i$, from which he will *not* eat a burger, then his happiness decreases by $B_i$, since Tim gets sad by only seeing the burgers. Tim's journey can start from any day $d$ at the burger restaurant $d$ and eats a burger from there. On each subsequent day $n > d$, Tim has the following options: * Stay at the previous restaurant $p$. * Or go to the new restaurant $n$ to eat a burger from there. If he decides for the latter option, then on the path from $p$ to $n$ he will look through all the windows that are on his path and maybe lose some happiness. Concretely, if $X_p < X_n$, then he will look through the window of every *opened* restaurant $i$, having $X_p \leq X_i < X_n$. Similar for the case $X_n < X_p$. Since Tim is a very good friend of yours you should help him finding a trip that will maximize his happiness. If he should stay at home since no trip would cheer him up, then print `0`. **Note**: Tim's happiness is 0 at the beginning of the trip and is allowed to be negative throughout the time. **Input Format** $N$ will be given on the first line, then $N$ lines will follow, describing the restaurants numbered from 1 to $N$ accordingly. Restaurant $i$ will be described by $X_i$, $A_i$ and $B_i$ separated by a single space. **Output Format** Output the maximium happiness on one line. **Constraints** * $1 \leq N \leq 10^5$ * $|A_i| \leq 10^6$ * $0 \leq B_i \leq 10^6$ * $0 \leq X_i \leq 10^9$ and no two restaurants will have the same $X$ coordinates. **Sample Input** 3 2 -5 1 1 5 1 3 5 1 **Sample Output** 8 **Sample Input** 4 4 10 0 1 -5 0 3 0 10 2 10 0 **Sample Output** 15 **Sample Input** 3 1 -1 0 2 -2 0 3 -3 0 **Sample Output** 0 First testcase: His trip starts on day 2 at restaurant 2 located at $X_2 = 1$. He gains $A_2 = 5$ happiness points there by eating a burger. On the next day he goes from restaurant 2 to 3, but will look through the window of restaurant 2 and 1. Therefore he loses $B_2 = 1$ and $B_1 = 1$ points on the way to restaurant 3. There he eats a burger and gains another $A_3 = 5$ points. In total his happiness is equal to $5 - 1 - 1 + 5 = $ `8` and this is optimal. Second testcase: His trip starts on day 1 at restaurant 1. Then his actions on day 2, 3 and 4 will be go to restaurant 2, stay at restaurant 2 and go to restaurant 4 respectively. The happiness of this optimal trip is equal to $10 - 5 + 10 = $ `15`. Third testcase: It's not worth to start the trip from any of the restaurant since he will only have negative happiness. That's why he should stay at home and `0` should be printed.
code
Tim is currently hunting for happiness by eating burgers after a disappointing programming contest result. Help him maximizing his happiness, given some conditions.
ai
2014-10-25T21:24:48
2022-09-02T10:00:36
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY restaurants as parameter. # def solve(restaurants): # 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()) restaurants = [] for _ in range(n): restaurants.append(list(map(int, input().rstrip().split()))) result = solve(restaurants) fptr.write(str(result) + '\n') fptr.close()
In Burger Town new burger restaurants will be opened! Concretely, $N$ restaurants will open in $N$ days, while restaurant $i$ will be opened on day $i$ and will be located at $X_i$. The town should be imagined as an one dimensional line in which every object's location can be described by the $x$ coordinate. Tim has just recently arrived the town after a very bad result in a programming contest. Thus he wants to cheer himself up by starting a trip to try out some new burgers. Every burger restaurant $i$ is associated with two integers $A_i$ and $B_i$. If Tim eats a burger from $i$, then his happiness will increase by $A_i$, which can also be negative, depending on the deliciousness of the burger. On the other hand, if Tim looks through the window of an opened restaurant $i$, from which he will *not* eat a burger, then his happiness decreases by $B_i$, since Tim gets sad by only seeing the burgers. Tim's journey can start from any day $d$ at the burger restaurant $d$ and eats a burger from there. On each subsequent day $n > d$, Tim has the following options: * Stay at the previous restaurant $p$. * Or go to the new restaurant $n$ to eat a burger from there. If he decides for the latter option, then on the path from $p$ to $n$ he will look through all the windows that are on his path and maybe lose some happiness. Concretely, if $X_p < X_n$, then he will look through the window of every *opened* restaurant $i$, having $X_p \leq X_i < X_n$. Similar for the case $X_n < X_p$. Since Tim is a very good friend of yours you should help him finding a trip that will maximize his happiness. If he should stay at home since no trip would cheer him up, then print `0`. **Note**: Tim's happiness is 0 at the beginning of the trip and is allowed to be negative throughout the time. **Input Format** $N$ will be given on the first line, then $N$ lines will follow, describing the restaurants numbered from 1 to $N$ accordingly. Restaurant $i$ will be described by $X_i$, $A_i$ and $B_i$ separated by a single space. **Output Format** Output the maximium happiness on one line. **Constraints** * $1 \leq N \leq 10^5$ * $|A_i| \leq 10^6$ * $0 \leq B_i \leq 10^6$ * $0 \leq X_i \leq 10^9$ and no two restaurants will have the same $X$ coordinates. **Sample Input** 3 2 -5 1 1 5 1 3 5 1 **Sample Output** 8 **Sample Input** 4 4 10 0 1 -5 0 3 0 10 2 10 0 **Sample Output** 15 **Sample Input** 3 1 -1 0 2 -2 0 3 -3 0 **Sample Output** 0 First testcase: His trip starts on day 2 at restaurant 2 located at $X_2 = 1$. He gains $A_2 = 5$ happiness points there by eating a burger. On the next day he goes from restaurant 2 to 3, but will look through the window of restaurant 2 and 1. Therefore he loses $B_2 = 1$ and $B_1 = 1$ points on the way to restaurant 3. There he eats a burger and gains another $A_3 = 5$ points. In total his happiness is equal to $5 - 1 - 1 + 5 = $ `8` and this is optimal. Second testcase: His trip starts on day 1 at restaurant 1. Then his actions on day 2, 3 and 4 will be go to restaurant 2, stay at restaurant 2 and go to restaurant 4 respectively. The happiness of this optimal trip is equal to $10 - 5 + 10 = $ `15`. Third testcase: It's not worth to start the trip from any of the restaurant since he will only have negative happiness. That's why he should stay at home and `0` should be printed.
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-10-25T21:27:45
2016-12-03T05:18:13
setter
#include <cstdio> #include <cstring> #include <algorithm> #include <cassert> using namespace std; typedef long long ll; const int MAX_N = 1e5; const ll INF = 1LL << 62; const int MAX_A = 1e6; const int MAX_X = 1e9; const int MAX_B = 1e6; int N; int X[MAX_N], A[MAX_N], B[MAX_N]; // Location, Gain, Lose ll F[MAX_N]; int tmp[MAX_N]; struct SegmentTree { ll lazy[MAX_N * 4]; ll T[MAX_N * 4]; void init(){ memset(lazy, 0, sizeof lazy); memset(T, 0, sizeof T); } void propagate(int n, int L, int R){ T[n] += lazy[n]; if(L != R){ lazy[n * 2] += lazy[n]; lazy[n * 2 + 1] += lazy[n]; } lazy[n] = 0; } void update(int n, int L, int R, int i, int j, ll x){ propagate(n, L, R); if(R < i || j < L) return; if(i <= L && R <= j){ lazy[n] = x; propagate(n, L, R); } else { update(n * 2, L, (L + R) / 2, i, j, x); update(n * 2 + 1, (L + R) / 2 + 1, R, i, j, x); T[n] = max(T[n * 2], T[n * 2 + 1]); } } void update(int i, int j, ll x){ if(i <= j) update(1, 0, N - 1, i, j, x); } ll query(int n, int L, int R, int i, int j){ if(R < i || j < L) return -INF; propagate(n, L, R); if(i <= L && R <= j) return T[n]; return max(query(n * 2, L, (L + R) / 2, i, j), query(n * 2 + 1, (L + R) / 2 + 1, R, i, j)); } ll query(int i, int j){ if(i > j) return -INF; return query(1, 0, N - 1, i, j); } }; SegmentTree T1; // Stores maximum f(x') + S[x' - 1] SegmentTree T2; // Stores maximum f(x') - S[x'] ll query(int x, int a){ ll S = -T2.query(x, x); // S[x], since F[x] = 0 ll S1 = T1.query(x, x); // S[x - 1], since F[x] = 0 // Case x' < x ll res1 = -S + a + T1.query(0, x - 1); // Case x < x' ll res2 = S1 + a + T2.query(x + 1, N - 1); // Case Beginning from x ll res3 = a; return max(max(res1, res2), res3); } void update(int x, int b){ T1.update(x, x, F[x]); T1.update(x + 1, N - 1, +b); T2.update(x, x, F[x]); T2.update(x, N - 1, -b); } int main(){ T1.init(), T2.init(); scanf("%d", &N); assert(1 <= N && N <= MAX_N); for(int i = 0; i < N; i++){ scanf("%d%d%d", X + i, A + i, B + i); assert(0 <= X[i] && X[i] <= MAX_X); assert(0 <= B[i] <= MAX_B); assert(-MAX_A <= A[i] && A[i] <= MAX_A); tmp[i] = X[i]; } sort(tmp, tmp + N); int m = unique(tmp, tmp + N) - tmp; for(int i = 0; i < N; i++){ X[i] = lower_bound(tmp, tmp + m, X[i]) - tmp; } ll res = 0; for(int i = 0; i < N; i++){ F[X[i]] = query(X[i], A[i]); update(X[i], B[i]); res = max(res, F[X[i]]); } printf("%lld\n", res); return 0; }
not-set
2016-04-24T02:03:13
2016-04-24T02:03:13
C++
226
4,972
save-middle-earth-1
Save Middle Earth
Frodo Baggins is on his mission to destroy The One Ring. He has entered the deadly Shelob's lair and is now challenged by the mighty spider Shelob. Both Frodo and Shelob get equal number of swords of varying lengths which are stacked behind them. The challenge is this: Both of them pull out their topmost sword. The lengths of both their swords are compared. Whoever has a longer sword gets a point. If the sword lengths are equal noone gets a point. Moreover, if the length of the longer sword is a prime number then the person having the longer sword gets 10 extra points. Also, if the length of the shorter sword is any root of the longer sword then the person having the longer sword gets 10 more points. The end of the input is indicated by **2 zeroes**. After all the swords have been compared, if Frodo has higher points than Shelob, he will get to escape her lair and move on towards Mount Doom to destroy the ring. Your job is simple. Find out who wins each round. Print the **player number**. Also print the **number of points** the winner has. If both Frodo and Shelob have equal number of points print **Tie**. ###Input The input consists of N pairs of numbers indicating the sword length of player 1 and 2 respectively. ###Ouput The output should be 2 numbers separated by a space. The first number indicates the winner. Second number should be the points obtained by him. If both the players have equal number of point then the output should be "Tie" (Quotes only for clarity). ###Constraints - 1 <= N <= 1000 - 1 <= sword length <= 1000 ###Sample Input 12 10 2 5 6 36 19 7 0 0 ###Sample Ouput 2 22
code
null
ai
2014-10-28T12:26:58
2016-09-09T09:57:30
null
null
null
Frodo Baggins is on his mission to destroy The One Ring. He has entered the deadly Shelob's lair and is now challenged by the mighty spider Shelob. Both Frodo and Shelob get equal number of swords of varying lengths which are stacked behind them. The challenge is this: Both of them pull out their topmost sword. The lengths of both their swords are compared. Whoever has a longer sword gets a point. If the sword lengths are equal noone gets a point. Moreover, if the length of the longer sword is a prime number then the person having the longer sword gets 10 extra points. Also, if the length of the shorter sword is any root of the longer sword then the person having the longer sword gets 10 more points. The end of the input is indicated by **2 zeroes**. After all the swords have been compared, if Frodo has higher points than Shelob, he will get to escape her lair and move on towards Mount Doom to destroy the ring. Your job is simple. Find out who wins each round. Print the **player number**. Also print the **number of points** the winner has. If both Frodo and Shelob have equal number of points print **Tie**. ###Input The input consists of N pairs of numbers indicating the sword length of player 1 and 2 respectively. ###Ouput The output should be 2 numbers separated by a space. The first number indicates the winner. Second number should be the points obtained by him. If both the players have equal number of point then the output should be "Tie" (Quotes only for clarity). ###Constraints - 1 <= N <= 1000 - 1 <= sword length <= 1000 ###Sample Input 12 10 2 5 6 36 19 7 0 0 ###Sample Ouput 2 22
0.5
["bash","c","cpp","java","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-10-28T12:29:15
2016-05-12T23:58:10
setter
//CSI OPC //SIMPLE SEARCH #include<stdio.h> #include<iostream> #include<math.h> using namespace std; bool isprime(int n) { int c=0; for(int i=2; i<=sqrt(n); i++) { if(n%i==0) c++; if(c>0) break; } if(c>0) return false; else return true; } bool ispower(int x, int y) { int flag=1, j=y, num=0; while(j>x) { if(j%x!=0) { flag=0; break; } j=j/x; num++; } if(pow(x,num+1)==y) flag=1; else flag=0; if(flag) return true; else return false; } int main() { int a, b, flag1=0, flag2=0, pointA=0, pointB=0, flag3=0, flag4=0; cin>>a>>b; while(a!=0 && b!=0) { flag1=0; flag2=0; flag3=0; flag4=0; if(isprime(a)) flag1=1; if(isprime(b)) flag2=1; if(a<b) { if(a!=1 && ispower(a,b)) flag4=1; pointB+=1; if(flag2==1) pointB+=10; if(flag4==1) pointB+=10; } if(b<a) { if(b!=1 && ispower(b,a)) flag3=1; pointA+=1; if(flag1==1) pointA+=10; if(flag3==1) pointA+=10; } cin>>a>>b; } if(pointA>pointB) cout<<1<<" "<<pointA<<endl; else if(pointA<pointB) cout<<2<<" "<<pointB<<endl; else cout<<"Tie"<<endl; }
not-set
2016-04-24T02:03:14
2016-04-24T02:03:14
C++
227
5,012
the-philosopher-box
The Philosopher Box
<p><em>n</em> philosophers were sitting at a table trying to find the key to open the box that unleashes all the secrets of the world .</p> <p>Each philosopher has a part of the key but none of them knows the whole full key to open the box .</p> <p>Each of the philosophers write down their keys on a piece of paper and finally they send all the papers to a cryptographer .</p> <p>After analaysing the papers , the cryptographer finds out that some of the letters were smudged so he may not be able to find out key to the box.</p> <p> If no letters were smudged in any of the paper , then he surely knows that if there is a key to the box then it must be a part of all the papers that he recieved . </p> <p>If some letters were smudged and still he is able to find out some common part in all of the papers then he is sure that it must be the key but if he is not able to find out any common key then he says that '<em>Maybe</em>' there is a key to the box but it needs futher investigation.</p> <p> You are given the number of philosophers <em>n</em> , all the contents of the paper and if there is any letter in a paper that was smudged then that letter is denoted by '<em>?</em>' </p> <p><strong>Input Format</p></strong> <p>First line contains '<em>n</em>' i.e. the number of philosophers.</p> <p>The next <em>n</em> lines contain a string i.e. the key that each philosopher wrote on the paper</p> <p><strong>Output Format</p></strong> <p>'<em>Yes</em>' or '<em>No</em>' or '<em>Maybe</em>'</p> <p><strong>Contraints</p></strong> <p> 1 &lt <em>n</em> &lt 50000 <br> Length of key given by each philosopher is less than 100 <br> Key only only contains letter from '<em>a</em>' to '<em>z</em>' and '<em>?</em>' </p> <p><strong>Examples</p></strong> <p><strong>Sample Input 1</p></strong> <pre> <code> 3 abc def ab? </code> </pre> <p><strong>Sample Output 1</p></strong> <pre> <code> No </code> </pre> <p><strong>Explanation</p></strong> <p>The first two strings has no common key so , the answer is '<em>No</em>'</p> <p><strong>Sample Input 2</p></strong> <pre> <code> 2 abc de? </code> </pre> <p><strong>Sample Output 2</p></strong> <pre> <code> Maybe </code> </pre> <p><strong>Explanation</p></strong> <p>The smudged letter might be '<em>a</em>' or '<em>b</em>' or '<em>c</em>' so answer is '<em>Maybe</em>'</p> <p><strong>Sample Input 2</p></strong> <pre> <code> 3 abc dc ac </code> </pre> <p><strong>Sample Output 2</p></strong> <pre> <code> Yes </code> </pre> <p><strong>Explanation:</p></strong> <p>All the strings have '<em>c</em>' in common so answer is '<em>Yes</em>'</p>
code
Help the philosopher to unleash the truth
ai
2014-10-31T11:22:35
2016-09-09T09:57:47
null
null
null
<p><em>n</em> philosophers were sitting at a table trying to find the key to open the box that unleashes all the secrets of the world .</p> <p>Each philosopher has a part of the key but none of them knows the whole full key to open the box .</p> <p>Each of the philosophers write down their keys on a piece of paper and finally they send all the papers to a cryptographer .</p> <p>After analaysing the papers , the cryptographer finds out that some of the letters were smudged so he may not be able to find out key to the box.</p> <p> If no letters were smudged in any of the paper , then he surely knows that if there is a key to the box then it must be a part of all the papers that he recieved . </p> <p>If some letters were smudged and still he is able to find out some common part in all of the papers then he is sure that it must be the key but if he is not able to find out any common key then he says that '<em>Maybe</em>' there is a key to the box but it needs futher investigation.</p> <p> You are given the number of philosophers <em>n</em> , all the contents of the paper and if there is any letter in a paper that was smudged then that letter is denoted by '<em>?</em>' </p> <p><strong>Input Format</p></strong> <p>First line contains '<em>n</em>' i.e. the number of philosophers.</p> <p>The next <em>n</em> lines contain a string i.e. the key that each philosopher wrote on the paper</p> <p><strong>Output Format</p></strong> <p>'<em>Yes</em>' or '<em>No</em>' or '<em>Maybe</em>'</p> <p><strong>Contraints</p></strong> <p> 1 &lt <em>n</em> &lt 50000 <br> Length of key given by each philosopher is less than 100 <br> Key only only contains letter from '<em>a</em>' to '<em>z</em>' and '<em>?</em>' </p> <p><strong>Examples</p></strong> <p><strong>Sample Input 1</p></strong> <pre> <code> 3 abc def ab? </code> </pre> <p><strong>Sample Output 1</p></strong> <pre> <code> No </code> </pre> <p><strong>Explanation</p></strong> <p>The first two strings has no common key so , the answer is '<em>No</em>'</p> <p><strong>Sample Input 2</p></strong> <pre> <code> 2 abc de? </code> </pre> <p><strong>Sample Output 2</p></strong> <pre> <code> Maybe </code> </pre> <p><strong>Explanation</p></strong> <p>The smudged letter might be '<em>a</em>' or '<em>b</em>' or '<em>c</em>' so answer is '<em>Maybe</em>'</p> <p><strong>Sample Input 2</p></strong> <pre> <code> 3 abc dc ac </code> </pre> <p><strong>Sample Output 2</p></strong> <pre> <code> Yes </code> </pre> <p><strong>Explanation:</p></strong> <p>All the strings have '<em>c</em>' in common so answer is '<em>Yes</em>'</p>
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-10-31T11:25:48
2016-05-12T23:58:07
setter
import sys tt="qwertyuiopasdfghjklzxcvbnm?" #all accepted characters tt=list(tt) t=int(raw_input()) seta=set() #Set A contains intersection of all strings without '?' setb=set() #Set B contains intersection of all strings with '?' seta_i=False #Flag to check if there is atleast a single string without '?' setb_i=False #Flag to check if there is atleast a single string with '?' for i in xrange(t): pp=str(raw_input()).strip() st=set(pp) #get only distinct characters from input string if '?' in st: #if string contains '?' if setb_i==False: setb_i=True setb=st else: setb=setb & st #Intersection with previous result else: #if string doesn't contains '?' if seta_i==False: seta_i=True seta=st else: seta=seta & st #Intersection with previous result if seta_i: # There is atleast one string without '?' if len(seta)==0: # If intersection of all strings without '?' is none then answer is 'No' print 'No' else: #If there is some common elements in all strings without '?' if len(setb)==0: #And no strings with '?' , So answer is 'No' print 'Yes' elif len(seta & setb)>0: # If both Sets have something common answer is 'Yes' print 'Yes' else: #If nothing common in both the sets then answer is 'Maybe' print 'Maybe' else: #If there were no strings without '?' if len(setb)==0: #not a necessary condition it would mean that there were no strings print 'No' elif len(setb)>1: #If some part is common in strings with '?' print 'Yes' else: #if only '?' is common is all the strings print 'Maybe'
not-set
2016-04-24T02:03:14
2016-04-24T02:03:14
Python
228
5,040
joey-and-divisibilty
Joey and Divisibilty
Joey is crazy about divisibility. He wants you to give the smallest natural number which is divisible by **n** and is solely made of digits from **0-d**, where **1<=d<=9** __Example__ if Joey tells you that n=8 and d=1, then your output should be 1000 as there is no natural number smaller than 1000 which is made of 1 and 0 only and is divisible by 8. __Input Format__ First line contains _**T**_, i.e the number of test cases. Each of the next _**T**_ lines contain 2 numbers, **n** and **d**. __Output Format__ Output T lines, one for each test case, containing the desired answer for the corresponding test case. Output -1 if an answer does not exist. __Constraints__ 1<=T<=50 1<=n<=100000 1<=d<=10 __Sample Input__ 3 8 1 7 3 5 9 __Sample Output__ 1000 21 5
code
null
ai
2014-11-01T15:50:15
2016-09-09T09:57:58
null
null
null
Joey is crazy about divisibility. He wants you to give the smallest natural number which is divisible by **n** and is solely made of digits from **0-d**, where **1<=d<=9** __Example__ if Joey tells you that n=8 and d=1, then your output should be 1000 as there is no natural number smaller than 1000 which is made of 1 and 0 only and is divisible by 8. __Input Format__ First line contains _**T**_, i.e the number of test cases. Each of the next _**T**_ lines contain 2 numbers, **n** and **d**. __Output Format__ Output T lines, one for each test case, containing the desired answer for the corresponding test case. Output -1 if an answer does not exist. __Constraints__ 1<=T<=50 1<=n<=100000 1<=d<=10 __Sample Input__ 3 8 1 7 3 5 9 __Sample Output__ 1000 21 5
0.5
["bash","c","cpp","java","csharp","python","python3","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-11-01T17:57:46
2016-05-12T23:58:05
setter
//#define LOCAL //uncomment for testing from local file #include <iostream> #include <cstring> #include <sstream> #include <fstream> #include <cstdlib> #include <cstdio> #include <cmath> #include <vector> #include <set> #include <map> #include <bitset> #include <climits> #include <ctime> #include <algorithm> #include <functional> #include <stack> #include <queue> #include <list> #include <deque> #include <sys/time.h> #include <iomanip> #include <cstdarg> #include <utility> //std::pair #include <cassert> #define tr(c,i) for(typeof(c.begin()) i = (c).begin(); i != (c).end(); i++) #define pb push_back #define mp make_pair #define clr(x,y) memset(x,y,sizeof x) #define lld long long int using namespace std; class Graph{ private: lld V; vector<lld> *adj; public: Graph(lld _V); void addEdge(lld u, lld v); void BFS(lld start, string &candidate); }; Graph::Graph(lld _V){ V = _V; adj = new vector<lld>[V]; } void Graph::addEdge(lld u, lld v){ adj[u].pb(v); } /*candidate stores the lowest natural number starting with start and divisible by n (or V)*/ void Graph::BFS(lld start, string &candidate){ queue<lld> nodes; lld parent[V], i, k, digit; bool visited[V]; clr(visited, false); clr(parent,-1); nodes.push(start); visited[start] = true; while(!nodes.empty()){ k = nodes.front(); tr(adj[k], it){ if(!visited[*it]){ visited[*it] = true; parent[*it] = k; nodes.push(*it); } } //if 0 is discovered if(visited[0]){ break; } nodes.pop(); } candidate=""; i = 0; //last state has to be 0 /*build candidate string from parent array*/ while(parent[i]!=-1) { /*just the reverse procedure of the way one added the edged in automata*/ digit = -10*parent[i]+i; while(digit<0)digit+=V; candidate = char('0'+digit)+candidate; i = parent[i]; } candidate = char('0'+start)+candidate; } int main() { #ifdef LOCAL freopen("input.txt","r",stdin); #endif lld t,n,d,i,j,minLength,nextState; string candidate, answer; scanf("%lld",&t); while(t--){ scanf("%lld %lld",&n, &d); if(n<=d){ cout<<n<<"\n"; continue; } Graph g(n); for(i=0;i<n;i++){ for(j=0;j<=d;j++){ /*if I'm in state i presently and the next digit is j, then the remainder of the number thus formed when divided by n becomes (10*i+j)%n*/ nextState = (10*i+j)%n; /*shouldn't care about self-loops*/ if(nextState!=i) g.addEdge(i, (10*i+j)%n); } } minLength = -1; for(i=1;i<=d;i++){ g.BFS(i, candidate); if(minLength>candidate.length()){ minLength = candidate.length(); answer = candidate; } } /*can't think of any case for which answer is -1*/ if(minLength<1)answer="-1"; cout<<answer<<"\n"; } }
not-set
2016-04-24T02:03:14
2016-04-24T02:03:14
C++
229
5,072
playing-board-games
Playing Board Games
Pingu recently got addicted to board games. Pingu was playing game called Box fitting. He has a $'4\times N'$ board and has lots of boxes of size $'1\times 4'$ and $'4 \times 1'$. He has a large number of boxes of both types(consider infinite for all practical purposes). Now in this game he needs to place the boxes in the such that, the whole board is exactly covered. He easily was able to complete the game, but he also observed that there can be more than one solution to this game and decided to find out all such solutions. He wants to know how many solutions actually exist so that he can find them all. Pingu asks you to write a program such that given $N$ you must tell how many solutions exits such that you can fill a $'4\times N'$ board with $'1\times 4'$ and $'4\times 1'$ size boxes. Since the answer can be very large print the answer modulo $1000000007$. **Input Format:** First line contains T, number of test cases. Next T lines each contain one number N. **Output Format:** Print T lines each containing the required answer for the given N. **Constraints:** $1 \le T \le 10^3$ $1 \le N \le 10^{18}$ **Sample Input #00** 2 1 4 **Sample Output #00** 1 2 **Explanation:** _Sample #00:_ In first case, only way to do is use one $'4\times 1'$ box. In second case, either use four $'4\times 1'$ boxes or use four $'1\times 4'$ boxes.
code
null
ai
2014-11-03T08:43:34
2016-09-09T09:58:09
null
null
null
Pingu recently got addicted to board games. Pingu was playing game called Box fitting. He has a $'4\times N'$ board and has lots of boxes of size $'1\times 4'$ and $'4 \times 1'$. He has a large number of boxes of both types(consider infinite for all practical purposes). Now in this game he needs to place the boxes in the such that, the whole board is exactly covered. He easily was able to complete the game, but he also observed that there can be more than one solution to this game and decided to find out all such solutions. He wants to know how many solutions actually exist so that he can find them all. Pingu asks you to write a program such that given $N$ you must tell how many solutions exits such that you can fill a $'4\times N'$ board with $'1\times 4'$ and $'4\times 1'$ size boxes. Since the answer can be very large print the answer modulo $1000000007$. **Input Format:** First line contains T, number of test cases. Next T lines each contain one number N. **Output Format:** Print T lines each containing the required answer for the given N. **Constraints:** $1 \le T \le 10^3$ $1 \le N \le 10^{18}$ **Sample Input #00** 2 1 4 **Sample Output #00** 1 2 **Explanation:** _Sample #00:_ In first case, only way to do is use one $'4\times 1'$ box. In second case, either use four $'4\times 1'$ boxes or use four $'1\times 4'$ boxes.
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-11-03T09:51:53
2018-08-04T22:15:15
setter
#include <bits/stdc++.h> #define ll long long #define matrix(x,n,m) vector<vector<ll> > x(n,vector<ll> (m,0)) using namespace std; ll mod=1000000007; void multiply(vector<vector<ll> > &a , vector<vector<ll> > b) { matrix(temp,4,4); for(int i=0;i<4;i++) for(int j=0;j<4;j++) for(int k=0;k<4;k++) temp[i][j] = (temp[i][j] +(a[i][k]*b[k][j])%mod)%mod; a=temp; } ll solve(ll n) { if(n<=4) return 1 + n/4; n-=4; matrix(id,4,4); for(int i=0;i<4;i++) id[i][i]=1; matrix(base,4,4); base[0][0]=base[0][1]=base[1][2]=base[2][3]=base[3][0]=1; while(n) { if(n&1) multiply(id,base); multiply(base,base); n>>=1; } return (2*id[0][0] + id[1][0] + id[2][0] + id[3][0])%mod; } int main() { ll t,n; cin>>t; while(t--) { cin>>n; cout<<solve(n)<<endl; } return 0; }
not-set
2016-04-24T02:03:15
2016-04-24T02:03:15
C++
230
5,100
challange1
Бодлого1
#ШАТАР Шатрын хөлөгний 2 буудал координатаараа өгөгдөв. (Буудлын координат гэдэг нь багана болон нүдний дугаарыг илтгэх 1-ээс 8 хүртэлх хоёр тоо.) Шатрын хөлөгний өгөгдсөн хоёр буудал ижил өнгөтэй юу. Тийм бол YES, үгүй бол NO гэж хэвлэ. Input Нэг мөрөнд 4 тоо зайгаар тусгаарлагдан өгөгдөнө. Output YES/NO Example Input: 1 1 2 2 Output: YES Input: 1 1 1 4 Output: NO
code
null
ai
2014-11-06T09:38:14
2019-11-23T09:47:02
null
null
null
#ШАТАР Шатрын хөлөгний 2 буудал координатаараа өгөгдөв. (Буудлын координат гэдэг нь багана болон нүдний дугаарыг илтгэх 1-ээс 8 хүртэлх хоёр тоо.) Шатрын хөлөгний өгөгдсөн хоёр буудал ижил өнгөтэй юу. Тийм бол YES, үгүй бол NO гэж хэвлэ. Input Нэг мөрөнд 4 тоо зайгаар тусгаарлагдан өгөгдөнө. Output YES/NO Example Input: 1 1 2 2 Output: YES Input: 1 1 1 4 Output: NO
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-11-06T09:39:02
2016-05-12T23:57:59
setter
б өйыбө быө ыбө ыбйө йыө й
not-set
2016-04-24T02:03:15
2016-04-24T02:03:15
Unknown
231
5,100
challange1
Бодлого1
#ШАТАР Шатрын хөлөгний 2 буудал координатаараа өгөгдөв. (Буудлын координат гэдэг нь багана болон нүдний дугаарыг илтгэх 1-ээс 8 хүртэлх хоёр тоо.) Шатрын хөлөгний өгөгдсөн хоёр буудал ижил өнгөтэй юу. Тийм бол YES, үгүй бол NO гэж хэвлэ. Input Нэг мөрөнд 4 тоо зайгаар тусгаарлагдан өгөгдөнө. Output YES/NO Example Input: 1 1 2 2 Output: YES Input: 1 1 1 4 Output: NO
code
null
ai
2014-11-06T09:38:14
2019-11-23T09:47:02
null
null
null
#ШАТАР Шатрын хөлөгний 2 буудал координатаараа өгөгдөв. (Буудлын координат гэдэг нь багана болон нүдний дугаарыг илтгэх 1-ээс 8 хүртэлх хоёр тоо.) Шатрын хөлөгний өгөгдсөн хоёр буудал ижил өнгөтэй юу. Тийм бол YES, үгүй бол NO гэж хэвлэ. Input Нэг мөрөнд 4 тоо зайгаар тусгаарлагдан өгөгдөнө. Output YES/NO Example Input: 1 1 2 2 Output: YES Input: 1 1 1 4 Output: NO
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-11-06T09:39:02
2016-05-12T23:57:59
tester
бөйбыөйыб өбый өыб өыб йөыб өыбй
not-set
2016-04-24T02:03:15
2016-04-24T02:03:15
Unknown
232
5,106
rahul-and-chemistry
Rahul and Chemistry
Rahul hates Chemistry and he wants to get his experiment done as quickly as possible. The experiment is to combine adjacent elements until you get one element with minimum cost. Cost of combining elements is explained later. So you are given an array with $N$ elements where $w_i$ is the weight of the ith element and the elements are arranged linearly. Rahul can fuse any two 2 neighbouring elements at a time and the cost of fusing $i^{th}$ element and $(i+1)^{th}$ element is $max(w_i,w_{i+1})$ and the weight of the new element is $w_i + w_{i+1}$. Now tell Rahul the minumum cumulative cost of fusing all the elements into $1$ element. Since the answer can be large print answer modulo $1000000007$. **Input Format:** The first line would contain $N$ the number of elements. Next line would contain $N$ space separated integers where the $i^{th}$ integer denotes $w_i$ weight of $i^{th}$ element. **Output Format:** A single line containing the required answer i.e the minimum cumulative cost modulo $1000000007$ to merge all elements into $1$ element. **Constraints:** $1 \le N \le 500$ $0 \le w_i \le 1000000$ **Sample Input #00** 3 1 4 2 **Sample Output #00** 9 **Explanation** _Sample #00:_ There are $2$ possible ways to combine the elements. - Combine $2^{nd}$ and $3^{rd}$ element. Cost = $max(4,2) = 4$. Weight of new element = $6$. Array now looks like {1, 6} Combine 1st and 2nd element. Cost= max(1,6) = 6. Total Cost=4+6=10. - Combine $1^{st}$ and $2^{nd}$ element. Cost = $max(1,4) = 4$. Weight of new element = $5$. Array now looks like {5, 2} Combine 1st and 2nd element. Cost= max(5,2) = 5. Total Cost=4+5=9. So the answer is 9.
code
null
ai
2014-11-07T09:32:10
2016-09-09T09:58:22
null
null
null
Rahul hates Chemistry and he wants to get his experiment done as quickly as possible. The experiment is to combine adjacent elements until you get one element with minimum cost. Cost of combining elements is explained later. So you are given an array with $N$ elements where $w_i$ is the weight of the ith element and the elements are arranged linearly. Rahul can fuse any two 2 neighbouring elements at a time and the cost of fusing $i^{th}$ element and $(i+1)^{th}$ element is $max(w_i,w_{i+1})$ and the weight of the new element is $w_i + w_{i+1}$. Now tell Rahul the minumum cumulative cost of fusing all the elements into $1$ element. Since the answer can be large print answer modulo $1000000007$. **Input Format:** The first line would contain $N$ the number of elements. Next line would contain $N$ space separated integers where the $i^{th}$ integer denotes $w_i$ weight of $i^{th}$ element. **Output Format:** A single line containing the required answer i.e the minimum cumulative cost modulo $1000000007$ to merge all elements into $1$ element. **Constraints:** $1 \le N \le 500$ $0 \le w_i \le 1000000$ **Sample Input #00** 3 1 4 2 **Sample Output #00** 9 **Explanation** _Sample #00:_ There are $2$ possible ways to combine the elements. - Combine $2^{nd}$ and $3^{rd}$ element. Cost = $max(4,2) = 4$. Weight of new element = $6$. Array now looks like {1, 6} Combine 1st and 2nd element. Cost= max(1,6) = 6. Total Cost=4+6=10. - Combine $1^{st}$ and $2^{nd}$ element. Cost = $max(1,4) = 4$. Weight of new element = $5$. Array now looks like {5, 2} Combine 1st and 2nd element. Cost= max(5,2) = 5. Total Cost=4+5=9. So the answer is 9.
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-11-07T09:51:03
2017-03-18T22:25:40
setter
#include<iostream> #include<cstdio> #include<cmath> #include<vector> #include<queue> #include<map> #include<set> #include<algorithm> #include<cstring> #include<numeric> #include<string> #include<functional> #include<complex> using namespace std; #define ll long long int #define loop(i,a,b) for(int i=a;i<b;i++) #define mod 1000000007 #define inf 999999999999999999 int n; ll dp[510][510]; ll a[510]; ll cs[510]; void Scan() { cin>>n; loop(i,0,n) cin>>a[i]; loop(i,0,n) loop(j,0,n) dp[i][j]=-1; return; } void pre() { cs[0]=0; for(int i=1;i<=n;i++) cs[i]=cs[i-1]+a[i-1]; } ll Solve(int i,int j) { if(dp[i][j]!=-1) return dp[i][j]; if(i==j) return dp[i][j]=0; ll res=inf; for(int k=i;k<j;k++) { ll p=Solve(i,k); p+=Solve(k+1,j); if(p>=mod) p%=mod; p+=max((cs[k+1]-cs[i]),(cs[j+1]-cs[k+1])); if(p>=mod) p%=mod; res=min(res,p); } return dp[i][j]=res; } void Out() { pre(); cout<<Solve(0,n-1)<<endl; return; } int main() { Scan(); Out(); return 0; }
not-set
2016-04-24T02:03:15
2016-04-24T02:03:15
C++
233
5,108
painting-balls-1
Painting Balls
Rahul once decided to paint things up to pass his time. Rahul had $N$ balls kept in a linear fashion all of them are initially not-colored. He has two types of paints _RED_ and _BLUE_. Now he wants to paint the balls such that there are *atmost* $2$ positions where a _RED_ colored ball touches a _BLUE_ colored ball. He has to always color all the balls. Rahul wants to know in how many ways can he color all the ball. Write a program to answer his question. **Input Format:** First line contains $T$, number of test cases. Next $T$ lines each contain a single numbers $N$, representing the number of balls. **Output Format:** $T$ lines each having a single number representing the required answer. **Constraints:** $1 \le T \le 10^3$ $1 \le N \le 10^5$ **Sample Input #00** 2 1 2 **Sample Output #00** 2 4 **Explanation** _Sample #00:_ _Case1:_ Possible ways to color are $\{\{R\},\{B\}\}$. So the answer is $2$. _Case2:_ Possible ways to color are $\{\{R,R\},\{B,B\},\{R,B\},\{B,R\}\}$. So the answer is $4$.
code
null
ai
2014-11-07T10:44:05
2016-09-09T09:58:23
null
null
null
Rahul once decided to paint things up to pass his time. Rahul had $N$ balls kept in a linear fashion all of them are initially not-colored. He has two types of paints _RED_ and _BLUE_. Now he wants to paint the balls such that there are *atmost* $2$ positions where a _RED_ colored ball touches a _BLUE_ colored ball. He has to always color all the balls. Rahul wants to know in how many ways can he color all the ball. Write a program to answer his question. **Input Format:** First line contains $T$, number of test cases. Next $T$ lines each contain a single numbers $N$, representing the number of balls. **Output Format:** $T$ lines each having a single number representing the required answer. **Constraints:** $1 \le T \le 10^3$ $1 \le N \le 10^5$ **Sample Input #00** 2 1 2 **Sample Output #00** 2 4 **Explanation** _Sample #00:_ _Case1:_ Possible ways to color are $\{\{R\},\{B\}\}$. So the answer is $2$. _Case2:_ Possible ways to color are $\{\{R,R\},\{B,B\},\{R,B\},\{B,R\}\}$. So the answer is $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-11-07T10:44:17
2016-05-12T23:57:58
setter
#include <iostream> using namespace std; int main() { long long n,t; cin>>t; while(t--) { cin>>n; cout<<2+ n*(n-1)<<endl; } return 0; }
not-set
2016-04-24T02:03:15
2016-04-24T02:03:15
C++
234
5,126
if-anweisung
if Anweisung
Prüfe die Zahl
code
if Anweisung
ai
2014-11-09T18:47:03
2016-09-09T09:58:29
null
null
null
Prüfe die Zahl
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-11-09T18:49:40
2016-05-12T23:57:56
tester
#include <iostream.h> #include <conio.h> main() { char pin1='0', pin2='8', pin3='1', pin4='5'; char e1, e2, e3, e4; pinInput: cout << "Geheimzahl bitte eingeben: "; e1 = getch(); cout << "*"; e2 = getch(); cout << "*"; e3 = getch(); cout << "*"; e4 = getch(); cout << "*"; if ((pin1!=e1) || (pin2!=e2) || (pin3!=e3) || (pin4!=e4)) { cout <<"\nGeheimzahl ist falsch\n"; goto pinInput; } cout <<"\nGeheimzahl ist richtig\n"; while (1); return 0; }
not-set
2016-04-24T02:03:15
2016-04-24T02:03:15
C++
235
5,138
superman-celebrates-diwali
Superman Celebrates Diwali
Superman has come to india with his girlfriend to celebrate diwali. Unfortunately a fire accident has happened. There are N buildings each of same height H before him which is in fire. Since it's diwali time,some floors may be free as they might have went to their hometown for celebration. He reaches the top of the building. He has lost his jumping power. Jumping power is required for two purposes. * For jumping from one building to another building * And also for jumping from one floor to another floor of the same building He prays to lord ganesha to give him his jumping power to save people. Lord ganesha gives him the jumping power due to his emergency but with some restrictions imposed. The restrictions are * Superman can use the jumping power only once ,which means he can use the jumping power only till he reaches the bottom (Ground floor), which ultimately means once he reaches the bottom floor ,he cannot move to the top floor again. * And when he switches building while jumping he'll lose a height I. Let me explain the second restriction clearly with an example. Assume I=2. Now superman is in 2nd building 5th floor(B=2 F=5),if he wants to switch to fifth building(B=5),he'll lose height(I=2),which means he'll be at floor 3 at building 5(B=5 F=3). He can freely jump from current floor to the floor below the current floor of the same building without losing any height. That is,suppose if he is at (B=5 F=4),he can go to (B=5 F=3) without losing any height. He cannot skip a floor while jumping in the same building. He can either go to the floor below the current floor or switch building and lose height I. Given the information about which floors are occupied in each of the N buildings,help superman to determine maximum number of people superman can save in one single descent with the above restrictions. __INPUT__ Input starts with three values (Number of buildings(N),Height of the buildings(H),Height superman will lose when he switches buildings(I)). Followed by N lines. Each ith line starts with a non negative integer u indicating how many people are in ith building. Each of the following u integers indicates that a person is at height ui in the ith buiding. Each of the following u integers are given and repetitions are allowed which means there can be more than one person in a floor. You can assume that 1<=H,N<=1900 and 1<=I<=450. You can also assume 0<=u<=1900 for each i. uij(floor numbers) will obviously lie between 1 and H inclusive (1<=uij<=H). i-indicates building number and j indicates floor number.Building number will not be given.Since N lines follow after the first line.You can assume that ith line indicates ith building specifications. __OUTPUT__ Output the maximum number of people superman can save. __TIME LIMIT__ 2s __SAMPLE INPUT__ 4 15 2 5 1 1 1 4 10 8 9 5 7 7 3 9 8 8 5 9 5 6 4 3 0 __SAMPLE OUTPUT__ 12 __EXPLANATION__ Input has N=4 H=15 and I=2 And N lines follow. Each ith line will have a non-negative integer in the beginning. Here u=5 in the 1st line ,which means five persons are in that building. This is followed by u numbers which indicates the floor number of the persons.Floor number can repeat as there can be more than one person in a floor. u=8 in the second line for second building. u=5 in the third line for third building. u=0 in the fourth line for fourth building which means the building has no persons. I've attached a figure here to explain the sample testcase. The connected line indicates the maximum number of people superman can save. ![Superman](http://i.imgur.com/N3SNC3j.jpg?1)
code
maximal sum possible by picking values from 2D matrix under some restrictions
ai
2014-11-10T11:53:03
2022-08-31T08:14:47
null
null
null
Superman has been invited to India to celebrate Diwali. Unfortunately, on his arrival he learns that he has been invited mainly to help rescue people from a fire accident that has happened in a posh residential locale of New Delhi, where rescue is proving to be especially difficult. As he reaches the place of the fire, before him there are $N$ buildings, each of the same height $H$, which are on fire. Since it is Diwali, some floors of the buildings are empty as the occupants have gone elsewhere for celebrations. In his hurry to start the rescue Superman reaches the top of the building, but realizes that his jumping power is depleted and restricted due to change in his geographical setting. He soon understands the restrictions of his jumping power, and they are as follows: + He can use the jumping power any number of times until he reaches the bottom floor, which means he can use the jumping power only until before he reaches the bottom (Ground floor), which means, once he reaches the bottom floor, he cannot move to the top floor again and try to save people. (In one single drop from the top to bottom) + While switching buildings, he loses height $I$ while jumping. The second restriction is explained below with an example. Assume $I = 2$. Now Superman is in the 2<sup>nd</sup> building 5<sup>th</sup> floor ($B = 2$, $F = 5$). If he wants to switch to the fifth building ($B = 5$), he will lose height ($I = 2$), which means he will be at floor _3_ at building _5_ ($B = 5$, $F = 3$). He can jump freely from the current floor to the floor below on the same building . That is, suppose if he is at $(B = 5, F = 4)$, he can go to $(B = 5, F = 3)$ without any restrictions. He cannot skip a floor while jumping in the same building. He can go to the floor below the current floor of the same building or use his jumping power, switch building, and lose height $I$. Given the information about the occupied floors in each of the $N$ buildings, help Superman to determine the maximum number of people he can save in one single drop from the top to the bottom floor with the given restrictions.
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"]
Input starts with three values: the number of buildings $N$, the height of the buildings $H$, and the height Superman will lose when he switches buildings $I$. These are followed by $N$ lines. Each $i^{th}$ line starts with a non negative integer $u$ indicating how many people are in the $i$<sup>th</sup> building. Each of the following $u$ integers indicates that a person is at height $u_i$ in the $i^{th}$ buiding. Each of the following $u$ integers are given and repetitions are allowed which means there can be more than one person in a floor. $i$ indicates building number and $j$ indicates floor number. Building number will not be given; since $N$ lines follow the first line, you can assume that the $i^{th}$ line indicates the $i^{th}$ building's specifications. **Constraints** $1 \le H,N \le 1900$ $1 \le I \le 450$ $0 \le u \le 1900$ (for each $i$, which means the maximum number of people in a particular building will not exceed $1900$) $1 \le u_{ij} \le H$
Output the maximum number of people Superman can save.
4 15 2 5 1 1 1 4 10 8 9 5 7 7 3 9 8 8 5 9 5 6 4 3 0
12
Hard
null
null
null
null
null
null
2014-11-10T18:01:23
2016-12-04T00:09:39
setter
###C++ ```cpp # include <iostream> # include <fstream> # include <sstream> # include <algorithm> # include <numeric> # include <cstdio> # include <cmath> # include <cstdlib> # include <cstring> # include <vector> # include <list> # include <set> # include <map> # include <stack> # include <queue> # include <cctype> # include <climits> using namespace std; typedef long long LL; typedef unsigned long long ULL; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector<vector<int> > vvi; #define GI ({int t;scanf("%d",&t);t;}) #define REP(i,a,b) for(int i=a;i<b;i++) #define ALL(v) (v).begin(),(v).end() #define TR(i,x) for(typeof(x.begin()) i=x.begin();i!=x.end();i++) #define pb push_back #define mp make_pair #define INF (int)1e9 #define EPS (double)(1e-9) #define PI (double)(3.141592653589793) int i, j, test_cases, num_buildings, height_b, height_l, a, n, people[2002][2002], dp[2002][2002],maxheight[2002]; int main() { scanf("%d %d %d", &num_buildings, &height_b, &height_l); for (i = 1; i <= num_buildings; i++) { scanf("%d", &a); for (j = 0; j < a; j++) { scanf("%d", &n); people[n][i]++; } } for( int i = 1; i <= height_b; i++ ) { maxheight[i]=0; for( int j = 1; j <= num_buildings; j++ ) { dp[i][j] = dp[i-1][j]; if( i - height_l >= 1 ) dp[i][j] = max( dp[i][j] , maxheight[ i - height_l ] ); dp[i][j] += people[i][j]; maxheight[i] = max( maxheight[i] , dp[i][j] ); } } int ans = 0; for(int i=1; i<=num_buildings; i++) { ans = max(ans,dp[height_b][i]); } printf("%d\n",ans); return 0; } ```
not-set
2016-04-24T02:03:15
2016-07-23T15:16:12
C++
236
5,146
hcf-lcm
HCF-LCM
**Input Format** First line contains the number of test cases, $T$. Next $2*T$ lines follow, each containing total number of elements $N$ in the first line and $N$ spaced positive integers, $a_i$ in the second line. **Output Format** Output $T$ lines each line in the format: H:L where $H$ is the highest common factor of the elements and $L$ is the lcm of the elements modulo 500. **Constraints** $1 \le T \le 10^5$ $1 \le N \le 10^6 $ $1 \le a_i \le 10^9$ **Sample Input** 1 3 4 12 20 **Sample Output** 4:60
code
Given $N$ numbers, find the HCF and LCM of all numbers.
ai
2014-11-11T00:01:37
2016-09-09T09:58:36
null
null
null
**Input Format** First line contains the number of test cases, $T$. Next $2*T$ lines follow, each containing total number of elements $N$ in the first line and $N$ spaced positive integers, $a_i$ in the second line. **Output Format** Output $T$ lines each line in the format: H:L where $H$ is the highest common factor of the elements and $L$ is the lcm of the elements modulo 500. **Constraints** $1 \le T \le 10^5$ $1 \le N \le 10^6 $ $1 \le a_i \le 10^9$ **Sample Input** 1 3 4 12 20 **Sample Output** 4:60
0.5
["bash","c","cpp","java","python","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-11-11T00:03:08
2016-05-12T23:57:54
setter
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define rep(i,n) for(int i = 0 ; i < n ; i++) #define gi(n) cin >> n #define pi(n) cout << n #define MAX 111111 ll a[MAX]; ll GCD(ll a, ll b) { return (b==0 ? a : GCD (b , a%b) ) ; } ll LCM(ll a[],ll n) { ll ans = 1, j; rep(i,n) { if(a[i]!=1) { for(j = i + 1 ; j < n ; j++) { a[j]/=GCD(a[i],a[j]); //reducing all remaining numbers by thier gcd with current number } ans = (ans * a[i]) % 500; } } return ans; } int main() { ll t, n, i, g, l; cin >> t; while (t--) { cin >> n; for (i=0 ; i<n ; i++) cin >> a[i]; g = a[0]; for(i=1 ; i<n ; i++){ g = GCD (g, a[i]); } l = LCM (a,n); cout << g << ":" << abs(l%500) << endl; } return 0; }
not-set
2016-04-24T02:03:16
2016-04-24T02:03:16
C++
237
5,146
hcf-lcm
HCF-LCM
**Input Format** First line contains the number of test cases, $T$. Next $2*T$ lines follow, each containing total number of elements $N$ in the first line and $N$ spaced positive integers, $a_i$ in the second line. **Output Format** Output $T$ lines each line in the format: H:L where $H$ is the highest common factor of the elements and $L$ is the lcm of the elements modulo 500. **Constraints** $1 \le T \le 10^5$ $1 \le N \le 10^6 $ $1 \le a_i \le 10^9$ **Sample Input** 1 3 4 12 20 **Sample Output** 4:60
code
Given $N$ numbers, find the HCF and LCM of all numbers.
ai
2014-11-11T00:01:37
2016-09-09T09:58:36
null
null
null
**Input Format** First line contains the number of test cases, $T$. Next $2*T$ lines follow, each containing total number of elements $N$ in the first line and $N$ spaced positive integers, $a_i$ in the second line. **Output Format** Output $T$ lines each line in the format: H:L where $H$ is the highest common factor of the elements and $L$ is the lcm of the elements modulo 500. **Constraints** $1 \le T \le 10^5$ $1 \le N \le 10^6 $ $1 \le a_i \le 10^9$ **Sample Input** 1 3 4 12 20 **Sample Output** 4:60
0.5
["bash","c","cpp","java","python","cpp14"]
null
null
null
null
Hard
null
null
null
null
null
null
2014-11-11T00:03:08
2016-05-12T23:57:54
tester
from fractions import * def lcm(x,y): return (x*y)/gcd(x,y) t=input() for i in range(t): n=input() a=map(int,raw_input().split()) print str(reduce(gcd,a)) + ':' + str(reduce(lcm,a)%500)
not-set
2016-04-24T02:03:16
2016-04-24T02:03:16
Python
238
5,147
stocks-prediction
Stock Prediction
Statement goes here. We support markdown + latex. Note that to insert new line, end a line with at least 2 spaces. **Input format** blah blah. **Output format** blah blah. **Constraints** ... ... **Note** (optional) ... **Sample Input #00** abc def... **Sample Output #00** pqr ef **Sample Input #00** abc def... **Sample Output #00** pqr ef **Explanation** *Test Case #00:* Explanation for test case #0. *Test Case #01:* Explanation for test case #1.
code
null
ai
2014-11-11T04:24:29
2016-09-01T16:43:12
null
null
null
George is very concerned about the stock options his company has granted him, because the company's stock price has fluctuated unpredictably and has often failed to meet expectations. With this in mind, George has decided to sell his options. Before doing so, he would like to perform a series of calculations. Stock price history is presented as an array of positive integers, $A = \{a_0, a_1, \ldots, a_{n-1}\}$, which represents the average price per day of that stock. For a given day $d\ (0 \le d < n)$ and margin $M$, George needs to find the longest subarray containing the day's entry as a minimum, $a_d$, and all other entries not exceeding $a_d+M$. That is, he has to find the longest subarray, $A[l, r] = \{a_l, a_{l+1}, \ldots, a_r\}$, such that - $0 \le l \le d \le r < n$ - $a_d = minimum\{A[l, r]\}$ - $ \forall i \in [l, r], a_d \le a_i \le a_d + M$ George asks you to help him solve this problem.
0.571429
["haskell","clojure","scala","erlang","sbcl","ocaml","fsharp","racket","elixir"]
The first list contains an integer $n$ which represents the length of the array $A$. The second line contains $n$ space-separated integers, $a_0, a_1, \ldots, a_{n-1}$, which represent the element of array $A$. The next line contains the number of queries $Q$. Each of the subsequent $Q$ lines contain two integers $d$ and $M$ which represent the index of the element, which should be minimal and be included in subarray, and margin, respectively.
For each query output the length of the longest subarray with the required properties. **Constraints** $1 \le n \le 5\cdot 10^4$ $1 \le A[i] \le 10^9, 0 \le i < n$ $1 \le Q \le 10^5$ $0 \le d < n$ $0 \le M \le 10^9$
5 3 5 2 6 1 2 0 2 2 3
2 3
Hard
null
null
null
null
null
null
2014-11-18T07:57:12
2016-12-24T15:53:12
setter
import java.io.{BufferedReader, FileReader, InputStreamReader, Reader} object Solution { class Query(_index: Int, _margin: Int) { def index = _index def margin = _margin } def parseQuery(s: String): Query = { val elements = s.split(' ').map(Integer.parseInt).toList new Query(elements.head, elements.tail.head) } def readData(reader: BufferedReader): (Array[Int], Array[Query]) = { reader.readLine() // ignore number of elements val elements = reader.readLine().split(' ').map(Integer.parseInt).toList.toArray val numQueries = Integer.parseInt(reader.readLine()) val queries = new Array[Query](numQueries) for (i <- 0 to numQueries - 1) { queries(i) = parseQuery(reader.readLine()) } Tuple2(elements, queries) } class Range(val begin: Int, val end: Int) { def split(): (Range, Range) = { val m = (begin + end) >> 1 Tuple2(new Range(begin, m), new Range(m, end)) } def isEmpty = begin >= end def isSingle = begin + 1 == end def contains(i: Int) = begin <= i && i < end def equals(o: Range) = begin == o.begin && end == o.end def doesIntersect(o: Range) = { begin < o.end && o.begin < end } def restrictBy(r: Range): Range = { new Range(Math.max(begin, r.begin), Math.min(end, r.end)) } def concatRight(o: Range): Range = { if (end != o.begin) { throw new RuntimeException("Cannot concat non-adjacent ranges") } new Range(begin, o.end) } def length: Int = end - begin override def toString = "(%d, %d)".format(begin, end) } class Node[T](val left: Node[T], val right: Node[T], val range: Range, val e: T) { def this(range: Range, e: T) = this(null, null, range, e) } class SegmentsTree[T](root: Node[T], op: (T, T) => T, default: T) { def size: Int = root.range.length def update(index: Int, value: T): SegmentsTree[T] = { if (root.range.contains(index)) { new SegmentsTree[T](updateImpl(root, index, value), op, default) } else { this } } def rmq(begin: Int, end: Int): T = { rmqImpl(root, new Range(begin, end).restrictBy(root.range)) } private def updateImpl(node: Node[T], i: Int, v: T): Node[T] = { if (node.range.isSingle) { new Node[T](node.range, v) } else { val split = node.range.split() val left = if (split._1.contains(i)) { updateImpl(node.left, i, v) } else { node.left } val right = if (split._2.contains(i)) { updateImpl(node.right, i, v) } else { node.right } new Node[T](left, right, left.range.concatRight(right.range), op(left.e, right.e)) } } private def rmqImpl(node: Node[T], query: Range): T = { //System.err.println(node) //System.err.println(node.range) //System.err.println(node.range, query) if (query.isEmpty) { default } else if (query.equals(node.range)) { node.e } else { val split = node.range.split() var result = default if (split._1.doesIntersect(query)) { result = op( result, rmqImpl(node.left, query.restrictBy(split._1))) } if (split._2.doesIntersect(query)) { result = op( result, rmqImpl(node.right, query.restrictBy(split._2)) ) } result } } } object IntSegmentsTree { def apply(range: Range, op: (Int, Int) => Int, default: Int) = { def buildImpl(range: Range): Node[Int] = { if (range.isSingle) { new Node[Int](range, default) } else { val split = range.split() val left = buildImpl(split._1) val right = buildImpl(split._2) new Node[Int](left, right, left.range.concatRight(right.range), op(left.e, right.e)) } } new SegmentsTree[Int](buildImpl(range), op, default) } } def compress(sequence: Array[Int]): Array[Int] = { sequence.sortWith(_ < _).distinct } class Compressor(data: Array[Int]) { def indexOfMaxNotGreaterThan(element: Int): Int = { indexOfMaxNotGreaterThanImpl(new Range(0, data.length), element) } def size: Int = data.length private def indexOfMaxNotGreaterThanImpl(range: Range, element: Int): Int = { if (range.isSingle) { range.begin } else { val split = range.split() if (data(split._2.begin) <= element) { indexOfMaxNotGreaterThanImpl(split._2, element) } else { indexOfMaxNotGreaterThanImpl(split._1, element) } } } } def generateTrees(compressor: Compressor, elements: Array[Int]): (Array[SegmentsTree[Int]], Array[SegmentsTree[Int]]) = { val INF = 1000000000 val leftTrees = new Array[SegmentsTree[Int]](elements.length) val rightTrees = new Array[SegmentsTree[Int]](elements.length) var treeRight = IntSegmentsTree(new Range(0, compressor.size), Math.min, INF) var treeLeft = IntSegmentsTree(new Range(0, compressor.size), Math.max, -INF) for (i <- elements.length - 1 to 0 by -1) { rightTrees(i) = treeRight treeRight = treeRight.update(compressor.indexOfMaxNotGreaterThan(elements(i)), i) } for (i <- 0 to elements.length - 1) { leftTrees(i) = treeLeft treeLeft = treeLeft.update(compressor.indexOfMaxNotGreaterThan(elements(i)), i) } (leftTrees, rightTrees) } def maxIntervalLength( elements: Array[Int], precalc: (Array[SegmentsTree[Int]], Array[SegmentsTree[Int]]), compressor: Compressor, query: Query): Int = { val leftTree = precalc._1(query.index) val rightTree = precalc._2(query.index) val minPriceIndex = compressor.indexOfMaxNotGreaterThan(elements(query.index)) val maxPriceIndex = compressor.indexOfMaxNotGreaterThan(elements(query.index) + query.margin) val range = new Range( Math.max( leftTree.rmq(0, minPriceIndex), leftTree.rmq(maxPriceIndex + 1, leftTree.size) ), Math.min( rightTree.rmq(0, minPriceIndex), rightTree.rmq(maxPriceIndex + 1, rightTree.size) )) range.restrictBy(new Range(-1, elements.length)).length - 1 } def solve(iStreamReader: Reader): Unit = { val reader = new BufferedReader(iStreamReader) val data = readData(reader) val elements = data._1 val queries = data._2 val compressor = new Compressor(compress(elements)) val precalc = generateTrees(compressor, elements) queries.map(query => maxIntervalLength(elements, precalc, compressor, query)).map(println) } def main(arguments: Array[String]) = solve(if (arguments.length == 0) new InputStreamReader(System.in) else new FileReader(arguments(0))) }
not-set
2016-04-24T02:03:17
2016-04-24T02:03:17
Python
239
5,147
stocks-prediction
Stock Prediction
Statement goes here. We support markdown + latex. Note that to insert new line, end a line with at least 2 spaces. **Input format** blah blah. **Output format** blah blah. **Constraints** ... ... **Note** (optional) ... **Sample Input #00** abc def... **Sample Output #00** pqr ef **Sample Input #00** abc def... **Sample Output #00** pqr ef **Explanation** *Test Case #00:* Explanation for test case #0. *Test Case #01:* Explanation for test case #1.
code
null
ai
2014-11-11T04:24:29
2016-09-01T16:43:12
null
null
null
George is very concerned about the stock options his company has granted him, because the company's stock price has fluctuated unpredictably and has often failed to meet expectations. With this in mind, George has decided to sell his options. Before doing so, he would like to perform a series of calculations. Stock price history is presented as an array of positive integers, $A = \{a_0, a_1, \ldots, a_{n-1}\}$, which represents the average price per day of that stock. For a given day $d\ (0 \le d < n)$ and margin $M$, George needs to find the longest subarray containing the day's entry as a minimum, $a_d$, and all other entries not exceeding $a_d+M$. That is, he has to find the longest subarray, $A[l, r] = \{a_l, a_{l+1}, \ldots, a_r\}$, such that - $0 \le l \le d \le r < n$ - $a_d = minimum\{A[l, r]\}$ - $ \forall i \in [l, r], a_d \le a_i \le a_d + M$ George asks you to help him solve this problem.
0.571429
["haskell","clojure","scala","erlang","sbcl","ocaml","fsharp","racket","elixir"]
The first list contains an integer $n$ which represents the length of the array $A$. The second line contains $n$ space-separated integers, $a_0, a_1, \ldots, a_{n-1}$, which represent the element of array $A$. The next line contains the number of queries $Q$. Each of the subsequent $Q$ lines contain two integers $d$ and $M$ which represent the index of the element, which should be minimal and be included in subarray, and margin, respectively.
For each query output the length of the longest subarray with the required properties. **Constraints** $1 \le n \le 5\cdot 10^4$ $1 \le A[i] \le 10^9, 0 \le i < n$ $1 \le Q \le 10^5$ $0 \le d < n$ $0 \le M \le 10^9$
5 3 5 2 6 1 2 0 2 2 3
2 3
Hard
null
null
null
null
null
null
2014-11-18T07:57:12
2016-12-24T15:53:12
tester
/** * Created by Bo You on 2014/12/2. */ object Solution { class Node(val l: Int, val r: Int, val minValue: Int, val maxValue: Int) def build(a: Array[Int], n: Int, sz: Int, ng: Int): Array[Node] = { def iter(cur: Int, ans: List[Node]): List[Node] = { if (cur == ng) { return ans } else { val l = sz * cur val r = Math.min(n, l + sz) val x = (l to r - 1).foldLeft(Integer.MAX_VALUE)((cur, idx) => Math.min(cur, a(idx))) val y = (l to r - 1).foldLeft(Integer.MIN_VALUE)((cur, idx) => Math.max(cur, a(idx))) return iter(cur + 1, ans.+:(new Node(l, r, x, y))) } } return iter(0, List[Node]()).reverse.toArray } def work(q: Array[Int], a: Array[Int], segs: Array[Node]): Int = { def iter(cur: Int, d: Int, acc: Int): Int = { if (cur < 0 || cur >= segs.length) { return acc } else if (segs(cur).minValue >= a(q(0)) && segs(cur).maxValue <= a(q(0)) + q(1)) { return iter(cur + d, d, acc + segs(cur).r - segs(cur).l) } else { val fi = if (d == 1) segs(cur).l else segs(cur).r - 1 var ret = acc var i = fi while (true) { if (a(i) < a(q(0)) || a(i) > a(q(0)) + q(1)) { return ret } ret += 1 i += d } return -1 } } var idx = -1 for (i <- 0 to segs.length - 1) { if (segs(i).l <= q(0) && segs(i).r > q(0)) { idx = i } } val lp = (segs(idx).l to q(0) - 1).reverse.takeWhile(i => a(i) >= a(q(0)) && a(i) <= a(q(0)) + q(1)) var rp = (q(0) + 1 to segs(idx).r - 1).takeWhile(i => a(i) >= a(q(0)) && a(i) <= a(q(0)) + q(1)) return 1 + lp.length + rp.length + (if (lp.length == q(0) - segs(idx).l) iter(idx - 1, -1, 0) else 0) + (if (rp.length == segs(idx).r - q(0) - 1) iter(idx + 1, 1, 0) else 0) } def main(args: Array[String]): Unit = { val n = readLine().toInt val a = readLine().split(" ").map(_.toInt).toArray val sz = Math.sqrt(n).toInt val ng = if (n % sz != 0) n / sz + 1 else n / sz val segs = build(a, n, sz, ng) val numQueries = readLine().toInt for (i <- 1 to numQueries) { val q = readLine().split(" ").map(_.toInt) println(work(q, a, segs)) } } }
not-set
2016-04-24T02:03:17
2016-04-24T02:03:17
Python
240
5,264
white-falcon-and-sequence
White Falcon and Sequence
null
code
null
ai
2014-11-20T13:26:55
2019-07-02T13:59:01
null
null
null
White Falcon has a sequence of integers $A$. You need to choose two contiguous disjoint subsequences of $A$, let's say $x$ and $y$, of the same size, $n$. After that you will calculate the sum given by $\sum x_i y_{n-i+1}$ (1-indexed) White Falcon asks you to choose such two $x$ and $y$ that maximizes the above summation. **Input Format** The first line contains $N$ that denotes size of $A$. The second line contains $N$ integers, all elements of $A$. **Constraints** $2 \le N \le 3000$ $-10^6 \le A_i \le 10^6$ **Output Format** Print out a line that contains maximum summation that is obtainable from $A$ under the conditions described above. **Sample Input** 12 1 7 4 0 9 4 0 1 8 8 2 4 **Sample Output** 120 **Explanation** $x = \{4, 0, 9, 4\}$ $y = \{8, 8, 2, 4\}$ $\sum x_i y_{n-i+1} = 4 \times 4 + 0 \times 2 + 9 \times 8 + 4 \times 8 = 120$. You can try for other subsequences this is the maximum value.
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-11-20T13:29:01
2016-12-10T18:29:59
setter
#include <algorithm> #include <iostream> #include <cstring> #include <complex> #include <cassert> #include <cstdlib> #include <cstdio> #include <bitset> #include <vector> #include <string> #include <cmath> #include <ctime> #include <queue> #include <list> #include <map> #include <set> #define all(x) (x).begin(), (x).end() #define type(x) __typeof((x).begin()) #define foreach(it, x) for(type(x) it = (x).begin(); it != (x).end(); it++) #ifdef KAZAR #define eprintf(...) fprintf(stderr,__VA_ARGS__) #else #define eprintf(...) 0 #endif using namespace std; template<class T> inline void umax(T &a,T b){if(a<b) a = b ; } template<class T> inline void umin(T &a,T b){if(a>b) a = b ; } template<class T> inline T abs(T a){return a>0 ? a : -a;} template<class T> inline T gcd(T a,T b){return __gcd(a, b);} template<class T> inline T lcm(T a,T b){return a/gcd(a,b)*b;} typedef long long ll; typedef pair<int, int> ii; const int inf = 1e9 + 143; const ll longinf = 1e18 + 143; inline int read(){int x;scanf(" %d",&x);return x;} const int N = 20001; int n; int a[N]; void read_inp(){ n = read(); assert(1 <= n && n <= 20000); for(int i = 1; i <= n; i++){ a[i] = read(); assert(abs(a[i]) <= int(1e6)); } } int main(){ #ifdef KAZAR freopen("f.input","r",stdin); freopen("f.output","w",stdout); freopen("error","w",stderr); #endif read_inp(); ll ans = -longinf; for(int i = 1; i <= n; i++){ { int l = i - 1, r = i; ll best = 0ll, cur = 0ll; while(l >= 1 && r <= n){ ll val = (ll)a[l] * a[r]; cur += val; umin(best, cur); umax(ans, cur - best); --l; ++r; } }{ int l = i - 1, r = i + 1; ll best = 0ll, cur = 0ll; while(l >= 1 && r <= n){ ll val = (ll)a[l] * a[r]; cur += val; umin(best, cur); umax(ans, cur - best); --l; ++r; } } } printf("%lld\n",ans); return 0; }
not-set
2016-04-24T02:03:17
2016-04-24T02:03:17
C++
241
5,300
putting-numbers
Putting Numbers
null
code
Counting is funny!
ai
2014-11-23T23:56:16
2016-09-09T09:59:44
null
null
null
My little brothers David and Goliath are learning to count up to large numbers, then they are playing a game that consist to put all the numbers from 1 to N in a table. The numbers are plastic and are in two boxes, they take it out and put it on the table in a straight line in ascending order. A box has numbers from 1 to N of a color and the other box has the numbers from 1 to N of another color. So that David and Goliath can choose a different color. David is a smart kid and comes up with a variation of the game, he says that if each player can only put groups of consecutive numbers of a fixed size before, then there will be fewer different ways to put all the numbers from 1 to N. A way of put all numbers from 1 to N is different to another if exists a same number with different color. Then to test the intellect of David, we ask you help calculating how many different ways to put the numbers from 1 to N if David can put sets of size k with consecutive numbers and Goliath sets of size p with consecutive numbers, but with very large numbers. They can take turns at whim.
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"]
The only line of input contains three integers N, p and k (2000 <= N <= 10^9) (1000 <= p,k < N) with k != p.
Print a line with the number if different ways to put the numbers from 1 to N modulo 10^9 + 7 (1000000007).
6 2 3
2
Hard
null
null
null
null
null
null
2014-11-23T23:57:13
2016-05-12T23:57:42
setter
#include <cstdio> #include <algorithm> #include <iostream> using namespace std; #define N 1000005 #define ll long long const ll mod = 1000000007; ll fact[N]; ll GCDext(ll a, ll b, ll &x, ll &y){ ll g = a; x = 1; y = 0; if(b!=0){ g = GCDext(b, a%b, y, x); y -= (a/b)*x; } return g; } ll invMod(ll a, ll m, ll &inv){ ll x,y; if(GCDext(a,m,x,y) != 1) return 0; inv = (x+m)%m; return 1; } ll n, k, p; int main(){ fact[0] = 1ULL; for(int i = 1; i <= 1000000; ++i) fact[i] = (fact[i-1] * (ll)i)%mod; cin >> n >> p >> k; if(p < k) swap(p,k); ll aux = 0, ct = 0, ct2 = 0, sol = 0, inv, sol2; while(aux <= n){ sol2 = 0; if((n - aux) % k == 0){ ct2 = (n - aux) / k; sol2 = fact[ct+ct2]; inv = 0; invMod((fact[ct2]*fact[ct])%mod, mod, inv); sol2 *= inv; sol2 %= mod; } sol += sol2; ct++; aux += p; } cout << sol%mod << endl; return 0; }
not-set
2016-04-24T02:03:17
2016-04-24T02:03:17
C++
242
5,369
minimum-multiple
Minimum Multiple
null
code
Find the least multiple of a subarray
ai
2014-12-01T17:45:55
2016-09-01T16:43:08
null
null
null
Calculi is Lambda's older brother. Lambda is mischievous and always annoys Calculi by asking silly questions. This time around, Lambda would like to surprise Calculi by asking a challenging and interesting question. To that end, Lambda gives Calculi an array of $N$ integers, $A = \{a_0, a_1,\ldots, a_{N-1}\}$, followed by $K$ queries. Each query is of two types: - $Q\ l\ r$: Find the minimum positive integer, $M$, such that each element in subarray $arr[l\ldots r]\ (\{a_l, a_{l+1},\ldots, a_r\})$ divides $M$. - $U\ idx\ val$: Multiply the value at $idx$ by $val$. That is $a_{idx}' = a_{idx} \times val$, where $a'_{idx}$ is the updated value. Your task is to help Calculi tackle this challenge. For each query of type $''Q\ l\ r''$, find the value of $M$. As this value can be very large, print the $M$ modulo $(10^9+7)$, i.e., $M \% (10^9+7)$. For query of type $''U\ idx\ val''$, update the required element.
0.571429
["haskell","clojure","scala","erlang","sbcl","ocaml","fsharp","racket","elixir"]
The first line contains an integer, $N$, which represents the length of array, $A$. In second line, there are $N$ space-separated integers, $a_0, a_1,\ldots, a_{N-1}$, representing the elements of $A$. In third line, there is another integer, $K$, which is the count of queries to follow. Then follows $K$ lines, each representing a query of one of the types described above.
For each query of type `Q l r`, print the value of $M \% (10^9+7)$ on a new line.
5 2 5 6 1 9 7 Q 0 4 U 1 2 Q 0 2 Q 3 4 Q 2 4 U 3 8 Q 2 3
90 30 9 18 24
Hard
null
null
null
null
null
null
2014-12-01T17:50:45
2016-12-02T06:01:22
setter
module Main where import Control.Applicative import Data.List import qualified Data.Map as Map import Control.Arrow ((&&&)) p :: Int p = 10^(9::Int)+7 primeFactors :: Map.Map Int [(Int, Int)] primeFactors = Map.fromList. zip [1..]. map (map (head &&& length). group. factorize 2) $ [1..100] where factorize v n | v*v > n = if n == 1 then [] else [n] | n `rem` v == 0 = v: factorize v (n`div`v) | otherwise = factorize (succ v) n power :: Int -> Int -> Int power _ 0 = 1 power a b | even b = ret | otherwise = (a*ret) `rem` p where tmp = power a (b`div`2) ret = (tmp*tmp)`rem`p factorToValue :: [(Int, Int)] -> Int factorToValue [] = 1 factorToValue ((a,b):xs) = let f = power a b in (f * factorToValue xs)`rem`p data SegTree = Node { factor :: Map.Map Int Int , startIdx, endIdx :: Int , leftChild, rightChild :: SegTree } | Leaf { factor :: Map.Map Int Int , startIdx, endIdx :: Int } isLeaf, isNode :: SegTree -> Bool isLeaf (Leaf {}) = True isLeaf _ = False isNode = not. isLeaf initSegTree :: Int -> SegTree initSegTree n = initSegTree' 0 (n-1) where initSegTree' l r | l == r = Leaf {factor = Map.empty, startIdx = l, endIdx = l} | otherwise = let mid = (l+r)`div`2 in Node { factor = Map.empty, startIdx = l, endIdx = r , leftChild = initSegTree' l mid , rightChild = initSegTree' (succ mid) r } getFactors :: Int -> SegTree -> Map.Map Int Int getFactors _ (Leaf {factor = f}) = f getFactors idx nd | idx <= endIdx (leftChild nd) = getFactors idx (leftChild nd) | otherwise = getFactors idx (rightChild nd) mergePowers :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] mergePowers [] ys = ys mergePowers xs [] = xs mergePowers xxs@((a1,b1):xs) yys@((a2,b2):ys) | a1 == a2 = (a1, b1+b2): mergePowers xs ys | a1 < a2 = (a1, b1) : mergePowers xs yys | otherwise = (a2, b2) : mergePowers xxs ys bestPowers :: [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] bestPowers [] ys = ys bestPowers xs [] = xs bestPowers xxs@((a1,b1):xs) yys@((a2,b2):ys) | a1 == a2 = (a1, max b1 b2): bestPowers xs ys | a1 < a2 = (a1, b1) : bestPowers xs yys | otherwise = (a2, b2) : bestPowers xxs ys main :: IO () main = do n <- read <$> getLine arr <- map read. words <$> getLine k <- (read::String->Int) <$> getLine queries <- map (\x -> (\[[p'], q, r] -> (p', read q, read r)). words $ x). lines <$> getContents mapM_ print (solve n arr queries) solve :: Int -> [Int] -> [(Char, Int, Int)] -> [Int] solve n arr queries = processQueries queries origTree where origTree = foldr (\(idx, val) root -> updateTree idx (primeFactors Map.! val) root) (initSegTree n) (zip [0..] arr) processQueries :: [(Char, Int, Int)] -> SegTree -> [Int] processQueries [] _ = [] processQueries (('Q', l, r):q) root = let ans = factorToValue $ rangeQuery (l, r) root in ans : processQueries q root processQueries (('U', idx, val):q) root = let origFactor = Map.toList (getFactors idx root) newFactor = mergePowers origFactor (primeFactors Map.! val) newRoot = updateTree idx newFactor root in processQueries q newRoot rangeQuery :: (Int, Int) -> SegTree -> [(Int, Int)] rangeQuery range@(l, r) nd | r < startIdx nd = [] | l > endIdx nd = [] | l <= startIdx nd && endIdx nd <= r = Map.toList (factor nd) | otherwise = bestPowers (rangeQuery range (leftChild nd)) (rangeQuery range (rightChild nd)) updateTree :: Int -> [(Int, Int)] -> SegTree -> SegTree updateTree idx factors node | startIdx node <= idx && idx <= endIdx node = case node of Leaf {} -> node {factor = updatedFactors} _ -> node {factor = updatedFactors, leftChild = lChild, rightChild = rChild} where lChild = updateTree idx factors (leftChild node) rChild = updateTree idx factors (rightChild node) updatedFactors = foldr (\(base, p_new) fact -> updatePower base p_new fact) (factor node) factors updateTree _ _ node = node updatePower :: Int -> Int -> Map.Map Int Int -> Map.Map Int Int updatePower base p_new fact = let p_old = Map.findWithDefault 0 base fact in if p_new > p_old then Map.insert base p_new fact else fact isPrime n = not. any (\x -> n `rem` x == 0) $ [2..(n-1)]
not-set
2016-04-24T02:03:18
2016-04-24T02:03:18
Python
243
5,396
fibonacci-lcm
Fibonacci LCM
null
code
Find the LCM of Fibonacci numbers
ai
2014-12-03T19:42:44
2022-09-02T09:54:43
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY f as parameter. # def solve(f): # 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') f_count = int(input().strip()) f = [] for _ in range(f_count): f_item = int(input().strip()) f.append(f_item) result = solve(f) fptr.write(str(result) + '\n') fptr.close()
After Derek (of district 5) discovered how to compute the greatest common divisor (gcd) of Fibonacci numbers, he now tried to answer the next obvious question: how does one compute the *least common multiple* (lcm) of Fibonacci numbers? Unfortunately, Derek found out that this wasn't as easy as the original problem, so he asked you to answer it for him. The Fibonacci numbers are defined as: $$F_1 = F_2 = 1$$ $$F_n = F_{n-1} + F_{n-2}$$ Given $N$ integers $a_1, a_2, \ldots, a_N$, find $\text{lcm}(F_{a_1},F_{a_2},\ldots,F_{a_N})$, and give your answer modulo $10^9+7$. **Input Format** The first line of input contains $N$. Each of the next $N$ lines contains a number: the $i^{\text{th}}$ line contains $a_i$. **Constraints** $1 \le N \le 100$ $1 \le a_i \le 10^9$ **Output Format** Print a single integer, which is the least common multiple of the $F_{a_i}$, modulo $10^9+7$. **Sample Input** 5 1 3 3 6 9 **Sample Output** 136 **Explanation** $\text{lcm}(F_1,F_3,F_3,F_6,F_9) = \text{lcm}(1,2,2,8,34) = 136$
0.5
["c","clojure","cpp","cpp14","cpp20","csharp","erlang","go","haskell","java","java8","java15","javascript","julia","kotlin","lua","objectivec","perl","php","pypy3","python3","ruby","rust","scala","swift","typescript","r"]
Hard
null
null
null
null
null
null
2014-12-03T20:34:25
2016-07-23T18:16:55
setter
###C++ ```cpp #include <stdio.h> #include <stdlib.h> #include <tr1/unordered_map> #include <tr1/unordered_set> #include <algorithm> #define mod 1000000007 #define L 10000000 #define ll long long using namespace std; ll ipow(ll b, ll e) { if (e == 1) return b; if (e & 1) return ipow(b, e - 1) * b % mod; return ipow(b * b % mod, e >> 1); } ll rx, ry; void mmul(ll c, ll d, ll g, ll h) { ll dh = d * h; rx = ((c + d) * (g + h) - dh) % mod; ry = (c * g + dh) % mod; } void mpow(int e) { if (e == 1) { rx = 1; ry = 0; } else if (e & 1) { mpow(e - 1); mmul(1, 0, rx, ry); } else { mpow(e >> 1); mmul(rx, ry, rx, ry); } } ll F[L]; ll Fm(int n) { if (n < L) { return F[n]; } mpow(n); return rx; } #define umap tr1::unordered_map #define uset tr1::unordered_set uset<int> dset; uset<int> a; int cs[311111]; int ds[311111]; int k; int main() { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { int v; scanf("%d", &v); a.insert(v); } F[0] = 0, F[1] = 1; for (int i = 2; i < L; i++) { F[i] = F[i-1] + F[i-2]; if (F[i] >= mod) F[i] -= mod; } for (uset<int>::iterator it = a.begin(); it != a.end(); it++) { int x = *it; if (x <= 2) { continue; } for (int d = 1; d * d <= x; d++) { if (x % d == 0) { dset.insert(d); dset.insert(x / d); } } } k = 0; for (uset<int>::iterator it = dset.begin(); it != dset.end(); it++) { int key = *it; ds[k++] = key; } sort(ds, ds + k); ll ans = 1; for (int i = k-1; i >= 0; i--) { cs[i] = 1; for (int j = k-1; j > i; j--) { if (!(ds[j] % ds[i])) { cs[i] -= cs[j]; } } int c = cs[i] % (mod-1); if (c < 0) c += mod-1; if (c) { ll f = Fm(ds[i]); if (f != 1) { ans *= ipow(f, c); ans %= mod; } } } if (ans < 0) ans += mod; printf("%lld\n", ans); } ```
not-set
2016-04-24T02:03:18
2016-07-23T18:14:29
C++
244
5,396
fibonacci-lcm
Fibonacci LCM
null
code
Find the LCM of Fibonacci numbers
ai
2014-12-03T19:42:44
2022-09-02T09:54:43
# # Complete the 'solve' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY f as parameter. # def solve(f): # 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') f_count = int(input().strip()) f = [] for _ in range(f_count): f_item = int(input().strip()) f.append(f_item) result = solve(f) fptr.write(str(result) + '\n') fptr.close()
After Derek (of district 5) discovered how to compute the greatest common divisor (gcd) of Fibonacci numbers, he now tried to answer the next obvious question: how does one compute the *least common multiple* (lcm) of Fibonacci numbers? Unfortunately, Derek found out that this wasn't as easy as the original problem, so he asked you to answer it for him. The Fibonacci numbers are defined as: $$F_1 = F_2 = 1$$ $$F_n = F_{n-1} + F_{n-2}$$ Given $N$ integers $a_1, a_2, \ldots, a_N$, find $\text{lcm}(F_{a_1},F_{a_2},\ldots,F_{a_N})$, and give your answer modulo $10^9+7$. **Input Format** The first line of input contains $N$. Each of the next $N$ lines contains a number: the $i^{\text{th}}$ line contains $a_i$. **Constraints** $1 \le N \le 100$ $1 \le a_i \le 10^9$ **Output Format** Print a single integer, which is the least common multiple of the $F_{a_i}$, modulo $10^9+7$. **Sample Input** 5 1 3 3 6 9 **Sample Output** 136 **Explanation** $\text{lcm}(F_1,F_3,F_3,F_6,F_9) = \text{lcm}(1,2,2,8,34) = 136$
0.5
["c","clojure","cpp","cpp14","cpp20","csharp","erlang","go","haskell","java","java8","java15","javascript","julia","kotlin","lua","objectivec","perl","php","pypy3","python3","ruby","rust","scala","swift","typescript","r"]
Hard
null
null
null
null
null
null
2014-12-03T20:34:25
2016-07-23T18:16:55
tester
###C++ ```cpp #define _USE_MATH_DEFINES #include <stdio.h> #include <math.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <iostream> #include <sstream> #include <vector> #include <algorithm> #include <set> #include <queue> #include <map> #include <string> #include <ctime> #include <unordered_map> #include <unordered_set> #define M 1000000007 using namespace std; int n,a[200],i,res[2]; unordered_map<int,int>fibs; int gcd(int a,int b) { if(a && b) while(a%=b^=a^=b^=a); return a+b; } int getFib(int n) { auto it=fibs.find(n); if(it!=fibs.end()) return it->second; int a[2][2]; int b[2]; int temp[2]; int c[2][2]; int i,j; for(i=0;i<2;i++) { for(j=0;j<2;j++) a[i][j]=i||j; b[i]=i; } while(n) { if(n%2) { for(j=0;j<2;j++) temp[j]=((long long)b[0]*a[0][j]+(long long)b[1]*a[1][j])%M; for(j=0;j<2;j++) b[j]=temp[j]; } for(i=0;i<2;i++) for(j=0;j<2;j++) c[i][j]=((long long)a[i][0]*a[0][j]+(long long)a[i][1]*a[1][j])%M; for(i=0;i<2;i++) for(j=0;j<2;j++) a[i][j]=c[i][j]; n/=2; } return b[0]; } void rec(int i,int ans,int isZ) { if(i==n && ans) { res[isZ]=(long long)res[isZ]*getFib(ans)%M; return; } int g=gcd(ans,a[i]); if(g==ans)return; rec(i+1,ans,isZ); rec(i+1,g,!isZ); } int obr(int x) { int p=M,a=0,b=1,q; while(x) { q=p/x; p-=x*q; a-=b*q; p^=x^=p^=x; a^=b^=a^=b; } return (a+M)%M; } int main() { scanf("%d",&n); if(n<1 || n>100)throw; for(i=0;i<n;i++) { scanf("%d",&a[i]); if(a[i]<1 || a[i]>1000000000)throw; } sort(a,a+n); n=unique(a,a+n)-a; res[0]=res[1]=1; rec(0,0,1); res[0]=(long long)res[0]*obr(res[1])%M; printf("%d\n",res[0]); return 0; } ```
not-set
2016-04-24T02:03:18
2016-07-23T18:16:55
C++
245
5,443
house-arrest
House Arrest
null
code
Help Jejeman find the best lot for his house arrest.
ai
2014-12-06T14:38:05
2016-09-09T10:00:39
null
null
null
After suddenly getting an illness that required him to use a wheel chair, the Supreme Court decided to put Jejeman under house arrest instead of the normal prison. According to the Constitution, the lot (the house including the garden and everything) where Jejeman will be banished to will have some constraints. First, the total land area of the lot must be exactly $A$ square meters. This is because less than $A$ square meters of space will worsen Jejeman's illness (according to doctors he enlisted). No one wants him to die of course since he gives people birthday cakes! Moreover, it must not exceed $A$ square meters, otherwise people will think that he's not being punished for his misdeeds. Of course, no one is supposed to visit Jejeman. Thus, there must be some sort of fencing. The budget for this is enough for $P$ meters worth of fencing material. Needless to say, $P$ meters worth of material should be able to fence an area of exactly $A$ square meters. It has to be exactly that, otherwise the contractor will not install it. Moreover, the lot he chooses must be one contiguous land area. This is common sense. If he makes it more than one contiguous land areas, then he would not be able to access both of them since he's not supposed to be outside the alloted area for him. Furthermore, there shouldn't be any "holes" in the area. The lot will also be a corner lot (between perpendicular streets). Hence, to make things beautiful, all fencing material must be parallel to any of the two streets. The following image shows examples of plans which are valid and invalid: <img src="https://s3.amazonaws.com/hr-challenge-images/5443/1428600624-67a4c72b56-Final-HouseArrest.jpg" title="Final - House Arrest.jpg" /> To summarize, the whole lot, when viewed from Jejeman's helicopter hovering in the sky must be a polygon. The architect assigned to do this is at a loss. Perhaps the perfect lot shape could be found using programming?
0.5
["c","cpp","java","python3","python","cpp14"]
The first line of input contains $C$, the number of test cases. The following lines describe the test cases. Each test case consists of one line containing two integers, $A$ and $P$, as discussed above.
For each test case, output `WALA` if there is no polygon satisfying all the above. Otherwise, write $M$ in the first line, where $M$ is the number of corners of the polygon. In the next $M$ lines, write the coordinates $(x_i, y_i)$ of the corners (in either order around the polygon). Naturally, $(x_M, y_M)$ is assumed to be connected to $(x_1, y_1)$. To keep things simple, no three consecutive points must lie on the same line. To keep things simpler, we limit the number of corners $M$ to be at most $50$. Moreover, the $x_i$'s and $y_i$'s must be *integers* satisfying the constraints written below. We assume that the two perpendicular streets described in the problem statement are parallel to the $x$ and $y$ axes. Take note that this polygon is not unique. We will accept any answer which satisfies the conditions. **Constraints** For any $i \in \{1, \ldots, M\}$ $-10^{15} \leq x_i \le 10^{15}$ $-10^{15} \leq y_i \le 10^{15}$ **Subtask 1** (4 points each): $1 \le C \le 1000$ $1 \le A \le 5$ $1 \le P \le 20$ **Subtask 2** (8 points each): $1 \le C \le 1000$ $1 \le A \le 30$ $1 \le P \le 300$ **Subtask 3** (11 points each): $1 \le C \le 1000$ $1 \le A \le 10000$ $1 \le P \le 10000$ **Subtask 4** (13 points each): $1 \le C \le 5000$ $1 \le A \le 10^9$ $1 \le P \le 10^9$ **Subtask 5** (14 points each): $1 \le C \le 5000$ $1 \le A \le 10^{16}$ $1 \le P \le 10^{16}$
3 4 8 3 8 1 20
4 1 1 1 -1 -1 -1 -1 1 6 0 0 2 0 2 1 1 1 1 2 0 2 WALA
Hard
null
null
null
null
null
null
2014-12-06T18:10:41
2017-10-05T00:13:30
setter
```c++ #include <stdio.h> #include <math.h> #include <set> using namespace std; #define ll long long #define BD (2000000000000000LL-10) // 2*10^15 - 10 #define DL 1000000000000000LL // 10^15 // computes the integer square root ll isqrt(ll n) { ll s = int(sqrt(n)); while (s * s < n) s += 1; while (s * s > n) s -= 1; return s; } ll xs[1111]; ll ys[1111]; ll min(ll a, ll b) { return a < b ? a : b; } int ans(ll a, ll p) { // odd perimeter: impossible if (p % 2) { return 0; } // too large perimeter if (p > 2*a + 2) { return 0; } ll s = isqrt(a); ll inner = (s-1)*(s-1); if (s * (s+1) < a) { inner += s-1 + a - s*(s+1) - 1; } else if (s * s < a) { inner += a - s*s - 1; } // too small perimeter ll min_p = 2*a - 2*inner + 2; if (p < min_p) { return 0; } int ct = 0; #define addpt(x,y) (xs[ct] = (x), ys[ct] = (y), ct++) // trivial case, a = 1 if (a == 1) { addpt(0,0); addpt(0,1); addpt(1,1); addpt(1,0); return ct; } // create a polygon with minimum perimeter // and with the desired number of interior points inner = a - p/2 + 1; s = isqrt(inner) + 1; if (inner == 0) { // no inner points addpt(0,0); addpt(1,0); addpt(1,2); addpt(0,2); } else if (inner > (s-1)*s) { // oblong rectangle + incomplete layer ll x = inner - (s-1)*s + 1; addpt(0,0); addpt(s+1,0); addpt(s+1,s); addpt(x,s); addpt(x,s+1); addpt(0,s+1); } else if (inner == (s-1)*s) { // oblong rectangle addpt(0,0); addpt(s+1,0); addpt(s+1,s); addpt(0,s); } else if (inner > (s-1)*(s-1)) { // square + incomplete layer ll y = inner - (s-1)*(s-1) + 1; addpt(0,0); addpt(s,0); addpt(s,s); addpt(y,s); addpt(y,s+1); addpt(0,s+1); } else { // square addpt(0,0); addpt(s,0); addpt(s,s); addpt(0,s); } // compute the current area, using area formula ll A = 0; for (int i = 0, j = ct - 1; i < ct; j = i++) { A += xs[i] * ys[j] - xs[j] * ys[i]; } if (A < 0) A = -A; A /= 2; // if a > A, then we need to add a few more blocks // WITHOUT adding new interior points (so we get // the desired perimeter) while (a > A) { #define move(_i,ch) do {\ for (int i = ct-1; i >= _i; i--) {\ xs[i+ch] = xs[i];\ ys[i+ch] = ys[i];\ }\ ct += ch;\ } while (0) #define insertpt(i,x,y) (xs[i] = (x), ys[i] = (y)) ll x1 = xs[1], y1 = ys[1]; ll x2 = xs[2], y2 = ys[2]; ll d = min(a - A, BD); // add a J branch with height d if (d <3) { // height-1 branch move(2, 2); insertpt(1,x1 + d,0); insertpt(2,x1 + d,1); insertpt(3,x1,1); A += d; } else { // tall branch move(2, 4); insertpt(1,x1 + 2,0); insertpt(2,x1 + 2,d-1); insertpt(3,x1 + 1,d-1); insertpt(4,x1 + 1,1); insertpt(5,x1,1); A += d; } } // adjust points ll mx = xs[0], my = ys[0]; for (int i = 0; i < ct; i++) { ll x = xs[i], y = ys[i]; mx = min(mx, x); my = min(my, y); } mx += DL; my += DL; for (int i = 0; i < ct; i++) { xs[i] -= mx; ys[i] -= my; } return ct; } int main() { int z; scanf("%d", &z); while (z--) { ll a, p; scanf("%lld%lld", &a, &p); int ct = ans(a,p); if (!ct) { printf("WALA\n"); } else { printf("%d\n", ct); for (int i = 0; i < ct; i++) { ll x = xs[i]; ll y = ys[i]; printf("%lld %lld\n", x, y); } } } } ```
not-set
2016-04-24T02:03:19
2017-10-05T00:13:30
C++
246
5,493
the-tide-is-high
The Tide is High
null
code
Compute the productivity of an archipelago when the tide is high.
ai
2014-12-08T06:31:36
2016-12-01T08:20:54
null
null
null
It is widely known that the Philippines has 7107 islands. But of course, that doesn't account for when some islands are covered during high tide and when some islands spring out during low tide. So it's definitely not a fixed number. Let's just say the Philippines has at least 7000 islands to be safe. In fact, there are a hundred islands nearby where you're sitting right now. Isn't that mind-blowing? <img src="https://s3.amazonaws.com/hr-challenge-images/5493/1431360352-6b7504b826-Hundred_Island.jpg" title="Hundred_Island.jpg" /> (Image taken from [Wikipedia](http://en.m.wikipedia.org/wiki/File:Hundred_Island.jpg)) Now, you are given a map of part of the Philippines represented by `#` for each square kilometer of land and `~` for each square kilometer of water. As you might (or might have not) learned from your HeKaSi subject, an island is a contiguous land mass surrounded by water. For our purposes, we treat any contiguous land mass to be an island. We define the *productivity of an island* to be the square of the numerical value of its area (in square kilometers). And the *productivity of an area* to be the sum of the productivity of each island in that map. You can assume that everything around the map is water. During times when the tides are high, some parts of the islands may get covered in water. Hence, the productivity of an island (and consequently, the productivity of an area) may change when the tides change. You are told that in the map given to you, the column of land with the lowest height submerge underwater during high tide. You are just told that if two land squares are in the same column, then they have the same height. Thus, being the genius that you are, you conclude that during high tide, exactly one column of land gets covered in water. Unfortunately, the map doesn't tell you how high each land is. And so, you decide to explore every case. What if the first column gets covered? What if the second column gets covered? And this is exactly what this problem asks of you. You're not that type of person who gives up just like that. So you decide to make a program that will address every possibility. <img src="https://s3.amazonaws.com/hr-challenge-images/5493/1431339437-bcffe24005-TheTideisHigh.jpg" title="The Tide is High.jpg" />
0.5
["c","cpp","java","python","python3","java8","cpp14"]
The first line of input contains $T$, the number of test cases. The following lines describe the test cases. The first line of each test case contains two integers $W$ and $L$ denoting the width and the length of the map. The next $W$ lines each contain $L$ characters where each character is either a `#` or a `~`, describing the area.
For each test case, output a single line containing $L$ integers, where the $x^{\text{th}}$ integer is the productivity of the area *during high tide* if the $x^{\text{th}}$ column of land has the lowest height. **Constraints** $1 \le T \le 20$ $L \ge 1$ $W \ge 1$ **Subtask 1** (11 points each): $1 \le L\cdot W \le 1000$ Every island is a long flat island, i.e. it consists of a sequence of contiguous `#` tiles on a row, without land tiles immediately above or below it. **Subtask 2** (14 points each): $1 \le L\cdot W \le 1000$ **Subtask 3** (25 points each): $1 \le L\cdot W \le 100000$
4 3 2 ~~ ~~ ~~ 3 3 ~~~ ~#~ ~~~ 5 7 ~~~~~~~ ####### ~~~~~~~ ~~~~##~ ####~~~ 7 15 ~~~~~~~~~~~~~~~ ~#~~#~~##~~###~ ~##~#~#~~#~~#~~ ~#~##~#~~#~~#~~ ~#~~#~#~~#~~#~~ ~#~~#~~##~~###~ ~~~~~~~~~~~~~~~
0 0 1 0 1 49 35 29 31 37 43 56 179 144 168 168 144 179 170 173 173 170 179 147 102 147 179
Hard
null
null
null
null
null
null
2014-12-18T06:39:57
2017-10-09T21:05:39
setter
```c++ #include <stdio.h> #define L 100011 #define ll long long char g[L]; ll lps[L]; ll rps[L]; int parent[L]; int size[L]; int find(int n) { return parent[n] < 0 ? n : parent[n] = find(parent[n]); } void onion(int i, int j) { if (parent[i] == parent[j]) { parent[i]--; } if (parent[i] > parent[j]) { parent[i] = j; size[j] += size[i]; } else { parent[j] = i; size[i] += size[j]; } } int main() { int z; scanf("%d", &z); while (z--) { int w, l; scanf("%d%d", &w, &l); for (int i = 0; i < w; i++) { scanf("%s", g + i*l); } ll pd; #define attach(_ni,_nj) do {\ int ni = (_ni);\ int nj = (_nj);\ if (g[ni*l+nj] == '#') {\ int fd1 = find( i*l+ j);\ int fd2 = find(ni*l+nj);\ if (fd1 != fd2) {\ ll sz1 = size[fd1];\ ll sz2 = size[fd2];\ ll sz = sz1 + sz2;\ pd += sz*sz - sz1*sz1 - sz2*sz2;;\ onion(fd1,fd2);\ }\ }\ } while (0) pd = lps[0] = 0; for (int j = 0; j < l; j++) { for (int i = 0; i < w; i++) { if (g[i*l+j] == '#') { size[i*l+j] = 1; parent[i*l+j] = -1; pd++; if (i > 0) { attach(i-1, j); } if (j > 0) { attach(i, j-1); } } } lps[j+1] = pd; } pd = rps[l] = 0; for (int j = l-1; j >= 0; j--) { for (int i = 0; i < w; i++) { if (g[i*l+j] == '#') { size[i*l+j] = 1; parent[i*l+j] = -1; pd++; if (i > 0) { attach(i-1, j); } if (j < l-1) { attach(i, j+1); } } } rps[j] = pd; } for (int x = 0; x < l; x++) { if (x) printf(" "); printf("%lld", lps[x] + rps[x+1]); } printf("\n"); } } ```
not-set
2016-04-24T02:03:21
2017-10-09T21:05:40
C++
247
5,493
the-tide-is-high
The Tide is High
null
code
Compute the productivity of an archipelago when the tide is high.
ai
2014-12-08T06:31:36
2016-12-01T08:20:54
null
null
null
It is widely known that the Philippines has 7107 islands. But of course, that doesn't account for when some islands are covered during high tide and when some islands spring out during low tide. So it's definitely not a fixed number. Let's just say the Philippines has at least 7000 islands to be safe. In fact, there are a hundred islands nearby where you're sitting right now. Isn't that mind-blowing? <img src="https://s3.amazonaws.com/hr-challenge-images/5493/1431360352-6b7504b826-Hundred_Island.jpg" title="Hundred_Island.jpg" /> (Image taken from [Wikipedia](http://en.m.wikipedia.org/wiki/File:Hundred_Island.jpg)) Now, you are given a map of part of the Philippines represented by `#` for each square kilometer of land and `~` for each square kilometer of water. As you might (or might have not) learned from your HeKaSi subject, an island is a contiguous land mass surrounded by water. For our purposes, we treat any contiguous land mass to be an island. We define the *productivity of an island* to be the square of the numerical value of its area (in square kilometers). And the *productivity of an area* to be the sum of the productivity of each island in that map. You can assume that everything around the map is water. During times when the tides are high, some parts of the islands may get covered in water. Hence, the productivity of an island (and consequently, the productivity of an area) may change when the tides change. You are told that in the map given to you, the column of land with the lowest height submerge underwater during high tide. You are just told that if two land squares are in the same column, then they have the same height. Thus, being the genius that you are, you conclude that during high tide, exactly one column of land gets covered in water. Unfortunately, the map doesn't tell you how high each land is. And so, you decide to explore every case. What if the first column gets covered? What if the second column gets covered? And this is exactly what this problem asks of you. You're not that type of person who gives up just like that. So you decide to make a program that will address every possibility. <img src="https://s3.amazonaws.com/hr-challenge-images/5493/1431339437-bcffe24005-TheTideisHigh.jpg" title="The Tide is High.jpg" />
0.5
["c","cpp","java","python","python3","java8","cpp14"]
The first line of input contains $T$, the number of test cases. The following lines describe the test cases. The first line of each test case contains two integers $W$ and $L$ denoting the width and the length of the map. The next $W$ lines each contain $L$ characters where each character is either a `#` or a `~`, describing the area.
For each test case, output a single line containing $L$ integers, where the $x^{\text{th}}$ integer is the productivity of the area *during high tide* if the $x^{\text{th}}$ column of land has the lowest height. **Constraints** $1 \le T \le 20$ $L \ge 1$ $W \ge 1$ **Subtask 1** (11 points each): $1 \le L\cdot W \le 1000$ Every island is a long flat island, i.e. it consists of a sequence of contiguous `#` tiles on a row, without land tiles immediately above or below it. **Subtask 2** (14 points each): $1 \le L\cdot W \le 1000$ **Subtask 3** (25 points each): $1 \le L\cdot W \le 100000$
4 3 2 ~~ ~~ ~~ 3 3 ~~~ ~#~ ~~~ 5 7 ~~~~~~~ ####### ~~~~~~~ ~~~~##~ ####~~~ 7 15 ~~~~~~~~~~~~~~~ ~#~~#~~##~~###~ ~##~#~#~~#~~#~~ ~#~##~#~~#~~#~~ ~#~~#~#~~#~~#~~ ~#~~#~~##~~###~ ~~~~~~~~~~~~~~~
0 0 1 0 1 49 35 29 31 37 43 56 179 144 168 168 144 179 170 173 173 170 179 147 102 147 179
Hard
null
null
null
null
null
null
2014-12-18T06:39:57
2017-10-09T21:05:39
tester
```c++ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cassert> #include <string> #include <cstring> using namespace std; char s[100005]; int f[100005]; int num[100005]; long long save[100005]; inline long long sqr(long long x) { return x * x; } int getf(int x) { return (f[x] == x)?x:(f[x] = getf(f[x])); } long long make(int x,int y) { int fx = getf(x), fy = getf(y); if (fx == fy) { return 0; } long long r = -sqr(num[fx]) - sqr(num[fy]); if (num[fx] > num[fy]) { f[fx] = fy; num[fy] += num[fx]; num[fx] = 0; r += sqr(num[fy]); } else { f[fy] = fx; num[fx] += num[fy]; num[fy] = 0; r += sqr(num[fx]); } return r; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int z; for (scanf("%d",&z); z; --z) { assert(z <= 20); int m,n; assert(scanf("%d%d",&m,&n) != EOF); assert((m > 0) && (m <= 100000)); assert((n > 0) && (n <= 100000 / m)); int total = 0; for (int i = 0; i < m; ++i) { assert(scanf("%s", s + total) != EOF); assert(strlen(s + total) == n); total += n; } memset(save, 0, sizeof(save)); for (int j = n - 2; j >= 0; --j) { int x = j + 1; save[j] = save[j + 1]; for (int i = 0; i < m; ++i) { if (s[x] == '#') { f[x] = x; num[x] = 1; ++save[j]; if ((j + 2 < n) && (s[x + 1] == '#')) { save[j] += make(x, x + 1); } if ((i) && (s[x - n] == '#')) { save[j] += make(x, x - n); } } x += n; } } printf("%lld", save[0]); long long result = 0; for (int j = 1; j < n; ++j) { int x = j - 1; for (int i = 0; i < m; ++i) { if (s[x] == '#') { f[x] = x; num[x] = 1; ++result; if ((j - 2 >= 0) && (s[x - 1] == '#')) { result += make(x, x - 1); } if ((i) && (s[x - n] == '#')) { result += make(x, x - n); } } x += n; } printf(" %lld", result + save[j]); } puts(""); } return 0; } ```
not-set
2016-04-24T02:03:21
2017-10-09T21:05:40
C++
248
5,452
confidentialegassem-8
Confidential Message
null
code
Yuo received a message but it was jumbled by some confidential process.
ai
2014-12-06T18:54:29
2016-12-01T08:20:40
null
null
null
Yuo is a new student in his class. The girls in his class apparently communicate information using a confidential process to somehow jumble the message. Each jumbled message has a corresponding sequence of integers attached to it: $s_1, \ldots, s_N$. To "unjumble" the message, look at the last $s_1$ letters of the jumbled message and reverse their order to get a new jumbled message. Then, look at the last $s_2$ letters of this new message and reverse their order to get a new jumbled message and so on. After the final reversal, you should get the real unjumbled message. Carly wanted to send a super secret SMS to her classmate Rae. Late night, while watching television, she finally decided she will send the SMS to her friend. But instead of texting Rae, she accidentally texted Yuo. Her text message reads: <pre> ireallyreallyreallyreallyreallyreallylikeyou 44 44 2 44 44 From: Carly 09987765321 </pre> Unlike her mobile service provider, Carly doesn't seem to be smart. Especially when you know how she got in this position. Now, Yuo can perfectly read the sentence but he knows that girls speak in code. Thus, he can't be too sure what it means. So, he wants to unjumble the message to be certain. Can you create a program that unjumbles messages such as these for Yuo?
0.5
["c","cpp","java","python","python3","java8","cpp14"]
The first line of input contains an integer $T$, the number of test cases. Each test case consists of three lines. The first line contains two integers $L$ and $N$, where $L$ is the length of the jumbled message (and of course, also the length of the unjumbled message). The second line contains a string $J$, the jumbled message. It is guaranteed to contain exactly $L$ characters and it only consists of lowercase letters from `a` to `z`. The third line consists the sequence $s_1, ..., s_N$ of $N$ integers.
For each test case, output a single line containing a string: the unjumbled message. **Constraints** $1 \le T \le 3$ $1 \le s_i \le L$ **Subtask 1** (8 points each): $1 \le L, N \le 20$ **Subtask 2** (8 points each): $1 \le L, N \le 1000$ **Subtask 3** (10 points each): $1 \le L, N \le 100000$ $s_1 \geq s_2 \geq \cdots \geq s_N$ **Subtask 4** (10 points each): $1 \le L, N \le 100000$ $s_1 \leq s_2 \leq \cdots \leq s_N$ **Subtask 5** (14 points each): $1 \le L, N \le 100000$
3 44 5 ireallyreallyreallyreallyreallyreallylikeyou 44 44 2 44 44 6 3 setter 6 3 6 13 8 elevenplustwo 3 13 11 8 9 6 7 2
ireallyreallyreallyreallyreallyreallylikeyuo tester twelveplusone
Hard
null
null
null
null
null
null
2014-12-18T08:34:21
2018-02-06T17:43:56
setter
```cpp #include <stdio.h> #include <math.h> #define LIM 100011 #define SLIM 1011 struct Piece { int i, length; bool back; Piece() {} Piece(int i, int length, bool back): i(i), length(length), back(back) {} int kth(int k) { return back ? i - k : i + k; } int end() { return kth(length - 1); } void reverse() { i = end(); back = !back; } Piece split(int k) { Piece piece = Piece(kth(k), length - k, back); length = k; return piece; } }; char *s = new char[LIM]; char *t = new char[LIM]; Piece pieces[SLIM]; int main() { int z; scanf("%d", &z); while (z--) { int n, q; scanf("%d%d%s", &n, &q, s); int sq = int(sqrt(n)) + 2; int l = 1; pieces[0] = Piece(0, n, false); #define flatten() do {\ int idx = 0;\ for (int I = 0; I < l; I++) {\ for (int i = 0; i < pieces[I].length; i++) {\ t[idx++] = s[pieces[I].kth(i)];\ }\ }\ char *u = s; s = t; t = u;\ pieces[0] = Piece(0, n, false);\ l = 1;\ } while (0) while (q--) { int k; scanf("%d", &k); k = n-k; int idx = 0; while (k) { if (pieces[idx].length > k) { for (int I = l-1; I > idx; I--) { pieces[I+1] = pieces[I]; } pieces[idx+1] = pieces[idx].split(k); l++; } k -= pieces[idx++].length; } for (int I = idx, J = l-1; I < J; I++, J--) { Piece temp = pieces[I]; pieces[I] = pieces[J]; pieces[J] = temp; } for (int I = idx; I < l; I++) { pieces[I].reverse(); } if (l == sq) flatten(); } flatten(); s[n] = 0; printf("%s\n", s); } } ```
not-set
2016-04-24T02:03:21
2018-02-06T17:43:56
C++
249
5,452
confidentialegassem-8
Confidential Message
null
code
Yuo received a message but it was jumbled by some confidential process.
ai
2014-12-06T18:54:29
2016-12-01T08:20:40
null
null
null
Yuo is a new student in his class. The girls in his class apparently communicate information using a confidential process to somehow jumble the message. Each jumbled message has a corresponding sequence of integers attached to it: $s_1, \ldots, s_N$. To "unjumble" the message, look at the last $s_1$ letters of the jumbled message and reverse their order to get a new jumbled message. Then, look at the last $s_2$ letters of this new message and reverse their order to get a new jumbled message and so on. After the final reversal, you should get the real unjumbled message. Carly wanted to send a super secret SMS to her classmate Rae. Late night, while watching television, she finally decided she will send the SMS to her friend. But instead of texting Rae, she accidentally texted Yuo. Her text message reads: <pre> ireallyreallyreallyreallyreallyreallylikeyou 44 44 2 44 44 From: Carly 09987765321 </pre> Unlike her mobile service provider, Carly doesn't seem to be smart. Especially when you know how she got in this position. Now, Yuo can perfectly read the sentence but he knows that girls speak in code. Thus, he can't be too sure what it means. So, he wants to unjumble the message to be certain. Can you create a program that unjumbles messages such as these for Yuo?
0.5
["c","cpp","java","python","python3","java8","cpp14"]
The first line of input contains an integer $T$, the number of test cases. Each test case consists of three lines. The first line contains two integers $L$ and $N$, where $L$ is the length of the jumbled message (and of course, also the length of the unjumbled message). The second line contains a string $J$, the jumbled message. It is guaranteed to contain exactly $L$ characters and it only consists of lowercase letters from `a` to `z`. The third line consists the sequence $s_1, ..., s_N$ of $N$ integers.
For each test case, output a single line containing a string: the unjumbled message. **Constraints** $1 \le T \le 3$ $1 \le s_i \le L$ **Subtask 1** (8 points each): $1 \le L, N \le 20$ **Subtask 2** (8 points each): $1 \le L, N \le 1000$ **Subtask 3** (10 points each): $1 \le L, N \le 100000$ $s_1 \geq s_2 \geq \cdots \geq s_N$ **Subtask 4** (10 points each): $1 \le L, N \le 100000$ $s_1 \leq s_2 \leq \cdots \leq s_N$ **Subtask 5** (14 points each): $1 \le L, N \le 100000$
3 44 5 ireallyreallyreallyreallyreallyreallylikeyou 44 44 2 44 44 6 3 setter 6 3 6 13 8 elevenplustwo 3 13 11 8 9 6 7 2
ireallyreallyreallyreallyreallyreallylikeyuo tester twelveplusone
Hard
null
null
null
null
null
null
2014-12-18T08:34:21
2018-02-06T17:43:56
tester
```cpp #include<bits/stdc++.h> using namespace std; struct { int sz, prior, lSon, rSon; bool rev; char c; } t[300001]; int newNode(char c) { static int tw = 0; tw++; t[tw].sz = 1; t[tw].prior = rand(); t[tw].c = c; return tw; } void push(int v) { if (t[v].rev) { t[v].lSon ^= t[v].rSon; t[v].rSon ^= t[v].lSon; t[v].lSon ^= t[v].rSon; t[t[v].lSon].rev ^= true; t[t[v].rSon].rev ^= true; t[v].rev = false; } } int merge(int l, int r) { if (min(l, r) == 0) return l + r; push(l); push(r); if (t[l].prior < t[r].prior) { t[l].sz += t[r].sz; t[l].rSon = merge(t[l].rSon, r); return l; } else { t[r].sz += t[l].sz; t[r].lSon = merge(l, t[r].lSon); return r; } } void split(int v, int k, int &l, int &r) { l = r = v; if (v == 0) return; push(v); if (t[t[v].lSon].sz >= k) { t[v].sz -= k; split(t[v].lSon, k, l, t[v].lSon); } else { t[v].sz = k; split(t[v].rSon, k - t[t[v].lSon].sz - 1, t[v].rSon, r); } } void dfs(int v) { if (v == 0) return; push(v); dfs(t[v].lSon); printf("%c", t[v].c); dfs(t[v].rSon); } char s[100001]; int main() { int T; scanf("%d", &T); while (T--) { int n, q; scanf("%d %d %s", &n, &q, s); int root = 0; for (int i = 0; i < n; i++) root = merge(root, newNode(s[i])); for (int i = 0; i < q; i++) { int p, l, r; scanf("%d", &p); split(root, n - p, l, r); t[r].rev ^= true; root = merge(l, r); } dfs(root); printf("\n"); } return 0; } ```
not-set
2016-04-24T02:03:21
2018-02-06T17:43:56
C++
250
5,206
waver1
Waver's Flight
Clock Tower is the official headquarters of the Mage's Association. Lord El-Melloi is a powerful magus who teaches here. Waver, an average magus who studies at Clock Tower was humiliated by his lecturer, Lord El-Melloi. In retaliation he stole an artifact belonging to his lecturer. He now needs to escape the Clock Tower without raising much suspicion. Clock Tower is a tree of N vertices. Additionally, there are E shortcut edges. Using shortcuts arouses suspicion, therefore Waver has decided that he will use shortcuts at most K times. He needs to get to an exit to leave the place. All leaf vertices except starting point are exits. Each edge, normal and shortcut, is weighted, which indicates the time taken to traverse this edge. Waver wants to exit the Clock Tower as soon as possible. He starts at the vertex 0. However, Clock Tower has lectures almost all the time. Waver is magically warped to the required lecture if he is in the Clock Tower. But if he is out of the Clock Tower's magical sphere when the lecture starts, he'll get away. Each Class runs from s[i] to e[i] at vertex v[i]. Initially, the time is 0. If Waver can escape in time t <= s[i], he won't be caught. Otherwise, he will attend the lecture i at vertex v[i]and be at v[i] after time e[i]. All lectures are given in the order they occur. It is guaranteed that no two lectures happen at the same time. Print the shortest time in which Waver can escape from the Clock Tower.
code
Given a weighted tree and some additional edges, find the shortest distances to leaves of the tree from all vertices, where you can only traverse the extra edges a limited number of times.
ai
2014-11-17T05:38:37
2019-07-02T13:59:00
null
null
null
Waver needs to get out of the Clock Tower immediately. The Clock Tower is a tree of $N$ vertices numbered $1$ through $N$. Additionally, there are $E$ shortcut edges. Using shortcuts arouses suspicion, therefore Waver has decided that he will use shortcuts at most $K$ times. He needs to get to an exit to leave the place. All leaf vertices are exit nodes. Each edge, normal and shortcut, is weighted, which indicates the time taken to traverse it. Waver wants to exit the Clock Tower as soon as possible. Print the least units of time Waver needs to reach an exit node from every vertex.
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"]
The first line contains three integers: $N$ (the number of vertices), $E$ (the number of shortcut edges), and $K$ (the number of times shortcut edges can be used). The next $N-1$ lines contain three integers, $a$, $b$, and $w$ each, indicating that vertices $a$ and $b$ are connected by a tree edge of weight $w$. $E$ lines follow, each having three integers, $a$, $b$, and $w$, such that $a$ and $b$ are connected by a shortcut edge of weight $w$. **Constraints** $1 \le N \le 10000$ $0 \le E \le 20000$ $0 \le K \le 1000$ For all edges: $1 \le w \le 1000$ There is at most one shortcut edge between any pair of vertices. There is no shortcut from a vertex to itself. All edges are bidirectional. Note that two vertices can be connected both by a tree edge and a shortcut edge.
Output must consist of $N$ lines, where the $i$<sup>$th$</sup> line has a single integer denoting the least units of time Waver needs to the exit from vertex $i$.
6 2 1 1 5 25 5 4 1 6 4 11 4 3 10 2 3 100 3 4 7 5 1 3
0 0 14 4 3 0
Hard
null
null
null
null
null
null
2014-12-19T09:13:09
2017-02-10T15:51:45
setter
#include <iostream> #include <cassert> #include <cstdio> #include <vector> #include <tuple> using namespace std; #define inc(i,a,b) for(int i=a;i<=b;++i) #define dec(i,a,b) for(int i=a;i>=b;--i) #define pb push_back #define mt make_tuple typedef long long ll; typedef tuple<int,int> ii; typedef vector<int> vi; typedef vector<ii> vii; const int maxN =1e4, maxK = 1e3, maxW = 1e3; const int maxE = 2*maxN; const int inf = 1e9; int n, e, k; vii T[maxN+1], S[maxN+1]; int D[maxN+1][maxK+1]; void input(); void solve(); void dfs1(int=0,int=1,int=-1); void dfs2(int=0,int=1,int=-1); int main() { ios::sync_with_stdio(false); cin.tie(NULL); input(); solve(); } void input() { cin >> n >> e >> k; assert(n<=maxN); assert(e<=maxE); assert(k<=maxK); inc(i,1,n-1) { int a, b, w; cin >> a >> b >> w; assert(a>=1 && a<=n); assert(b>=1 && b<=n); assert(w>=0 && w<=maxW); T[a].pb(mt(b,w)); T[b].pb(mt(a,w)); } inc(i,1,e) { int a, b, w; cin >> a >> b >> w; S[a].pb(mt(b,w)); S[b].pb(mt(a,w)); } } void solve() { inc(u,1,n) { if(T[u].size() < 2) D[u][0] = 0; else D[u][0] = inf; } dfs1(); dfs2(); inc(s,1,k) { inc(u,1,n) { D[u][s] = D[u][s-1]; for(auto x : S[u]) { int v, w; tie(v,w) = x; D[u][s] = min(D[u][s],D[v][s-1]+w); } } dfs1(s); dfs2(s); } inc(u,1,n) { cout << D[u][k] << "\n"; } } void dfs1(int s, int u, int p) { for(auto x : T[u]) { int v, w; tie(v,w) = x; if(v == p) continue; dfs1(s,v,u); D[u][s] = min(D[u][s],D[v][s]+w); } } void dfs2(int s, int u, int p) { for(auto x : T[u]) { int v, w; tie(v,w) = x; if(v == p) continue; D[v][s] = min(D[v][s],D[u][s]+w); dfs2(s,v,u); } }
not-set
2016-04-24T02:03:21
2016-04-24T02:03:21
C++
251
5,206
waver1
Waver's Flight
Clock Tower is the official headquarters of the Mage's Association. Lord El-Melloi is a powerful magus who teaches here. Waver, an average magus who studies at Clock Tower was humiliated by his lecturer, Lord El-Melloi. In retaliation he stole an artifact belonging to his lecturer. He now needs to escape the Clock Tower without raising much suspicion. Clock Tower is a tree of N vertices. Additionally, there are E shortcut edges. Using shortcuts arouses suspicion, therefore Waver has decided that he will use shortcuts at most K times. He needs to get to an exit to leave the place. All leaf vertices except starting point are exits. Each edge, normal and shortcut, is weighted, which indicates the time taken to traverse this edge. Waver wants to exit the Clock Tower as soon as possible. He starts at the vertex 0. However, Clock Tower has lectures almost all the time. Waver is magically warped to the required lecture if he is in the Clock Tower. But if he is out of the Clock Tower's magical sphere when the lecture starts, he'll get away. Each Class runs from s[i] to e[i] at vertex v[i]. Initially, the time is 0. If Waver can escape in time t <= s[i], he won't be caught. Otherwise, he will attend the lecture i at vertex v[i]and be at v[i] after time e[i]. All lectures are given in the order they occur. It is guaranteed that no two lectures happen at the same time. Print the shortest time in which Waver can escape from the Clock Tower.
code
Given a weighted tree and some additional edges, find the shortest distances to leaves of the tree from all vertices, where you can only traverse the extra edges a limited number of times.
ai
2014-11-17T05:38:37
2019-07-02T13:59:00
null
null
null
Waver needs to get out of the Clock Tower immediately. The Clock Tower is a tree of $N$ vertices numbered $1$ through $N$. Additionally, there are $E$ shortcut edges. Using shortcuts arouses suspicion, therefore Waver has decided that he will use shortcuts at most $K$ times. He needs to get to an exit to leave the place. All leaf vertices are exit nodes. Each edge, normal and shortcut, is weighted, which indicates the time taken to traverse it. Waver wants to exit the Clock Tower as soon as possible. Print the least units of time Waver needs to reach an exit node from every vertex.
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"]
The first line contains three integers: $N$ (the number of vertices), $E$ (the number of shortcut edges), and $K$ (the number of times shortcut edges can be used). The next $N-1$ lines contain three integers, $a$, $b$, and $w$ each, indicating that vertices $a$ and $b$ are connected by a tree edge of weight $w$. $E$ lines follow, each having three integers, $a$, $b$, and $w$, such that $a$ and $b$ are connected by a shortcut edge of weight $w$. **Constraints** $1 \le N \le 10000$ $0 \le E \le 20000$ $0 \le K \le 1000$ For all edges: $1 \le w \le 1000$ There is at most one shortcut edge between any pair of vertices. There is no shortcut from a vertex to itself. All edges are bidirectional. Note that two vertices can be connected both by a tree edge and a shortcut edge.
Output must consist of $N$ lines, where the $i$<sup>$th$</sup> line has a single integer denoting the least units of time Waver needs to the exit from vertex $i$.
6 2 1 1 5 25 5 4 1 6 4 11 4 3 10 2 3 100 3 4 7 5 1 3
0 0 14 4 3 0
Hard
null
null
null
null
null
null
2014-12-19T09:13:09
2017-02-10T15:51:45
tester
/* * Bidhan Roy * University of Dhaka */ using namespace std; #include <bits/stdc++.h> #define rep(i,n) for(auto 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<<30) #define ins insert #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<int,int> pii; typedef vector<pii> vpii; int getInteger( int lo, int hi, st var = "" ) { int ret; cin >> ret; if( lo <= ret && ret <= hi ) return ret; cout << var << " should be between [" << lo <<"," << hi << "]" << endl; throw; } #define mx 10010 vpii edge[mx]; vector< tuple< int, int, int > > extra; int dp[mx]; void dfs( int u, int par = -1 ) { //if( par != -1 ) cout << par << " " << u << endl; bool ent = false; for( auto &x: edge[u] ) { int v = x.xx; int w = x.yy; if( v == par ) continue; ent = true; dfs( v, u ); dp[u] = min( dp[u], dp[v] + w ); } //cout << u << " = " << ent << endl; if( !ent || ( par == -1 && sz(edge[u]) == 1 ) ) dp[u] = 0; } void dfs2( int u, int par = -1 ) { bool ent = false; for(auto &x: edge[u]) { int v = x.xx; int w = x.yy; if(v == par) continue; ent = true; dp[v] = min( dp[v], dp[u] + w ); dfs2( v, u ); } if( !ent ) dp[u] = 0; } int temp[mx], n; void relax( ) { fill( temp, temp+n, 1<<29 ); rep(i,n) temp[i] = dp[i]; for( auto &x : extra ) { int u = get<0>(x); int v = get<1>(x); int w = get<2>(x); temp[u] = min( temp[u], dp[v] + w ); temp[v] = min( temp[v], dp[u] + w ); } rep(i,n) dp[i] = temp[i]; } int main() { //read("in.txt"); ios_base::sync_with_stdio(0); int e, k; n = getInteger(1,10000,"n"); e = getInteger(0,20000,"e"); k = getInteger(0,1000,"k"); rep( i, n-1 ) { int u, v, w; u = getInteger(1,n,"u"); v = getInteger(1,n,"v"); w = getInteger(1,1000,"w"); u--, v--; edge[u].pb( {v,w} ); edge[v].pb( {u,w} ); } while( e-- ){ int u, v, w; u = getInteger(1,n,"u"); v = getInteger(1,n,"v"); w = getInteger(1,1000,"w"); u--, v--; extra.pb( tuple<int,int,int>( u, v, w) ); } fill( dp, dp+n, 1<<29 ); dfs(0); dfs2(0); while( k-- ) { relax(); dfs(0); dfs2(0); } rep(i,n) cout << dp[i] << endl; return 0; }
not-set
2016-04-24T02:03:21
2016-04-24T02:03:21
C++
252
5,617
contiguous-subsequences
Contiguous subsequences
null
code
null
ai
2014-12-19T19:33:59
2016-09-09T10:02:13
null
null
null
Yash got a sequence of n positive integers ! He likes contiguous subsequences whose sum(mod)p = 0. He asks you to write a program to count them for him.
0.5
["c","cpp","java","cpp14"]
The first line contains T, the number of testcases. T testcases follow. Each testcase consists of 2 lines. The first line contains n and p separated by a single space. And the second line contains n space separated integers.
For each test case, output the number of contiguous subsequenences whose sum(mod)p = 0 in a newline. Constraints 1 ≤ T ≤ 20 1 ≤ n ≤ 10^6 1 ≤ k ≤ 100 1 ≤ a[i] ≤ 10^4
2 4 3 1 2 3 4 5 2 1 2 1 2 1
4 6
Hard
null
null
null
null
null
null
2014-12-19T19:43:55
2017-07-20T10:40:47
setter
<pre><p> #include &lt;bits/stdc++.h> </p> using namespace std; typedef long long LL; int main(){ LL test,n,k,x; cin >> test; while(test --) { cin >> n >> k; LL sum[n+3],cnt[k+3]; sum[0] = 0; memset(cnt, 0, sizeof cnt); cnt[0] = 1; for(int i = 1; i &lt;= n; i ++) { cin >> x; sum[i] = (sum[i-1] + x)%k; cnt[ sum[i] ] ++; } LL res = 0; for(int r = 0; r < k; r ++) res += (cnt[r]*(cnt[r]-1)/2); cout << res << endl; } }
not-set
2016-04-24T02:03:22
2016-04-24T02:03:22
C++
253
5,617
contiguous-subsequences
Contiguous subsequences
null
code
null
ai
2014-12-19T19:33:59
2016-09-09T10:02:13
null
null
null
Yash got a sequence of n positive integers ! He likes contiguous subsequences whose sum(mod)p = 0. He asks you to write a program to count them for him.
0.5
["c","cpp","java","cpp14"]
The first line contains T, the number of testcases. T testcases follow. Each testcase consists of 2 lines. The first line contains n and p separated by a single space. And the second line contains n space separated integers.
For each test case, output the number of contiguous subsequenences whose sum(mod)p = 0 in a newline. Constraints 1 ≤ T ≤ 20 1 ≤ n ≤ 10^6 1 ≤ k ≤ 100 1 ≤ a[i] ≤ 10^4
2 4 3 1 2 3 4 5 2 1 2 1 2 1
4 6
Hard
null
null
null
null
null
null
2014-12-19T19:43:55
2017-07-20T10:40:47
tester
<pre><p> #include &lt;bits/stdc++.h> </p> using namespace std; int main(){ long long t; cin>>t; while(t--) { long long int n,k,i,j; cin>>n>>k; long long int x,sum[n+3],cnt[k+3]; sum[0]=0; memset(cnt,0,sizeof(cnt)); cnt[0]=1; for(i=1;i&lt;=n;i++) { cin>>x; sum[i]=(sum[i-1]+x)%k; cnt[sum[i]]++; } long long int res=0; for(i=0;i&lt;k;i++) res+=(cnt[i]*(cnt[i]-1))/2; printf("%lld\n",res); } return 0; }
not-set
2016-04-24T02:03:22
2016-04-24T02:03:22
C++
254
5,595
dijkstrashortreach
Dijkstra: Shortest Reach 2
null
code
Learn to use Dijkstra's shortest path algorithm !
ai
2014-12-19T07:54:20
2022-08-31T08:14:24
# # Complete the 'shortestReach' function below. # # The function is expected to return an INTEGER_ARRAY. # The function accepts following parameters: # 1. INTEGER n # 2. 2D_INTEGER_ARRAY edges # 3. INTEGER s # def shortestReach(n, edges, 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]) m = int(first_multiple_input[1]) edges = [] for _ in range(m): edges.append(list(map(int, input().rstrip().split()))) s = int(input().strip()) result = shortestReach(n, edges, s) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
Given an undirected graph and a starting node, determine the lengths of the shortest paths from the starting node to all other nodes in the graph. If a node is unreachable, its distance is -1. Nodes will be numbered consecutively from $1$ to $n$, and edges will have varying distances or lengths. For example, consider the following graph of 5 nodes: ``` Begin End Weight 1 2 5 2 3 6 3 4 2 1 3 15 ``` [##]: "![image](https://s3.amazonaws.com/hr-assets/0/1523465555-dcd300c21d-drawing.jpg)" ![image](https://s3.amazonaws.com/hr-assets/0/1535120384-c96f8f586f-djikstraexample.png) Starting at node $1$, the shortest path to $2$ is direct and distance $5$. Going from $1$ to $3$, there are two paths: $1\rightarrow2\rightarrow3$ at a distance of $5+6=11$ or $1\rightarrow3$ at a distance of $15$. Choose the shortest path, $11$. From $1$ to $4$, choose the shortest path through $3$ and extend it: $1\rightarrow2\rightarrow3\rightarrow4$ for a distance of $11+2=13$ There is no route to node $5$, so the distance is $-1$. The distances to all nodes in increasing node order, omitting the starting node, are `5 11 13 -1`. **Function Description** Complete the *shortestReach* function in the editor below. It should return an array of integers that represent the shortest distance to each node from the start node in ascending order of node number. shortestReach has the following parameter(s): - *n*: the number of nodes in the graph - *edges*: a 2D array of integers where each $edges[i]$ consists of three integers that represent the start and end nodes of an edge, followed by its length - *s*: the start node number
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 $t$, the number of test cases. Each test case is as follows: - The first line contains two space-separated integers $n$ and $m$, the number of nodes and edges in the graph. - Each of the next $m$ lines contains three space-separated integers $x$, $y$, and $r$, the beginning and ending nodes of an edge, and the length of the edge. - The last line of each test case has an integer $s$, denoting the starting position.
For each of the $t$ test cases, print a single line consisting $n-1$ space separated integers denoting the shortest distance to the $n-1$ nodes from starting position $s$ in increasing order of their labels, excluding $s$. For unreachable nodes, print $-1$.
1 4 4 1 2 24 1 4 20 3 1 3 4 3 12 1
24 3 15
Hard
null
null
null
null
null
null
2014-12-21T08:52:49
2018-04-11T16:09:48
setter
###C++ ```cpp #define INF 99999999 #define pb push_back #define mp make_pair using namespace std; vector<pair<'int','int'> >adj[10009]; vector<int> dijkstra(vector<int>d,int s,int n) { d.clear(); d.resize(n+1); for(int i=0;i<=n;i++) d[i]=INF; set<pair<int,int> >q; q.clear(); bool vis[n+2]; memset(vis,false,sizeof(vis)); vis[s]=true; d[s]=0; q.insert(mp(0,s)); while(!q.empty()) { pair<int,int> top = *q.begin(); q.erase(q.begin()); int u=top.second; vector<pair<int,int> >::iterator it; for(it=adj[u].begin();it!=adj[u].end();it++) { int v=it->second; int cost=it->first; if(d[v]>d[u]+cost) { if(d[v]!=INF) { q.erase(q.find(mp(d[v],v))); } d[v]=d[u]+cost; q.insert(mp(d[v],v)); } } } return d; } int main() { int T,r,x,y,n,m,i,s,d; cin>>T; while(T--) { cin>>n>>m; for(i=0;i<=n+9;i++) adj[i].clear(); vector<int>d1; d1.resize(n+1); for(i=0;i<m;i++) { cin>>x>>y>>r; adj[x].pb(mp(r,y)); adj[y].pb(mp(r,x)); } cin>>s; d1=dijkstra(d1,s,n); for(i=1;i<=n;i++) { if(i!=s) { if(d1[i]!=INF) cout<<d1[i]<<" "; else cout<<"-1 "; } } cout<<endl; } return 0; } ```
not-set
2016-04-24T02:03:22
2017-05-25T10:14:52
C++
255
5,643
wet-shark-and-kth-largest-number
Kth Number
null
code
null
ai
2014-12-23T04:00:41
2019-07-02T13:59:23
null
null
null
You are given an array of $N$ positive integers, $A_1, A_2, \ldots, A_n$. You have to answer $Q$ queries. Each query consists of two integers $L$ and $K$. For each query, you have to consider all the elements of array greater than or equal to $L$, in _original order of occurrence_ in array $A$ and then find the $K^{th}$ element from the selected elements. It is guaranteed that the $K^{th}$ number will exist.
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"]
The first line contains two integers $N$ and $Q$. The next line contains $N$ space separated integers, representing the array, $A_1,\ A_2,\ \ldots,\ A_n$. Each of the next $Q$ lines contain two space separated integers $L$ and $K$. **Constraints**: $1\le N \le 10^5$ $1 \le Q \le 10^5$ $1 \le A_i \le 10^5$ $1 \le L \le 10^5$ $1 \le K \le 10^5$ **Note on TL:** C/cpp 1sec, Java 3sec
Output $Q$ lines, the answer for each query.
10 4 1 9 2 8 3 7 4 6 5 10 4 4 3 2 1 6 8 1
4 8 7 9
Hard
null
null
null
null
null
null
2014-12-23T04:01:38
2016-12-03T15:01:31
setter
#include <bits/stdc++.h> using namespace std; vector <int> indices[100005]; int arr[100005]; struct node { node * first; node * second; int count; node (node * a, node * b, int c){first=a; second=b; count=c;} }; node * root = new node (NULL, NULL, 0); node * x[100005]; node * insert (int start, int end, node * r, int num) { if (start<=num && end>=num) { if (r==NULL) r=new node (NULL, NULL, 0); if (start==end) { return new node (r->first, r->second, r->count+1); } node * n=insert(start, (start+end)/2, r->first, num); node * m=insert((start+end)/2+1, end, r->second, num); int z= (n==NULL)?0:n->count; int zz=(m==NULL)?0:m->count; return new node (n, m, z+zz); } return r; } int query (int start, int end, node * a, int kth) { if (start==end) return start; int z=(a->first==NULL)?0:a->first->count; if (z>=kth) { return query(start, (start+end)/2, a->first, kth); } else return query((start+end)/2+1, end, a->second, kth-z); } int main() { int a,b; cin >> a >> b; for (int g=1; g<=a; g++) { int c; cin >> c; arr[g]=c; indices[c].push_back(g); } x[100001]=root; for (int g=100000; g>=1; g--) { x[g]=x[g+1]; for (int y=0; y<indices[g].size(); y++) { x[g]=insert(1, 100000, x[g], indices[g][y]); } } for (int g=0; g<b; g++) { int above, kth; cin >> above >> kth; cout << arr[query(1, 100000, x[above], kth)]<< '\n'; } return 0; }
not-set
2016-04-24T02:03:22
2016-04-24T02:03:22
C++
256
5,574
k-repeated-1s
K repeated 1s
null
code
null
ai
2014-12-16T17:47:44
2016-09-09T10:01:44
null
null
null
One day Sanchit decided to write all numbers starting from 1 in binary format. The list goes like this 1,10,11,100,... and so on. Now he gets bored of this list and decides to remove all the numbers having atleast k consecutive ones and prepare a new list. He then thought if a number n is given to him can he find the nth member of the new list. After trying for some time he comes to you for help. Can you help him by writing a program for him that coud do the specified task. **Constraints** 2<=K<=10 1<=T<=1000 1<=n<=10<sup>15</sup>
0.5
["c","cpp","java","csharp","ruby","python","perl","pascal","python3","objectivec","cpp14"]
First line of each input is T and k separated by spaces where T is number of test cases and k is explained above. T lines folow. Each line contains one number n.
You have to output n<sup>th</sup> binary number for each case. Each case must be in a new line.
5 2 1 2 3 4 5
1 10 100 101 1000
Hard
null
null
null
null
null
null
2014-12-26T13:25:55
2017-01-08T09:31:26
setter
#include<stdio.h> int main() { int t,k,p,l; long long int n,i,j; long long int a[2001],ans[2001]; scanf("%d %d",&t,&k); p=0; l=1; while(p<k) { a[p]=l; l*=2; p++; } for(i=k;i<2000;i++) { p=1; a[i]=0; while(p<=k) { a[i]+=a[i-p]; p++; } if(a[i]>(long long)1000000000000000) break; } while(t--) { scanf("%lld",&n); for(i=0;;i++) { if(a[i]>n) break; } j=0; while(i>0) { ans[j]=n/a[i-1]; n=n%a[i-1]; j++; i--; } for(i=0;i<j;i++) printf("%lld",ans[i]); printf("\n"); } return 0; }
not-set
2016-04-24T02:03:23
2016-04-24T02:03:23
C++
257
5,692
detective-and-santa
Detective and Santa
null
code
null
ai
2014-12-26T16:37:56
2016-09-09T10:03:10
null
null
null
Its Chritmas ! You and your friend are waiting for Santa. But he hasnt come yet. You are getting paranoid of his archenemy. One of your friend mentioned that the everyone in the town has been facing weird problems with their computer, whom thet call 'The Monster', recently.On Chritmas afternoon, you received a note from one of his archenemy, saying that he has infected everyones computer 'The Monster' with a virus and if we solve them he will release our Santa. Moreover, the note had the number *P* printed on it. After doing some calculations, you figured out that the 'password' to remove the virus is the largest 'Best' Number having *P* digits. A 'Best' Number has - 3 or 5 or both in the number. No other digit is allowed. Number of times 3 appears mod 5 is 0. Number of times 5 appears mod 3 is 0. Meanwhile, the counter to destruction of 'The Monster' is running very fast. Can you save 'The Monster' and our Santa, and find the 'password' before me?
0.5
["c","cpp","java","cpp14"]
The 1st line contain an integer T, the number of test cases.Followed by T lines, each having an integer P which is number of digits.
Largest Best number having P digits of password. If no such number exists, then print '-1' Constraints 1<=T<=20 1<=P<=100000
3 1 8 15
-1 55533333 555555555555555
Hard
null
null
null
null
null
null
2014-12-26T16:39:11
2016-05-12T23:57:03
setter
<pre> <p>#include &ltbits/stdc++.h></p> using namespace std; int main() { int n,test,k,kstart; cin>>test; while(test--) { cin>>n; string ks; for(int j=n ; j&gt;=0 ; i--) { if(j%3==0 && (n-j)%5==0) { ks=""; for(int k=0 ; k&lt;j ; k++) ks+='5';<br> for(int k=0 ; k&lt;n-j ; k++) ks+='3'; break; } } if(ks == "") cout&lt;&lt;"-1"&lt;&lt;endl; else cout&lt;&lt;ks&lt;&lt;endl; } return 0; } </pre>
not-set
2016-04-24T02:03:23
2016-04-24T02:03:23
C++
258
5,698
search-numbers
Search Numbers
null
code
null
ai
2014-12-26T20:58:57
2016-09-09T10:03:12
null
null
null
Mohit has just learnt multiplying two integers. Such that **A(multiply)B=C**. To make the problem hard he will select *A* in the range *1 to P* and *B* in the range *1 to Q*. Help him to find the number of methods.
0.5
["c","cpp","java","cpp14"]
First line of the input is the number of test cases *T*. It is followed by T lines. Each line has three space separated integers, the numbers *C*, *P* and *Q*.
For each test case output a single integer, the number of ways. **Constraints** 1 <= T <= 50 1 <= C <= 10^12 1 <= P <= 10^12 1 <= Q <= 10^12
4 4 7 9 5 2 10 5 5 6 2 8 1
3 1 2 1
Hard
null
null
null
null
null
null
2014-12-26T21:02:42
2016-05-12T23:57:02
setter
<pre> <p>#include&lt;stdio.h></p> <p>#include&lt;math.h></p> void solve(unsigned long long ,unsigned long long ,unsigned long long); int main() { unsigned long long N,M,Z; int test_case; scanf("%d",&test_case); while(test_case--) { scanf("%llu",&Z); scanf("%llu",&N); scanf("%llu",&M); solve(N,M,Z); } return 0; } void solve(unsigned long long N,unsigned long long M,unsigned long long Z) { unsigned long long number2,no_of_ways=0; int sqrt_val=0,number1; sqrt_val=sqrt(Z); for(number1=1;number1&lt;=sqrt_val;number1++) { number2=Z/number1; if((number2*number1)==Z) { if(number2&lt;=M) { no_of_ways++; } if(number2&lt;=N && number1!=number2) { no_of_ways++; } } } printf("%llu\n",no_of_ways); } </pre>
not-set
2016-04-24T02:03:23
2016-04-24T02:03:23
C++
259
5,697
floyd-city-of-blinding-lights
Floyd : City of Blinding Lights
null
code
Learn to use Floyd Warshall's algorithm !
ai
2014-12-26T20:38:53
2022-08-31T08:14:27
#!/bin/python3 import math import os import random import re import sys
if __name__ == '__main__': road_nodes, road_edges = map(int, input().rstrip().split()) road_from = [0] * road_edges road_to = [0] * road_edges road_weight = [0] * road_edges for i in range(road_edges): road_from[i], road_to[i], road_weight[i] = map(int, input().rstrip().split()) q = int(input().strip()) for q_itr in range(q): first_multiple_input = input().rstrip().split() x = int(first_multiple_input[0]) y = int(first_multiple_input[1])
Given a directed weighted graph where weight indicates distance, for each query, determine the length of the shortest path between nodes. There may be many queries, so efficiency counts. For example, your graph consists of $5$ nodes as in the following: ![image](https://s3.amazonaws.com/hr-assets/0/1525461069-142e0d306a-blindingLightsExample.png) A few queries are from node $4$ to node $3$, node $2$ to node $5$, and node $5$ to node $3$. <br> 1. There are two paths from $4$ to $3$: + $4 \Rightarrow 1 \Rightarrow 2 \Rightarrow 3$ at a distance of $4 + 5 + 1 = 10$ + $4 \Rightarrow 1 \Rightarrow 5 \Rightarrow 3$ at a distance of $4 + 3 + 2 = 9$ In this case we choose path $2$. 2. There is no path from $2$ to $5$, so we return $-1$. 3. There is one path from $5$ to $3$: + $5 \Rightarrow 3$ at a distance of $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"]
The first line has two integers $n$ and $m$, the number of nodes and the number of edges in the graph. Each of the next $m$ lines contains three space-separated integers $u$ $v$ and $w$, the two nodes between which the _directed_ edge $u \Rightarrow v$ exists, and $w$, the length of the edge. The next line contains a single integer $q$, the number of queries. Each of the next $q$ lines contains two space-separated integers $a$ and $b$, denoting the start and end nodes for traversal.
Print $q$ lines, each containing a single integer specifying the shortest distance for the query. If the destination node is not reachable, return $-1$.
<pre> STDIN Function ----- -------- 4 5 n = 4, m = 5 1 2 5 u = 1, v = 2, w = 5 1 4 24 u = 1, v =4, w = 24 ... 2 4 6 3 4 4 3 2 7 3 q = 3 1 2 query 0: from 1 to 2 3 1 query 1: from 3 to 1 1 4 query 2: from 1 to 4 </pre>
5 -1 11
Hard
null
null
null
null
null
null
2014-12-28T09:15:27
2018-05-04T18:43:52
setter
###C++ ```cpp '#'define INF 9999999 using namespace std; int main() { int n,m,i,x,y,r,a,b,j,k,q; cin>>n>>m; int adj[n][n]; for(i=0;i<n;i++) { for(j=0;j<n;j++) { adj[i][j]=INF; } } for(i=0;i<n;i++) adj[i][i]=0; int floyd[n][n]; for(i=0;i<m;i++) { cin>>x>>y>>r; adj[x-1][y-1]=r; } for(i=0;i<n;i++) { for(j=0;j<n;j++) { floyd[i][j]=adj[i][j]; } } for(k=0;k<n;k++) { for(i=0;i<n;i++) { for(j=0;j<n;j++) { floyd[i][j]=min(floyd[i][j],floyd[i][k]+floyd[k][j]); } } } cin>>q; while(q--) { cin>>a>>b; int ans=floyd[a-1][b-1]; if(ans!=INF) cout<<ans<<endl; else cout<<"-1\n"; } return 0; } ```
not-set
2016-04-24T02:03:24
2016-07-23T13:53:58
C++
260
5,715
fibonacci-sum
Fibonacci Sum
null
code
null
ai
2015-01-01T17:41:06
2016-09-09T10:03:19
null
null
null
The series defined below is called fibonacci series. 1,1,2,3,5,8 Recursively it is defined as follow:- Fib[1]=1 Fib[2]=1 Fib[i]=Fib[i-1]+Fib[i-2] ,i>2 Let us define a function Sum(N) Sum(N)=Fib[1]+Fib[2]+..Fib[N] You are given the value of N, you need to out Sum(N)%1000000007
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"]
The only line of the input will contain N. 1<=N<=10^16
For each N print Sum(N)%1000000007 i.e the sum of the series(Fib[1]+Fib[2]+..Fib[N])%1000000007.
2
2
Hard
null
null
null
null
null
null
2015-01-01T17:42:25
2016-05-12T23:56:59
setter
#include <iostream> #include <cstdio> using namespace std; #define mod 1000000007 #define rep(i,a,N) for(int i=a;i<N;++i) typedef long long ll; void multiply(ll F[2][2], ll M[2][2]){ ll x = (F[0][0]*M[0][0])%mod + (F[0][1]*M[1][0])%mod; ll y = (F[0][0]*M[0][1])%mod + (F[0][1]*M[1][1])%mod; ll z = (F[1][0]*M[0][0])%mod + (F[1][1]*M[1][0])%mod; ll w = (F[1][0]*M[0][1])%mod + (F[1][1]*M[1][1])%mod; F[0][0] = x%mod; F[0][1] = y%mod; F[1][0] = z%mod; F[1][1] = w%mod; } void power(ll F[2][2], ll n){ if( n == 0 || n == 1) return; ll M[2][2] = {{1,1},{1,0}}; power(F, n/2); multiply(F, F); if (n%2 != 0) multiply(F, M); } ll fib(ll n){ ll F[2][2] = {{1,1},{1,0}}; if (n == 0) return 0; if(n==1 || n==2) return 1; power(F, n-1); return F[0][0]; } int main() { int T; ll N; scanf("%lld",&N); printf("%lld\n", ((fib(N+2)+mod)%mod)); }
not-set
2016-04-24T02:03:24
2016-04-24T02:03:24
C++
261
5,717
toposut
Topological Sort : Uniqueness Test
null
code
Perform the uniqueness test !
ai
2015-01-01T21:43:48
2016-09-09T10:03:20
null
null
null
Given a directed, unweighted and acyclic graph, it is required to test the graph, whether in it, an ordering of all the vertices of the graph exists, such that : * If there is a path from u to v, then v appears after u in the ordering. is the __only one__ that exists in the graph or __not__. Print in a single line `YES` or `NO`, according to the answer. __Note:__ In the case when no such ordering exists, "NO" is to be printed.
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"]
First line has two integers $N$, denoting the number of nodes in the graph and $M$, denoting the number of edges in the graph. The next $M$ lines each consist of three space separated integers $x$ $y$, where $x$ and $y$ denote the two nodes between which the directed edge $(x->y)$ exists. **Constraints** $2 \le N \le 2500$ $1 \le x,y \le N$ __ If there are multiple instances of the same edge between two given nodes, it is to be considered as a single edge only.__
Print a single line consisting either `YES` or `NO` according to the question.
6 6 5 1 6 1 6 3 3 4 4 2 5 2
NO
Hard
null
null
null
null
null
null
2015-01-02T21:48:03
2016-05-12T23:56:58
setter
'#'define pb push_back using namespace std; vector<'int'>adj[9000]; bool mat[9000][9000]; void dfs(int s,bool vis[],stack<'int'> &stk) { vis[s]=true; for(int i=0;i<adj[s].size();i++) { int v=adj[s][i]; if(!vis[v]) { dfs(v,vis,stk); } } stk.push(s); } bool check(int n,int topo[]) { for(int i=0;i<n-1;i++) { int u=topo[i]; int v=topo[i+1]; if(!mat[u][v]) return false; } return true; } int main() { int n,m,i,j,x,y; cin>>n>>m; for(i=0;i<=n+1;i++) for(j=0;j<=n+1;j++) mat[i][j]=false; for(i=0;i<m;i++) { cin>>x>>y; adj[x].pb(y); mat[x][y]=true; } stack<int>stk; bool vis[n+9]; for(i=0;i<=n+1;i++) vis[i]=false; for(i=1;i<=n;i++) { if(!vis[i]) dfs(i,vis,stk); } int topo[n+1],idx=0; while(!stk.empty()) { topo[idx++]=stk.top(); stk.pop(); } bool ans=check(n,topo); if(ans) cout<<"YES\n"; else cout<<"NO\n"; return 0; }
not-set
2016-04-24T02:03:24
2016-04-24T02:03:24
C++
262
5,734
knapres
Knapsack (Greedy) : Greedy Results
null
code
Exactly how greedy are you !
ai
2015-01-03T21:07:42
2016-09-09T10:03:26
null
null
null
Take a look at the following video to understand greedy knapsack algorithm. * The Knapsack problem is a pretty famous combinatorial problem which states the following * Given a set of items, each with a mass and a value, find the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. * The problem is optimally solved using Dynamic Programming when a 0-1 approach is used (where an item is either fully taken or fully rejected) * However, a greedy approximation exists, where the items are chosen according to ratio of value to mass. * For a 0-1 approach, the greedy solution fails to produce an optimal answer as compared to a DP approach, however , the Fractional Knapsack problem, has an optimal greedy solution. [(iframe youtube ZFK9_jgCBrE 560 315)] __Online Resources:__ [Link 1](http://oucsace.cs.ohiou.edu/~razvan/courses/cs4040/lecture15.pdf) [Link 2](http://www.cs.upc.edu/~mjserna/docencia/algofib/P06/tr111.pdf) __Algorithm:__ * Item i has benefit bi and weighs wi. * So its value (per pound) is vi=bi/wi. * Make the greedy choice and pick the most valuable item and take all of it or as much as the knapsack can hold. * Pick the second most valuable and do the same. * This clearly is optimal since it never makes sense to leave over some valuable item to take some less valuable item. ** The algorithm stops when the knapsack acannot hold anymore items. The implementation oriented algorithm is as : GreedyKnapsack(S,W) { Input: Set S of items i with weight wi and benefit bi all positive. Knapsack capacity W>0. Output: Amount xi of i that maximizes the total benefit without exceeding the capacity. for each i in S do xi ← 0 { for items not chosen in next phase } vi ← bi/wi { the value of item i "per pound" } w ← W { remaining capacity in knapsack } while w > 0 do remove from S an item of maximal value { greedy choice } xi ← min(wi,w) { can't carry more than w more } w ← w-xi } __Problem:__ Given a set of __N__ items, each with a weight Wi and a value Vi, find the number of each item to include in a collection so that the total weight is less than or equal to a given limit __X__ and the total value is as large as possible. It is required to find the results of two greedy strategies (defined above), as follows : * Where the choice on items is 0-1 (Integer), either taken or rejected. * Where the choice on items can be fractional (an item can be partially chosen) Print the results of the given knapsack problem, using the above two strategies, in the same order as above.
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"]
First line consists of a single integer __T__, denoting the number of test cases. First line of each test case, contains a single integer __N__, denoting the number of items. The next two lines containing __N__ space separated integes each, where the first line deontes the weights of N items, and the second line denotes the value associated with each of the __N__ items. The last line of each test case, denotes the capacity __X__ of the knapsack. __Constraints:__ 1<= T <=10 1<= N <=1000 1<= X <=1000 The weights and values will easily fit in a 32-bit integer.
For each test case, print a single lines containing two integer, first, an integer deonting the result of first strategy and second, an integer (integeral part of the floating point value), denoting answer to the second strategy.
1 5 12 1 2 1 4 4 2 2 1 10 15
15 17
Hard
null
null
null
null
null
null
2015-01-03T23:16:05
2016-05-12T23:56:57
setter
#include <iostream> #include<cstdio> #include<cstdlib> #include<algorithm> using namespace std; struct obj { int wt,v; }; bool cmp(struct obj a,struct obj b) { double ratio1 = a.v*1.0 / a.wt; double ratio2 = b.v*1.0 / b.wt; if(ratio1 > ratio2) return 1; else return 0; } int main() { //freopen("inp1.txt","r",stdin); //freopen("op1.txt","w",stdout); int t,n,X,i; cin>>t; while(t--) { cin>>n; obj xx[n]; for(i=0;i<n;i++) cin>>xx[i].wt; for(i=0;i<n;i++) cin>>xx[i].v; cin>>X; sort(xx,xx+n,cmp); int Y=X; int ans1=0; for(i=0;i<n;i++) { if(Y>=xx[i].wt) { ans1+=xx[i].v; Y-=xx[i].wt; } else break; } //cout<<Y<<endl; double ans2 = 0.0; int pw = 0; for(i=0;i<n;i++) { if(pw + xx[i].wt< X) { pw += xx[i].wt; ans2+=xx[i].v; } else { int rem=X-pw; ans2+= xx[i].v*rem*1.0/xx[i].wt; break; } } cout<<ans1<<" "<<(int)ans2<<endl; } return 0; }
not-set
2016-04-24T02:03:24
2016-04-24T02:03:24
C++
263
5,827
compare-pairs
Compare pairs
null
code
null
ai
2015-01-09T11:49:39
2016-09-09T10:03:57
null
null
null
Count the number of Comparison in an array. A comparsion in an array is a pair of *indices(x,y)* such that **a[x] > a[y] and x < y**. In this problem you are given 2 arrays C and D and you have to return number of such pairs such that **c[x] > d[y] and x < y**.
0.4
["c","cpp","java","cpp14"]
First line contains n denoting the total number of elements.The next line contains n space separated integers of array C.This line is again followed by n space separated integers of array D.
Print the total number of pairs according to comparison. **Constraints:** 1<=n<=200000 1<=C[i]<=10<sup>6</sup> 1<=D[i]<=10<sup>6</sup>
3 3 4 5 1 2 3
2
Hard
null
null
null
null
null
null
2015-01-09T12:32:04
2016-05-12T23:56:51
setter
<p>#include&lt;bits/stdc++.h></p> using namespace std; long long tree[200005]; int A[200005]; int B[200005]; long long query(int idx) { long long res = 0; while ( idx > 0 ) { res += tree[idx]; idx -= (idx & (-idx)); } return res; } void update(int idx) { while ( idx <= 100001 ) { tree[idx] += 1; idx += (idx &(-idx)); } return; } int main() { int t=1,n; while ( t-- ){ cin >> n; for ( int i = 0; i < n; i++ ) cin >> A[i]; for ( int i = 0; i < n; i++ ) cin >> B[i]; memset(tree, 0, sizeof(tree)); long long ans = 0; for ( int i = n-1; i >= 0; i-- ) { ans += query(A[i]-1); update(B[i]); } cout << ans << endl; } return 0; }
not-set
2016-04-24T02:03:25
2016-04-24T02:03:25
C++
264
5,681
zeroshark-and-magician
ZeroShark and Magician
null
code
ZeroShark meets magician!?!
ai
2014-12-25T20:21:37
2019-07-02T13:59:26
null
null
null
ZeroShark has $T$ numbers, $n_1, ..., n_T$, that he wants a magic trick to be performed on. Wet Shark will take each of these numbers, and do magic tricks on them. Wet Shark will perform the following magic trick: For an integer $x$, Wet Shark will replace this integer with a new integer $x_1$, randomly chosen from $0$ to $x-1$, inclusive. He will then replace $x_1$ with an integer $x_2$, chosen from $0$ to $x_1-1$, inclusive. He will repeat this process until he reaches an integer $x_i = 0$. Calculate the expected value of $i$ for each number $n_i$. For example, if $x=3$, the replacement sequences can go as follows: $x = 3, x_1 = 2, x_2 = 1, x_3 = 0$ $x = 3, x_1 = 2, x_2 = 0$ $x = 3, x_1 = 1, x_2 = 0$ $x = 3, x_1 = 0$ The probability of picking the first replacement sequence is $\frac{1}{3} \cdot \frac{1}{2} = \frac{1}{6}$, because the probability that $x_1 = 2$ is equal to $\frac{1}{3}$ and the probability that $x_2 = 1$ is $\frac{1}{2}$, after $x_1 = 2$. The probability of the 2nd, 3rd, and 4th sequences can be similarly calculated as $\frac{1}{6}, \frac{1}{3},$ and $\frac{1}{3}$, respectively. The expected value is then $3 * 1/6 + 2 * 1/6 + 2 * 1/3 + 1 * 1/3 = \frac{11}{6}$.
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"]
The first line contains an integer $T (1 \le T \le 100)$, representing the number of integers ZeroShark wants a magic trick to be performed on. The next $T$ lines of the input contain integers $1 \le n_1, ..., n_T \le 3 \cdot 10^5$, representing the integers Wet Shark wants magic tricks performed on.
Output $T$ lines, each containing the expected value of $i$ for each starting value $x = n_i$. Your answers will be considered correct if their absolute or relative error does not exceed $10^{-5}$.
2 2 3
1.5 1.8333333333333333
Hard
null
null
null
null
null
null
2015-01-10T04:04:15
2018-08-28T12:00:13
setter
tcs = int(input()) tc = [int(input()) for _ in range(tcs)] n = max(tc) dp = [0] * (n + 1) x = 0 sumx = 0 for i in range(1, n+1): x = 1/i * sumx + 1 sumx += x dp[i] = x for i in tc: print(dp[i])
not-set
2016-04-24T02:03:25
2016-04-24T02:03:25
Unknown
265
5,809
mcmdp
Matrix Chain Multiplication (DP) : Just Short Of Optimal
null
code
Learn the optimal matrix chain multiplication using DP !
ai
2015-01-08T08:56:26
2016-09-09T10:03:51
null
null
null
Given a sequence of __N__ matrices A[i], i=1 to N+1, multiply them so that the product of the matrices, in order, is unambiguous and needs __Just Short of Optimal__ number of scalar multiplication. __Just Short of Optimal__ is defined as the __second most optimal__ number of scalar multiplications. It is assured that matrix dimensions allow multiplication, in order. __Note:__ In the case where there are two equally optimal answers, any one of them is to be given as output.
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"]
First line contains an integer __T__ First line of each test case contains a single integer __N__ . The next line contains __N+1__ space separated integers denoting the dimensions of matrices in the order specified above. __Contraints:__ 1<= T <=10 3<= N <= 150 1<= Dimensions of Matrices <= 60
For each test case, print a single integer denoting the __Just Short of Optimal__ number of scalar multiplications involved for the given matrices.
1 3 10 30 5 60
27000
Hard
null
null
null
null
null
null
2015-01-10T07:33:53
2016-05-12T23:56:50
setter
#include <iostream> #include<limits.h> #include<vector> #include<algorithm> using namespace std; int main() { int t,n,i,j,k,L; cin>>t; while(t--) { cin>>n; int a[n+1]; for(i=0;i<=n;i++) { cin>>a[i]; } int m[n+1][n+1]; for(i=1;i<=n;i++) m[i][i]=0; for (L=2; L<n; L++) { for (i=1; i<=n-L+1; i++) { j = i+L-1; m[i][j] = INT_MAX; for (k=i; k<=j-1; k++) { int q = m[i][k] + m[k+1][j] + a[i-1]*a[k]*a[j]; if (q < m[i][j]) m[i][j] = q; } } } vector<int>v; for(k=1;k<n;k++) v.push_back(m[1][k] + m[k+1][n] + a[0]*a[k]*a[n]); sort(v.begin(),v.end()); m[1][n-1]=v[0]; if(v.size()>1) m[1][n-1]=v[1]; cout<<m[1][n-1]<<endl; } return 0; }
not-set
2016-04-24T02:03:25
2016-04-24T02:03:25
C++
266
5,847
sprinklers
Sprinklers
null
code
Help John to set up sprinklers in the most efficient way
ai
2015-01-11T06:45:24
2019-07-02T13:59:29
null
null
null
Roses are planted in a row and numbered from $1$ to $N$. The distance between two consecutive roses is $1$ meter. John wants to automate the watering of these plants and wants to set up some sprinklers in the ground. The cost for setting up each sprinkler is $S$ coins. John chooses several roses behind which it is allowed to set up a sprinkler and sets some sprinklers behind them. A sprinkler can water the roses depending on the force of the water jet. Initially it can only water one flower behind which it stands. To expand the range of __all__ the sprinklers by $1$ meter John has to pay $Q$ coins. Sprinklers can water roses in both directions. For eg: A sprinkler with its range increased by 1 meter can water three roses: the rose behind which it stands and the roses to its immediate left and immediate right . A sprinkler can water all the plants within its range. John wants to water all the plants i.e. no plant should be left dry. Help John minimize his expenditure on watering the plants. Find the number of sprinklers John needs to buy and determine the amount by which we need to increase each sprinklers range in order to water all the roses in the cheapest way. Besides that, you should determine the positions at which we need to set up sprinklers. **Input Format** Input starts with number of test cases $T$. Each test case consists of two lines. The first line contains four space-separated integers $N$ (the number of roses), $M$ (the number of allowed positions), $S$ (the cost for setting up 1 sprinkler) and $Q$ (the cost for increasing the range of all the sprinklers by 1 meter). The second line contains $M$ indices in ascending order $p_i$ that denote the roses behind which it is allowed to set up a sprinkler. **Constraints** $1 \le T \le 50 $ $1 \le M \le N \le 10^4$ $1 \le S, Q \le 10^5$ $1 \le p_i \le N $ $p_i \lt p_{i+1}$, for $1 \le i \lt M $ **Output Format** The answer for each test case is described by two lines. The first line should contain two integers $B$ - number of sprinklers to buy and $E$ - meters to expand water jet. The second line holds $B$ numbers in ascending order, denoting the positions of the sprinklers; these set of sprinkler's positions must be a subset of the array _p_. If more than one solution exists, output any of them. **Sample Input** 3 7 5 2 5 1 2 3 6 7 8 3 1 2 1 3 8 10 2 8 2 4 7 **Sample Output** 3 1 1 3 6 2 2 3 8 1 6 7 **Explanation** In the first case, John sets up three sprinklers on positions __1__, __3__ and __6__. Each sprinklers range is one meter, so all roses are reachable. Total price is _11_ coins. Illustration for this test case below.<img src="https://s3.amazonaws.com/hr-challenge-images/5847/1421095441-da3c25a785-drawing.svg" title="drawing.svg" /> In the second case, two sprinklers on positions __3__ and __8__ cover all roses when the range of the sprinklers is increased to two meters. The total price is _6_ coins. In the third case, one sprinkler with range __6__ is the optimal solution. The sprinkler can be placed at position __4__ or __7__ and the total price is _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","r","racket","rust","swift","cpp14"]
Hard
null
null
null
null
null
null
2015-01-11T06:59:31
2017-01-17T18:50:12
setter
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; const int INF = 2000000001; int greedySetup(int n, vector<int> & p, int expand) { int j = 0; while (j + 1<p.size() && p[j + 1] - expand <= 1) ++j; int cnt = 1; while (p[j] + expand<n) { int temp = j; while (j + 1<p.size() && p[j + 1] - p[temp] <= 2 * expand + 1) ++j; ++cnt; } return cnt; } int greedySetup2(int n, vector<int> & p, vector<int> & sol, int expand) { int j = 0; while (j + 1<p.size() && p[j + 1] - expand <= 1) ++j; int cnt = 1; sol.push_back(p[j]); while (p[j] + expand<n) { int temp = j; while (j + 1<p.size() && p[j + 1] - p[temp] <= 2 * expand + 1) ++j; ++cnt; sol.push_back(p[j]); } return cnt; } void brute(int n, vector<int> & p, int s, int q, vector<int> & sol, int & E) { int start = max(p[0] - 1, n - p.back()); for (int i = 1; i<p.size(); ++i) start = max(start, (p[i] - p[i - 1]) / 2); int minSum = INF; int best = -1; for (int i = start; i < n; ++i) { int need = greedySetup(n, p, i); if (need*s + i*q<minSum) { minSum = need*s + i*q; best = i; } } greedySetup2(n, p, sol, best); E = best; } void solve(int n, vector<int> p, int s, int q, vector<int> & sol, int & E) { int start = max(p[0] - 1, n - p.back()); for (int i = 1; i<p.size(); ++i) start = max(start, (p[i] - p[i - 1]) / 2); int minSum = INF; int best = -1; while (start<n) { int need = greedySetup(n, p, start); if (need*s + start*q<minSum) { minSum = need*s + start*q; best = start; } int l = start; int r = n; while (r - l>1) { int m = (l + r) / 2; if (greedySetup(n, p, m) != need) r = m; else l = m; } start = r; } greedySetup2(n, p, sol, best); E = best; } int main() { ios::sync_with_stdio(false); int _t; cin >> _t; while (_t--) { int _n, _m, _s, _q; vector<int> _positions; cin >> _n >> _m >> _s >> _q; for (int _i = 0; _i<_m; ++_i) { int _x; cin >> _x; _positions.push_back(_x); } int _E; vector<int> _sol; solve(_n, _positions, _s, _q, _sol, _E); cout << _sol.size() << " " << _E << endl; for (int _i = 0; _i<_sol.size() - 1; ++_i) cout << _sol[_i] << " "; cout << _sol.back() << endl; } return 0; }
not-set
2016-04-24T02:03:25
2016-04-24T02:03:25
C++
267
5,879
calculate-the-medians
Calculate The Medians
null
code
null
ai
2015-01-14T07:12:20
2019-07-02T13:59:30
null
null
null
<sub>*Time limits* for this challenges is two times of the [default one](https://www.hackerrank.com/environment).</sub> The math teacher loves the concept of median very much. One day, he comes up with a question about medians and wants the students to solve it. He provides his students with two arrays of integers, - $A = \{a_1, a_2, \ldots, a_n\}$ - $B = \{b_1, b_2, \ldots, b_m\}$ , followed by $k$ queries. Each query consists of two ranges, $(x, y)$ and $(z, w)$ for both arrays, respectively. The students need to compute the median of a new array formed by concatenating subarrays $A[x \ldots y] = \{a_x, a_{x+1}, ... , a_y\}$ and $B[z \ldots w] = \{b_z, b_{z+1}, ... , b_w\}$. Could you solve it by writing a computer program? *Note* - Indexing starts from 1. - Median of a sorted array with - an odd number of elements is the middle integer. - an even number of elements is the average of two middle integers.
0.5
["haskell","clojure","scala","erlang","sbcl","ocaml","racket","fsharp"]
The first line contains two integers, $n$ and $m$, indicating lengths of the two arrays $A$ and $B$, respectively.<br> The second line contains $n$ integers, representing the array $A$.<br> The third line contains $m$ integers, representing the array $B$.<br> The fourth line contains an integer $k$, indicating the number of queries.<br> Then follows $k$ lines, each line contains four integers $x$, $y$, $z$ and $w$, as described above.
For each query, output the answer in a single line. **Constraints** - $1 \le n, m \le 50000$ - $1 \le a_i, b_j \le 10^9\ , i \in [1, n], j \in [1, m]$ - $1 \le k \le 20000$ - $1 \le x \le y \le n$ - $1 \le z \le w \le m$ - The absolute error between your and expected output should not exceed $10^{-6}$.
5 6 4 3 9 7 8 1 8 3 6 5 2 4 1 5 1 6 1 1 2 4 1 2 3 4 3 5 4 6
5.0 5.0 3.5 6.5
Hard
null
null
null
null
null
null
2015-01-14T07:13:52
2016-12-27T13:25:38
setter
**Solution with partition trees** import Control.Applicative import Control.Monad import Data.Int import Data.List import qualified Data.Vector as V import Text.Printf data Tree = Node (V.Vector Int32) Tree Tree | Leaf Int32 type Struct = (Tree, V.Vector Int32) buildStruct :: [Int32] -> Struct buildStruct xs = (tree, vs) where vs = V.fromList . sort $ xs n = fromIntegral $! V.length vs tree = innerBuild 0 (n - 1) xs innerBuild a b xs | a == b = Leaf a | otherwise = Node toLeft ch0 ch1 where mid = (a + b) `div` 2 ch0 = innerBuild a mid lxs ch1 = innerBuild (mid + 1) b rxs toLeft = V.fromList $! reverse $! toLeftRev (lxs, rxs, toLeftRev) = getLeft xs [] getLeft [] ll = ([], [], ll) getLeft (x:xs) ll = (ls, rs, rll) where i = case ll of [] -> 0 x:ll -> x half = mid + 1 - a midX = vs V.! fromIntegral mid flag = x < midX || i < half && x == midX (ls', rs', rll) = if flag then getLeft xs ((i+1):ll) else getLeft xs (i:ll) ls = if flag then x:ls' else ls' rs = if flag then rs' else x:rs' queryStruct :: Struct -> Int32 -> Int32 -> Int32 -> Int32 queryStruct (tree,vs) x y k = query tree x y k where query (Leaf a) _ _ k = vs V.! fromIntegral a query (Node toLeft ch0 ch1) x y k = result where lx = if x > 0 then toLeft V.! fromIntegral (x-1) else 0 ly = toLeft V.! fromIntegral y result = if lx + k > ly then query ch1 (x - lx) (y - ly) (k - (ly - lx)) else query ch0 lx (ly - 1) k oo = 2 * 10 ^ 9 queryMedian :: Struct -> Struct -> Int32 -> Int32 -> Int32 -> Int32 -> Double queryMedian s1 s2 x y z w = fromIntegral (r1 + r2) / 2.0 where tot = y - x + 1 + w - z + 1 p = (tot + 1) `div` 2 getKth s x y k | k == 0 = 0 | k > y - x + 1 = oo | otherwise = queryStruct s x y k i = bin 0 (min (y - x + 2) (p + 1)) j = p - i bin l r = if l + 1 == r then l else if getKth s1 x y mid <= getKth s2 z w (p - mid + 1) then bin mid r else bin l mid where mid = (l + r) `div` 2 r1 = max (getKth s1 x y i) (getKth s2 z w j) r2 = if tot `mod` 2 == 1 then r1 else min (getKth s1 x y (i + 1)) (getKth s2 z w (j + 1)) solveQuery :: Struct -> Struct -> [[Int32]] -> IO () solveQuery s1 s2 qs = innerSolve qs where innerSolve :: [[Int32]] -> IO () innerSolve [] = return () innerSolve ([x,y,z,w]:qs) = do printf "%.1f\n" $! queryMedian s1 s2 (x-1) (y-1) (z-1) (w-1) innerSolve qs main = do getLine xs <- map read . words <$> getLine ys <- map read . words <$> getLine getLine qs <- map (map read . words) . lines <$> getContents let s1 = buildStruct xs s2 = buildStruct ys solveQuery s1 s2 qs **Solution with segment trees** import Control.Applicative import Control.Monad import Data.List import qualified Data.Vector as V import Text.Printf data Tree = Node Int Int Int Tree Tree | Leaf Int Int initTree :: V.Vector Int -> Tree initTree vs = build 0 (n - 1) where n = V.length vs build a b | a == b = Leaf (vs V.! a) 0 | otherwise = Node (vs V.! a) (vs V.! b) 0 lt rt where mid = (a + b) `div` 2 lt = build a mid rt = build (mid + 1) b insertNum :: Tree -> Int -> Tree insertNum tree x = inner tree where inner leaf@(Leaf a cc) = if a == x then Leaf x (cc + 1) else leaf inner node@(Node a b cc lt rt) | a <= x && x <= b = Node a b (cc + 1) (inner lt) (inner rt) | otherwise = node buildTrees :: [Int] -> Tree -> V.Vector Tree buildTrees xs init = V.fromList $! inner xs init [] where inner [] t ts = reverse (t:ts) inner (x:xs) t ts = inner xs (insertNum t x) (t:ts) queryKth :: Tree -> Tree -> Tree -> Tree -> Int -> Double queryKth (Leaf x _) _ _ _ _ = fromIntegral x queryKth (Node _ _ _ ly ry) (Node _ _ _ lx rx) (Node _ _ _ lw rw) (Node _ _ _ lz rz) k = if k <= th then queryKth ly lx lw lz k else queryKth ry rx rw rz $! k - th where th = getCC ly - getCC lx + getCC lw - getCC lz getCC (Leaf _ cc) = cc getCC (Node _ _ cc _ _) = cc solveQuery :: V.Vector Tree -> V.Vector Tree -> [[Int]] -> IO () solveQuery ts1 ts2 qs = innerSolve qs where innerSolve :: [[Int]] -> IO () innerSolve [] = return () innerSolve ([x,y,z,w]:qs) = do let n = y - x + w - z + 2 m = (n + 1) `div` 2 qk = queryKth (ts1 V.! y) (ts1 V.! (x - 1)) (ts2 V.! w) (ts2 V.! (z - 1)) r1 = qk m r2 = if n `mod` 2 == 1 then r1 else qk (m + 1) printf "%.1f\n" $! (r1 + r2) / 2.0 innerSolve qs main = do contents <- lines <$> getContents let xs = map read . words $! contents !! 1 ys = map read . words $! contents !! 2 vs = V.fromList $! map head $! group $! sort $! xs ++ ys it = initTree vs ts1 = buildTrees xs it ts2 = buildTrees ys it qs = map (map read . words) $! drop 4 contents solveQuery ts1 ts2 qs
not-set
2016-04-24T02:03:25
2016-04-24T02:03:25
Python
268
5,879
calculate-the-medians
Calculate The Medians
null
code
null
ai
2015-01-14T07:12:20
2019-07-02T13:59:30
null
null
null
<sub>*Time limits* for this challenges is two times of the [default one](https://www.hackerrank.com/environment).</sub> The math teacher loves the concept of median very much. One day, he comes up with a question about medians and wants the students to solve it. He provides his students with two arrays of integers, - $A = \{a_1, a_2, \ldots, a_n\}$ - $B = \{b_1, b_2, \ldots, b_m\}$ , followed by $k$ queries. Each query consists of two ranges, $(x, y)$ and $(z, w)$ for both arrays, respectively. The students need to compute the median of a new array formed by concatenating subarrays $A[x \ldots y] = \{a_x, a_{x+1}, ... , a_y\}$ and $B[z \ldots w] = \{b_z, b_{z+1}, ... , b_w\}$. Could you solve it by writing a computer program? *Note* - Indexing starts from 1. - Median of a sorted array with - an odd number of elements is the middle integer. - an even number of elements is the average of two middle integers.
0.5
["haskell","clojure","scala","erlang","sbcl","ocaml","racket","fsharp"]
The first line contains two integers, $n$ and $m$, indicating lengths of the two arrays $A$ and $B$, respectively.<br> The second line contains $n$ integers, representing the array $A$.<br> The third line contains $m$ integers, representing the array $B$.<br> The fourth line contains an integer $k$, indicating the number of queries.<br> Then follows $k$ lines, each line contains four integers $x$, $y$, $z$ and $w$, as described above.
For each query, output the answer in a single line. **Constraints** - $1 \le n, m \le 50000$ - $1 \le a_i, b_j \le 10^9\ , i \in [1, n], j \in [1, m]$ - $1 \le k \le 20000$ - $1 \le x \le y \le n$ - $1 \le z \le w \le m$ - The absolute error between your and expected output should not exceed $10^{-6}$.
5 6 4 3 9 7 8 1 8 3 6 5 2 4 1 5 1 6 1 1 2 4 1 2 3 4 3 5 4 6
5.0 5.0 3.5 6.5
Hard
null
null
null
null
null
null
2015-01-14T07:13:52
2016-12-27T13:25:38
tester
import scala.collection.mutable.TreeSet /** * Created by Bo You (stoundmire) on 2015/3/4. */ object Solution { def combine(a: Array[Int], b: Array[Int]): Array[Int] = { val s = new TreeSet[Int]() for (x <- a) { s.add(x) } for (x <- b) { s.add(x) } return s.toArray } def bisearch(a: Array[Int], v: Int): Int = { def iter(l: Int, r: Int): Int = { if (l == r) { return l } else { val mid = (l + r) / 2 return if (a(mid) >= v) iter(l, mid) else iter(mid + 1, r) } } return iter(0, a.length - 1) } class Node(val l: Int, val r: Int, val v: Int, val leftChild: Node, val rightChild: Node) { } def build(a: Array[Int], all: Array[Int]): Array[Node] = { val r = Array.fill[Node](a.length + 1)(null) // initialize an empty segment tree def init(): Node = { def iter(l: Int, r: Int): Node = { if (l == r) { return new Node(l, r, 0, null, null) } else { val mid = (l + r) / 2 return new Node(l, r, 0, iter(l, mid), iter(mid + 1, r)) } } return iter(0, all.length - 1) } // alter one path from root to leaf def process(idx: Int): Unit = { if (idx > a.length) { return } val x = bisearch(all, a(idx - 1)) def update(node: Node): Node = { val l = node.l val r = node.r val v = node.v val mid = (l + r) / 2 if (l == r) { return new Node(l, r, v + 1, null, null) } else if (mid >= x) { return new Node(l, r, v + 1, update(node.leftChild), node.rightChild) } else { return new Node(l, r, v, node.leftChild, update(node.rightChild)) } } r(idx) = update(r(idx - 1)) process(idx + 1) } r(0) = init() process(1) return r } def query(x: Int, root: Node): Int = { def iter(node: Node): Int = { val l = node.l val r = node.r val mid = (l + r) / 2 if (l == r) { return node.v } else if (x > mid) { return node.v + iter(node.rightChild) } else { return iter(node.leftChild) } } return iter(root) } def solve(x: Int, y: Int, z: Int, w: Int, treeA: Array[Node], treeB: Array[Node], all: Array[Int]): Double = { def getValue(rank: Int, lo: Int, hi: Int): Int = { def getRank(v: Int): Int = { return query(v, treeA(y)) - query(v, treeA(x - 1)) + query(v, treeB(w)) - query(v, treeB(z - 1)) } if (lo == hi) { return lo } else { val mid = (lo + hi) / 2 if (getRank(mid) < rank) { return getValue(rank, mid + 1, hi) } else { return getValue(rank, lo, mid) } } } val cnt = y - x + 1 + w - z + 1 if (cnt % 2 != 0) { return all(getValue((cnt + 1) / 2, 0, all.length - 1)) } else { val m = cnt / 2 return (all(getValue(m, 0, all.length - 1)) + all(getValue(m + 1, 0, all.length - 1))) / 2.0 } } def main(args: Array[String]): Unit = { val sz = readLine.split(" ", -1).map(_.toInt) val a = readLine.split(" ", -1).map(_.toInt) val b = readLine.split(" ", -1).map(_.toInt) val all = combine(a, b) val treeA = build(a, all) val treeB = build(b, all) val q = readLine.toInt for (i <- 1 to q) { val tmp = readLine.split(" ", -1).map(_.toInt) println("%.1f".format(solve(tmp(0), tmp(1), tmp(2), tmp(3), treeA, treeB, all))) } } }
not-set
2016-04-24T02:03:25
2016-04-24T02:03:25
Python
269
5,951
audit-sale
Audit Sale
null
code
Calculate your maximum expected sale price.
ai
2015-01-19T21:40:20
2019-07-02T13:59:31
null
null
null
After carefully auditing your portfolio, you notice you have $N$ securities left over from previous trades. You have only one unit of each of these $N$ securities, and you want to sell *at most* $M$ of these to avoid extra accounting. As an experienced portfolio manager, you rely on your previous body of work to predict the price at which you can sell each lone security. For each of the $N$ securities, you write down two pieces of information: 1. The price, $P$, at which you want to sell that security. 2. The probability (or confidence), $C$, that you can sell the security at that price. Thus, the $i^{th}$ security has two values associated with it: the price, $P_i$, and the confidence, $C_i$. Drawing on your experience, you know with $100\%$ certainty that you can sell at least $K$ of the $N$ securities. Given the information discussed above, find the maximum amount of money [expected](http://mathworld.wolfram.com/ExpectationValue.html) from $M$ sales, multiply it by $100$, and print the result. The first $K$ sales of your choice are guaranteed to be successful.
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","pypy","pypy3"]
The first line contains three space-separated integers: $N$ (the number of lone securities you have), $M$ (the maximum number of securities you wish to sell), and $K$ (the minimum number of securities you can definitely sell), respectively. Each line $i$ of the $N$ subsequent lines contains two space-separated integers describing the respective $P_i$ and $C_i$ values for security $i$ (where $0 \le i \lt N$).
Print a single integer denoting the maximum amount of money expected from $M$ sales, multiplied by $100$.
3 2 1 5 10 6 60 8 40
1160
Hard
null
null
null
null
null
null
2015-01-19T21:44:31
2016-12-17T11:23:04
setter
#include <bits/stdc++.h> using namespace std; #define int long long const int N = 100010; int n, m, k; vector<pair<int, pair<int, int> > > v; int hSum[N], hpSum[N]; //hSum[i] stores sum of mamimum K pricw values till i //hpSum[i] stores sum of maximum (M - K) price * probability values with index >= i #undef int int main() { #define int long long ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m >> k; for(int i=0; i<n; i++) { int hi, pi; cin >> hi >> pi; v.push_back({hi * (100 - pi), {hi, pi}}); } sort(v.begin(), v.end()); reverse(v.begin(), v.end()); multiset<int> s; long long curSum = 0; for(int i=0; i<n; i++) { int curH = v[i].second.first; if(i < k) { s.insert(curH); curSum += curH; } else if(s.size()) { int mn = *(s.begin()); if(mn < curH) { s.erase(s.begin()); curSum -= mn; curSum += curH; s.insert(curH); } } hSum[i] = curSum; } s.clear(); curSum = 0; for(int i=n-1; i>=0; i--) { int curHp = v[i].second.first * v[i].second.second; if(n - i - 1 < m - k) { s.insert(curHp); curSum += curHp; } else if(s.size()) { int mn = *(s.begin()); if(mn < curHp) { s.erase(s.begin()); curSum -= mn; curSum += curHp; s.insert(curHp); } } hpSum[i] = curSum; } hpSum[n] = 0; long long ans = -1; for(int i=0; i<n; i++) { ans = max(ans, hSum[i]*100 + hpSum[i+1]); } ans = max(ans, hpSum[0]); cout << ans << "\n"; }
not-set
2016-04-24T02:03:27
2016-06-13T12:53:53
C++