source
stringclasses 4
values | task_type
stringclasses 1
value | in_source_id
stringlengths 0
138
| problem
stringlengths 219
13.2k
| gold_standard_solution
stringlengths 0
413k
| problem_id
stringlengths 5
10
| metadata
dict | verification_info
dict |
---|---|---|---|---|---|---|---|
code_contests | verifiable_code | 1246_D. Tree Factory | Solve the following coding problem using the programming language python:
Bytelandian Tree Factory produces trees for all kinds of industrial applications. You have been tasked with optimizing the production of a certain type of tree for an especially large and important order.
The tree in question is a rooted tree with n vertices labelled with distinct integers from 0 to n - 1. The vertex labelled 0 is the root of the tree, and for any non-root vertex v the label of its parent p(v) is less than the label of v.
All trees at the factory are made from bamboo blanks. A bamboo is a rooted tree such that each vertex has exactly one child, except for a single leaf vertex with no children. The vertices of a bamboo blank can be labelled arbitrarily before its processing is started.
To process a bamboo into another tree a single type of operation can be made: choose an arbitrary non-root vertex v such that its parent p(v) is not a root either. The operation consists of changing the parent of v to its parent's parent p(p(v)). Note that parents of all other vertices remain unchanged, in particular, the subtree of v does not change.
Efficiency is crucial, hence you have to minimize the number of operations to make the desired tree from a bamboo blank. Construct any optimal sequence of operations to produce the desired tree.
Note that the labelling of the resulting tree has to coincide with the labelling of the desired tree. Formally, the labels of the roots have to be equal, and for non-root vertices with the same label the labels of their parents should be the same.
It is guaranteed that for any test present in this problem an answer exists, and further, an optimal sequence contains at most 10^6 operations. Note that any hack that does not meet these conditions will be invalid.
Input
The first line contains a single integer n β the number of vertices in the tree (2 β€ n β€ 10^5).
The second line contains n - 1 integers p(1), β¦, p(n - 1) β indices of parent vertices of 1, β¦, n - 1 respectively (0 β€ p(i) < i).
Output
In the first line, print n distinct integers id_1, β¦, id_n β the initial labelling of the bamboo blank starting from the root vertex (0 β€ id_i < n).
In the second line, print a single integer k β the number of operations in your sequence (0 β€ k β€ 10^6).
In the third line print k integers v_1, β¦, v_k describing operations in order. The i-th operation consists of changing p(v_i) to p(p(v_i)). Each operation should be valid, i.e. neither v_i nor p(v_i) can be the root of the tree at the moment.
Examples
Input
5
0 0 1 1
Output
0 2 1 4 3
2
1 3
Input
4
0 1 2
Output
0 1 2 3
0
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_35937 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 512000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0 1 2\n",
"output": "0 1 2 3\n0\n\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1266_B. Dice Tower | Solve the following coding problem using the programming language python:
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 β the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 β€ x_i β€ 10^{18}) β Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 14:08:47 2020
@author: Varun
"""
from sys import stdin, stdout
stdin.readline()
numbers = map(int, stdin.readline().split())
def check(n):
if n < 15:
return False
m = n%14
return 1 <= m <= 6
for el in numbers:
if check(el):
stdout.write("YES")
else:
stdout.write("NO")
stdout.write("\n")
``` | vfc_35941 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n29 34 19 38\n",
"output": "YES\nYES\nYES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n29 34 18 38\n",
"output": "YES\nYES\nYES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n29 13 19 38\n",
"output": "YES\nNO\nYES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n29 13 19 57\n",
"output": "YES\nNO\nYES\nYES\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1287_D. Numbers on Tree | Solve the following coding problem using the programming language python:
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i β the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first integer is a_i and the integer in parentheses is c_i
After the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.
Help him to restore initial integers!
Input
The first line contains an integer n (1 β€ n β€ 2000) β the number of vertices in the tree.
The next n lines contain descriptions of vertices: the i-th line contains two integers p_i and c_i (0 β€ p_i β€ n; 0 β€ c_i β€ n-1), where p_i is the parent of vertex i or 0 if vertex i is root, and c_i is the number of vertices j in the subtree of vertex i, such that a_j < a_i.
It is guaranteed that the values of p_i describe a rooted tree with n vertices.
Output
If a solution exists, in the first line print "YES", and in the second line output n integers a_i (1 β€ a_i β€ {10}^{9}). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all a_i are between 1 and 10^9.
If there are no solutions, print "NO".
Examples
Input
3
2 0
0 2
2 0
Output
YES
1 2 1
Input
5
0 1
1 3
2 1
3 0
2 0
Output
YES
2 3 2 1 2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n = int(input())
cs = [0] * (n + 1)
ps = [0] * (n + 1)
children = [[] for _ in range(n+1)]
for i in range(1, n+1):
p, c = map(int, input().split())
ps[i] = p
children[p].append(i)
cs[i] = c
def sortDescendants(v):
result = []
pos = cs[v]
for child in children[v]:
result += sortDescendants(child)
if len(result) < pos:
print('NO')
sys.exit()
result.insert(pos, v)
return result
root = children[0][0]
order = sortDescendants(root)
a = [0] * n
for i, v in enumerate(order):
a[v - 1] = i + 1
print('YES')
print(*a)
# inf.close()
``` | vfc_35945 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 0\n0 2\n2 0\n",
"output": "YES\n1 3 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n0 1\n1 3\n2 1\n3 0\n2 0\n",
"output": "YES\n2 5 3 1 4 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 0\n0 2\n2 0\n",
"output": "YES\n1 3 2 \n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1330_D. Dreamoon Likes Sequences | Solve the following coding problem using the programming language python:
Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers d, m, find the number of arrays a, satisfying the following constraints:
* The length of a is n, n β₯ 1
* 1 β€ a_1 < a_2 < ... < a_n β€ d
* Define an array b of length n as follows: b_1 = a_1, β i > 1, b_i = b_{i - 1} β a_i, where β is the bitwise exclusive-or (xor). After constructing an array b, the constraint b_1 < b_2 < ... < b_{n - 1} < b_n should hold.
Since the number of possible arrays may be too large, you need to find the answer modulo m.
Input
The first line contains an integer t (1 β€ t β€ 100) denoting the number of test cases in the input.
Each of the next t lines contains two integers d, m (1 β€ d, m β€ 10^9).
Note that m is not necessary the prime!
Output
For each test case, print the number of arrays a, satisfying all given constrains, modulo m.
Example
Input
10
1 1000000000
2 999999999
3 99999998
4 9999997
5 999996
6 99995
7 9994
8 993
9 92
10 1
Output
1
3
5
11
17
23
29
59
89
0
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
t = int(input())
for _ in range(t):
d, m = map(int, input().split())
a = []
i = 0
while d > (1<<(i+1))-1:
a.append(1<<i)
i += 1
a.append((1<<i) - (1<<(i+1)) + d + 1)
#print(a)
ans = 1
for x in a:
ans *= x+1
ans %= m
print((ans-1)%m)
``` | vfc_35953 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n7 9994\n8 993\n9 92\n10 1\n",
"output": "1\n3\n5\n11\n17\n23\n29\n59\n89\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n10 99995\n7 9994\n8 993\n9 92\n10 1\n",
"output": "1\n3\n5\n11\n17\n119\n29\n59\n89\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n10 99995\n7 9994\n8 993\n12 92\n19 1\n",
"output": "1\n3\n5\n11\n17\n119\n29\n59\n87\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n6 99995\n5 9994\n8 993\n9 92\n10 1\n",
"output": "1\n3\n5\n11\n17\n23\n17\n59\n89\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n9 999996\n10 99995\n7 9994\n8 993\n9 92\n19 1\n",
"output": "1\n3\n5\n11\n89\n119\n29\n59\n89\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 1000000000\n2 999999999\n3 99999998\n4 9999997\n5 999996\n10 99995\n9 9994\n8 993\n12 92\n19 1\n",
"output": "1\n3\n5\n11\n17\n119\n89\n59\n87\n0\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1370_F2. The Hidden Pair (Hard Version) | Solve the following coding problem using the programming language python:
Note that the only difference between the easy and hard version is the constraint on the number of queries. You can make hacks only if all versions of the problem are solved.
This is an interactive problem.
You are given a tree consisting of n nodes numbered with integers from 1 to n. Ayush and Ashish chose two secret distinct nodes in the tree. You need to find out both the nodes. You can make the following query:
* Provide a list of nodes and you will receive a node from that list whose sum of distances to both the hidden nodes is minimal (if there are multiple such nodes in the list, you will receive any one of them). You will also get the sum of distances of that node to the hidden nodes.
Recall that a tree is a connected graph without cycles. The distance between two nodes is defined as the number of edges in the simple path between them.
More formally, let's define two hidden nodes as s and f. In one query you can provide the set of nodes \\{a_1, a_2, β¦, a_c\} of the tree. As a result, you will get two numbers a_i and dist(a_i, s) + dist(a_i, f). The node a_i is any node from the provided set, for which the number dist(a_i, s) + dist(a_i, f) is minimal.
You can ask no more than 11 queries.
Input
The first line contains a single integer t (1 β€ t β€ 10) β the number of test cases. Please note, how the interaction process is organized.
The first line of each test case consists of a single integer n (2 β€ n β€ 1000) β the number of nodes in the tree.
The next n - 1 lines consist of two integers u, v (1 β€ u, v β€ n, u β v) β the edges of the tree.
Interaction
To ask a query print a single line:
* In the beginning print "? c " (without quotes) where c (1 β€ c β€ n) denotes the number of nodes being queried, followed by c distinct integers in the range [1, n] β the indices of nodes from the list.
For each query, you will receive two integers x, d β the node (among the queried nodes) with the minimum sum of distances to the hidden nodes and the sum of distances from that node to the hidden nodes. If the subset of nodes queried is invalid or you exceeded the number of queries then you will get x = d = -1. In this case, you should terminate the program immediately.
When you have guessed the hidden nodes, print a single line "! " (without quotes), followed by two integers in the range [1, n] β the hidden nodes. You can output the hidden nodes in any order.
After this, you should read a string. If you guess the nodes correctly, you will receive the string "Correct". In this case, you should continue solving the remaining test cases or terminate the program, if all test cases were solved. Otherwise, you will receive the string "Incorrect". In this case, you should terminate the program immediately.
Guessing the hidden nodes does not count towards the number of queries asked.
The interactor is not adaptive. The hidden nodes do not change with queries.
Do not forget to read the string "Correct" / "Incorrect" after guessing the hidden nodes.
You need to solve each test case before receiving the input for the next test case.
The limit of 11 queries applies to each test case and not to the entire input.
After printing a query do not forget to output the end of the line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see the documentation for other languages.
Hacks
To hack the solution, use the following test format:
The first line should contain a single integer t (1 β€ t β€ 10) β the number of test cases. The description of the test cases follows.
The first line of each test case should contain a single integer n (2 β€ n β€ 1000) β the number of nodes in the tree. The second line should contain two distinct integers in the range [1, n] β the hidden nodes. The next n - 1 lines should contain two integers u, v (1 β€ u, v β€ n, u β v) β the edges of the tree.
Example
Input
1
3
1 2
1 3
1 1
2 3
3 1
3 1
Correct
Output
? 1 1
? 1 2
? 1 3
? 2 2 3
! 1 3
Note
The tree from the first test is shown below, and the hidden nodes are 1 and 3.
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_35961 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n3\n1 2\n1 3\n\n1 1\n\n2 3\n\n3 1\n\n3 1\n\nCorrect",
"output": "? 3 1 2 3\n? 2 2 3\n? 2 2 3\n! 1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4\n2 4\n1 2\n2 4\n4 3\n",
"output": "4\n2 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3\n1 3\n1 2\n1 3\n",
"output": "4\n1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3\n2 3\n2 3\n1 3\n6\n1 4\n3 4\n2 5\n2 1\n4 6\n2 3\n3\n3 2\n3 2\n1 2\n2\n1 2\n2 1\n3\n2 1\n3 1\n2 3\n2\n2 1\n2 1\n9\n5 7\n2 5\n3 4\n9 8\n1 5\n9 2\n8 4\n9 6\n7 3\n6\n6 3\n3 1\n3 2\n6 4\n6 5\n6 2\n6\n4 3\n1 2\n5 4\n3 5\n6 3\n6 2\n4\n4 1\n3 2\n4 3\n4 1\n",
"output": "3\n2 3\n3\n1 4\n4\n2 3\n4\n1 2\n3\n1 2\n4\n1 2\n5\n5 7\n4\n3 6\n3\n3 4\n3\n1 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3\n1 3\n1 2\n2 3\n2\n1 2\n2 1\n10\n10 8\n6 5\n7 8\n3 8\n6 3\n2 10\n10 7\n9 4\n5 9\n1 2\n8\n8 3\n6 3\n6 8\n2 3\n4 1\n7 2\n7 5\n4 7\n2\n2 1\n1 2\n9\n8 1\n5 9\n1 3\n8 7\n3 5\n8 1\n6 4\n2 6\n4 8\n9\n9 3\n9 6\n5 2\n8 7\n6 3\n6 5\n7 1\n4 8\n9 4\n2\n1 2\n1 2\n5\n2 5\n1 2\n5 4\n5 3\n4 2\n5\n1 2\n2 4\n5 4\n4 1\n3 2\n",
"output": "3\n1 3\n4\n1 2\n5\n8 10\n4\n3 8\n4\n1 2\n5\n1 8\n5\n3 9\n4\n1 2\n4\n2 5\n3\n1 2\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1393_C. Pinkie Pie Eats Patty-cakes | Solve the following coding problem using the programming language python:
Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.
Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.
Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!
Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!
Input
The first line contains a single integer T (1 β€ T β€ 100): the number of bags for which you need to solve the problem.
The first line of each bag description contains a single integer n (2 β€ n β€ 10^5): the number of patty-cakes in it. The second line of the bag description contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n): the information of patty-cakes' fillings: same fillings are defined as same integers, different fillings are defined as different integers. It is guaranteed that each bag contains at least two patty-cakes with the same filling.
It is guaranteed that the sum of n over all bags does not exceed 10^5.
Output
For each bag print in separate line one single integer: the largest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating for that bag.
Example
Input
4
7
1 7 1 6 4 4 6
8
1 1 4 6 4 6 4 7
3
3 3 3
6
2 5 2 3 1 4
Output
3
2
0
4
Note
For the first bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 6, 4, 7, 1, 6, 4 (in this way, the minimum distance is equal to 3).
For the second bag Pinkie Pie can eat the patty-cakes in the following order (by fillings): 1, 4, 6, 7, 4, 1, 6, 4 (in this way, the minimum distance is equal to 2).
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def solve(n,ar):
freq = [0] * 200000
for i in range(n):
freq[ar[i]] += 1
maxi = 0
max_freq = 0
for i in range(len(freq)):
if maxi < freq[i]:
maxi = max(maxi,freq[i])
max_freq = 1
elif freq[i] == maxi:
max_freq += 1
print((n-max_freq)//(maxi-1) -1)
if __name__ == '__main__':
t = int(input())
for _ in range(t):
n = int(input())
ar = list(map(int,input().split()))
solve(n,ar)
``` | vfc_35965 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n7\n1 7 1 6 4 4 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4\n",
"output": "3\n2\n0\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n15\n1 2 3 4 5 1 2 3 4 5 1 2 3 4 5\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n15\n1 2 3 4 5 1 2 3 4 5 2 2 3 4 5\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n1 7 1 6 4 7 6\n8\n1 1 4 6 4 6 4 7\n3\n3 3 3\n6\n2 5 2 3 1 4\n",
"output": "3\n2\n0\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n15\n1 2 3 4 5 1 2 3 4 5 2 1 3 4 5\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1418_B. Negative Prefixes | Solve the following coding problem using the programming language python:
You are given an array a, consisting of n integers.
Each position i (1 β€ i β€ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.
For example, let a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}], the underlined positions are locked. You can obtain the following arrays:
* [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}];
* [-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}];
* [1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}];
* [1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}];
* and some others.
Let p be a sequence of prefix sums of the array a after the rearrangement. So p_1 = a_1, p_2 = a_1 + a_2, p_3 = a_1 + a_2 + a_3, ..., p_n = a_1 + a_2 + ... + a_n.
Let k be the maximum j (1 β€ j β€ n) such that p_j < 0. If there are no j such that p_j < 0, then k = 0.
Your goal is to rearrange the values in such a way that k is minimum possible.
Output the array a after the rearrangement such that the value k for it is minimum possible. If there are multiple answers then print any of them.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
Then t testcases follow.
The first line of each testcase contains a single integer n (1 β€ n β€ 100) β the number of elements in the array a.
The second line of each testcase contains n integers a_1, a_2, ..., a_n (-10^5 β€ a_i β€ 10^5) β the initial array a.
The third line of each testcase contains n integers l_1, l_2, ..., l_n (0 β€ l_i β€ 1), where l_i = 0 means that the position i is unlocked and l_i = 1 means that the position i is locked.
Output
Print n integers β the array a after the rearrangement. Value k (the maximum j such that p_j < 0 (or 0 if there are no such j)) should be minimum possible. For each locked position the printed value should be equal to the initial one. The values on the unlocked positions should be an arrangement of the initial ones.
If there are multiple answers then print any of them.
Example
Input
5
3
1 3 2
0 0 0
4
2 -3 4 -1
1 1 1 1
7
-8 4 -2 -6 4 7 1
1 0 0 0 1 1 0
5
0 1 -4 6 3
0 0 0 1 1
6
-1 7 10 4 -8 -1
1 0 0 0 0 1
Output
1 2 3
2 -3 4 -1
-8 -6 1 4 4 7 -2
-4 0 1 6 3
-1 4 7 -8 10 -1
Note
In the first testcase you can rearrange all values however you want but any arrangement will result in k = 0. For example, for an arrangement [1, 2, 3], p=[1, 3, 6], so there are no j such that p_j < 0. Thus, k = 0.
In the second testcase you are not allowed to rearrange any elements. Thus, the printed array should be exactly the same as the initial one.
In the third testcase the prefix sums for the printed array are p = [-8, -14, -13, -9, -5, 2, 0]. The maximum j is 5, thus k = 5. There are no arrangements such that k < 5.
In the fourth testcase p = [-4, -4, -3, 3, 6].
In the fifth testcase p = [-1, 3, 10, 2, 12, 11].
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
from sys import stdin
import math
import fractions
#Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1))
def iinput():
return int(input())
def minput():
return map(int,input().split())
def linput():
return list(map(int,input().split()))
def fiinput():
return int(stdin.readline())
def fminput():
return map(int,stdin.readline().strip().split())
def flinput():
return list(map(int,stdin.readline().strip().split()))
for _ in range(iinput()):
n=iinput()
list1=linput()
list2=linput()
list3=[]
for i in range(n):
if(list2[i]==0):
list3.append(list1[i])
list3.sort()
for i in range(n):
if(list2[i]==0):
list1[i]=list3.pop()
print(*list1)
``` | vfc_35969 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1\n",
"output": "3 2 1 \n2 -3 4 -1 \n-8 4 1 -2 4 7 -6 \n1 0 -4 6 3 \n-1 10 7 4 -8 -1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1\n",
"output": "3 2 1 \n2 -3 4 -1 \n-8 4 1 -2 4 7 -6 \n1 0 -4 6 3 \n-1 10 7 4 -8 -1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -2 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 5 10 4 -8 -1\n1 0 0 0 0 1\n",
"output": "3 2 1\n2 -3 4 -1\n-8 4 1 -2 4 7 -6\n1 0 -4 6 3\n-1 10 5 4 -8 -1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3\n1 3 2\n0 0 0\n4\n2 -3 4 -1\n1 1 1 1\n7\n-8 4 -1 -6 4 7 1\n1 0 0 0 1 1 0\n5\n0 1 -4 6 3\n0 0 0 1 1\n6\n-1 7 10 4 -8 -1\n1 0 0 0 0 1\n",
"output": "3 2 1\n2 -3 4 -1\n-8 4 1 -1 4 7 -6\n1 0 -4 6 3\n-1 10 7 4 -8 -1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1436_A. Reorder | Solve the following coding problem using the programming language python:
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that β_{i=1}^{n}{β_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, 5/2=2.5.
Input
The first line contains a single integer t β the number of test cases (1 β€ t β€ 100). The test cases follow, each in two lines.
The first line of a test case contains two integers n and m (1 β€ n β€ 100, 0 β€ m β€ 10^6). The second line contains integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 10^6) β the elements of the array.
Output
For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.
Example
Input
2
3 8
2 5 1
4 4
0 1 2 3
Output
YES
NO
Note
In the first test case one of the reorders could be [1, 2, 5]. The sum is equal to (1/1 + 2/2 + 5/3) + (2/2 + 5/3) + (5/3) = 8. The brackets denote the inner sum β_{j=i}^{n}{(a_j)/(j)}, while the summation of brackets corresponds to the sum over i.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
#import numpy as np
#import collections
#import sys
# =============================================================================
#def get_primeFactor(n):
# res=[1]
# x=2
# while x*x<=n:
# while n%x==0:
# res.append(x)
# n//=x
# x+=1
# if n>1:res.append(n)
# return res
#
#def getFactor(n):
# res={1,n}
# x=2
# while x*x<=n:
# if n%x==0:
# res.add(x)
# res.add(n//x)
# x+=1
# return res
#for _ in range(int(input())):
# r,b,g,w=tuple(map(int,input().split()))
# f=tuple(filter(lambda x:x%2!=0,(r,b,g,w)))
# if len(f)<=1 or len(f)==4:print("Yes")
# elif len(f)==2:print("No")
# else:
# if w%2==0:print("Yes")
# elif all(t!=0 for t in (r,b,g) ):print("Yes")
# else :print("No")
#
for _ in range(int(input())):
n,m=map(int,input().split())
ar=map(int,input().split())
total=sum(ar)
if total != m:print("NO")
else: print("YES")
``` | vfc_35973 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n3 8\n2 5 1\n4 4\n0 1 2 3\n",
"output": "YES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 6\n4 4 4\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 2\n1 2 3\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 16\n2 5 1\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 2\n4\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 145_D. Lucky Pair | Solve the following coding problem using the programming language python:
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has an array a of n integers. The numbers in the array are numbered starting from 1. Unfortunately, Petya has been misbehaving and so, his parents don't allow him play with arrays that have many lucky numbers. It is guaranteed that no more than 1000 elements in the array a are lucky numbers.
Petya needs to find the number of pairs of non-intersecting segments [l1;r1] and [l2;r2] (1 β€ l1 β€ r1 < l2 β€ r2 β€ n, all four numbers are integers) such that there's no such lucky number that occurs simultaneously in the subarray a[l1..r1] and in the subarray a[l2..r2]. Help Petya count the number of such pairs.
Input
The first line contains an integer n (2 β€ n β€ 105) β the size of the array a. The second line contains n space-separated integers ai (1 β€ ai β€ 109) β array a. It is guaranteed that no more than 1000 elements in the array a are lucky numbers.
Output
On the single line print the only number β the answer to the problem.
Please do not use the %lld specificator to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specificator.
Examples
Input
4
1 4 2 4
Output
9
Input
2
4 7
Output
1
Input
4
4 4 7 7
Output
9
Note
The subarray a[l..r] is an array that consists of elements al, al + 1, ..., ar.
In the first sample there are 9 possible pairs that satisfy the condition: [1, 1] and [2, 2], [1, 1] and [2, 3], [1, 1] and [2, 4], [1, 1] and [3, 3], [1, 1] and [3, 4], [1, 1] and [4, 4], [1, 2] and [3, 3], [2, 2] and [3, 3], [3, 3] and [4, 4].
In the second sample there is only one pair of segments β [1;1] and [2;2] and it satisfies the condition.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_35977 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n4 7\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 4 2 4\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1485_F. Copy or Prefix Sum | Solve the following coding problem using the programming language python:
You are given an array of integers b_1, b_2, β¦, b_n.
An array a_1, a_2, β¦, a_n of integers is hybrid if for each i (1 β€ i β€ n) at least one of these conditions is true:
* b_i = a_i, or
* b_i = β_{j=1}^{i} a_j.
Find the number of hybrid arrays a_1, a_2, β¦, a_n. As the result can be very large, you should print the answer modulo 10^9 + 7.
Input
The first line contains a single integer t (1 β€ t β€ 10^4) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 2 β
10^5).
The second line of each test case contains n integers b_1, b_2, β¦, b_n (-10^9 β€ b_i β€ 10^9).
It is guaranteed that the sum of n for all test cases does not exceed 2 β
10^5.
Output
For each test case, print a single integer: the number of hybrid arrays a_1, a_2, β¦, a_n modulo 10^9 + 7.
Example
Input
4
3
1 -1 1
4
1 2 3 4
10
2 -1 1 -2 2 3 -5 0 2 -1
4
0 0 0 1
Output
3
8
223
1
Note
In the first test case, the hybrid arrays are [1, -2, 1], [1, -2, 2], [1, -1, 1].
In the second test case, the hybrid arrays are [1, 1, 1, 1], [1, 1, 1, 4], [1, 1, 3, -1], [1, 1, 3, 4], [1, 2, 0, 1], [1, 2, 0, 4], [1, 2, 3, -2], [1, 2, 3, 4].
In the fourth test case, the only hybrid array is [0, 0, 0, 1].
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
for s in[*open(0)][2::2]:
C=[0];N=0;D={0:1};S=1
for n in map(int,s.split()):C+=C[-1]+n,;N+=1
for i in range(1,N):D[C[i]],S=S,(2*S-D.get(C[i],0))%(10**9+7)
print(S)
``` | vfc_35981 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n3\n1 -1 1\n4\n1 2 3 4\n10\n2 -1 1 -2 2 3 -5 0 2 -1\n4\n0 0 0 1\n",
"output": "\n3\n8\n223\n1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 150_D. Mission Impassable | Solve the following coding problem using the programming language python:
Market stalls now have the long-awaited game The Colder Scrools V: Nvodsk. The game turned out to be difficult as hell and most students can't complete the last quest ("We don't go to Nvodsk..."). That threatened winter exams. The rector already started to wonder whether he should postpone the winter exams till April (in fact, he wanted to complete the quest himself). But all of a sudden a stranger appeared at the door of his office. "Good afternoon. My name is Chuck and I solve any problems" β he said.
And here they are sitting side by side but still they can't complete the mission. The thing is, to kill the final boss one should prove one's perfect skills in the art of managing letters. One should be a real magician to do that. And can you imagine what happens when magicians start competing...
But let's put it more formally: you are given a string and a set of integers ai. You are allowed to choose any substring that is a palindrome and delete it. At that we receive some number of points equal to ak, where k is the length of the deleted palindrome. For some k, ak = -1, which means that deleting palindrome strings of such length is forbidden. After a substring is deleted, the remaining part "shifts together", that is, at no moment of time the string has gaps. The process is repeated while the string has at least one palindrome substring that can be deleted. All gained points are summed up.
Determine what maximum number of points can be earned.
"Oh" β said Chuck, raising from the chair, β "I used to love deleting palindromes, just like you, but one day I took an arrow in the Knee".
Input
The first line contains an integer l (1 β€ l β€ 150) β the length of the string.
The second line contains exactly l integers ak ( - 1 β€ ak β€ 105) β the points a player gains for deleting.
The third line contains exactly l lowercase Latin letters β the original string from which a player can delete palindromes. The line contains no other characters apart from the newline character at the end of the string.
Output
Print a single number β the maximum number of points one can gain if he plays on the given string.
Examples
Input
7
-1 -1 -1 -1 -1 -1 -1
abacaba
Output
0
Input
7
1 -1 -1 -1 -1 -1 -1
abacaba
Output
7
Input
7
1 5 -1 -1 -1 -1 10
abacaba
Output
16
Note
In the first sample we cannot delete any substring, so the best result is 0. In the second sample we are allowed to delete only those palindromes whose length equals 1, thus, if we delete the whole string, we get 7 points. In the third sample the optimal strategy is: first we delete character c, then string aa, then bb, and the last one aa. At that we get 1 + 3 * 5 = 16 points.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_35985 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\n1 5 -1 -1 -1 -1 10\nabacaba\n",
"output": "16\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n-1 -1 -1 -1 -1 -1 -1\nabacaba\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 -1 -1 -1 -1 -1 -1\nabacaba\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50\n0 0 11057 0 -1 -1 0 813 83956 34902 -1 -1 -1 -1 -1 24269 27949 77312 13114 0 94411 -1 -1 7470 -1 -1 -1 0 62769 32281 0 -1 0 -1 0 0 19677 44696 25806 0 -1 20689 -1 54344 0 10937 0 0 0 16997\nbabacbbbbacbaabcaacbaabbcacacacaacaacbbccbbcaaccca\n",
"output": "368995\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50\n0 11 0 26 32 44 54 -1 83 -1 117 -1 -1 -1 231 -1 292 332 368 392 439 493 538 586 616 667 722 -1 851 906 -1 -1 -1 1165 1227 -1 1372 1434 -1 1603 1673 1759 1841 1936 2028 2121 2205 2304 2393 -1\ncccbcbacbabbcabccabbabcbcabacbbabbcccacabbcacaccca\n",
"output": "1445\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n-1 -1 -1 58701 0 -1 -1 -1 -1 0 0 -1 68415 0 0 13034 -1 0 17995 -1 -1 0 53267 0 56188 -1 0 52354 -1 87127 10277 99477 -1 78787 -1 -1 0 -1 0 -1 64439 40035 0 37454 -1 86045 -1 0 -1 0 0 0 29954 4848 -1 0 0 20578 0 35894 0 0 0 83267 0 26081 -1 0 42668 -1 0 0 0 0 0 -1 0 0 38072 7248 81171 23882 -1 93014 -1 -1 8992 0 0 37264 81797 0 -1 0 -1 -1 0 -1 -1 -1\nacabcbacaaaaabccbbbbbcabacaccbcbbbbbccbccbcabaaccaabaabbabaacbaabcacccbccaaabcabbbbcbabbabacccacccab\n",
"output": "1174020\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 163_A. Substring and Subsequence | Solve the following coding problem using the programming language python:
One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences.
The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|.
A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 β€ a β€ b β€ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a β c or b β d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same.
A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 β€ p1 < p2 < ... < p|y| β€ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different.
Input
The input consists of two lines. The first of them contains s (1 β€ |s| β€ 5000), and the second one contains t (1 β€ |t| β€ 5000). Both strings consist of lowercase Latin letters.
Output
Print a single number β the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7).
Examples
Input
aa
aa
Output
5
Input
codeforces
forceofcode
Output
60
Note
Let's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from sys import stdin
s=[ord(i)-97 for i in stdin.readline().strip()]
s1=[ord(i)-97 for i in stdin.readline().strip()]
n=len(s)
m=len(s1)
mod=1000000007
dp=[[0 for i in range(n)] for j in range(26)]
for i in range(m):
arr=[0 for j in range(n)]
for j in range(n):
if s1[i]==s[j] :
arr[j]=1
if j>0 :
arr[j]=(arr[j]+dp[s[j-1]][j-1])%mod
for j in range(n):
dp[s1[i]][j]=(arr[j] +dp[s1[i]][j]) %mod
x=0
for i in dp:
for j in i:
x=(x+j)%mod
print(x)
``` | vfc_35993 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "codeforces\nforceofcode\n",
"output": "60\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aa\naa\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "bbabb\nbababbbbab\n",
"output": "222\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ab\nbbbba\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "xzzxxxzxzzzxzzzxxzzxzzxzxzxxzxxzxxzxzzxxzxxzxxxzxzxzxxzzxxxxzxzzzxxxzxzxxxzzxxzxxzxxzzxxzxxzxzxzzzxzzzzxzxxzzxzxxzxxzzxzxzx\nzzx\n",
"output": "291\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a\nb\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 183_B. Zoo | Solve the following coding problem using the programming language python:
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.
In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.
Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.
Input
The first line contains two space-separated integers n and m (1 β€ n β€ 106, 1 β€ m β€ 250), denoting the number of binoculars and the number of flamingos, respectively.
Then m lines follow, the i-th line will contain two space-separated integers xi and yi (1 β€ xi, yi β€ 109), which means that the i-th flamingo is located at point (xi, yi).
All flamingos will be located at distinct points.
Output
Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.
Examples
Input
5 5
2 1
4 1
3 2
4 3
4 4
Output
11
Note
This picture shows the answer to the example test case.
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b)
def normalize_rational(num,den):
#associate the -ve with the num or cancel -ve sign when both are -ve
if num ^ den < 0 and num > 0 or num ^ den > 0 and num < 0:
num = -num; den = -den
#put it in its simplest form
g = gcd(abs(num),abs(den))
num //= g; den //=g
return (num,den)
from sys import *
l = stdin.readline()
(n,m) = (int(tkn) for tkn in l.split())
xs = [0] * m; ys = [0] * m
#maxhits = [set() for i in range(n+1)]
maxhits = [1] * (n + 1)
maxhits[0] = 0
for i in range(m):
l = stdin.readline()
(x,y) = (int(tkn) for tkn in l.split())
xs[i] = x; ys[i] = y
line_to_points = {}
for i in range(m):
for j in range(m):
#m = dy/dx; y = (dy/dx)x + c ==> y.dx = x.dy + c.dx
#y.dx = x.dy + c'
#c' = y.dx - x.dy
#c' = ys[i]*dx - xs[i]*dy
#Now, at y = 0, x = -c' / dy
dy = ys[i] - ys[j]; dx = xs[i] - xs[j]
if dy == 0:
continue
#not a special case anymore
# if dx == 0:
# if xs[i] > n:
# continue
# else:
# count_seen_from_x = len([x for x in xs if x == xs[i]])
# maxhits[xs[i]] = max(count_seen_from_x, maxhits[xs[i]])
else:
slope = normalize_rational(dy,dx)
c_prime = ys[i]*dx - xs[i]*dy
x_intercept = -c_prime / dy
line = (slope,x_intercept)
if line in line_to_points:
#print("line: ", line)
#print("now: ", points)
points = line_to_points[line]
points.add(i); points.add(j)
#print("after addition: ", points)
continue
#if (i == 1 and j == 2):
# print(c_prime, x_intercept, dy, dx)
if int(x_intercept) == x_intercept and x_intercept <= n and x_intercept > 0:
points = set([i,j])
line_to_points[line] = points
#maxhits[int(x_intercept)] = points
# count_on_line = 2
# for k in range(m):
# if k != i and k != j and ys[k] * dx == xs[k]*dy + c_prime:
# count_on_line += 1
# maxhits[int(x_intercept)] = max(count_on_line, maxhits[int(x_intercept)])
for line,points in line_to_points.items():
x_intercept = int(line[1])
maxhits[x_intercept] = max(maxhits[x_intercept],len(points))
#print(maxhits)
#print(sum([max(len(points),1) for points in maxhits]) - 1)
print(sum(maxhits))
``` | vfc_35997 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 5\n2 1\n4 1\n3 2\n4 3\n4 4\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000 2\n194305 1024\n4388610 1023\n",
"output": "1000000\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 207_B1. Military Trainings | Solve the following coding problem using the programming language python:
The Smart Beaver from ABBYY started cooperating with the Ministry of Defence. Now they train soldiers to move armoured columns. The training involves testing a new type of tanks that can transmit information. To test the new type of tanks, the training has a special exercise, its essence is as follows.
Initially, the column consists of n tanks sequentially numbered from 1 to n in the order of position in the column from its beginning to its end. During the whole exercise, exactly n messages must be transferred from the beginning of the column to its end.
Transferring one message is as follows. The tank that goes first in the column transmits the message to some tank in the column. The tank which received the message sends it further down the column. The process is continued until the last tank receives the message. It is possible that not all tanks in the column will receive the message β it is important that the last tank in the column should receive the message.
After the last tank (tank number n) receives the message, it moves to the beginning of the column and sends another message to the end of the column in the same manner. When the message reaches the last tank (tank number n - 1), that tank moves to the beginning of the column and sends the next message to the end of the column, and so on. Thus, the exercise is completed when the tanks in the column return to their original order, that is, immediately after tank number 1 moves to the beginning of the column.
If the tanks were initially placed in the column in the order 1, 2, ..., n, then after the first message their order changes to n, 1, ..., n - 1, after the second message it changes to n - 1, n, 1, ..., n - 2, and so on.
The tanks are constructed in a very peculiar way. The tank with number i is characterized by one integer ai, which is called the message receiving radius of this tank.
Transferring a message between two tanks takes one second, however, not always one tank can transmit a message to another one. Let's consider two tanks in the column such that the first of them is the i-th in the column counting from the beginning, and the second one is the j-th in the column, and suppose the second tank has number x. Then the first tank can transmit a message to the second tank if i < j and i β₯ j - ax.
The Ministry of Defense (and soon the Smart Beaver) faced the question of how to organize the training efficiently. The exercise should be finished as quickly as possible. We'll neglect the time that the tanks spend on moving along the column, since improving the tanks' speed is not a priority for this training.
You are given the number of tanks, as well as the message receiving radii of all tanks. You must help the Smart Beaver and organize the transferring of messages in a way that makes the total transmission time of all messages as small as possible.
Input
The first line contains integer n β the number of tanks in the column. Each of the next n lines contains one integer ai (1 β€ ai β€ 250000, 1 β€ i β€ n) β the message receiving radii of the tanks in the order from tank 1 to tank n (let us remind you that initially the tanks are located in the column in ascending order of their numbers).
To get the full points for the first group of tests it is sufficient to solve the problem with 2 β€ n β€ 300.
To get the full points for the second group of tests it is sufficient to solve the problem with 2 β€ n β€ 10000.
To get the full points for the third group of tests it is sufficient to solve the problem with 2 β€ n β€ 250000.
Output
Print a single integer β the minimum possible total time of transmitting the messages.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3
2
1
1
Output
5
Input
5
2
2
2
2
2
Output
10
Note
In the first sample the original order of tanks is 1, 2, 3. The first tank sends a message to the second one, then the second tank sends it to the third one β it takes two seconds. The third tank moves to the beginning of the column and the order of tanks now is 3, 1, 2. The third tank sends a message to the first one, then the first one sends it to the second one β it takes two more seconds. The second tank moves to the beginning and the order of the tanks is now 2, 3, 1. With this arrangement, the second tank can immediately send a message to the first one, since the message receiving radius of the first tank is large enough β it takes one second. Finally, the tanks return to their original order 1, 2, 3. In total, the exercise takes 5 seconds.
In the second sample, all five tanks are the same and sending a single message takes two seconds, so in total the exercise takes 10 seconds.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36001 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n2\n2\n2\n2\n2\n",
"output": " 10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2\n1\n1\n",
"output": " 5\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 230_C. Shifts | Solve the following coding problem using the programming language python:
You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.
To cyclically shift a table row one cell to the right means to move the value of each cell, except for the last one, to the right neighboring cell, and to move the value of the last cell to the first cell. A cyclical shift of a row to the left is performed similarly, but in the other direction. For example, if we cyclically shift a row "00110" one cell to the right, we get a row "00011", but if we shift a row "00110" one cell to the left, we get a row "01100".
Determine the minimum number of moves needed to make some table column consist only of numbers 1.
Input
The first line contains two space-separated integers: n (1 β€ n β€ 100) β the number of rows in the table and m (1 β€ m β€ 104) β the number of columns in the table. Then n lines follow, each of them contains m characters "0" or "1": the j-th character of the i-th line describes the contents of the cell in the i-th row and in the j-th column of the table.
It is guaranteed that the description of the table contains no other characters besides "0" and "1".
Output
Print a single number: the minimum number of moves needed to get only numbers 1 in some column of the table. If this is impossible, print -1.
Examples
Input
3 6
101010
000100
100000
Output
3
Input
2 3
111
000
Output
-1
Note
In the first sample one way to achieve the goal with the least number of moves is as follows: cyclically shift the second row to the right once, then shift the third row to the left twice. Then the table column before the last one will contain only 1s.
In the second sample one can't shift the rows to get a column containing only 1s.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def solve(rows):
all_dists = [0 for _ in range(len(rows[0]))]
for r in rows:
dists = [len(r) for _ in r]
if '1' not in r:
return -1
start = r.index('1')
for i in range(len(r)):
right = (i+start)%len(r) # going right
left = (start+2*len(r)-i)%len(r) # going left
dists[right] = 0 if r[right]=='1' else min(dists[right],dists[(i+start-1)%len(r)]+1)
dists[left] = 0 if r[left]=='1' else min(dists[left],dists[(start+2*len(r)-i+1)%len(r)]+1)
for i,c in enumerate(r):
all_dists[i] += dists[i]
return min(all_dists)
if __name__ == "__main__":
n,m = (int(i) for i in input().split())
rows = [input() for _ in range(n)]
print(solve(rows))
``` | vfc_36005 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 6\n101010\n000100\n100000\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n111\n000\n",
"output": "-1",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 256_B. Mr. Bender and Square | Solve the following coding problem using the programming language python:
Mr. Bender has a digital table of size n Γ n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to n, and the columns β numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.
For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1).
In how many seconds will Mr. Bender get happy?
Input
The first line contains four space-separated integers n, x, y, c (1 β€ n, c β€ 109; 1 β€ x, y β€ n; c β€ n2).
Output
In a single line print a single integer β the answer to the problem.
Examples
Input
6 4 3 1
Output
0
Input
9 3 8 10
Output
2
Note
Initially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. <image>.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
x, y, n, c = 0, 0, 0, 0
def suma_impares(m):
return m * m
def suma_n(m):
return m * (m - 1) // 2
def cnt(t):
u, d, l, r = x + t, x - t, y - t, y + t
suma = t ** 2 + (t + 1) ** 2
if u > n: suma -= suma_impares(u - n)
if d < 1: suma -= suma_impares(1 - d)
if l < 1: suma -= suma_impares(1 - l)
if r > n: suma -= suma_impares(r - n)
if 1 - l > x - 1 and 1 - d > y - 1:
suma += suma_n(2 - l - x)
if r - n > x - 1 and 1 - d > n - y:
suma += suma_n(r - n - x + 1)
if 1 - l > n - x and u - n > y - 1:
suma += suma_n(1 - l - n + x)
if u - n > n - y and r - n > n - x:
suma += suma_n(u - n - n + y)
return suma
n, x, y, c = input().split()
n, x, y, c = int(n), int(x), int(y), int(c)
#for i in range(10):
# print(i, cnt(i))
ini, fin = 0, int(1e9)
cont = int(1e9)
while cont > 0:
m = ini
paso = cont // 2
m += paso
if cnt(m) < c:
ini = m + 1
cont -= paso + 1
else:
cont = paso
print(ini)
``` | vfc_36009 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9 3 8 10\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 4 3 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000 44 30 891773002\n",
"output": "42159\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000 999999938 999999936 384381709\n",
"output": "27600\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000 999999946 60 715189365\n",
"output": "37707\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000000 999999946 999999941 715189365\n",
"output": "37707\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 27_B. Tournament | Solve the following coding problem using the programming language python:
The tournament Β«Sleepyhead-2010Β» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. nΒ·(n - 1) / 2 games were played during the tournament, and each participant had a match with each other participant.
The rules of the game are quite simple β the participant who falls asleep first wins. The secretary made a record of each game in the form Β«xi yiΒ», where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws.
Recently researches form the Β«Institute Of SleepΒ» have found that every person is characterized by a value pj β the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life.
It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.
Input
The first line contains one integer n (3 β€ n β€ 50) β the number of participants. The following nΒ·(n - 1) / 2 - 1 lines contain the results of the games. Each game is described in a single line by two integers xi, yi (1 β€ xi, yi β€ n, xi β yi), where xi ΠΈ yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n - 1 games, one game with each other participant.
Output
Output two integers x and y β the missing record. If there are several solutions, output any of them.
Examples
Input
4
4 2
4 1
2 3
2 1
3 1
Output
4 3
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
a = int(input())
d = {}
f = {}
for i in range(a*(a-1)//2-1):
v, c = map(int, input().split())
if v not in f:
f[v] = []
f[v].append(c)
if v in d:
d[v] += 1
else:
d[v] = 1
if c in d:
d[c] += 1
else:
d[c] = 1
s = []
m = 0
for i in range(1, a + 1):
if d[i] > m:
m = d[i]
for i in range(1, a + 1):
if d[i] < m:
s.append(i)
m = 0
for i in range(1, a + 1):
if i not in s:
if s[0] in f and i in f and s[1] in f:
if i in f[s[1]] and s[0] in f[i]:
m = 1
s.reverse()
break
print(*s)
``` | vfc_36013 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n4 2\n4 1\n2 3\n2 1\n3 1\n",
"output": "4 3\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 302_A. Eugeny and Array | Solve the following coding problem using the programming language python:
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 β€ li β€ ri β€ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 β€ n, m β€ 2Β·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 β€ li β€ ri β€ n).
Output
Print m integers β the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from collections import Counter
num, cases = map(int, input().split())
arr = list(map(int, input().split()))
count = Counter(arr)
minus = count[-1]
plus = count[1]
mn = min(plus, minus)
ans = []
while cases:
cases -= 1
a, b = map(int, input().split())
if (b - a + 1) % 2 != 0:
ans.append(0)
elif (b - a + 1) // 2 <= mn:
ans.append(1)
else:
ans.append(0)
print(*ans)
``` | vfc_36017 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 5\n-1 1 1 1 -1\n1 1\n2 3\n3 5\n2 5\n1 5\n",
"output": "0\n1\n0\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n1 -1\n1 1\n1 2\n2 2\n",
"output": "0\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n-1 -1 -1 -1 -1\n1 1\n1 1\n3 4\n1 1\n1 4\n",
"output": "0\n0\n0\n0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 7\n-1 -1 -1 1 -1 -1 -1\n1 1\n2 7\n1 3\n1 5\n4 7\n1 7\n6 7\n",
"output": "0\n0\n0\n0\n0\n0\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 9\n-1 1 1 1 1 1 1 1 1\n1 7\n5 6\n1 4\n1 1\n1 1\n6 8\n1 1\n6 7\n3 5\n",
"output": "0\n1\n0\n0\n0\n0\n0\n1\n0\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 329_B. Biridian Forest | Solve the following coding problem using the programming language python:
You're a mikemon breeder currently in the middle of your journey to become a mikemon master. Your current obstacle is go through the infamous Biridian Forest.
The forest
The Biridian Forest is a two-dimensional grid consisting of r rows and c columns. Each cell in Biridian Forest may contain a tree, or may be vacant. A vacant cell may be occupied by zero or more mikemon breeders (there may also be breeders other than you in the forest). Mikemon breeders (including you) cannot enter cells with trees. One of the cells is designated as the exit cell.
The initial grid, including your initial position, the exit cell, and the initial positions of all other breeders, will be given to you. Here's an example of such grid (from the first example):
<image>
Moves
Breeders (including you) may move in the forest. In a single move, breeders may perform one of the following actions:
* Do nothing.
* Move from the current cell to one of the four adjacent cells (two cells are adjacent if they share a side). Note that breeders cannot enter cells with trees.
* If you are located on the exit cell, you may leave the forest. Only you can perform this move β all other mikemon breeders will never leave the forest by using this type of movement.
After each time you make a single move, each of the other breeders simultaneously make a single move (the choice of which move to make may be different for each of the breeders).
Mikemon battle
If you and t (t > 0) mikemon breeders are located on the same cell, exactly t mikemon battles will ensue that time (since you will be battling each of those t breeders once). After the battle, all of those t breeders will leave the forest to heal their respective mikemons.
Note that the moment you leave the forest, no more mikemon battles can ensue, even if another mikemon breeder move to the exit cell immediately after that. Also note that a battle only happens between you and another breeders β there will be no battle between two other breeders (there may be multiple breeders coexisting in a single cell).
Your goal
You would like to leave the forest. In order to do so, you have to make a sequence of moves, ending with a move of the final type. Before you make any move, however, you post this sequence on your personal virtual idol Blog. Then, you will follow this sequence of moves faithfully.
Goal of other breeders
Because you post the sequence in your Blog, the other breeders will all know your exact sequence of moves even before you make your first move. All of them will move in such way that will guarantee a mikemon battle with you, if possible. The breeders that couldn't battle you will do nothing.
Your task
Print the minimum number of mikemon battles that you must participate in, assuming that you pick the sequence of moves that minimize this number. Note that you are not required to minimize the number of moves you make.
Input
The first line consists of two integers: r and c (1 β€ r, c β€ 1000), denoting the number of rows and the number of columns in Biridian Forest. The next r rows will each depict a row of the map, where each character represents the content of a single cell:
* 'T': A cell occupied by a tree.
* 'S': An empty cell, and your starting position. There will be exactly one occurence of this in the map.
* 'E': An empty cell, and where the exit is located. There will be exactly one occurence of this in the map.
* A digit (0-9): A cell represented by a digit X means that the cell is empty and is occupied by X breeders (in particular, if X is zero, it means that the cell is not occupied by any breeder).
It is guaranteed that it will be possible for you to go from your starting position to the exit cell through a sequence of moves.
Output
A single line denoted the minimum possible number of mikemon battles that you have to participate in if you pick a strategy that minimize this number.
Examples
Input
5 7
000E0T3
T0TT0T0
010T0T0
2T0T0T0
0T0S000
Output
3
Input
1 4
SE23
Output
2
Note
The following picture illustrates the first example. The blue line denotes a possible sequence of moves that you should post in your blog:
<image>
The three breeders on the left side of the map will be able to battle you β the lone breeder can simply stay in his place until you come while the other two breeders can move to where the lone breeder is and stay there until you come. The three breeders on the right does not have a way to battle you, so they will stay in their place.
For the second example, you should post this sequence in your Blog:
<image>
Here's what happens. First, you move one cell to the right.
<image>
Then, the two breeders directly to the right of the exit will simultaneously move to the left. The other three breeder cannot battle you so they will do nothing.
<image>
You end up in the same cell with 2 breeders, so 2 mikemon battles are conducted. After those battles, all of your opponents leave the forest.
<image>
Finally, you make another move by leaving the forest.
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from sys import stdin
rints = lambda: [int(x) for x in stdin.readline().split()]
rstr = lambda: stdin.readline().strip()
rstr_2d = lambda n: [rstr() for _ in range(n)]
valid = lambda x, y: 0 <= x < n and 0 <= y < m and grid[x][y] != 'T'
dx, dy = [0, 1, 0, -1, 1, -1, 1, -1], [1, 0, -1, 0, 1, -1, -1, 1]
n, m = rints()
grid, ans, que, flag, vis = rstr_2d(n), 0, [], 0, set()
for i in range(n):
for j in range(m):
if grid[i][j] == 'E':
que.append((i, j))
vis.add((i, j))
break
while que:
que1 = []
while que:
x, y = que.pop()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if valid(nx, ny) and (nx, ny) not in vis:
que1.append((nx, ny))
vis.add((nx, ny))
if grid[nx][ny] == 'S':
flag = 1
try:
ans += int(grid[nx][ny])
except:
continue
if not flag:
que = que1
print(ans)
``` | vfc_36021 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 4\nSE23\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 7\n000E0T3\nT0TT0T0\n010T0T0\n2T0T0T0\n0T0S000\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10\n9T9TSET9T9\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n920\n752\nE8S\n",
"output": "29\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 34_E. Collisions | Solve the following coding problem using the programming language python:
On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored.
The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds will be:
<image>.
Your task is to find out, where each ball will be t seconds after.
Input
The first line contains two integers n and t (1 β€ n β€ 10, 0 β€ t β€ 100) β amount of balls and duration of the process. Then follow n lines, each containing three integers: xi, vi, mi (1 β€ |vi|, mi β€ 100, |xi| β€ 100) β coordinate, speed and weight of the ball with index i at time moment 0.
It is guaranteed that no two balls have the same coordinate initially. Also each collision will be a collision of not more than two balls (that is, three or more balls never collide at the same point in all times from segment [0;t]).
Output
Output n numbers β coordinates of the balls t seconds after. Output the numbers accurate to at least 4 digits after the decimal point.
Examples
Input
2 9
3 4 5
0 7 8
Output
68.538461538
44.538461538
Input
3 10
1 2 3
4 -5 6
7 -8 9
Output
-93.666666667
-74.666666667
-15.666666667
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
class Ball:
def __init__(self, x, v, m):
self.v = v
self.x = x
self.m = m
def move(self, time):
self.x += self.v * time
def collisionTime(self, other):
if self.v == other.v:
return float("inf")
t = - (self.x - other.x) / (self.v - other.v)
if t < 1e-9:
return float("inf")
return t
def __str__(self):
return "Ball(x={:.2f} v={:.2f} m={:.2f})".format(self.x, self.v, self.m)
def findFirst():
global nBalls, balls
minTime = float("inf")
minPairs = []
for i in range(nBalls):
for j in range(i + 1, nBalls):
time = balls[i].collisionTime(balls[j])
if time < minTime:
minTime = time
minPairs = [(i, j)]
elif abs(time - minTime) < 1e-9:
minPairs.append((i, j))
return minTime, minPairs
def collidePair(i, j):
global balls
v1 = balls[i].v
v2 = balls[j].v
m1 = balls[i].m
m2 = balls[j].m
balls[i].v = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2)
balls[j].v = ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2)
nBalls, maxTime = map(int, input().split())
balls = []
for i in range(nBalls):
x, v, m = map(int, input().split())
balls.append(Ball(x, v, m))
while True:
time, pairs = findFirst()
if time > maxTime:
break
for i in range(nBalls):
balls[i].move(time)
# print(time, maxTime)
for i, j in pairs:
collidePair(i, j)
# print(i, balls[i], j, balls[j])
# print()
maxTime -= time
for ball in balls:
ball.move(maxTime)
print("{:.6f}".format(ball.x))
``` | vfc_36025 | {
"difficulty": "11",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 9\n3 4 5\n0 7 8\n",
"output": "68.538461538\n44.538461538\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 374_A. Inna and Pink Pony | Solve the following coding problem using the programming language python:
Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n Γ m chessboard, a very tasty candy and two numbers a and b.
Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said he would give the candy if it reaches one of the corner cells of the board. He's got one more condition. There can only be actions of the following types:
* move the candy from position (x, y) on the board to position (x - a, y - b);
* move the candy from position (x, y) on the board to position (x + a, y - b);
* move the candy from position (x, y) on the board to position (x - a, y + b);
* move the candy from position (x, y) on the board to position (x + a, y + b).
Naturally, Dima doesn't allow to move the candy beyond the chessboard borders.
Inna and the pony started shifting the candy around the board. They wonder what is the minimum number of allowed actions that they need to perform to move the candy from the initial position (i, j) to one of the chessboard corners. Help them cope with the task!
Input
The first line of the input contains six integers n, m, i, j, a, b (1 β€ n, m β€ 106; 1 β€ i β€ n; 1 β€ j β€ m; 1 β€ a, b β€ 106).
You can assume that the chessboard rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to m from left to right. Position (i, j) in the statement is a chessboard cell on the intersection of the i-th row and the j-th column. You can consider that the corners are: (1, m), (n, 1), (n, m), (1, 1).
Output
In a single line print a single integer β the minimum number of moves needed to get the candy.
If Inna and the pony cannot get the candy playing by Dima's rules, print on a single line "Poor Inna and pony!" without the quotes.
Examples
Input
5 7 1 3 2 2
Output
2
Input
5 5 2 3 1 1
Output
Poor Inna and pony!
Note
Note to sample 1:
Inna and the pony can move the candy to position (1 + 2, 3 + 2) = (3, 5), from there they can move it to positions (3 - 2, 5 + 2) = (1, 7) and (3 + 2, 5 + 2) = (5, 7). These positions correspond to the corner squares of the chess board. Thus, the answer to the test sample equals two.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n, m, i, j, a, b = map(int, input().split())
corners = [(1, 1), (1, m), (n, 1), (n, m)]
result = False
ans = -1
for cnt in corners:
if (abs(cnt[0] - i) % a == 0) and (abs(cnt[1] - j) % b == 0):
result = True
t1, t2 = abs(cnt[0] - i) // a, abs(cnt[1] - j) // b
if (t1 + t2) % 2 == 0:
if ans == -1:
ans = max(abs(cnt[0] - i) // a, abs(cnt[1] - j) // b)
else:
ans = min(max(abs(cnt[0] - i) // a, abs(cnt[1] - j) // b), ans)
if ans == 0:
print(ans)
elif not result or (i+a > n and i-a < 1) or (j+b > m and j-b < 1) or ans == -1:
print("Poor Inna and pony!")
else:
print(ans)
``` | vfc_36029 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 5 2 3 1 1\n",
"output": "Poor Inna and pony!\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 7 1 3 2 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 6 1 2 2 2\n",
"output": "Poor Inna and pony!\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 100 50 50 500 500\n",
"output": "Poor Inna and pony!\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000 2 2 2 2 1\n",
"output": "499999\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 418_D. Big Problems for Organizers | Solve the following coding problem using the programming language python:
The Finals of the "Russian Code Cup" 2214 will be held in n hotels. Two hotels (let's assume that they are the main hotels), will host all sorts of events, and the remaining hotels will accommodate the participants. The hotels are connected by n - 1 roads, you can get from any hotel to any other one.
The organizers wonder what is the minimum time all the participants need to get to the main hotels, if each participant goes to the main hotel that is nearest to him and moving between two hotels connected by a road takes one unit of time.
The hosts consider various options for the location of the main hotels. For each option help the organizers to find minimal time.
Input
The first line contains an integer n (2 β€ n β€ 100000) β the number of hotels. The next n - 1 lines contain two integers each β the numbers of the hotels that have a road between them. Consider hotels are numbered from 1 to n.
The next line contains an integer m (1 β€ m β€ 100000) β the number of queries. The following m lines contains two distinct integers each β the numbers of the hotels we assume to be the main.
Output
For each request of the organizers print a single integer β the time that all participants need to reach the main hotels.
Examples
Input
3
2 3
3 1
3
2 1
2 3
3 1
Output
1
1
1
Input
4
1 4
1 2
2 3
3
1 4
1 3
2 3
Output
2
1
2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36037 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 4\n1 2\n2 3\n3\n1 4\n1 3\n2 3\n",
"output": "2\n1\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 3\n3 1\n3\n2 1\n2 3\n3 1\n",
"output": "1\n1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4 3\n3 1\n1 5\n5 2\n20\n4 3\n4 1\n4 5\n4 2\n3 4\n3 1\n3 5\n3 2\n1 4\n1 3\n1 5\n1 2\n5 4\n5 3\n5 1\n5 2\n2 4\n2 3\n2 1\n2 5\n",
"output": "3\n2\n1\n2\n3\n2\n1\n1\n2\n2\n2\n2\n1\n1\n2\n3\n2\n1\n2\n3\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 445_B. DZY Loves Chemistry | Solve the following coding problem using the programming language python:
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.
Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
Input
The first line contains two space-separated integers n and m <image>.
Each of the next m lines contains two space-separated integers xi and yi (1 β€ xi < yi β€ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.
Consider all the chemicals numbered from 1 to n in some order.
Output
Print a single integer β the maximum possible danger.
Examples
Input
1 0
Output
1
Input
2 1
1 2
Output
2
Input
3 2
1 2
2 3
Output
4
Note
In the first sample, there's only one way to pour, and the danger won't increase.
In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.
In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def iterative_dfs(graph, start, path=[]):
visited = {}
for i in graph:
visited[i] = []
q=[start]
while q:
v=q.pop(0)
if not visited[v]:
visited[v] = True
path=path+[v]
q=graph[v]+q
return path
nodes, edges = map(int, input().split(' '))
graph = {}
for i in range(nodes):
graph[i] = []
for i in range(edges):
a, b = map(int, input().split(' '))
graph[a-1].append(b-1)
graph[b-1].append(a-1)
marked = [False] * nodes
num = 0
for i in range(nodes):
if not marked[i]:
for j in iterative_dfs(graph, i):
marked[j] = True
num += 1
print(2**(nodes-num))
``` | vfc_36041 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2\n2 3\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "26 17\n1 2\n2 3\n1 6\n6 7\n7 8\n2 9\n4 10\n3 11\n11 12\n9 13\n6 14\n2 16\n5 18\n6 19\n11 22\n15 24\n6 26\n",
"output": "131072\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 5\n1 2\n1 3\n1 4\n5 6\n7 8\n",
"output": "32\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n1 8\n4 10\n4 6\n5 10\n2 3\n1 7\n3 4\n3 6\n6 9\n3 7\n",
"output": "512\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 467_C. George and Job | Solve the following coding problem using the programming language python:
The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.
Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers:
[l1, r1], [l2, r2], ..., [lk, rk] (1 β€ l1 β€ r1 < l2 β€ r2 < ... < lk β€ rk β€ n; ri - li + 1 = m),
in such a way that the value of sum <image> is maximal possible. Help George to cope with the task.
Input
The first line contains three integers n, m and k (1 β€ (m Γ k) β€ n β€ 5000). The second line contains n integers p1, p2, ..., pn (0 β€ pi β€ 109).
Output
Print an integer in a single line β the maximum possible value of sum.
Examples
Input
5 2 1
1 2 3 4 5
Output
9
Input
7 1 3
2 10 7 18 5 33 0
Output
61
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
p_a = [0 for _ in range(n)]
p_a[0] = a[0]
for i in range(1, n):
p_a[i] = p_a[i - 1] + a[i]
INF = -1e10
# print(p_a)
dp = {}
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def solve(i, k, m):
if (i, k, m) in dp:
yield dp[(i, k, m)]
if k == 0:
dp[(i, k, m)] = 0
yield 0
if i + m == n:
if k == 1:
# print(p_a[n - 1] - p_a[i - 1])
if i==0:
dp[(i, k, m)]=p_a[n - 1]
else:
dp[(i, k, m)] = p_a[n - 1] - p_a[i - 1]
yield dp[(i, k, m)]
if k > 1:
dp[(i, k, m)] = INF
yield INF
if i + m > n - 1:
dp[(i, k, m)] = INF
yield INF
if k == 0:
dp[(i, k, m)] = 0
yield 0
if i == 0:
a=yield solve(i + 1, k, m)
b=yield solve(i + m, k - 1, m)
dp[(i, k, m)] = max(a ,b+ p_a[i + m - 1])
yield dp[(i, k, m)]
else:
a = yield solve(i + 1, k, m)
b=yield solve(i + m, k - 1, m)
dp[(i, k, m)] = max(a, b+ p_a[i + m - 1] - p_a[i - 1])
yield dp[(i, k, m)]
if m==1:print(sum(sorted(a)[n-k:]))
else:
print(solve(0, k, m))
``` | vfc_36045 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2 1\n1 2 3 4 5\n",
"output": "9",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 1 3\n2 10 7 18 5 33 0\n",
"output": "61",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 48_F. Snow sellers | Solve the following coding problem using the programming language python:
The New Year celebrations in Berland last n days. Only this year the winter is snowless, thatβs why the winter celebrationsβ organizers should buy artificial snow. There are m snow selling companies in Berland. Every day the i-th company produces wi cubic meters of snow. Next day the snow thaws and the company has to produce wi cubic meters of snow again. During the celebration new year discounts are on, thatβs why the snow cost decreases every day. It is known that on the first day the total cost of all the snow produced by the i-th company is equal to ci bourles. Every day this total cost decreases by ai bourles, i.e. on the second day it is equal to ci - ai,and on the third day β to ci - 2ai, and so on. It is known that for one company the cost of the snow produced by it does not get negative or equal to zero. You have to organize the snow purchase so as to buy every day exactly W snow cubic meters. At that it is not necessary to buy from any company all the snow produced by it. If you buy ni cubic meters of snow (0 β€ ni β€ wi, the number ni is not necessarily integer!) from the i-th company at one of the days when the cost of its snow is equal to si, then its price will total to <image> bourles. During one day one can buy the snow from several companies. In different days one can buy the snow from different companies. It is required to make the purchases so as to spend as little money as possible. It is guaranteed that the snow produced by the companies will be enough.
Input
The first line contains integers n, m and W (1 β€ n β€ 100, 1 β€ m β€ 500000, 1 β€ W β€ 109) which represent the number of days, the number of companies and the amount of snow that needs to be purchased on every one of the n days. The second line contains m integers wi. The third line contains m integers ci. The fourth line contains m integers ai. All the numbers are strictly positive and do not exceed 109. For all the i the inequation ci - (n - 1)ai > 0 holds true.
Output
Print a single number β the answer to the given problem. Print the answer in the format with the decimal point (even if the answer is integer, it must contain the decimal point), without "e" and without leading zeroes. The answer should differ with the right one by no more than 10 - 9.
Examples
Input
2 3 10
4 4 4
5 5 8
1 2 5
Output
22.000000000000000
Input
100 2 1000000000
999999998 999999999
1000000000 1000000000
1 1
Output
99999995149.999995249999991
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36049 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 10, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3 10\n4 4 4\n5 5 8\n1 2 5\n",
"output": " 22.000000000000000",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100 2 1000000000\n999999998 999999999\n1000000000 1000000000\n1 1\n",
"output": "99999995149.999995249999987\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 100\n7 22 30 18 8 11 29 4 1 15\n739908515 103897339 292149487 627693889 321875108 621026883 878134409 301368128 491776213 273686163\n43011142 9735142 17133115 17374004 17689733 19577498 24702040 12144850 36321240 15773438\n",
"output": "13589342531.597701149425287\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 513_G1. Inversions problem | Solve the following coding problem using the programming language python:
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l β€ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 β€ n β€ 100, 1 β€ k β€ 109). The next line contains n integers p1, p2, ..., pn β the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 β€ n β€ 6, 1 β€ k β€ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 β€ n β€ 30, 1 β€ k β€ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 β€ n β€ 100, 1 β€ k β€ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n, k = map(int, input().split())
p = list(map(int, input().split()))
def count_invs(a):
ans = 0
for i in range(n-1):
for j in range(i + 1, n):
if a[i] > a[j]:
ans += 1
return ans
def inv_in_perms(a, count):
if count > 0:
ans = 0
for l in range(n):
for r in range(l, n):
a[l: r + 1] = a[l: r + 1][::-1]
ans += inv_in_perms(a, count - 1)
a[l: r + 1] = a[l: r + 1][::-1]
return(ans)
else:
return(count_invs(a))
total = (n * (n + 1) // 2) ** k
perms = 0
print(inv_in_perms(p, k) / total)
``` | vfc_36053 | {
"difficulty": "13",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1\n1 2 3\n",
"output": "0.83333333333333\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 4\n1 3 2\n",
"output": "1.45833333333333\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 53_D. Physical Education | Solve the following coding problem using the programming language python:
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 β€ n β€ 300) which is the number of students. The second line contains n space-separated integers ai (1 β€ ai β€ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 β€ bi β€ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 β€ k β€ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 β€ pi β€ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
n = int(sys.stdin.readline ())
a= [int (x) for x in sys.stdin.readline ().split ()]
assert len(a) == n
b = [int (x) for x in sys.stdin.readline ().split ()]
assert len(b) == n
ans = []
for i in range (n):
j = i;
while b[j] != a[i] :
j += 1
while j > i:
ans += [(j, j + 1)]
b[j - 1], b[j] = b[j], b[j - 1]
j -= 1
print (len(ans))
for p, q in ans:
print (p, + q)
``` | vfc_36057 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 100500\n1 100500\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 2 3 2\n3 2 1 2\n",
"output": "3\n2 3\n1 2\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n800950546\n800950546\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n873725529\n873725529\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n344379439 344379439\n344379439 344379439\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n470138369 747764103 729004864 491957578 874531368\n874531368 729004864 491957578 747764103 470138369\n",
"output": "9\n4 5\n3 4\n2 3\n1 2\n4 5\n3 4\n2 3\n3 4\n4 5\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 567_F. Mausoleum | Solve the following coding problem using the programming language python:
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 Γ 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then β non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 β€ xi, yi β€ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 β€ n β€ 35, 0 β€ k β€ 100) β the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 β€ xi, yi β€ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
a,c,b = input().split()
a,b = int(a), int(b)
if c=="=":
if a==b:
continue
if (e[a] and e[a]!=b) or (e[b] and e[b]!=a):
ok = 0
e[a], e[b] = b,a
if c=="<":
a,b,c = b,a,">"
if c==">":
l[a].append(b)
if c=="<=":
a,b,c = b,a,">="
if c==">=":
le[a].append(b)
def check(i, j, a, b):
if e[a] and e[a]!=a and e[a]!=b:
return 0
for x in l[a]:
if x>i and x<j:
return 0
for x in le[a]:
if x>i and x<j and x!=a and x!=b:
return 0
return 1
dp = [[0]*n for i in range(n)]
dp[0][n-1] = 1
ans = 0
for i in range(n):
for j in range(n-1,i,-1):
if i+1==j:
ans+=dp[i][j]
elif ((i+j)%2)==1:
if check(i,j,i+1,i+2) and check(i,j,i+2,i+1):
dp[i+2][j]+=dp[i][j]
if i+3<j and check(i,j,j-2,j-1) and check(i,j,j-1,j-2):
dp[i][j-2]+=dp[i][j]
if i+3<j and check(i,j,i+1,j-1) and check(i,j,j-1,i+1):
dp[i+1][j-1]+=dp[i][j]
print(ans if ok else 0)
``` | vfc_36061 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 0\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n3 = 6\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n2 > 3\n",
"output": " 9\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 589_b | Solve the following coding problem using the programming language python:
Dasha decided to bake a big and tasty layer cake. In order to do that she went shopping and bought n rectangular cake layers. The length and the width of the i-th cake layer were ai and bi respectively, while the height of each cake layer was equal to one.
From a cooking book Dasha learned that a cake must have a form of a rectangular parallelepiped constructed from cake layers of the same sizes.
Dasha decided to bake the biggest possible cake from the bought cake layers (possibly, using only some of them). It means that she wants the volume of the cake to be as big as possible. To reach this goal, Dasha can cut rectangular pieces out of the bought cake layers. She always cuts cake layers in such a way that cutting lines are parallel to the edges of that cake layer. Dasha isn't very good at geometry, so after cutting out a piece from the original cake layer, she throws away the remaining part of it. Also she can rotate a cake layer in the horizontal plane (swap its width and length).
Dasha wants her cake to be constructed as a stack of cake layers of the same sizes. Each layer of the resulting cake should be made out of only one cake layer (the original one or cut out from the original cake layer).
Help Dasha to calculate the maximum possible volume of the cake she can bake using given cake layers.
Input
The first line contains an integer n (1ββ€βnββ€β4000)Β β the number of cake layers that Dasha can use.
Each of the following n lines contains two integer numbers ai and bi (1ββ€βai,βbiββ€β10^6)Β β the length and the width of i-th cake layer respectively.
Output
The first line of the output should contain the maximum volume of cake that can be baked using given layers.
The second line of the output should contain the length and the width of the resulting cake. If there are many solutions with maximum possible volume, print any of them.
Examples
Input
5
5 12
1 1
4 6
6 4
4 6
Output
96
6 4
Input
2
100001 900000
900001 100000
Output
180000000000
900000 100000
Note
In the first example Dasha doesn't use the second cake layer. She cuts 4βΓβ6 rectangle from the first cake layer and she uses other cake layers as is.
In the second example Dasha cuts off slightly from the both cake layers.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
#coding:utf-8
n = int(raw_input())
cakes = []
for i in xrange(n):
cakes.append(sorted(map(int, raw_input().split())))
#print cakes
cakes.sort(key = lambda x:x[0])
ans = 0
w = []
for i in xrange(n-1,-1,-1):
w.append(cakes[i][1])
w.sort()
for j in xrange(len(w)):
tmp = cakes[i][0]*w[j]*(len(w)-j)
if ans < tmp:
ans = tmp
length = cakes[i][0]
width = w[j]
print ans
print length,width
``` | vfc_36065 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n5 12\n1 1\n4 6\n6 4\n4 6",
"output": "96\n6 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n100001 900000\n900001 100000",
"output": "180000000000\n900000 100000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000\n1000000 1000000",
"output": "10000000000000\n1000000 1000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n7 7\n10 8\n7 7\n5 10\n7 7",
"output": "196\n7 7\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 630_O. Arrow | Solve the following coding problem using the programming language python:
Petya has recently started working as a programmer in the IT city company that develops computer games.
Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to paint different arrows on the screen.
A user of this tool will choose a point on the screen, specify a vector (the arrow direction) and vary several parameters to get the required graphical effect. In the first version of the program Petya decided to limit parameters of the arrow by the following: a point with coordinates (px, py), a nonzero vector with coordinates (vx, vy), positive scalars a, b, c, d, a > c.
The produced arrow should have the following properties. The arrow consists of a triangle and a rectangle. The triangle is isosceles with base of length a and altitude of length b perpendicular to the base. The rectangle sides lengths are c and d. Point (px, py) is situated in the middle of the triangle base and in the middle of side of rectangle that has length c. Area of intersection of the triangle and the rectangle is zero. The direction from (px, py) point to the triangle vertex opposite to base containing the point coincides with direction of (vx, vy) vector.
Enumerate the arrow points coordinates in counter-clockwise order starting from the tip.
<image>
Input
The only line of the input contains eight integers px, py, vx, vy ( - 1000 β€ px, py, vx, vy β€ 1000, vx2 + vy2 > 0), a, b, c, d (1 β€ a, b, c, d β€ 1000, a > c).
Output
Output coordinates of the arrow points in counter-clockwise order. Each line should contain two coordinates, first x, then y. Relative or absolute error should not be greater than 10 - 9.
Examples
Input
8 8 0 2 8 3 4 5
Output
8.000000000000 11.000000000000
4.000000000000 8.000000000000
6.000000000000 8.000000000000
6.000000000000 3.000000000000
10.000000000000 3.000000000000
10.000000000000 8.000000000000
12.000000000000 8.000000000000
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from math import atan2, pi
EPS = 0.00000001
def eq(a, b):
return abs(a - b) < EPS
class Vector:
def __init__(self, x2, y2, x1=0, y1=0):
self.x = (x2 - x1)
self.y = y2 - y1
self.s = (self.x ** 2 + self.y ** 2) ** 0.5
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def mul_k(self, k):
self.x *= k
self.y *= k
def mul_kk(self, k):
return Vector(self.x * k, self.y * k)
def rotate(self):
return Vector(-self.y, self.x)
def rotate2(self):
return self.rotate().rotate().rotate()
def reverseee(self):
return Vector(-self.x, -self.y)
def __mul__(self, other):
return self.x * other.x + self.y * other.y
def vectormul(self, other):
return self.x * other.y - self.y * other.x
def get_angle(self, other):
return atan2(self.vectormul(other), self * other)
def norm(self):
if self.s == 0:
return Vector(self.x, self.y)
return Vector(self.x / self.s, self.y / self.s)
def __str__(self):
return f'{self.x} {self.y}'
def middle(self, point):
return Vector((self.x + point.x) / 2, (self.y + point.y) / 2)
class Line:
def __init__(self, point=None, vector=None, point2=None, a=None, b=None, c=None):
if a is not None:
self.v = Vector(a, b).rotate()
self.p = Vector(a, b)
self.p.mul_k(-c / (a ** 2 + b ** 2))
self.A = a
self.B = b
self.C = c
return
if vector is None:
vector = point2 - point
self.p = point
self.v = vector
self.A = self.v.y
self.B = -self.v.x
self.C = - self.A * self.p.x - self.p.y * self.B
def get_abc(self):
return self.A, self.B, self.C
def __str__(self):
return str(self.A) + ' ' + str(self.B) + ' ' + str(self.C)
def check(self, point):
return eq(- point.x * self.A - self.B * point.y, self.C)
def get_s_from_point(self, point):
v = self.v.norm()
v2 = point - self.p
a = v * v2
v.mul_k(a)
v3 = v + self.p
s = v3 - point
return s.s
def get_bisect(self, line):
return Line(point=self.get_peresech(line)[1], vector=self.v.norm() + line.v.norm())
def get_proection(self, point):
v = self.v.norm()
v2 = point - self.p
a = v * v2
v.mul_k(a)
v3 = v + self.p
return v3
def get_paral_line(self, le):
v = self.v.norm().rotate()
v.mul_k(le)
return Line(point=self.p + v, vector=self.v)
def get_peresech(self, lin):
u = lin.v.rotate()
a = self.v * u
if eq(a, 0):
if eq(self.get_s_from_point(lin.p), 0):
return (2,)
return (0,)
t = ((lin.p - self.p) * u) / (self.v * u)
v = Vector(self.v.x, self.v.y)
v.mul_k(t)
return (1, self.p + v)
def get_mirror(self, point):
v = self.v.norm()
v2 = point - self.p
a = v * v2
v.mul_k(a)
v3 = v + self.p
s = v3 - point
return s + v3
def is_on_line(v1, v2):
return eq(v1.vectormul(v2), 0)
def is_on_luch(v1, v2):
return eq(v1.get_angle(v2), 0)
def is_on_otr(v1, v2, v3, v4):
return eq(v1.get_angle(v2), 0) and eq(v3.get_angle(v4), 0)
def get_s_from_luch(xp, yp, x1, y1, x2, y2):
v = Vector(x2, y2, x1, y1).norm()
v2 = Vector(xp, yp, x1, y1)
a = v * v2
v1 = Vector(x2, y2, x1, y1)
v.mul_k(a)
v3 = v + Vector(x1, y1)
xh, yh = v3.x, v3.y
v4 = Vector(xh, yh, x1, y1)
b = v1.get_angle(v4)
if eq(b, 0):
se = v3 - Vector(xp, yp)
return se.s
else:
return (Vector(x1, y1) - Vector(xp, yp)).s
def get_s_from_otr(xp, yp, x1, y1, x2, y2):
return max(get_s_from_luch(xp, yp, x1, y1, x2, y2), get_s_from_luch(xp, yp, x2, y2, x1, y1))
def get_s_from_line(xp, yp, x1, y1, x2, y2):
v = Vector(x2, y2, x1, y1).norm()
v2 = Vector(xp, yp, x1, y1)
a = v * v2
return a
def peresec_otr(x1, y1, x2, y2, x3, y3, x4, y4):
AB = Vector(x2, y2, x1, y1)
CD = Vector(x4, y4, x3, y3)
AC = Vector(x3, y3, x1, y1)
AD = Vector(x4, y4, x1, y1)
CA = Vector(x1, y1, x3, y3)
CB = Vector(x2, y2, x3, y3)
yg1 = AB.get_angle(AD)
yg2 = AB.get_angle(AC)
yg3 = CD.get_angle(CA)
yg4 = CD.get_angle(CB)
flag = False
if (yg1 < 0 and yg2 < 0) or (yg1 > 0 and yg2 > 0):
flag = True
if (yg3 < 0 and yg4 < 0) or (yg3 > 0 and yg4 > 0):
flag = True
if max(min(x1, x2), min(x3, x4)) > min(max(x1, x2), max(x3, x4)):
flag = True
if max(min(y1, y2), min(y3, y4)) > min(max(y1, y2), max(y3, y4)):
flag = True
return not flag
def get_s_from_otr_to_otr(x1, y1, x2, y2, x3, y3, x4, y4):
if peresec_otr(x1, y1, x2, y2, x3, y3, x4, y4):
return 0
return min(get_s_from_otr(x1, y1, x3, y3, x4, y4), get_s_from_otr(x2, y2, x3, y3, x4, y4),
get_s_from_otr(x3, y3, x1, y1, x2, y2), get_s_from_otr(x4, y4, x1, y1, x2, y2))
def main():
px, py, vx, vy, a, b, c, d = map(int, input().split())
P = Vector(px, py)
V = Vector(vx, vy).norm()
A = V.mul_kk(b) + P
B = V.mul_kk(a/2).rotate() + P
C = V.mul_kk(c/2).rotate() + P
D = C + V.rotate().rotate().mul_kk(d)
E = D + V.rotate2().mul_kk(c)
F = P + V.rotate2().mul_kk(c/2)
G = P + V.rotate2().mul_kk(a/2)
print(A, B, C, D, E, F, G, sep='\n')
main()
``` | vfc_36073 | {
"difficulty": "22",
"memory_limit": null,
"memory_limit_bytes": 64000000,
"problem_url": null,
"time_limit": "{'seconds': 0, 'nanos': 500000000}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8 8 0 2 8 3 4 5\n",
"output": "8.0000000000000000000000000 11.0000000000000000000000000\n4.0000000000000000000000000 8.0000000000000000000000000\n6.0000000000000000000000000 8.0000000000000000000000000\n6.0000000000000000000000000 3.0000000000000000000000000\n10.0000000000000000000000000 3.0000000000000000000000000\n10.0000000000000000000000000 8.0000000000000000000000000\n12.0000000000000000000000000 8.0000000000000000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10 -7 0 5 8 2 11\n",
"output": "2.0000000000000000000000000 10.0000000000000000000000000\n10.0000000000000000000000000 7.5000000000000000000000000\n10.0000000000000000000000000 9.0000000000000000000000000\n21.0000000000000000000000000 9.0000000000000000000000000\n21.0000000000000000000000000 11.0000000000000000000000000\n10.0000000000000000000000000 11.0000000000000000000000000\n10.0000000000000000000000000 12.5000000000000000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "870 396 187 223 444 202 222 732\n",
"output": "999.7945324433952405951409048 550.7817151597707949206572664\n699.8933625471825917263579697 538.6454762496719970710223890\n784.9466812735912958354234092 467.3227381248359985355111945\n314.6021379638620081853339627 -93.5694178006700504057757684\n484.7087754166794164589759930 -236.2148940503420475045537330\n955.0533187264087041645765908 324.6772618751640014644888055\n1040.1066374528174083291531815 253.3545237503280029150998232\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 659_G. Fence Divercity | Solve the following coding problem using the programming language python:
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).
Input
The first line contains integer n (1 β€ n β€ 1 000 000) β the number of boards in Vasily's fence.
The second line contains n space-separated numbers h1, h2, ..., hn (1 β€ hi β€ 109), where hi equals the height of the i-th board to the left.
Output
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
Examples
Input
2
1 1
Output
0
Input
3
3 4 2
Output
13
Note
From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.
All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
mod = 10 ** 9 + 7
n = int(input())
h = list(map(lambda x: int(x) - 1, input().split()))
ans = x = 0
for i in range(n):
ans += h[i] + min(h[i], h[i - 1]) * x
if i < n - 1:
x *= min(h[i - 1], h[i], h[i + 1])
x += min(h[i], h[i + 1])
ans %= mod
x %= mod
print(ans)
``` | vfc_36077 | {
"difficulty": "13",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 4 2\n",
"output": "13",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 682_D. Alyona and Strings | Solve the following coding problem using the programming language python:
After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.
Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants.
Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions:
* s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty);
* t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty);
* sum of the lengths of strings in sequence is maximum possible.
Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.
A substring of a string is a subsequence of consecutive characters of the string.
Input
In the first line of the input three integers n, m, k (1 β€ n, m β€ 1000, 1 β€ k β€ 10) are given β the length of the string s, the length of the string t and Alyona's favourite number respectively.
The second line of the input contains string s, consisting of lowercase English letters.
The third line of the input contains string t, consisting of lowercase English letters.
Output
In the only line print the only non-negative integer β the sum of the lengths of the strings in a desired sequence.
It is guaranteed, that at least one desired sequence exists.
Examples
Input
3 2 2
abc
ab
Output
2
Input
9 12 4
bbaaababb
abbbabbaaaba
Output
7
Note
The following image describes the answer for the second sample case:
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n, m, k = map(int, input().split())
s, t = input(), input()
n += 1
m += 1
p = [i for i in range(n * m - n) if (i + 1) % n]
r = p[::-1]
d = [0] * n * m
for i in p:
if s[i % n] == t[i // n]: d[i] = d[i - n - 1] + 1
f = d[:]
for y in range(k - 1):
for i in p: f[i] = max(f[i], f[i - 1], f[i - n])
for i in r: f[i] = f[i - d[i] * (n + 1)] + d[i]
print(max(f))
``` | vfc_36081 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "9 12 4\nbbaaababb\nabbbabbaaaba\n",
"output": "7",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2 2\nabc\nab\n",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "120 362 6\ncaaccbbbabbbcbaacbaccacaaccacaaababccaccaabaccacccbbaaaaababbccbbacccaacabacbaaacabbacbabcccbccbcbbcaabaaabaabcccaabacbb\nabcbbaaccbbcabbcbbcacbabaacbaaacabcbabcabbabccbcaaacaccaaabbcbaacccccbcabacaacabbbcabaabcbbccabacbaaaacbbbbbccabccccbababcbacbbbcbbaabcaabcacbaaaaaccbaabbabacbcbbbaabbbcabcaacbcccbcbbacababbcaababcbbbbbbcbbaaaababacabcbbcbbaccccbcacccabbbabccabcabacccbbbcaccaccaacacaabacaabccccaabccccaabaccbabcaabbcbbccccbbabccbbccbaacaccabbacacabbacccbbaaacaabacccbcbacbcbcaca\n",
"output": "43",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "279 89 9\nbbbbaabbbbabaaaabbbababbaabbaabaaabababaabbaaaaabaababbbaababaaaaaabaababababbaaaababaaaabaaaaabaaaaaababbabaaababaaabbbabaaabaaabbbaabbaabaababbaaaaabaaabbabababababbaabbabbbaaababbbabbaaabaaabaaababaaabbaaaabababbabbabaabaabbbabbbabbbaababbabaaabaabbaabaabaaaaaaaabbbaabbbbabba\nabaaaabbabbbbaabaaaabbbbbbbbbbaaababaabaabbaaabbaabababababbbabaaabaaababbbbbbabbaabbbaba\n",
"output": "71",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 705_C. Thor | Solve the following coding problem using the programming language python:
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are about to happen (in chronological order). They are of three types:
1. Application x generates a notification (this new notification is unread).
2. Thor reads all notifications generated so far by application x (he may re-read some notifications).
3. Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation.
Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.
Input
The first line of input contains two integers n and q (1 β€ n, q β€ 300 000) β the number of applications and the number of events to happen.
The next q lines contain the events. The i-th of these lines starts with an integer typei β type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 β€ typei β€ 3, 1 β€ xi β€ n, 1 β€ ti β€ q).
Output
Print the number of unread notifications after each event.
Examples
Input
3 4
1 3
1 1
1 2
2 3
Output
1
2
3
2
Input
4 6
1 2
1 4
1 2
3 3
1 3
1 3
Output
1
2
3
0
1
2
Note
In the first sample:
1. Application 3 generates a notification (there is 1 unread notification).
2. Application 1 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads the notification generated by application 3, there are 2 unread notifications left.
In the second sample test:
1. Application 2 generates a notification (there is 1 unread notification).
2. Application 4 generates a notification (there are 2 unread notifications).
3. Application 2 generates a notification (there are 3 unread notifications).
4. Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.
5. Application 3 generates a notification (there is 1 unread notification).
6. Application 3 generates a notification (there are 2 unread notifications).
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import collections
import copy
n, q = map(int, input().split())
Q = collections.deque()
A = n * [0]
B = copy.copy(A)
L = []
s = n = 0
for _ in range(q):
y, x = map(int, input().split())
if 2 > y:
x -= 1
Q.append(x)
B[x] += 1
A[x] += 1
s += 1
elif 3 > y:
x -= 1
s -= A[x]
A[x] = 0
else:
while x > n:
n += 1
y = Q.popleft()
B[y] -= 1
if B[y] < A[y]:
A[y] -= 1
s -= 1
L.append(str(s))
print('\n'.join(L))
``` | vfc_36085 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 6\n1 2\n1 4\n1 2\n3 3\n1 3\n1 3\n",
"output": "1\n2\n3\n0\n1\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 4\n1 3\n1 1\n1 2\n2 3\n",
"output": "1\n2\n3\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "300000 1\n1 300000\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 85\n2 2\n1 10\n1 1\n2 6\n1 2\n1 4\n1 7\n2 1\n1 1\n3 3\n1 9\n1 6\n1 8\n1 10\n3 8\n2 8\n1 6\n1 3\n1 9\n1 6\n1 3\n1 8\n1 1\n1 6\n1 10\n2 1\n2 10\n1 10\n1 1\n1 10\n1 6\n1 2\n1 8\n1 3\n1 4\n1 9\n1 5\n1 5\n2 2\n2 4\n1 7\n1 1\n2 4\n1 9\n1 1\n1 7\n1 8\n3 33\n1 10\n2 2\n1 3\n1 10\n1 6\n3 32\n2 3\n1 5\n2 10\n2 2\n2 4\n2 3\n3 16\n1 3\n2 2\n1 1\n3 18\n2 2\n2 5\n1 5\n1 9\n2 4\n1 3\n1 4\n1 3\n1 6\n1 10\n2 2\n1 7\n1 7\n2 8\n1 1\n3 1\n1 8\n1 10\n1 7\n1 8\n",
"output": "0\n1\n2\n2\n3\n4\n5\n4\n5\n3\n4\n5\n6\n7\n2\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n9\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n17\n16\n17\n18\n18\n19\n20\n21\n22\n3\n4\n4\n5\n6\n7\n7\n6\n7\n5\n5\n5\n5\n5\n6\n6\n7\n7\n7\n6\n7\n8\n8\n9\n10\n11\n12\n13\n13\n14\n15\n14\n15\n15\n16\n17\n18\n19\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 85\n2 2\n1 10\n1 1\n2 6\n1 2\n1 4\n1 7\n2 1\n1 1\n3 3\n1 9\n1 6\n1 8\n1 10\n3 8\n2 8\n1 6\n1 3\n1 9\n1 6\n1 3\n1 6\n1 1\n1 6\n1 10\n2 1\n2 10\n1 10\n1 1\n1 10\n1 6\n1 2\n1 8\n1 3\n1 4\n1 9\n1 5\n1 5\n2 2\n2 4\n1 7\n1 1\n2 4\n1 9\n1 1\n1 7\n1 8\n3 33\n1 10\n2 2\n1 3\n1 10\n1 6\n3 32\n2 3\n1 5\n2 10\n2 2\n2 4\n2 3\n3 16\n1 3\n2 2\n1 1\n3 18\n2 2\n2 5\n1 5\n1 9\n2 4\n1 3\n1 4\n1 3\n1 6\n1 10\n2 2\n1 7\n1 7\n2 8\n1 1\n3 1\n1 8\n1 10\n1 7\n1 8\n",
"output": "0\n1\n2\n2\n3\n4\n5\n4\n5\n3\n4\n5\n6\n7\n2\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n9\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n17\n16\n17\n18\n18\n19\n20\n21\n22\n3\n4\n4\n5\n6\n7\n7\n6\n7\n5\n5\n5\n5\n5\n6\n6\n7\n7\n7\n6\n7\n8\n8\n9\n10\n11\n12\n13\n13\n14\n15\n14\n15\n15\n16\n17\n18\n19\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 85\n2 2\n1 10\n1 1\n2 6\n1 2\n1 4\n1 7\n2 1\n1 1\n3 3\n1 9\n1 6\n1 8\n1 10\n3 8\n2 8\n1 6\n1 3\n1 9\n1 6\n1 3\n1 6\n1 1\n1 6\n1 10\n2 1\n2 10\n1 10\n1 1\n1 10\n1 6\n1 2\n1 8\n1 3\n1 4\n1 9\n1 5\n1 5\n2 2\n2 4\n1 7\n1 1\n2 4\n1 9\n1 2\n1 7\n1 8\n3 33\n1 10\n2 2\n1 3\n1 10\n1 6\n3 32\n2 3\n1 5\n2 10\n2 2\n2 4\n2 3\n3 16\n1 3\n2 2\n1 1\n3 18\n2 2\n2 5\n1 5\n1 9\n2 4\n1 3\n1 4\n1 3\n1 6\n1 10\n2 2\n1 7\n1 7\n2 8\n1 1\n3 1\n1 8\n1 10\n1 7\n1 8\n",
"output": "0\n1\n2\n2\n3\n4\n5\n4\n5\n3\n4\n5\n6\n7\n2\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n9\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n17\n16\n17\n18\n18\n19\n20\n21\n22\n3\n4\n3\n4\n5\n6\n6\n5\n6\n4\n4\n4\n4\n4\n5\n5\n6\n6\n6\n5\n6\n7\n7\n8\n9\n10\n11\n12\n12\n13\n14\n13\n14\n14\n15\n16\n17\n18\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 727_F. Polycarp's problems | Solve the following coding problem using the programming language python:
Polycarp is an experienced participant in Codehorses programming contests. Now he wants to become a problemsetter.
He sent to the coordinator a set of n problems. Each problem has it's quality, the quality of the i-th problem is ai (ai can be positive, negative or equal to zero). The problems are ordered by expected difficulty, but the difficulty is not related to the quality in any way. The easiest problem has index 1, the hardest problem has index n.
The coordinator's mood is equal to q now. After reading a problem, the mood changes by it's quality. It means that after the coordinator reads a problem with quality b, the value b is added to his mood. The coordinator always reads problems one by one from the easiest to the hardest, it's impossible to change the order of the problems.
If after reading some problem the coordinator's mood becomes negative, he immediately stops reading and rejects the problemset.
Polycarp wants to remove the minimum number of problems from his problemset to make the coordinator's mood non-negative at any moment of time. Polycarp is not sure about the current coordinator's mood, but he has m guesses "the current coordinator's mood q = bi".
For each of m guesses, find the minimum number of problems Polycarp needs to remove so that the coordinator's mood will always be greater or equal to 0 while he reads problems from the easiest of the remaining problems to the hardest.
Input
The first line of input contains two integers n and m (1 β€ n β€ 750, 1 β€ m β€ 200 000) β the number of problems in the problemset and the number of guesses about the current coordinator's mood.
The second line of input contains n integers a1, a2, ..., an ( - 109 β€ ai β€ 109) β the qualities of the problems in order of increasing difficulty.
The third line of input contains m integers b1, b2, ..., bm (0 β€ bi β€ 1015) β the guesses of the current coordinator's mood q.
Output
Print m lines, in i-th line print single integer β the answer to the problem with q = bi.
Example
Input
6 3
8 -5 -4 1 -7 4
0 7 3
Output
2
0
1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36089 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 3\n8 -5 -4 1 -7 4\n0 7 3\n",
"output": "2 0 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n0 0 -1 0 1\n1 0 1 5 8\n",
"output": "0 1 0 0 0 ",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 749_A. Bachgold Problem | Solve the following coding problem using the programming language python:
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors β 1 and k.
Input
The only line of the input contains a single integer n (2 β€ n β€ 100 000).
Output
The first line of the output contains a single integer k β maximum possible number of primes in representation.
The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.
Examples
Input
5
Output
2
2 3
Input
6
Output
3
2 2 2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n=int(input())
c=0
if(n%2==1):
n-=3
l=[2]*(n//2)
l.append(3)
print(len(l))
print(*l)
else:
l=[2]*(n//2)
print(len(l))
print(*l)
``` | vfc_36093 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n",
"output": "3\n2 2 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "2\n2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15326\n",
"output": "7663\n2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "23\n",
"output": "11\n2 2 2 2 2 2 2 2 2 2 3\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 796_F. Sequence Recovery | Solve the following coding problem using the programming language python:
Zane once had a good sequence a consisting of n integers a1, a2, ..., an β but he has lost it.
A sequence is said to be good if and only if all of its integers are non-negative and do not exceed 109 in value.
<image>
However, Zane remembers having played around with his sequence by applying m operations to it.
There are two types of operations:
1. Find the maximum value of integers with indices i such that l β€ i β€ r, given l and r.
2. Assign d as the value of the integer with index k, given k and d.
After he finished playing, he restored his sequence to the state it was before any operations were applied. That is, sequence a was no longer affected by the applied type 2 operations. Then, he lost his sequence at some time between now and then.
Fortunately, Zane remembers all the operations and the order he applied them to his sequence, along with the distinct results of all type 1 operations. Moreover, among all good sequences that would produce the same results when the same operations are applied in the same order, he knows that his sequence a has the greatest cuteness.
We define cuteness of a sequence as the bitwise OR result of all integers in such sequence. For example, the cuteness of Zane's sequence a is a1 OR a2 OR ... OR an.
Zane understands that it might not be possible to recover exactly the lost sequence given his information, so he would be happy to get any good sequence b consisting of n integers b1, b2, ..., bn that:
1. would give the same results when the same operations are applied in the same order, and
2. has the same cuteness as that of Zane's original sequence a.
If there is such a sequence, find it. Otherwise, it means that Zane must have remembered something incorrectly, which is possible.
Input
The first line contains two integers n and m (1 β€ n, m β€ 3Β·105) β the number of integers in Zane's original sequence and the number of operations that have been applied to the sequence, respectively.
The i-th of the following m lines starts with one integer ti (<image>) β the type of the i-th operation.
If the operation is type 1 (ti = 1), then three integers li, ri, and xi follow (1 β€ li β€ ri β€ n, 0 β€ xi β€ 109) β the leftmost index to be considered, the rightmost index to be considered, and the maximum value of all integers with indices between li and ri, inclusive, respectively.
If the operation is type 2 (ti = 2), then two integers ki and di follow (1 β€ ki β€ n, 0 β€ di β€ 109) β meaning that the integer with index ki should become di after this operation.
It is guaranteed that xi β xj for all pairs (i, j) where 1 β€ i < j β€ m and ti = tj = 1.
The operations are given in the same order they were applied. That is, the operation that is given first was applied first, the operation that is given second was applied second, and so on.
Output
If there does not exist a valid good sequence, print "NO" (without quotation marks) in the first line.
Otherwise, print "YES" (without quotation marks) in the first line, and print n space-separated integers b1, b2, ..., bn (0 β€ bi β€ 109) in the second line.
If there are multiple answers, print any of them.
Examples
Input
5 4
1 1 5 19
1 2 5 1
2 5 100
1 1 5 100
Output
YES
19 0 0 0 1
Input
5 2
1 1 5 0
1 1 5 100
Output
NO
Note
In the first sample, it is easy to verify that this good sequence is valid. In particular, its cuteness is 19 OR 0 OR 0 OR 0 OR 1 = 19.
In the second sample, the two operations clearly contradict, so there is no such good sequence.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36101 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\n1 1 5 0\n1 1 5 100\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4\n1 1 5 19\n1 2 5 1\n2 5 100\n1 1 5 100\n",
"output": "YES\n19 1 0 0 0 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n2 1 0\n2 2 1\n",
"output": "YES\n1000000000 73741823 ",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 817_B. Makes And The Product | Solve the following coding problem using the programming language python:
After returning from the army Makes received a gift β an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that aiΒ·ajΒ·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 β€ n β€ 105) β the number of elements in array a. The second line contains n positive integer numbers ai (1 β€ ai β€ 109) β the elements of a given array.
Output
Print one number β the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and aiΒ·ajΒ·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n=int(input())
a=list(map(int,(input().split(' '))))
a=sorted(a)
a.append(0)
ans=1
t=0
while a[3+t]==a[2]:t=t+1
if a[3]==a[0]:ans=(t+3)*(t+2)*(t+1)/6
elif a[3]==a[1]:ans=(t+2)*(t+1)/2
elif a[3]==a[2]:ans=t+1
print(int(ans))
``` | vfc_36105 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 3 2 3 4\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 3 3 1 3 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 1 1 1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n1 1 3 3\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 842_B. Gleb And Pizza | Solve the following coding problem using the programming language python:
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.
The pizza is a circle of radius r and center at the origin. Pizza consists of the main part β circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).
Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.
Input
First string contains two integer numbers r and d (0 β€ d < r β€ 500) β the radius of pizza and the width of crust.
Next line contains one integer number n β the number of pieces of sausage (1 β€ n β€ 105).
Each of next n lines contains three integer numbers xi, yi and ri ( - 500 β€ xi, yi β€ 500, 0 β€ ri β€ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri β radius of i-th peace of sausage.
Output
Output the number of pieces of sausage that lay on the crust.
Examples
Input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1
Output
2
Input
10 8
4
0 0 9
0 0 10
1 0 1
1 0 2
Output
0
Note
Below is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
'''input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1
'''
r, d = map(int, input().split())
n = int(input())
c = 0
for _ in range(n):
x, y, r1 = map(int, input().split())
s = (x**2 + y**2)**0.5
if r-d <= s-r1 and s+r1 <= r:
c += 1
print(c)
``` | vfc_36109 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 8\n4\n0 0 9\n0 0 10\n1 0 1\n1 0 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8 4\n7\n7 8 1\n-7 3 2\n0 2 1\n0 -2 2\n-3 -3 1\n0 6 2\n5 3 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\n1\n1 1 0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 0\n5\n3 0 0\n0 3 0\n-3 0 0\n0 -3 0\n3 0 1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\n1\n500 500 10\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 0\n5\n8 1 0\n8 2 0\n8 3 0\n-8 3 0\n-8 2 0\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 863_B. Kayaking | Solve the following coding problem using the programming language python:
Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2Β·n people in the group (including Vadim), and they have exactly n - 1 tandem kayaks (each of which, obviously, can carry two people) and 2 single kayaks. i-th person's weight is wi, and weight is an important matter in kayaking β if the difference between the weights of two people that sit in the same tandem kayak is too large, then it can crash. And, of course, people want to distribute their seats in kayaks in order to minimize the chances that kayaks will crash.
Formally, the instability of a single kayak is always 0, and the instability of a tandem kayak is the absolute difference between weights of the people that are in this kayak. Instability of the whole journey is the total instability of all kayaks.
Help the party to determine minimum possible total instability!
Input
The first line contains one number n (2 β€ n β€ 50).
The second line contains 2Β·n integer numbers w1, w2, ..., w2n, where wi is weight of person i (1 β€ wi β€ 1000).
Output
Print minimum possible total instability.
Examples
Input
2
1 2 3 4
Output
1
Input
4
1 3 4 6 3 4 100 200
Output
5
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n = int(input())
n = 2*n
w = [int(i) for i in input().split()]
w.sort()
import math
res = math.inf
for x in range(n):
for y in range(x+1, n):
wc = w[:]
wc.pop(y); wc.pop(x)
# print(wc)
s = 0
for i in range(0, n-3, 2):
s += wc[i+1]-wc[i]
res = min(s, res)
print(res)
``` | vfc_36113 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 3 4 6 3 4 100 200\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2 3 4\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "45\n476 103 187 696 463 457 588 632 763 77 391 721 95 124 378 812 980 193 694 898 859 572 721 274 605 264 929 615 257 918 42 493 1 3 697 349 990 800 82 535 382 816 943 735 11 272 562 323 653 370 766 332 666 130 704 604 645 717 267 255 37 470 925 941 376 611 332 758 504 40 477 263 708 434 38 596 650 990 714 662 572 467 949 799 648 581 545 828 508 636\n",
"output": "355\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 933_B. A Determined Cleanup | Solve the following coding problem using the programming language python:
In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)Β·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients).
Input
The only line of input contains two space-separated integers p and k (1 β€ p β€ 1018, 2 β€ k β€ 2 000).
Output
If the polynomial does not exist, print a single integer -1, or output two lines otherwise.
In the first line print a non-negative integer d β the number of coefficients in the polynomial.
In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial <image> fulfilling the given requirements. Your output should satisfy 0 β€ ai < k for all 0 β€ i β€ d - 1, and ad - 1 β 0.
If there are many possible solutions, print any of them.
Examples
Input
46 2
Output
7
0 1 0 0 1 1 1
Input
2018 214
Output
3
92 205 1
Note
In the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)Β·(x + 2) + 46.
In the second example, f(x) = x2 + 205x + 92 = (x - 9)Β·(x + 214) + 2018.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
s = input()
# s = '46 2'
p, k = list(map(int, s.split()))
res = []
f = True
while p != 0:
if f:
n = p % k
m = (p - n) // k
f = False
else:
n = (-p) % k
m = (p + n) // k
f = True
res.append(n)
p = m
print(len(res))
print(' '.join(list(map(str, res))))
``` | vfc_36125 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "46 2\n",
"output": "7\n0 1 0 0 1 1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2018 214\n",
"output": "3\n92 205 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n",
"output": "1\n2 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "393939393939393939 393\n",
"output": "7\n237 191 82 181 11 30 107 \n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 95_D. Horse Races | Solve the following coding problem using the programming language python:
Petya likes horse racing very much. Horses numbered from l to r take part in the races. Petya wants to evaluate the probability of victory; for some reason, to do that he needs to know the amount of nearly lucky horses' numbers. A nearly lucky number is an integer number that has at least two lucky digits the distance between which does not exceed k. Petya learned from some of his mates from Lviv that lucky digits are digits 4 and 7. The distance between the digits is the absolute difference between their positions in the number of a horse. For example, if k = 2, then numbers 412395497, 404, 4070400000070004007 are nearly lucky and numbers 4, 4123954997, 4007000040070004007 are not.
Petya prepared t intervals [li, ri] and invented number k, common for all of them. Your task is to find how many nearly happy numbers there are in each of these segments. Since the answers can be quite large, output them modulo 1000000007 (109 + 7).
Input
The first line contains two integers t and k (1 β€ t, k β€ 1000) β the number of segments and the distance between the numbers correspondingly. Next t lines contain pairs of integers li and ri (1 β€ l β€ r β€ 101000). All numbers are given without the leading zeroes. Numbers in each line are separated by exactly one space character.
Output
Output t lines. In each line print one integer β the answer for the corresponding segment modulo 1000000007 (109 + 7).
Examples
Input
1 2
1 100
Output
4
Input
1 2
70 77
Output
2
Input
2 1
1 20
80 100
Output
0
0
Note
In the first sample, the four nearly lucky numbers are 44, 47, 74, 77.
In the second sample, only 74 and 77 are in the given segment.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36129 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 2\n70 77\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1 20\n80 100\n",
"output": "0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n1 100\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1\n1 100000\n47 100000\n20 100000\n200 100000\n1000 100000\n",
"output": "13472\n13471\n13472\n13464\n13400\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\n6 52\n5 925\n3 505\n8 7729\n3 152\n",
"output": "2\n100\n52\n1458\n6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 1\n4487142 7207579446\n6 46386141\n943 85570\n18945 7485692032\n29 436337\n7947 616330\n45 3950\n1 886\n2391 37228988\n6 21756778\n",
"output": "906531650\n9598004\n11882\n35716254\n57612\n96431\n285\n68\n7116744\n4150143\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 987_B. High School: Become Human | Solve the following coding problem using the programming language python:
Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-class android which is produced by a little-known company. His design is not perfect, his characteristics also could be better. So he is bullied by other androids.
One of the popular pranks on Vasya is to force him to compare x^y with y^x. Other androids can do it in milliseconds while Vasya's memory is too small to store such big numbers.
Please help Vasya! Write a fast program to compare x^y with y^x for Vasya, maybe then other androids will respect him.
Input
On the only line of input there are two integers x and y (1 β€ x, y β€ 10^{9}).
Output
If x^y < y^x, then print '<' (without quotes). If x^y > y^x, then print '>' (without quotes). If x^y = y^x, then print '=' (without quotes).
Examples
Input
5 8
Output
>
Input
10 3
Output
<
Input
6 6
Output
=
Note
In the first example 5^8 = 5 β
5 β
5 β
5 β
5 β
5 β
5 β
5 = 390625, and 8^5 = 8 β
8 β
8 β
8 β
8 = 32768. So you should print '>'.
In the second example 10^3 = 1000 < 3^{10} = 59049.
In the third example 6^6 = 46656 = 6^6.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import math
x,y=map(lambda x:math.log(int(x))/int(x),input().split())
print('<=>'[(x>=y)+(x>y)])
``` | vfc_36133 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 8\n",
"output": ">\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 6\n",
"output": "=\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | alexanders-journey-4 | Solve the following coding problem using the programming language python:
There are N (labelled 1 to N) kingdoms in a country. Our king Alexander is living in the kingdom S. We are given R distances, these distances are between two kingdoms and the distance between any two kingdom may or may not be unique.
Now Alexander wants to visit each kingdom in minimum distance possible starting from his kingdom S.
If a kingdom is unreachable the distance is assumed as -1.
INPUT:::
The first line denotes T, the number of test cases.
First line of each test case has two integers, denoting the no of kingdom "N" and the next number denotes the no of distance given between two different kingdoms "R".
The next "R" line contains three integers x,y,d, the first two numbers denoting kingdom number and the next integer denotes the distance between them.
If the distance between two kingdom say a and b is given as x then this distance will remain same if the Alexander travels from a to b or from b to a.
The last line of test case denotes the kingdom in which Alexander is living.
Note::: If there are many distances given between the same two kingdoms then it is considered that Alexander has many different ways to travel between these two kingdoms.
Output:::
For each test case print a single line containing N-1 space separated integers denoting the shortest distance of N-1 kingdoms from Alexander's Kingdom.
For unreachable kingdoms print "-1".
Constraints:::
1β€Tβ€10,
2β€Nβ€3000,
1β€Rβ€NΓ(Nβ1))2,
1β€x,y,Sβ€N,
1β€dβ€350
SAMPLE INPUT
1
4 4
1 2 24
1 4 20
3 1 3
4 3 12
1
SAMPLE OUTPUT
24 3 15
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def killdoubles(l):
i=0
a=l[i]
ll=[a]
while i<len(l):
if a!=l[i]:
a=l[i]
ll.append(a)
i+=1
return ll
def argminnonmarque(l,m):
mini=min([l[i] for i in range(len(l)) if not(m[i])])
for i in range(len(l)):
if ((l[i]==mini) & (not(m[i]))):
break
return i
def subs(a,l):
i=0
dont=False
while i<len(l):
if l[i][0]==a[0]:
if l[i][1]>a[1]:
break
dont=True
i+=1
ll=[list(k) for k in l]
if i<len(l):
ll[i]=a
elif not(dont):
ll.append(a)
return ll
def solve(n,m,r,s):
G=[[] for _ in range(n+1)]
for [i,j,w] in r:
G[i]=subs([j,w],G[i])
G[j]=subs([i,w],G[j])
infinity=1+sum([r[i][2] for i in range(m)])
for debut in [s]:
marque=[False for _ in range(n+1)]
labels=[infinity for _ in range(n+1)]
labels[debut]=0
while marque!=[True for _ in range(n+1)]:
a=argminnonmarque(labels,marque)
marque[a]=True
for [b,w] in G[a]:
if not(marque[b]):
labels[b]=min(labels[b],labels[a]+w)
for i in range(n+1):
if labels[i]==infinity:
labels[i]=-1
st=""
for i in (labels[1:s]+labels[s+1:]):
st+=str(i)+" "
return st
T=int(raw_input())
for _ in range(T):
[n,m]=map(int,raw_input().strip().split())
r=[]
for _ in range(m):
r.append(map(int,raw_input().strip().split()))
s=int(raw_input())
print(solve(n,m,r,s))
``` | vfc_36137 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n4 4\n1 2 24\n1 4 20\n3 1 3\n4 3 12\n1\n\nSAMPLE",
"output": "24 3 15",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | burger-deliver-time-1 | Solve the following coding problem using the programming language python:
In McD's Burger, n hungry burger fans are ordering burgers. The ith order is placed by the ith fan at ti time and it takes di time to procees. What is the order in which the fans will get their burgers?
Input Format
On the first line you will get n, the number of orders. Then n lines will follow. On the (i+1)th line, you will get ti and di separated by a single space.
Output Format
Print the order ( as single space separated integers ) in which the burger fans get their burgers. If two fans get the burger at the same time, then print the smallest numbered order first.(remember, the fans are numbered 1 to n).
Constraints
1β€nβ€103
1β€ti,diβ€106
SAMPLE INPUT
5
8 1
4 2
5 6
3 1
4 3
SAMPLE OUTPUT
4 2 5 1 3
Explanation
The first order is placed at time 3 and it takes 1 unit of time to process, so the burger is sent to the customer at time 4.
The second order is placed at time 4 and it takes 2 units of time to process, the burger is sent to customer at time 6.
The third order is placed at time 4 and it takes 3 units of time to process, the burger is sent to the customer at time 7.
Similarly, the fourth and fifth orders are sent to the customer at time 9 and time 11.
So the order of delivery of burgers is, 4 2 5 1 3.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
a=[]
T=input()
for i in xrange(T):
c,d=map(int,raw_input().split())
a.append((c+d,i))
a.sort()
for i in a:
print i[1]+1,
``` | vfc_36141 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n8 1\n4 2\n5 6\n3 1\n4 3\n\nSAMPLE",
"output": "4 2 5 1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 3\n2 3\n3 3",
"output": "1 2 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 3\n2 3\n6 3",
"output": "1 2 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n8 1\n4 0\n5 6\n3 1\n4 3\n\nSAMPLE",
"output": "2 4 5 1 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n8 1\n4 0\n1 6\n6 1\n5 3\n\nSAMPLE",
"output": "2 3 4 5 1 \n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | day-6-advanced-mathematics | Solve the following coding problem using the programming language python:
Problem :
Bajirao is on a date with his girlfriend Avni. It is a romantic night and they are
playing a game of words.
The rule of this game is that if Bajirao says a word such that no adjacent letters occurring in the word are same then he gets a kiss from her otherwise he gets a slap.
Input :
The first line consists of T the number of test cases. The next T lines are such that each line consists of a single word spoken by Bajirao.
Output
For every test case, on a new line print 'KISS' if Bajirao gets a kiss and 'SLAP' if Bajirao gets a slap.
Constraints :
1 β€ T β€ 100
2 β€ Length of Word spoken by Bajirao β€ 100
The input word will comprise only of lower case English alphabets (a-z).
Problem Setter : Shreyans
Problem Tester : Sandeep
Problem Statement : Ravi
(By IIT Kgp HackerEarth Programming Club)
SAMPLE INPUT
2
remember
occurring
SAMPLE OUTPUT
KISS
SLAP
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
t=input()
for i in range(t):
a=raw_input()
c=0
for i in range(0,len(a)-1):
if a[i]==a[i+1]:
c=1
if c==1:
print "SLAP"
else:
print "KISS"
``` | vfc_36145 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\nremember\noccurring\n\nSAMPLE",
"output": "KISS\nSLAP\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nremember\noccurring\n\nELPMAS",
"output": "KISS\nSLAP\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | game-of-numbers-7 | Solve the following coding problem using the programming language python:
Game of numbers is a game where you are given two integers (X and Y), and you have to print the number of special numbers between X and Y both inclusive.
The property of a special numbers is as follows:
A special number is not divisible by any number of the form ZZ* where (Z\; >\; 1).
Input:
T, the number of test cases. Each test case consists of two space separated integers denoting X and Y.
Output:
The required answer in one line for each test case.
Constraints:
1 β€ T β€ 10
1 β€ X,Y β€ 10 ^ 9
0 β€ |X-Y| β€ 10^6
SAMPLE INPUT
1
1 10
SAMPLE OUTPUT
7
Explanation
In given test case, 4,8 and 9 are not special.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import math
def count(x, y):
z = [1] * ( y - x + 1)
for i in range(2, int(math.sqrt(y)) + 1):
step = i ** 2
if x % step == 0: j = x
else: j = x + step - (x%step)
while(j <= y):
z[j - x] = 0
j += step
return z.count(1)
def get():
t = int(raw_input())
for i in range(t):
s = raw_input().split()
x, y = int(s[0]), int(s[1])
if x > y: x, y = y, x
print count(x, y)
if __name__=="__main__":
get()
``` | vfc_36149 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1 10\n\nSAMPLE",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 10\n\nELPMAS",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 9\n\nELPMAS",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2 9\n\nELPMAS",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2 4\n\nSAMPLE",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2 2\n\nSANPLE",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | mobile-conversations | Solve the following coding problem using the programming language python:
You have just purchased a new mobile phone and you want to call all of your relatives to brag about your new phone. You have N relatives. You will talk to i^th relative for exactly Ti minutes. Each minute costs you 1 dollar . However, your relatives are generous. Hence after the conversation, they will add a recharge of Xi dollars in your mobile. Initially, you have M dollars balance in your mobile phone.
Find the minimum value of M, that you must have initially, in your phone, so that you don't run out of balance during any of the call (encounter negative balance).
Note : You can call relatives in any order. Each relative will be called exactly once.
INPUT
The first line will contain N, the number of relatives. Next N lines will have two space separated integers, "Ti Xi" (quotes for clarity), representing call duration with the i^th relative and the amount of recharge you will get from that relative after the conversation.
OUTPUT
Output a single integer M, the minimum required initial balance in your mobile phone.
CONSTRAINTS
1 β€ N,X,T β€ 10^5
SAMPLE INPUT
2
1 1
2 1
SAMPLE OUTPUT
2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n = int(raw_input())
lists = []
while n > 0:
n = n-1
lists.append(map(int,raw_input().split(" ")))
# lists.sort(lambda k : k[1]/k[0])
list2 = []
list3 = []
for x in lists:
# print x[0],x[1]
if x[1]/x[0] > 0:
list2.append(x)
else:
list3.append(x)
list2.sort(key=lambda k: k[0])
list3.sort(key = lambda k : k[1], reverse=True)
sum1 = 0
#print list2,list3
min_sum = 999999
for item in list2:
sum1 = sum1- item[0]
min_sum = min(min_sum, sum1)
sum1 = sum1 + item[1]
for item in list3:
sum1 = sum1 - item[0]
min_sum = min(min_sum, sum1)
sum1 = sum1 + item[1]
print int(abs(min_sum))
``` | vfc_36157 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 1\n2 1\n\nSAMPLE",
"output": "2",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | panda-and-maximum-product | Solve the following coding problem using the programming language python:
Panda has started learning about subsets. His professor gave him a simple task. Given a list of numbers, Panda has to choose the subset which gives the maximum product. However, the professor asked Panda only to submit the maximum product obtained by taking exactly two numbers from the list. Please help Panda in finding out the answer to this assignment.
Input Format:
The first line will contain the integer N, the length of the array. The next line contains N space separated integers.
Output Format:
For each test case, output Panda's query.
Constraints:
2 β€ N β€ 10^5
Subtask 1: (25 points)
0 β€ Integers β€ 10^9
Subtask 2: (75 points)
-10^9 β€ Integers β€ 10^9SAMPLE INPUT
2
2 3
SAMPLE OUTPUT
6
Explanation
The only combination possible is {2,3} whose product is 6 .
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
#print 'Hello World!'
n=int(raw_input())
l=[int(i) for i in raw_input().split(" ")]
l.sort()
x=l[::-1]
if x[0]>0 and x[1]>0:
print x[0]*x[1]
else:
print l[0]*l[1]
``` | vfc_36161 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n2 3\n\nSAMPLE",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 3\n\nTAMPLE",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 6\n\nTAMPEL",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 2\n\nTAMPEL",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n0 2\n\nTAMPDL",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | roots | Solve the following coding problem using the programming language python:
Bosky needs your help in completing his maths homework today. He has to solve some questions as homework from a book named Jungly Mathematics. He knows that Jungly Mathematics contains certain quadratic equations which have imaginary roots. He is not yet introduced to the concept of imaginary roots and is only concerned with the questions having real roots.
The book contains N quadratic equation of the form a[i]x^2 + b[i]x + c[i] = 0 where a[i] != 0 and i represents the index of the question.
You have to make a program which will take N, a, b and c as input and tell him how many questions he can solve out of those N questions (i.e. You have to find how many quadratic equations in the book have real roots).
Input
Input will contain a number N denoting the number of quadratic equations.
N line follow, each one consisting of three space separated integers a[i], b[i] and c[i] representing the quadratic equation a[i]x^2 + b[i]x + c[i] = 0. where [0 β€ i < N].
Output
Print a single integer denoting the number of quadratic equations Bosky can solve.
Constraints
1 β€ N β€ 100
-100 β€ a[i] , b[i], c[i] β€ 100
SAMPLE INPUT
2
1 0 -1
1 1 1
SAMPLE OUTPUT
1
Explanation
The book contains only 2 quadratic equations:
1: x^2 - 1 = 0
2: x^2 + x +1 = 0
1st equation has two roots x = 1, -1, thus it can be solved by Bosky.
2nd equation has complex roots, hence it can't be solved by Bosky.
Therefore, Bosky can solve only 1 question from the book.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
'''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
def can_solve(equation):
a = equation[0]
b = equation[1]
c = equation[2]
if b * b < 4 * a * c:
return False
else:
return True
if __name__ == '__main__':
cases = int(raw_input().strip())
start = 1
solved = 0
while start <= cases:
equation = [int(x) for x in raw_input().strip().split(' ')]
if can_solve(equation):
solved = solved + 1
start = start + 1
print solved
``` | vfc_36165 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 0 -1\n1 1 1\n\nSAMPLE",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 0 -1\n1 1 1\n\nSAMPLE",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 0 -1\n1 2 1\n\nSAMPLE",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | stock-market-calculation-1 | Solve the following coding problem using the programming language python:
Your algorithm is so good at predicting the market that you now know what the share price of Mahindra & Mahindra. (M&M) will be for the next N days.
Each day, you can either buy one share of M&M, sell any number of shares of M&M that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?
Input
The first line contains the number of test cases T. T test cases follow:
The first line of each test case contains a number N. The next line contains N integers, denoting the predicted price of M&M shares for the next N days.
Output
Output T lines, containing the maximum profit which can be obtained for the corresponding test case.
Constraints
1 β€ T β€ 10
1 β€ N β€ 50000
All share prices are between 1 and 100000
SAMPLE INPUT
3
3
5 3 2
3
1 2 100
4
1 3 1 2
SAMPLE OUTPUT
0
197
3
Explanation
For the 1st case, you cannot obtain any profit because the share price never rises.
For the 2nd case, you can buy one share on the first two days, and sell both of them on the third day.
For the 3rd case, you can buy one share on day 1, sell one on day 2, buy one share on day 3, and sell one share on day 4.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def calcprofit(stockvalues):
prof=0
m=0
for i in range(len(stockvalues)-1,-1,-1):
ai=stockvalues[i]
if m<=ai:
m=ai
prof+=m-ai
return (prof)
for iti in xrange(input()):
n=input()
l=map(int, raw_input().split())
print calcprofit(l)
``` | vfc_36169 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3\n5 3 2\n3\n1 2 100\n4\n1 3 1 2\n\nSAMPLE",
"output": "0\n197\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3\n5 3 2\n3\n1 2 100\n4\n1 3 1 2",
"output": "0\n197\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3\n5 3 2\n3\n0 2 100\n4\n1 3 1 2",
"output": "0\n198\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n3\n5 3 2\n3\n1 2 100\n4\n1 3 1 1\n\nSAMPLE",
"output": "0\n197\n2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | unique | Solve the following coding problem using the programming language python:
There are N people in a group. The personality of each person is denoted by A[i] from the set A, where A[i] denotes the personality of the ith person.
Your task is to find the total persons of different personalities.
INPUT:
First line contains the total number of test cases T, for each test cases, first line denotes the total number of persons N and second line contains list of N space separated integers denoting the personality of the person.
OUTPUT:
For each test case, print the result in a single line.
Constraints:
1 β€ T β€ 100
1 β€ N β€ 100000
1 β€ A[i] β€ 1000000000
SAMPLE INPUT
1
5
1 2 3 4 5
SAMPLE OUTPUT
5
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
a = input()
for i in xrange(a) :
d = input();
b = [int(i) for i in raw_input().strip().split()]
c = {}
for i in xrange(d) :
c[b[i]]=i;
print len(c)
``` | vfc_36173 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n5\n1 2 3 4 5\n\nSAMPLE",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n1 2 3 4 5",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n1 2 3 6 5",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n1 0 3 4 4\n\nSAMPLE",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n0 2 3 2 0\n\nPAMSLE",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n-1 -1 -1 0 0",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p00009 Prime Number | Solve the following coding problem using the programming language python:
Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Input
Input consists of several datasets. Each dataset has an integer n (1 β€ n β€ 999,999) in a line.
The number of datasets is less than or equal to 30.
Output
For each dataset, prints the number of prime numbers.
Example
Input
10
3
11
Output
4
2
5
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
import math
LIMIT = 1000000
p = 2
pList = [True] * (LIMIT + 1)
while p ** 2 <= LIMIT:
if(pList[p]):
for i in range(p * 2, LIMIT + 1 , p):
pList[i] = False
p += 1
# print(pList)
lines = str(sys.stdin.read()).strip().split("\n")
for line in lines:
line = int(line)
count = 0
for i in range(2, line + 1):
if pList[i]:
count += 1
print(count)
``` | vfc_36217 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10\n3\n11",
"output": "4\n2\n5",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3\n5",
"output": "4\n2\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3\n9",
"output": "4\n2\n4\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p00274 A Pair of Prizes | Solve the following coding problem using the programming language python:
Jou and Yae are a good couple. Jou is collecting prizes for capsule toy vending machines (Gachapon), and even when they go out together, when they find Gachapon, they seem to get so hot that they try it several times. Yae was just looking at Jou, who looked happy, but decided to give him a Gachapon prize for his upcoming birthday present. Yae wasn't very interested in Gachapon itself, but hopefully he would like a match with Jou.
For Gachapon that Yae wants to try, one prize will be given in one challenge. You can see how many types of prizes there are, including those that are out of stock, and how many of each prize remains. However, I don't know which prize will be given in one challenge. Therefore, regardless of the order in which the prizes are given, create a program that outputs the minimum number of challenges required for Yae to get two of the same prizes.
input
The input consists of multiple datasets. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format:
N
k1 k2 ... kN
Each dataset has two lines, and the first line is given the integer N (1 β€ N β€ 10000), which indicates how many types of prizes there are. The next line is given the integer ki (0 β€ ki β€ 10000), which indicates how many prizes are left.
The number of datasets does not exceed 100.
output
For each dataset, the minimum number of challenges required to get two identical prizes is output. However, if it is not possible, NA is output.
Example
Input
2
3 2
3
0 1 1
1
1000
0
Output
3
NA
2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# AOJ 0279: A Pair of Prizes
# Python3 2018.6.25 bal4u
while True:
n = int(input())
if n == 0: break
k = list(map(int, input().split()))
one, many = 0, 0
for i in k:
if i == 1: one += 1
elif i > 1: many += 1
print(one+many+1 if many > 0 else "NA")
``` | vfc_36225 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n3 2\n3\n0 1 1\n1\n1000\n0",
"output": "3\nNA\n2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n3 0\n3\n0 1 1\n1\n1000\n0",
"output": "2\nNA\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n3 2\n3\n0 1 1\n1\n0000\n0",
"output": "3\nNA\nNA\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 0\n3\n0 1 1\n1\n1000\n0",
"output": "NA\nNA\n2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p00462 Pizza | Solve the following coding problem using the programming language python:
problem
JOI Pizza sells pizza home delivery along the d-meter-long ring road that runs through the city center.
JOI Pizza has n stores S1, ..., Sn on the loop line. The head office is S1. The distance from S1 to Si when moving the loop line clockwise is set to di meters. D2 , ..., dn is an integer greater than or equal to 1 and less than or equal to d -1. D2, ..., dn are all different. Bake and deliver pizza at the shortest store.
The location of the delivery destination is represented by an integer k that is greater than or equal to 0 and less than or equal to d -1. This means that the distance from the head office S1 to the delivery destination in the clockwise direction is k meters. Pizza delivery is done along the loop line and no other road is allowed. However, the loop line may move clockwise or counterclockwise.
For example, if the location of the store and the location of the delivery destination are as shown in the figure below (this example corresponds to Example 1 of "I / O example").
<image>
The store closest to the delivery destination 1 is S2, so the delivery is from store S2. At this time, the distance traveled from the store is 1. Also, the store closest to delivery destination 2 is S1 (main store), so store S1 (main store). ) To deliver to home. At this time, the distance traveled from the store is 2.
Total length of the loop line d, Number of JOI pizza stores n, Number of orders m, N --1 integer representing a location other than the main store d2, ..., dn, Integer k1, .. representing the location of the delivery destination Given ., km, create a program to find the sum of all orders for each order by the distance traveled during delivery (ie, the distance from the nearest store to the delivery destination).
input
The input consists of multiple datasets. Each dataset is given in the following format.
The first line is a positive integer d (2 β€ d β€ 1000000000 = 109) that represents the total length of the loop line, the second line is a positive integer n (2 β€ n β€ 100000) that represents the number of stores, and the third line is A positive integer m (1 β€ m β€ 10000) is written to represent the number of orders. The n --1 lines after the 4th line are integers d2, d3, ..., dn that represent the location of stores other than the main store. (1 β€ di β€ d -1) is written in this order, and the integers k1, k2, ..., km (0 β€ ki β€ d) representing the delivery destination location are in the m lines after the n + 3rd line. --1) are written in this order.
Of the scoring data, for 40% of the points, n β€ 10000 is satisfied. For 40% of the points, the total distance traveled and the value of d are both 1000000 or less. In the scoring data, the total distance traveled is 1000000000 = 109 or less.
When d is 0, it indicates the end of input. The number of data sets does not exceed 10.
output
For each data set, one integer representing the total distance traveled during delivery is output on one line.
Examples
Input
8
3
2
3
1
4
6
20
4
4
12
8
16
7
7
11
8
0
Output
3
3
Input
None
Output
None
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0539
AC
"""
import sys
from sys import stdin
from bisect import bisect_right
input = stdin.readline
def main(args):
while True:
d = int(input()) # ??Β°??ΒΆ????????????
if d == 0:
break
n = int(input()) # ??Β¬????????????????????Β°
m = int(input()) # ??Β¨????????Β°
cw_pos = [int(input()) for _ in range(n-1)]
dests = [int(input()) for _ in range(m)]
cw_pos.append(0) # ??Β¬????????????
cw_pos.append(d) # ??Β°??ΒΆ??????1??Β¨??????????????Β¬????????????(??????)
cw_pos.sort()
# ccw_pos = [d-x for x in cw_pos] # ??Β°??ΒΆ?????????????????Β£????????????????????????
# ccw_pos.sort()
total_distance = 0
for t in dests:
if t == 0: # ?????????????????????0?????\??Β£????????????bisect_right?????Β¨????????????????????Β§??????
continue
i = bisect_right(cw_pos, t) # ????Β¨?????????Β§??????????????????
a1 = min(t-cw_pos[i-1], cw_pos[i]-t) # ?????????????????????????????Β’
# j = bisect_right(ccw_pos, d-t) # ???????Β¨?????????Β§???????????Β¨?????????
# a2 = min(d-t-ccw_pos[j-1], ccw_pos[j]-(d-t))
# ans = min(a1, a2)
total_distance += a1 # ?????????????????????????????Β°OK
print(total_distance)
if __name__ == '__main__':
main(sys.argv[1:])
``` | vfc_36229 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8\n3\n2\n3\n1\n4\n6\n20\n4\n4\n12\n8\n16\n7\n7\n11\n8\n0",
"output": "3\n3",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p00652 Cutting a Chocolate | Solve the following coding problem using the programming language python:
Turtle Shi-ta and turtle Be-ko decided to divide a chocolate. The shape of the chocolate is rectangle. The corners of the chocolate are put on (0,0), (w,0), (w,h) and (0,h). The chocolate has lines for cutting. They cut the chocolate only along some of these lines.
The lines are expressed as follows. There are m points on the line connected between (0,0) and (0,h), and between (w,0) and (w,h). Each i-th point, ordered by y value (i = 0 then y =0), is connected as cutting line. These lines do not share any point where 0 < x < w . They can share points where x = 0 or x = w . However, (0, li ) = (0,lj ) and (w,ri ) = (w,rj ) implies i = j . The following figure shows the example of the chocolate.
<image>
There are n special almonds, so delicious but high in calories on the chocolate. Almonds are circle but their radius is too small. You can ignore radius of almonds. The position of almond is expressed as (x,y) coordinate.
Two turtles are so selfish. Both of them have requirement for cutting.
Shi-ta's requirement is that the piece for her is continuous. It is possible for her that she cannot get any chocolate. Assume that the minimum index of the piece is i and the maximum is k . She must have all pieces between i and k . For example, chocolate piece 1,2,3 is continuous but 1,3 or 0,2,4 is not continuous.
Be-ko requires that the area of her chocolate is at least S . She is worry about her weight. So she wants the number of almond on her chocolate is as few as possible.
They doesn't want to make remainder of the chocolate because the chocolate is expensive.
Your task is to compute the minumum number of Beko's almonds if both of their requirment are satisfied.
Input
Input consists of multiple test cases.
Each dataset is given in the following format.
n m w h S
l0 r0
...
lm-1 rm-1
x0 y0
...
xn-1 yn-1
The last line contains five 0s. n is the number of almonds. m is the number of lines. w is the width of the chocolate. h is the height of the chocolate. S is the area that Be-ko wants to eat. Input is integer except xi yi.
Input satisfies following constraints.
1 β€ n β€ 30000
1 β€ m β€ 30000
1 β€ w β€ 200
1 β€ h β€ 1000000
0 β€ S β€ w*h
If i < j then li β€ lj and ri β€ rj and then i -th lines and j -th lines share at most 1 point. It is assured that lm-1 and rm-1 are h. xi yi is floating point number with ten digits. It is assured that they are inside of the chocolate. It is assured that the distance between points and any lines is at least 0.00001.
Output
You should output the minumum number of almonds for Be-ko.
Example
Input
2 3 10 10 50
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 70
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 30
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 40
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
2 3 10 10 100
3 3
6 6
10 10
4.0000000000 4.0000000000
7.0000000000 7.0000000000
0 0 0 0 0
Output
1
1
0
1
2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# AOJ 1067 Cutting a Chocolate
# Python3 2018.7.10 bal4u
from bisect import bisect_left
while True:
n, m, w, h, S = map(int, input().split())
if n == 0: break
m, wh2 = m+1, 2*(w*h)
S = wh2-2*S
tbl, s = [[0,0,0,0]], [0]
for i in range(1, m):
l, r = map(int, input().split())
tbl.append([l, r, 0, r-l])
s.append((l+r)*w)
p = []
for i in range(n):
x, y = map(float, input().split())
p.append((x, y))
p.sort(key=lambda x:(x[1],x[0]))
j = 1
for i in range(n):
x, y = p[i]
while True:
y1 = tbl[j-1][3]*x/w + tbl[j-1][0]
y2 = tbl[j ][3]*x/w + tbl[j ][0]
if y1 < y:
if y < y2: break
j += 1
else: j -= 1
tbl[j][2] += 1
for i in range(1, m): tbl[i][2] += tbl[i-1][2]
if S == 0:
print(n)
continue
elif S == wh2:
print(0)
continue
j = bisect_left(s, S, 0, m)
if s[j] != S: j -= 1
ans, i = tbl[j][2], 1
while j+1 < m:
j += 1
while s[j]-s[i] > S: i += 1
ans = max(ans, tbl[j][2]-tbl[i][2])
print(n - ans)
``` | vfc_36233 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 4, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3 10 10 50\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 70\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 30\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 40\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 100\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n0 0 0 0 0",
"output": "1\n1\n0\n1\n2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3 10 10 50\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 70\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 30\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 40\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.0000000000 7.0000000000\n2 3 10 10 100\n3 3\n6 6\n10 10\n4.0000000000 4.0000000000\n7.332538817147148 7.0000000000\n0 0 0 0 0",
"output": "1\n1\n0\n1\n2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p00797 Family Tree | Solve the following coding problem using the programming language python:
A professor of anthropology was interested in people living in isolated islands and their history. He collected their family trees to conduct some anthropological experiment. For the experiment, he needed to process the family trees with a computer. For that purpose he translated them into text files. The following is an example of a text file representing a family tree.
John
Robert
Frank
Andrew
Nancy
David
Each line contains the given name of a person. The name in the first line is the oldest ancestor in this family tree. The family tree contains only the descendants of the oldest ancestor. Their husbands and wives are not shown in the family tree. The children of a person are indented with one more space than the parent. For example, Robert and Nancy are the children of John, and Frank and Andrew are the children of Robert. David is indented with one more space than Robert, but he is not a child of Robert, but of Nancy. To represent a family tree in this way, the professor excluded some people from the family trees so that no one had both parents in a family tree.
For the experiment, the professor also collected documents of the families and extracted the set of statements about relations of two persons in each family tree. The following are some examples of statements about the family above.
John is the parent of Robert.
Robert is a sibling of Nancy.
David is a descendant of Robert.
For the experiment, he needs to check whether each statement is true or not. For example, the first two statements above are true and the last statement is false. Since this task is tedious, he would like to check it by a computer program.
Input
The input contains several data sets. Each data set consists of a family tree and a set of statements. The first line of each data set contains two integers n (0 < n < 1000) and m (0 < m < 1000) which represent the number of names in the family tree and the number of statements, respectively. Each line of the input has less than 70 characters.
As a name, we consider any character string consisting of only alphabetic characters. The names in a family tree have less than 20 characters. The name in the first line of the family tree has no leading spaces. The other names in the family tree are indented with at least one space, i.e., they are descendants of the person in the first line. You can assume that if a name in the family tree is indented with k spaces, the name in the next line is indented with at most k + 1 spaces. This guarantees that each person except the oldest ancestor has his or her parent in the family tree. No name appears twice in the same family tree. Each line of the family tree contains no redundant spaces at the end.
Each statement occupies one line and is written in one of the following formats, where X and Y are different names in the family tree.
X is a child of Y.
X is the parent of Y.
X is a sibling of Y.
X is a descendant of Y.
X is an ancestor of Y.
Names not appearing in the family tree are never used in the statements. Consecutive words in a statement are separated by a single space. Each statement contains no redundant spaces at the beginning and at the end of the line.
The end of the input is indicated by two zeros.
Output
For each statement in a data set, your program should output one line containing True or False. The first letter of True or False in the output must be a capital. The output for each data set should be followed by an empty line.
Examples
Input
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Output
True
True
True
False
False
True
Input
6 5
John
Robert
Frank
Andrew
Nancy
David
Robert is a child of John.
Robert is an ancestor of Andrew.
Robert is a sibling of Nancy.
Nancy is the parent of Frank.
John is a descendant of Andrew.
2 1
abc
xyz
xyz is a child of abc.
0 0
Output
True
True
True
False
False
True
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
while(1):
[n,m]=[int(x) for x in raw_input().split()]
if n==0:
break
else:
familymatrix=[[-100000 for x in range(n)] for y in range(n)]
for i in range(n):
familymatrix[i][i]=0
namedic={}
returned=[0 for x in range(n)]
spacenum=0
spacenumold=0
for i in range(n):
indata=raw_input()
name=indata.strip()
spacenum=len(indata)-len(name)
namedic[name]=i
for j in range(i):
familymatrix[j][i]=familymatrix[j][i-1]+(spacenum-spacenumold)
#if familymatrix[j][i]<0:
# familymatrix[j][i]=-1000000
#if familymatrix[j][i]>0 and returned[j]:
# familymatrix[j][i]=-1000000
spacenumold=spacenum
for i in range(n):
for j in range(i):
if familymatrix[j][i]==0 and returned[j]==0:
returned[j]=1
elif familymatrix[j][i]<0:
returned[j]=2
if familymatrix[j][i]>0 and returned[j]==1:
familymatrix[j][i]=-1
elif returned[j]==2:
familymatrix[j][i]=-1
#for i in range(n):
# print familymatrix[i]
for i in range(m):
query=raw_input().split()
X=namedic[query[0]]
Y=namedic[query[-1][:-1]]
question=' '.join(query[1:-1])
if question == 'is a child of':
print familymatrix[Y][X]==1
elif question == 'is the parent of':
print familymatrix[X][Y]==1
elif question == 'is a sibling of':
print (familymatrix[X][Y]==0) or (familymatrix[Y][X]==0)
elif question == 'is a descendant of':
print familymatrix[Y][X]>0
elif question == 'is an ancestor of':
print familymatrix[X][Y]>0
print ''
``` | vfc_36237 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 8, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 5\nJohn\nRobert\nFrank\nAndrew\nNancy\nDavid\nRobert is a child of John.\nRobert is an ancestor of Andrew.\nRobert is a sibling of Nancy.\nNancy is the parent of Frank.\nJohn is a descendant of Andrew.\n2 1\nabc\nxyz\nxyz is a child of abc.\n0 0",
"output": "True\nTrue\nTrue\nFalse\nFalse\n\nTrue",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5\nJohn\n Robert\n Frank\n Andrew\n Nancy\n David\nRobert is a child of John.\nRobert is an ancestor of Andrew.\nRobert is a sibling of Nancy.\nNancy is the parent of Frank.\nJohn is a descendant of Andrew.\n2 1\nabc\n xyz\nxyz is a child of abc.\n0 0",
"output": "True\nTrue\nTrue\nFalse\nFalse\n\nTrue",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5\nJohn\nRobert\nFrank\nAndrew\nNancy\nDivad\nRobert is a child of John.\nRobert is an ancestor of Andrew.\nRobert is a sibling of Nancy.\nNancy is the parent of Frank.\nJohn is a descendant of Andrew.\n2 1\nabc\nxyz\nxyz is a child of abc.\n0 0",
"output": "False\nFalse\nTrue\nFalse\nFalse\n\nFalse\n\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p00928 Automotive Navigation | Solve the following coding problem using the programming language python:
Example
Input
4 2 1 1
1 1 1 2
2 2 2 1
2 2 1 2
1 1 2 1
9 N
Output
1 1
2 2
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# coding: utf-8
import sys
sys.setrecursionlimit(50000000)
max_c=101
vec=[(0,2),(2,0),(0,-2),(-2,0)]
try:
while True:
log=[-1 for i in range(10001)]
n,x0,y0,t=map(int,input().split())
field=[[0 for i in range(max_c)]for i in range(max_c)]
for i in range(n):
a,b,c,d=map(lambda x:int(x)*2,input().split())
if b==d:
field[b][min(a,c):max(a,c)+1]=[1 for i in range(max(a,c)+1-min(a,c))]
else:
for p in field[min(b,d):max(b,d)+1]:
p[a]=1
a,b=-1,-1
pt=0
for i in range(t):
a,b=input().split()
a=int(a)+pt
pt=a
b='NESW'.find(b)
log[a]=b
end_t=pt
end_v=b
ans=[]
memo=set({})
def check(t,x,y,v):
if t>end_t or (log[t]!=-1 and not((v+2)%4!=log[t])) or ((t,x,y,v) in memo):
return
memo.add((t,x,y,v))
if t==end_t:
ex,ey=vec[end_v]
if v==end_v or 0<=y+ey//2<=100 and 0<=x+ex//2<=100 and field[y+ey//2][x+ex//2]==1 and (v+2)%4!=end_v:
ans.append((x,y))
return
if log[t]!=-1 and v==log[t] or log[t]==-1:
i=0
for mx,my in vec:
if i==(v+2)%4:
i+=1
continue
nx,ny=x+mx,y+my
if 0<=nx<=100 and 0<=ny<=100 and field[ny-my//2][nx-mx//2]==1:
check(t+1,nx,ny,i)
i+=1
elif log[t]!=-1:
i=0
for mx,my in vec:
if i!=log[t]:
i+=1
continue
nx,ny=x+mx,y+my
if 0<=nx<=100 and 0<=ny<=100 and field[ny-my//2][nx-mx//2]==1:
check(t+1,nx,ny,i)
i+=1
for i in range(4):
check(0,x0*2,y0*2,i)
for q in sorted(set(ans)):
print(q[0]//2,q[1]//2)
except:
pass
``` | vfc_36241 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 268435456,
"problem_url": null,
"time_limit": "{'seconds': 5, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2 1 1\n1 1 1 2\n2 2 2 1\n2 2 1 2\n1 1 2 1\n9 N",
"output": "1 1\n2 2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2 1 1\n1 1 1 2\n2 2 2 1\n2 2 1 2\n1 1 2 1\n17 N",
"output": "1 1\n2 2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p01193 First Experience | Solve the following coding problem using the programming language python:
After spending long long time, you had gotten tired of computer programming. Instead you were inter- ested in electronic construction. As your first work, you built a simple calculator. It can handle positive integers of up to four decimal digits, and perform addition, subtraction and multiplication of numbers. You didnβt implement division just because it was so complicated. Although the calculator almost worked well, you noticed that it displays unexpected results in several cases. So, you decided to try its simulation by a computer program in order to figure out the cause of unexpected behaviors.
The specification of the calculator you built is as follows. There are three registers on the calculator. The register R1 stores the value of the operation result of the latest operation; the register R2 stores the new input value; and the register R3 stores the input operator. At the beginning, both R1 and R2 hold zero, and R3 holds a null operator. The calculator has keys for decimal digits from β0β to β9β and operators β+β, β-β, βΓβ and β=β. The four operators indicate addition, subtraction, multiplication and conclusion, respectively. When a digit key is pressed, R2 is multiplied by ten, and then added by the pressed digit (as a number). When β+β, β-β or βΓβ is pressed, the calculator first applies the binary operator held in R3 to the values in R1 and R2 and updates R1 with the result of the operation. Suppose R1 has 10, R2 has 3, and R3 has β-β (subtraction operator), R1 is updated with 7 ( = 10 - 3). If R3 holds a null operator, the result will be equal to the value of R2. After R1 is updated, R2 is cleared to zero and R3 is set to the operator which the user entered. β=β indicates termination of a computation. So, when β=β is pressed, the calculator applies the operator held in R3 in the same manner as the other operators, and displays the final result to the user. After the final result is displayed, R3 is reinitialized with a null operator.
The calculator cannot handle numbers with five or more decimal digits. Because of that, if the intermediate computation produces a value less than 0 (i.e., a negative number) or greater than 9999, the calculator displays βEβ that stands for error, and ignores the rest of the user input until β=β is pressed.
Your task is to write a program to simulate the simple calculator.
Input
The input consists of multiple test cases.
Each line of the input specifies one test case, indicating the order of key strokes which a user entered. The input consists only decimal digits (from β0β to β9β) and valid operators β+β, β-β, β*β and β=β where β*β stands for βΓβ.
You may assume that β=β occurs only at the end of each line, and no case contains more than 80 key strokes.
The end of input is indicated by EOF.
Output
For each test case, output one line which contains the result of simulation.
Example
Input
1+2+3+4+5+6+7+8+9+10=
1000-500-250-125=
1*2*3*4*5*6=
5000*5000=
10-100=
100*100=
10000=
Output
55
125
720
E
E
E
E
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36249 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 8, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1+2+3+4+5+6+7+8+9+10=\n1000-500-250-125=\n1*2*3*4*5*6=\n5000*5000=\n10-100=\n100*100=\n10000=",
"output": "55\n125\n720\nE\nE\nE\nE",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | p01331 Warp Hall | Solve the following coding problem using the programming language python:
In 20XX, an efficient material transfer method was established for distant places, and human beings' advance into space was accelerated more and more. This transfer method was innovative in that, in principle, larger substances could be transferred when trying to transfer the substance farther. The details of the transfer method are described below.
First, the substance to be transferred is divided into particles for each unit mass at the start coordinates (1, 1). Each particle must be given a different wave energy. Wave energy is represented by a character string of arbitrary length consisting of V and H, and defines how particles drift in outer space. V means the movement on the coordinates (+1, 0), and H means the movement of (0, +1). For example, a particle given wave energy called VHHV drifts in the universe on the trajectories (2, 1), (2, 2), (2, 3) and then reaches the coordinates (3, 3).
In addition, there are multiple warp holes in outer space, which affect the trajectory of particles. The warp hole has an entrance and an exit, and when a particle moves to the entrance of the warp hole, it always warps to the coordinates of the exit. If the coordinates of the entrance and exit of the i-th warp hole are (ai, bi), (ci, di), the condition ai β€ ci, bi β€ di, (ai, bi) β (ci, di) is satisfied. It is guaranteed that the entrance to the warp hole does not exist at the same coordinates as the entrance to other warp holes or at (1, 1). However, there may be multiple exits in the same location, or one warp hole exit may have another warp hole entrance (in this case, warp consecutively).
For example, if there is a warp hole with (1, 2) as the inlet and (3, 2) as the exit, the particles given HH and wave energy move to (1, 2) and then (3, 2). Warp to 2) and reach (3, 3).
When particles are given wave energy, they move according to it in an instant. When all the particles reach the destination at the same time, they are automatically reconstructed into the original substance.
You are a programmer of Japan Aerospace Exploration Agency. Since the target coordinates (N, M) of the transfer and the coordinate pairs of K warp holes are given, please write a program to find the maximum mass of the substance that can be transferred at one time. The answer can be very large, so print the remainder divided by 1,000,000,007.
Notes on Test Cases
Multiple datasets are given in the above input format. Create a program that outputs each data set in the above output format.
When N, M, K are all 0, it indicates the end of input.
<!-
Input
NMK
a1 b1 c1 d1
...
aK bK cK dK
Satisfy 1 β€ N, M β€ 105, 0 β€ K β€ 103. Also, for any 1 β€ i β€ K, ai β€ ci, bi β€ di, (ai, bi) β (ci, di) is satisfied.
Output
Divide the maximum mass by 1,000,000,007 and output the remainder in one line.
Examples
Input
4 4 1
2 2 3 3
1 4 1
1 2 1 3
5 5 2
2 2 3 4
3 3 5 3
5 5 3
4 4 5 5
2 2 3 3
3 3 4 4
100000 100000 1
2 2 99999 99999
1 1 0
0 0 0
Output
12
1
26
18
615667476
1
Input
4 4 1
2 2 3 3
Output
12
Input
1 4 1
1 2 1 3
Output
1
Input
5 5 2
2 2 3 4
3 3 5 3
Output
26
Input
5 5 3
4 4 5 5
2 2 3 3
3 3 4 4
Output
18
Input
100000 100000 1
2 2 99999 99999
Output
615667476
Input
1 1 0
Output
1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36253 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 8, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1 0",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5 3\n4 4 5 5\n2 2 3 3\n3 3 4 4",
"output": "18",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 4 1\n1 2 1 3",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 1\n2 2 3 3",
"output": "12",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 1\n2 2 3 3\n1 4 1\n1 2 1 3\n5 5 2\n2 2 3 4\n3 3 5 3\n5 5 3\n4 4 5 5\n2 2 3 3\n3 3 4 4\n100000 100000 1\n2 2 99999 99999\n1 1 0\n0 0 0",
"output": "12\n1\n26\n18\n615667476\n1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100000 100000 1\n2 2 99999 99999",
"output": "615667476",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | p01498 King Slime | Solve the following coding problem using the programming language python:
There is a grid of size W Γ H surrounded by walls. Some cells in the grid are occupied by slimes. The slimes want to unite with each other and become a "King Slime".
In each move, a slime can move to east, west, south and north direction until it enters a cell occupied by another slime or hit the surrounding wall. If two slimes come together, they unite and become a new slime.
Your task is write a program which calculates the minimum number of moves that all the slimes unite and become a King Slime. Suppose slimes move one by one and they never move simultaneously.
Input
The first line contains three integers N (2 β€ N β€ 40,000), W and H (1 β€ W, H β€ 100,000), which denote the number of slimes, the width and the height of the grid respectively.
The following N lines describe the initial coordinates of the slimes. The i-th line contains two integers xi (1 β€ xi β€ W) and yi (1 β€ yi β€ H), which indicate the coordinates of the i-th slime . All the coordinates are 1-based.
You may assume that each cell is occupied by at most one slime initially.
Output
Output the minimum number of moves that all the slimes unite and become a King Slime.
Examples
Input
4 3 3
1 1
1 3
3 1
3 3
Output
3
Input
2 3 3
2 2
3 3
Output
2
Input
2 4 4
2 2
3 3
Output
3
Input
2 4 4
2 2
2 3
Output
1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
class UnionFind:
def __init__(self,sz):
self.__ranks = [1] * sz
self.__parents = [ i for i in range(sz) ]
def find_parent(self, x):
if x == self.__parents[x]:
return x
else:
self.__parents[x] = self.find_parent(self.__parents[x])
return self.__parents[x]
def same(self, x, y):
return self.find_parent(x) == self.find_parent(y)
def unite(self, x, y):
px = self.find_parent(x)
py = self.find_parent(y)
if px == py:
return
if self.__ranks[px] > self.__ranks[py]:
self.__parents[py] = px
else:
self.__parents[px] = py
if self.__ranks[px] == self.__ranks[py]:
self.__ranks[py] += 1
def main():
n,w,h = map(int, input().split())
uf = UnionFind(n)
xd = {}
yd = {}
is_edges_slime = False
for i in range(n):
x,y = map(int, sys.stdin.readline().split())
if x == 1 or x == w:
is_edges_slime = True
if y == 1 or y == h:
is_edges_slime = True
if x in xd:
uf.unite(xd[x], i)
else:
xd[x] = i
if y in yd:
uf.unite(yd[y], i)
else:
yd[y] = i
root = set()
for i in range(n):
root.add( uf.find_parent(i) )
if len(root) == 1:
print(n - 1)
else:
ans = n - len(root) # ????Β΄?????????Β¨??????
ans += len(root) - (1 if is_edges_slime else 0) # ???????????????
ans += len(root) - 1 # ????????Β°???????????????
print(ans)
if __name__ == '__main__':
main()
``` | vfc_36257 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 8, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3 3\n2 2\n3 3",
"output": "2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 3\n1 1\n1 3\n3 1\n3 3",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 4 4\n2 2\n3 3",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 4 4\n2 2\n2 3",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3 3\n2 4\n3 3",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3 3\n1 1\n0 3\n3 1\n3 3",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p01946 Slimming Plan | Solve the following coding problem using the programming language python:
Chokudai loves eating so much. However, his doctor Akensho told him that he was overweight, so he finally decided to lose his weight.
Chokudai made a slimming plan of a $D$-day cycle. It is represented by $D$ integers $w_0, ..., w_{D-1}$. His weight is $S$ on the 0-th day of the plan and he aims to reduce it to $T$ ($S > T$). If his weight on the $i$-th day of the plan is $x$, it will be $x + w_{i\%D}$ on the $(i+1)$-th day. Note that $i\%D$ is the remainder obtained by dividing $i$ by $D$. If his weight successfully gets less than or equal to $T$, he will stop slimming immediately.
If his slimming plan takes too many days or even does not end forever, he should reconsider it.
Determine whether it ends or not, and report how many days it takes if it ends.
Input
The input consists of a single test case formatted as follows.
$S$ $T$ $D$
$w_0 ... w_{D-1}$
The first line consists of three integers $S$, $T$, $D$ ($1 \leq S, T, D \leq 100,000, S > T$). The second line consists of $D$ integers $w_0, ..., w_{D-1}$ ($-100,000 \leq w_i \leq 100,000$ for each $i$).
Output
If Chokudai's slimming plan ends on the $d$-th day, print $d$ in one line. If it never ends, print $-1$.
Examples
Input
65 60 3
-2 3 -4
Output
4
Input
65 60 3
-2 10 -3
Output
-1
Input
100000 1 1
-1
Output
99999
Input
60 59 1
-123
Output
1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
S, T, D = map(int, input().split())
S -= T
*W, = map(int, input().split())
F = sum(W)
if F >= 0:
su = S
for i, w in enumerate(W):
su += w
if su <= 0:
print(i+1)
break
else:
print(-1)
exit(0)
su = 0
mi = 0
for d in W:
su += d
mi = min(mi, su)
k = max((S+mi-F-1) // -F, 0)
S += k*F
for i, w in enumerate(W):
S += w
if S <= 0:
print(i+1+k*D)
break
else:
assert 0
``` | vfc_36269 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 536870912,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "100000 1 1\n-1",
"output": "99999",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "65 60 3\n-2 3 -4",
"output": "4",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "60 59 1\n-123",
"output": "1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "65 60 3\n-2 10 -3",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "65 1 3\n-2 3 -4",
"output": "64\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "60 59 1\n-68",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p02095 Colorful Tree | Solve the following coding problem using the programming language python:
H: Colorful Tree
Story
Yamiuchi (assassination) is a traditional event that is held annually in JAG summer camp. Every team displays a decorated tree in the dark and all teams' trees are compared from the point of view of their colorfulness. In this competition, it is allowed to cut the other teamsβ tree to reduce its colorfulness. Despite a team would get a penalty if it were discovered that the team cuts the tree of another team, many teams do this obstruction.
You decided to compete in Yamiuchi and write a program that maximizes the colorfulness of your teamβs tree. The program has to calculate maximum scores for all subtrees in case the other teams cut your tree.
Problem Statement
You are given a rooted tree G with N vertices indexed with 1 through N. The root is vertex 1. There are K kinds of colors indexed with 1 through K. You can paint vertex i with either color c_i or d_i. Note that c_i = d_i may hold, and if so you have to paint vertex i with c_i (=d_i).
Let the colorfulness of tree T be the number of different colors in T. Your task is to write a program that calculates maximum colorfulness for all rooted subtrees. Note that coloring for each rooted subtree is done independently, so previous coloring does not affect to other coloring.
Input
N K
u_1 v_1
:
u_{N-1} v_{N-1}
c_1 d_1
:
c_N d_N
The first line contains two integers N and K in this order.
The following N-1 lines provide information about the edges of G. The i-th line of them contains two integers u_i and v_i, meaning these two vertices are connected with an edge.
The following N lines provide information about color constraints. The i-th line of them contains two integers c_i and d_i explained above.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq K \leq 2\times 10^5
* 1 \leq u_i , v_i \leq N
* 1 \leq c_i , d_i \leq K
* The input graph is a tree.
* All inputs are integers.
Output
Output N lines.
The i-th line of them contains the maximum colorfulness of the rooted subtree of G whose root is i.
Sample Input 1
2 10
1 2
1 9
8 7
Output for Sample Input 1
2
1
Sample Input 2
3 2
1 2
1 3
1 2
1 1
1 2
Output for Sample Input 2
2
1
1
Note that two color options of a vertex can be the same.
Sample Input 3
5 100000
4 3
3 5
1 3
2 1
3 2
1 3
2 1
4 2
1 4
Output for Sample Input 3
4
1
3
1
1
Example
Input
2 10
1 2
1 9
8 7
Output
2
1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36273 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 536870912,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 10\n1 2\n1 9\n8 7",
"output": "2\n1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 10\n1 2\n1 9\n6 7",
"output": "2\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 10\n2 2\n1 9\n10 7",
"output": "1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10\n1 2\n1 9\n8 7",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 10\n1 2\n1 9\n10 7",
"output": "2\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 20\n2 2\n1 9\n10 7",
"output": "1\n0\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | p02233 Fibonacci Number | Solve the following coding problem using the programming language python:
Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:
\begin{equation*} fib(n)= \left \\{ \begin{array}{ll} 1 & (n = 0) \\\ 1 & (n = 1) \\\ fib(n - 1) + fib(n - 2) & \\\ \end{array} \right. \end{equation*}
Constraints
* $0 \leq n \leq 44$
Input
An integer $n$ is given.
Example
Input
3
Output
3
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n = int(input())
num = [1,1]
for i in range(2,45):
f = num[i - 1] + num[i - 2]
num.append(f)
print(num[n])
``` | vfc_36277 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | p02379 Distance | Solve the following coding problem using the programming language python:
Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).
Input
Four real numbers x1, y1, x2 and y2 are given in a line.
Output
Print the distance in real number. The output should not contain an absolute error greater than 10-4.
Example
Input
0 0 1 1
Output
1.41421356
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
x1,y1,x2,y2=map(float,input().split())
n=((x1-x2)**2+(y1-y2)**2)**(1/2)
print('{:.8f}'.format(n))
``` | vfc_36281 | {
"difficulty": "0",
"memory_limit": null,
"memory_limit_bytes": 134217728,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "0 0 1 1",
"output": "1.41421356",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 0 1 2",
"output": "2.2360679775\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 0 2 2",
"output": "2.82842712475\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "-1 0 2 2",
"output": "3.60555127546\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 0 4 2",
"output": "4.472135955\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 1 4 2",
"output": "4.12310562562\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | cd202 | Solve the following coding problem using the programming language python:
Brachiosaurus is trying to become a detective by writing words in codes. It manipulates each word in a sentence by putting the letter 'z' after each vowel, followed by that very vowel.
Eg- "belina" translates into "bezelizinaza" and "zazhiba" translates into "zazazhizibaza". A team of secret agents want to decode the sentences of Brachiosaurus.
Write a program that decodes Brachiosaurus's coded sentences.
Input
The coded sentence is given on a single line. The sentence comprises only of lowercase letters of the English alphabet and spaces. The words will be separated by exactly one space and there will be no spaces at beginning or end. The number of characters (total) will be 100 at the max.
Output
The decoded sentence is to be outputted on a single line.
Example
Input:
razat geze hozotazamnaza ozoraza bezehizisaza
Output:
rat ge hotamna ora behisa
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# imports
import sys
import StringIO
class Problem(object):
def __init__(self, reader):
self.reader = reader
def run(self):
vowels = frozenset(["a", "e", "i", "o", "u"])
last_vowel_block = -1
# decode the message, by replacing the vowel pattterns
for i, letter in enumerate( self.reader.readline().strip() ) :
if i > last_vowel_block :
if letter in vowels:
last_vowel_block = i + 2
sys.stdout.write(letter)
# Main entry point
############################################################
if __name__ == "__main__":
#data = StringIO.StringIO("""razat geze hozotazamnaza ozoraza bezehizisaza""")
data = sys.stdin
problem = Problem(data)
problem.run()
``` | vfc_36285 | {
"difficulty": "6",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "razat geze hozotazamnaza ozoraza bezehizisaza",
"output": "rat ge hotamna ora behisa\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | cw1 | Solve the following coding problem using the programming language python:
While Tom Cruise(Cage) fighting in the movie "Edge of Tomorrow", he finds himself in a modern lab, where he needs to kill the brain of a mutant species Omega.
The DNA of the Omega is made up of characters of A, T, G and C like ours. He has certain enzymes which will cut and remove certain parts of this DNA.
The mutant being an intelligent species, is able to reform its DNA, even after a piece of DNA is removed.
You will be given a DNA sequence, and few enzymes. Suppose, a DNA sequence goes like this : ATGCTGCTATGCATGCAGTGACT, and you are given enzymes which can remove AT and GC sequences. Thereby, you need to remove all occurrences of AT from the DNA first and then reform the DNA and apply the next enzyme to remove all occurrences of GC. The output of the problem would be the string you get at last reforming the pieces which are not removed by these enzymes.
Input
The first line of input consists of an integer n that denotes the number of enzymes. The second line has the DNA sequence.
The next n lines has the input B1, B2, B3... Bn.
Output
For given input DNA sequence, output a single line containing the final reformed DNA that is formed by repeatedly removing all the occurrences of B1, B2, B3... Bn from A.
In case the DNA is completely consumed print 0 to indicate that there is no DNA left.
Constraints
1 <= n <= 10
Example
Input:
2
ATACGCATGACGATGCATGCAGCAT
ATA
GC
Output:
CATGACGATATAAT
Input:
3
ATGCATGCATCGACTCAGCATCAGCATCGACTA
TG
GC
AT
Output:
ACACCGACTCACACGACTA
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
t=input()
str1=raw_input()
for _ in range(t):
ss=raw_input()
str1=str1.replace(ss, "")
if(len(str1)==0):
print '0'
else:
print str1
``` | vfc_36289 | {
"difficulty": "6",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\nATGCATGCATCGACTCAGCATCAGCATCGACTA\nTG\nGC\nAT",
"output": "ACACCGACTCACACGACTA\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\nATACGCATGACGATGCATGCAGCAT\nATA\nGC",
"output": "CATGACGATATAAT\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nATGCATGCATCGACTCAGCATCAGCATCGACTA\nTH\nGC\nAT",
"output": "CGACTCACACGACTA\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | icq1 | Solve the following coding problem using the programming language python:
The success of IEEE code-quest depends on number of times the factor is present in a given string.Help core members to find them
Β Factor of string is defined as a substring.In this case it's '01'.
Input
First line of input contains an integer T, denoting the number of test cases. Then follows description of T cases.Each line of input is a binary form.
Β
Output
Print the number of times the factor is present in a given string.
Β
Constraints
1 <= S <= 100000
1 <= T <= 50
Β
Example
Input:
1
1001010100001
Output:
4
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
'''
Coded by Abhishek The Hacktivist
'''
test = int(raw_input())
for i in range(test):
count = 0
num = str(raw_input().split())
for j in range(len(num)):
if (num[j] == '0') and (num[j+1] == '1'):
count += 1
print count
``` | vfc_36293 | {
"difficulty": "6",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1001010100001",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1001010110001",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1001010110000",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1001011110000",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | mqry | Solve the following coding problem using the programming language python:
One day maths teacher gave the following task for the students, only upon completion students will be taken out for a school fun trip.
First you are a given a list of n numbers and q queries. For each query you are given two indices x and y , you have to report the between the maximum number and minimum number whose indices lie within x and y (both inclusive)
Β
Input
First line of input has two integers n and q , denoting the size of list and number of queries
Next line consists of n spaced integers denoting the elements of the array
Next q lines consists of two integer x and y , denoting the leftmost and rightmost indices of the query
Note : List is 0-indexed
Output
For each query , print the answer in a new line.
Constraints
0< n,q < 100000
0< element of list < 1000000000
0 < x,y < n
Example
Input:
5 2
1 2 3 4 5
1 2
4 4
Output:
1
0
Explanation
Example case .
First query maximum number in given range is 3 and minimum number is 2 so difference 1
Second Query maximum and mimimum both are 5 ,difference is 0
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
dic={}
n, q = map(int, raw_input().split())
li = map(int, raw_input().split())
for i in xrange(q):
l, r = map(int, raw_input().split())
tli=li[l:r+1]
s=str(l) + '+' + str(r)
if s not in dic:
dic[s] = max(tli) - min(tli)
print dic[s]
``` | vfc_36297 | {
"difficulty": "6",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\n1 2 3 4 5\n1 2\n4 4",
"output": "1\n0",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | reverse | Solve the following coding problem using the programming language python:
Sometimes mysteries happen. Chef found a directed graph with N vertices and M edges in his kitchen!
The evening was boring and chef has nothing else to do, so to entertain himself, Chef thought about a question "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to vertex N, where the vertices are numbered from 1 to N.
Input
Each test file contains only one test case.
The first line of the input contains two space separated integers N and M, denoting the number of vertices and the number of edges in the graph respectively. The i^th line of the next M lines contains two space separated integers Xi and Yi, denoting that the i^th edge connects vertices from Xi to Yi.
Output
In a single line, print the minimum number of edges we need to revert. If there is no way of having at least one path from 1 to N, print -1.
Constraints
1 β€ N, M β€ 100000 = 10^5
1 β€ Xi, Yi β€ N
There can be multiple edges connecting the same pair of vertices, There can be self loops too i.e. Xi = Yi
Example
Input:
7 7
1 2
3 2
3 4
7 4
6 2
5 6
7 5
Output:
2
Explanation
We can consider two paths from 1 to 7:
1-2-3-4-7
1-2-6-5-7
In the first one we need to revert edges (3-2), (7-4). In the second one - (6-2), (5-6), (7-5). So the answer is min(2, 3) = 2.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from sys import stdin
from heapq import heappush, heappop
def v_con(M, graph, N):
while M > 0:
a, b = map(int, stdin.readline().split())
graph[a][b] = 0
if not graph[b].has_key(a):
if a == 1 and b == N:
graph[b][a] = 1
elif a != 1:
graph[b][a] = 1
M = M - 1
return graph
def relax(G, u, v, D):
d = D.get(u, float('inf'))+G[u][v]
if d < D.get(v, float('inf')):
D[v] = d
return True
def dijkstra(G, s=1):
D, Q, S = {s:0}, [(0,s)], set()
while Q:
_, u = heappop(Q)
if u in S: continue
S.add(u)
for v in graph[u]:
relax(graph, u, v, D)
heappush(Q, (D[v], v))
return D
N, M = map(int, stdin.readline().split())
graph = [0]
L = N
while L>0:
graph.append({})
L = L - 1
graph = v_con(M, graph, N)
D = dijkstra(graph)
if D.has_key(N):
print D[N]
else:
print -1
``` | vfc_36301 | {
"difficulty": "2",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 7\n1 2 \n3 2\n3 4\n7 4\n6 2\n5 6\n7 5",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 7\n1 2 \n4 2\n3 4\n7 4\n6 2\n5 6\n7 5",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | twtclose | Solve the following coding problem using the programming language python:
Little kids, Jack and Evan like playing their favorite game Glass-and-Stone. Today they want to play something new and came across Twitter on their father's laptop.
They saw it for the first time but were already getting bored to see a bunch of sentences having at most 140 characters each. The only thing they liked to play with it is, closing and opening tweets.
There are N tweets on the page and each tweet can be opened by clicking on it, to see some statistics related to that tweet. Initially all the tweets are closed. Clicking on an open tweet closes it and clicking on a closed tweet opens it. There is also a button to close all the open tweets. Given a sequence of K clicks by Jack, Evan has to guess the total number of open tweets just after each click. Please help Evan in this game.
Input
First line contains two integers N K, the number of tweets (numbered 1 to N) and the number of clicks respectively (1 β€ N, K β€ 1000). Each of the following K lines has one of the following.
CLICK X , where X is the tweet number (1 β€ X β€ N)
CLOSEALL
Output
Output K lines, where the i^th line should contain the number of open tweets just after the i^th click.
Example
Input:
3 6
CLICK 1
CLICK 2
CLICK 3
CLICK 2
CLOSEALL
CLICK 1
Output:
1
2
3
2
0
1
Explanation:
Let open[x] = 1 if the x^th tweet is open and 0 if its closed.
Initially open[1..3] = { 0 , 0 , 0 }. Here is the state of open[1..3] after each click and corresponding count of open tweets.
CLICK 1 : { 1, 0, 0 }, open count = 1
CLICK 2 : { 1, 1, 0 }, open count = 2
CLICK 3 : { 1, 1, 1 }, open count = 3
CLICK 2 : { 1, 0, 1 }, open count = 2
CLOSEALL : { 0, 0, 0 }, open count = 0
CLICK 1 : { 1, 0, 0 }, open count = 1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# your code goes here
n,k=map(int,raw_input().split())
a=[0 for i in range(n)]
cou=0
for i in range(k):
t=raw_input().split()
if len(t)==1:
for j in range(n):
a[j]=0
cou=0
else:
x=int(t[1])-1
a[x]^=1
if a[x]==0:
cou-=1
else:
cou+=1
print cou
``` | vfc_36305 | {
"difficulty": "3",
"memory_limit": null,
"memory_limit_bytes": 0,
"problem_url": null,
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 6\nCLICK 1\nCLICK 2\nCLICK 3\nCLICK 2\nCLOSEALL\nCLICK 1",
"output": "1\n2\n3\n2\n0\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 6\nCLICK 1\nCLICK 2\nCLICK 3\nCLICK 2\nCLOSEALL\nCLICK 1",
"output": "1\n2\n3\n2\n0\n1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1019_B. The hat | Solve the following coding problem using the programming language python:
This is an interactive problem.
Imur Ishakov decided to organize a club for people who love to play the famous game Β«The hatΒ». The club was visited by n students, where n is even. Imur arranged them all in a circle and held a draw to break the students in pairs, but something went wrong. The participants are numbered so that participant i and participant i + 1 (1 β€ i β€ n - 1) are adjacent, as well as participant n and participant 1. Each student was given a piece of paper with a number in such a way, that for every two adjacent students, these numbers differ exactly by one. The plan was to form students with the same numbers in a pair, but it turned out that not all numbers appeared exactly twice.
As you know, the most convenient is to explain the words to the partner when he is sitting exactly across you. Students with numbers i and <image> sit across each other. Imur is wondering if there are two people sitting across each other with the same numbers given. Help him to find such pair of people if it exists.
You can ask questions of form Β«which number was received by student i?Β», and the goal is to determine whether the desired pair exists in no more than 60 questions.
Input
At the beginning the even integer n (2 β€ n β€ 100 000) is given β the total number of students.
You are allowed to ask no more than 60 questions.
Output
To ask the question about the student i (1 β€ i β€ n), you should print Β«? iΒ». Then from standard output you can read the number ai received by student i ( - 109 β€ ai β€ 109).
When you find the desired pair, you should print Β«! iΒ», where i is any student who belongs to the pair (1 β€ i β€ n). If you determined that such pair doesn't exist, you should output Β«! -1Β». In both cases you should immediately terminate the program.
The query that contains your answer is not counted towards the limit of 60 queries.
Please make sure to flush the standard output after each command. For example, in C++ use function fflush(stdout), in Java call System.out.flush(), in Pascal use flush(output) and stdout.flush() for Python language.
Hacking
Use the following format for hacking:
In the first line, print one even integer n (2 β€ n β€ 100 000) β the total number of students.
In the second line print n integers ai ( - 109 β€ ai β€ 109) separated by spaces, where ai is the number to give to i-th student. Any two adjacent elements, including n and 1, must differ by 1 or - 1.
The hacked solution will not have direct access to the sequence ai.
Examples
Input
8
<span class="tex-span"></span>
2
<span class="tex-span"></span>
2
Output
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 8
<span class="tex-span"></span>
! 4
Input
6
<span class="tex-span"></span>
1
<span class="tex-span"></span>
2
<span class="tex-span"></span>
3
<span class="tex-span"></span>
2
<span class="tex-span"></span>
1
<span class="tex-span"></span>
0
Output
<span class="tex-span"></span>
? 1
<span class="tex-span"></span>
? 2
<span class="tex-span"></span>
? 3
<span class="tex-span"></span>
? 4
<span class="tex-span"></span>
? 5
<span class="tex-span"></span>
? 6
<span class="tex-span"></span>
! -1
Note
Input-output in statements illustrates example interaction.
In the first sample the selected sequence is 1, 2, 1, 2, 3, 4, 3, 2
In the second sample the selection sequence is 1, 2, 3, 2, 1, 0.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
# this sequence is a bit scary
# 8
# 1 2 3 2 3 2 1 0
import sys
#sys.stdin=open("data.txt")
#input=sys.stdin.readline
got=[10**18]*100005
def getnum(i):
if got[i]==10**18:
print("? %d"%i)
sys.stdout.flush()
got[i]=int(input())
return got[i]
n=int(input())
if n%4==2:
# the opposite person has a different parity
print("! -1")
else:
lo=1
hi=n//2+1
t1=getnum(lo)
t2=getnum(hi)
lo2=t1-t2
hi2=t2-t1
if lo2==0:
print("! 1")
else:
# binary search
# let's hope that 1 <= mid <= n/2
while lo<hi:
mid=(lo+hi)//2
#print(lo,hi,mid)
mid2=getnum(mid)-getnum(mid+n//2)
if mid2==0:
print("! %d"%mid)
break
if (lo2>0) == (mid2>0):
lo=mid+1
else:
hi=mid-1
else:
print("! %d"%lo)
sys.stdout.flush()
``` | vfc_36309 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n3 \n<span class=\"tex-span\"></span>\n2\n<span class=\"tex-span\"></span>\n1\n<span class=\"tex-span\"></span>\n0",
"output": "! -1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1042_A. Benches | Solve the following coding problem using the programming language python:
There are n benches in the Berland Central park. It is known that a_i people are currently sitting on the i-th bench. Another m people are coming to the park and each of them is going to have a seat on some bench out of n available.
Let k be the maximum number of people sitting on one bench after additional m people came to the park. Calculate the minimum possible k and the maximum possible k.
Nobody leaves the taken seat during the whole process.
Input
The first line contains a single integer n (1 β€ n β€ 100) β the number of benches in the park.
The second line contains a single integer m (1 β€ m β€ 10 000) β the number of people additionally coming to the park.
Each of the next n lines contains a single integer a_i (1 β€ a_i β€ 100) β the initial number of people on the i-th bench.
Output
Print the minimum possible k and the maximum possible k, where k is the maximum number of people sitting on one bench after additional m people came to the park.
Examples
Input
4
6
1
1
1
1
Output
3 7
Input
1
10
5
Output
15 15
Input
3
6
1
6
5
Output
6 12
Input
3
7
1
6
5
Output
7 13
Note
In the first example, each of four benches is occupied by a single person. The minimum k is 3. For example, it is possible to achieve if two newcomers occupy the first bench, one occupies the second bench, one occupies the third bench, and two remaining β the fourth bench. The maximum k is 7. That requires all six new people to occupy the same bench.
The second example has its minimum k equal to 15 and maximum k equal to 15, as there is just a single bench in the park and all 10 people will occupy it.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import math
n=int(input())
m=int(input())
a=[]
for i in range(n):
a.append(int(input()))
maxa=max(a)+m
mina=max(max(a),math.ceil((sum(a)+m)/n))
print(str(mina)+" "+str(maxa))
``` | vfc_36313 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n6\n1\n1\n1\n1\n",
"output": "3 7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n10\n5\n",
"output": "15 15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n6\n1\n6\n5\n",
"output": "6 12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n7\n1\n6\n5\n",
"output": "7 13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "100\n66\n95\n19\n88\n15\n29\n52\n37\n75\n21\n90\n93\n75\n91\n71\n53\n55\n90\n78\n19\n63\n43\n25\n52\n10\n55\n76\n47\n42\n57\n45\n35\n53\n2\n62\n61\n99\n59\n59\n43\n45\n31\n37\n50\n68\n51\n91\n34\n48\n40\n69\n77\n33\n16\n64\n19\n82\n76\n35\n41\n41\n79\n29\n69\n100\n30\n81\n47\n55\n79\n21\n59\n3\n11\n43\n49\n100\n27\n87\n64\n8\n6\n7\n88\n71\n98\n6\n32\n53\n91\n85\n60\n35\n55\n5\n44\n66\n76\n99\n7\n58\n",
"output": "100 166\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1064_F. Candies for Children | Solve the following coding problem using the programming language python:
At the children's festival, children were dancing in a circle. When music stopped playing, the children were still standing in a circle. Then Lena remembered, that her parents gave her a candy box with exactly k candies "Wilky May". Lena is not a greedy person, so she decided to present all her candies to her friends in the circle. Lena knows, that some of her friends have a sweet tooth and others do not. Sweet tooth takes out of the box two candies, if the box has at least two candies, and otherwise takes one. The rest of Lena's friends always take exactly one candy from the box.
Before starting to give candies, Lena step out of the circle, after that there were exactly n people remaining there. Lena numbered her friends in a clockwise order with positive integers starting with 1 in such a way that index 1 was assigned to her best friend Roma.
Initially, Lena gave the box to the friend with number l, after that each friend (starting from friend number l) took candies from the box and passed the box to the next friend in clockwise order. The process ended with the friend number r taking the last candy (or two, who knows) and the empty box. Please note that it is possible that some of Lena's friends took candy from the box several times, that is, the box could have gone several full circles before becoming empty.
Lena does not know which of her friends have a sweet tooth, but she is interested in the maximum possible number of friends that can have a sweet tooth. If the situation could not happen, and Lena have been proved wrong in her observations, please tell her about this.
Input
The only line contains four integers n, l, r and k (1 β€ n, k β€ 10^{11}, 1 β€ l, r β€ n) β the number of children in the circle, the number of friend, who was given a box with candies, the number of friend, who has taken last candy and the initial number of candies in the box respectively.
Output
Print exactly one integer β the maximum possible number of sweet tooth among the friends of Lena or "-1" (quotes for clarity), if Lena is wrong.
Examples
Input
4 1 4 12
Output
2
Input
5 3 4 10
Output
3
Input
10 5 5 1
Output
10
Input
5 4 5 6
Output
-1
Note
In the first example, any two friends can be sweet tooths, this way each person will receive the box with candies twice and the last person to take sweets will be the fourth friend.
In the second example, sweet tooths can be any three friends, except for the friend on the third position.
In the third example, only one friend will take candy, but he can still be a sweet tooth, but just not being able to take two candies. All other friends in the circle can be sweet tooths as well, they just will not be able to take a candy even once.
In the fourth example, Lena is wrong and this situation couldn't happen.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36317 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 1 4 12\n",
"output": " 2",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 5 5 1\n",
"output": " 10",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4 5 6\n",
"output": "-1",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3 4 10\n",
"output": " 3",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1086_D. Rock-Paper-Scissors Champion | Solve the following coding problem using the programming language python:
n players are going to play a rock-paper-scissors tournament. As you probably know, in a one-on-one match of rock-paper-scissors, two players choose their shapes independently. The outcome is then determined depending on the chosen shapes: "paper" beats "rock", "rock" beats "scissors", "scissors" beat "paper", and two equal shapes result in a draw.
At the start of the tournament all players will stand in a row, with their numbers increasing from 1 for the leftmost player, to n for the rightmost player. Each player has a pre-chosen shape that they will use in every game throughout the tournament. Here's how the tournament is conducted:
* If there is only one player left, he is declared the champion.
* Otherwise, two adjacent players in the row are chosen arbitrarily, and they play the next match. The losing player is eliminated from the tournament and leaves his place in the row (with his former neighbours becoming adjacent). If the game is a draw, the losing player is determined by a coin toss.
The organizers are informed about all players' favoured shapes. They wish to find out the total number of players who have a chance of becoming the tournament champion (that is, there is a suitable way to choose the order of the games and manipulate the coin tosses). However, some players are still optimizing their strategy, and can inform the organizers about their new shapes. Can you find the number of possible champions after each such request?
Input
The first line contains two integers n and q β the number of players and requests respectively (1 β€ n β€ 2 β
10^5, 0 β€ q β€ 2 β
10^5).
The second line contains a string of n characters. The i-th of these characters is "R", "P", or "S" if the player i was going to play "rock", "paper", or "scissors" before all requests respectively.
The following q lines describe the requests. The j-th of these lines contain an integer p_j and a character c_j meaning that the player p_j is going to use the shape described by the character c_j from this moment (1 β€ p_j β€ n).
Output
Print q + 1 integers r_0, β¦, r_q, where r_k is the number of possible champions after processing k requests.
Example
Input
3 5
RPS
1 S
2 R
3 P
1 P
2 P
Output
2
2
1
2
2
3
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36321 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\nRPS\n1 S\n2 R\n3 P\n1 P\n2 P\n",
"output": "2\n2\n1\n2\n2\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 0\nS\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\nPSSSSPSPRR\n9 S\n2 P\n6 R\n6 P\n4 R\n1 S\n4 P\n7 P\n1 R\n5 R\n",
"output": "8\n7\n7\n9\n7\n9\n8\n5\n4\n9\n9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 80\nRRRR\n4 P\n4 S\n3 P\n4 P\n4 R\n3 S\n4 P\n4 S\n2 P\n4 P\n4 R\n3 P\n4 P\n4 S\n3 R\n4 P\n4 R\n2 S\n4 P\n4 S\n3 P\n4 P\n4 R\n3 S\n4 P\n4 S\n1 P\n4 P\n4 R\n3 P\n4 P\n4 S\n3 R\n4 P\n4 R\n2 P\n4 P\n4 S\n3 P\n4 P\n4 R\n3 S\n4 P\n4 S\n2 R\n4 P\n4 R\n3 P\n4 P\n4 S\n3 R\n4 P\n4 R\n1 S\n4 P\n4 S\n3 P\n4 P\n4 R\n3 S\n4 P\n4 S\n2 P\n4 P\n4 R\n3 P\n4 P\n4 S\n3 R\n4 P\n4 R\n2 S\n4 P\n4 S\n3 P\n4 P\n4 R\n3 S\n4 P\n4 S\n",
"output": "4\n1\n3\n3\n2\n1\n3\n3\n2\n3\n3\n3\n2\n3\n2\n3\n2\n1\n3\n2\n2\n2\n3\n3\n2\n2\n1\n3\n2\n2\n3\n1\n2\n3\n3\n3\n2\n3\n3\n1\n4\n3\n3\n1\n2\n3\n3\n2\n2\n3\n2\n2\n2\n1\n3\n2\n2\n3\n3\n3\n2\n3\n1\n3\n2\n2\n2\n1\n2\n3\n2\n3\n2\n3\n1\n3\n2\n3\n1\n3\n4\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1106_D. Lunar New Year and a Wander | Solve the following coding problem using the programming language python:
Lunar New Year is approaching, and Bob decides to take a wander in a nearby park.
The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, β¦, a_n is recorded.
Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it.
A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds:
* x is a prefix of y, but x β y (this is impossible in this problem as all considered sequences have the same length);
* in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 10^5), denoting the number of nodes and edges, respectively.
The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 β€ u_i, v_i β€ n), representing the nodes the i-th edge connects.
Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected.
Output
Output a line containing the lexicographically smallest sequence a_1, a_2, β¦, a_n Bob can record.
Examples
Input
3 2
1 2
1 3
Output
1 2 3
Input
5 5
1 4
3 4
5 4
3 2
1 5
Output
1 4 3 2 5
Input
10 10
1 4
6 8
2 5
3 7
9 4
5 6
3 4
8 10
8 9
1 10
Output
1 4 3 7 9 8 6 5 2 10
Note
In the first sample, Bob's optimal wandering path could be 1 β 2 β 1 β 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one.
In the second sample, Bob's optimal wandering path could be 1 β 4 β 3 β 2 β 3 β 4 β 1 β 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from heapq import heappush, heappop
n,m = map(int,input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
a,b = map(int,input().split())
a-=1
b-=1
adj[a].append(b)
adj[b].append(a)
st = set()
hp = []
v = [False for _ in range(n)]
heappush(hp,0)
v[0] = True
ans = []
while hp:
x = heappop(hp)
ans += [x]
for i in adj[x]:
if v[i]:
continue
v[i] = True
heappush(hp,i)
print(*[i+1 for i in ans])
``` | vfc_36325 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 2\n1 3\n",
"output": "1 2 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n1 4\n6 8\n2 5\n3 7\n9 4\n5 6\n3 4\n8 10\n8 9\n1 10\n",
"output": "1 4 3 7 9 8 6 5 2 10 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n1 4\n3 4\n5 4\n3 2\n1 5\n",
"output": "1 4 3 2 5 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\n1 2\n",
"output": "1 2 ",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1133_E. K Balanced Teams | Solve the following coding problem using the programming language python:
You are a coach at your local university. There are n students under your supervision, the programming skill of the i-th student is a_i.
You have to form k teams for yet another new programming competition. As you know, the more students are involved in competition the more probable the victory of your university is! So you have to form no more than k (and at least one) non-empty teams so that the total number of students in them is maximized. But you also know that each team should be balanced. It means that the programming skill of each pair of students in each team should differ by no more than 5. Teams are independent from one another (it means that the difference between programming skills of two students from two different teams does not matter).
It is possible that some students not be included in any team at all.
Your task is to report the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.
If you are Python programmer, consider using PyPy instead of Python when you submit your code.
Input
The first line of the input contains two integers n and k (1 β€ k β€ n β€ 5000) β the number of students and the maximum number of teams, correspondingly.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^9), where a_i is a programming skill of the i-th student.
Output
Print one integer β the maximum possible total number of students in no more than k (and at least one) non-empty balanced teams.
Examples
Input
5 2
1 2 15 15 15
Output
5
Input
6 1
36 4 1 25 9 16
Output
2
Input
4 4
1 10 100 1000
Output
4
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n,k= kk()
ls = sorted(ll())
vs,ne = [0]*n,[-1]*n
b = 0
for a in range(n):
while b < n and ls[b] - ls[a] < 6: b+=1
vs[a],ne[a] = b-a, b
curr = [0]*(n+1)
# print(vs)
for _ in range(k):
# print(curr)
prev = curr
curr = [0]*(n+1)
for i in range(n):
curr[i] = vs[i]+prev[ne[i]]
m = 0
for i in range(n-1, -1, -1):
if m > curr[i]: curr[i]=m
else: m = curr[i]
print(m)
``` | vfc_36329 | {
"difficulty": "11",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4\n1 10 100 1000\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 1\n36 4 1 25 9 16\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n1 2 15 15 15\n",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1154_B. Make Them Equal | Solve the following coding problem using the programming language python:
You are given a sequence a_1, a_2, ..., a_n consisting of n integers.
You can choose any non-negative integer D (i.e. D β₯ 0), and for each a_i you can:
* add D (only once), i. e. perform a_i := a_i + D, or
* subtract D (only once), i. e. perform a_i := a_i - D, or
* leave the value of a_i unchanged.
It is possible that after an operation the value a_i becomes negative.
Your goal is to choose such minimum non-negative integer D and perform changes in such a way, that all a_i are equal (i.e. a_1=a_2=...=a_n).
Print the required D or, if it is impossible to choose such value D, print -1.
For example, for array [2, 8] the value D=3 is minimum possible because you can obtain the array [5, 5] if you will add D to 2 and subtract D from 8. And for array [1, 4, 7, 7] the value D=3 is also minimum possible. You can add it to 1 and subtract it from 7 and obtain the array [4, 4, 4, 4].
Input
The first line of the input contains one integer n (1 β€ n β€ 100) β the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 100) β the sequence a.
Output
Print one integer β the minimum non-negative integer value D such that if you add this value to some a_i, subtract this value from some a_i and leave some a_i without changes, all obtained values become equal.
If it is impossible to choose such value D, print -1.
Examples
Input
6
1 4 4 7 4 1
Output
3
Input
5
2 2 5 2 5
Output
3
Input
4
1 3 3 7
Output
-1
Input
2
2 8
Output
3
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n = int(input())
L = [int(i) for i in input().split()]
F = []
mi = 101
ma = 0
for i in L:
if i not in F:
F.append(i)
if len(F) > 3:
print(-1)
else:
F.sort()
if len(F) == 3:
D = F[1] - F[0]
if F[2] - F[1] == D:
print(D)
else:
print(-1)
elif len(F) == 2:
D = F[1] - F[0]
if D % 2:
print(D)
else:
print(D // 2)
else:
print(0)
``` | vfc_36333 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n2 8\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1175_G. Yet Another Partiton Problem | Solve the following coding problem using the programming language python:
You are given array a_1, a_2, ..., a_n. You need to split it into k subsegments (so every element is included in exactly one subsegment).
The weight of a subsegment a_l, a_{l+1}, ..., a_r is equal to (r - l + 1) β
max_{l β€ i β€ r}(a_i). The weight of a partition is a total weight of all its segments.
Find the partition of minimal weight.
Input
The first line contains two integers n and k (1 β€ n β€ 2 β
10^4, 1 β€ k β€ min(100, n)) β the length of the array a and the number of subsegments in the partition.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 2 β
10^4) β the array a.
Output
Print single integer β the minimal weight among all possible partitions.
Examples
Input
4 2
6 1 7 4
Output
25
Input
4 3
6 1 7 4
Output
21
Input
5 4
5 1 5 1 5
Output
21
Note
The optimal partition in the first example is next: 6 1 7 \bigg| 4.
The optimal partition in the second example is next: 6 \bigg| 1 \bigg| 7 4.
One of the optimal partitions in the third example is next: 5 \bigg| 1 5 \bigg| 1 \bigg| 5.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36337 | {
"difficulty": "13",
"memory_limit": null,
"memory_limit_bytes": 512000000,
"problem_url": null,
"time_limit": "{'seconds': 5, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4\n5 1 5 1 5\n",
"output": "21\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1194_F. Crossword Expert | Solve the following coding problem using the programming language python:
Today Adilbek is taking his probability theory test. Unfortunately, when Adilbek arrived at the university, there had already been a long queue of students wanting to take the same test. Adilbek has estimated that he will be able to start the test only T seconds after coming.
Fortunately, Adilbek can spend time without revising any boring theorems or formulas. He has an app on this smartphone which contains n Japanese crosswords to solve. Adilbek has decided to solve them all one by one in the order they are listed in the app, without skipping any crossword. For each crossword, a number t_i is given that represents the time it takes an average crossword expert to solve this crossword (the time is given in seconds).
Adilbek is a true crossword expert, but, unfortunately, he is sometimes unlucky in choosing the way to solve the crossword. So, it takes him either t_i seconds or t_i + 1 seconds to solve the i-th crossword, equiprobably (with probability 1/2 he solves the crossword in exactly t_i seconds, and with probability 1/2 he has to spend an additional second to finish the crossword). All these events are independent.
After T seconds pass (or after solving the last crossword, if he manages to do it in less than T seconds), Adilbek closes the app (if he finishes some crossword at the same moment, that crossword is considered solved; otherwise Adilbek does not finish solving the current crossword at all). He thinks it would be an interesting probability theory problem to calculate E β the expected number of crosswords he will be able to solve completely. Can you calculate it?
Recall that the expected value of a discrete random variable is the probability-weighted average of all possible values β in this problem it means that the expected value of the number of solved crosswords can be calculated as E = β _{i = 0}^{n} i p_i, where p_i is the probability that Adilbek will solve exactly i crosswords.
We can represent E as rational fraction P/Q with Q > 0. To give the answer, you should print P β
Q^{-1} mod (10^9 + 7).
Input
The first line contains two integers n and T (1 β€ n β€ 2 β
10^5, 1 β€ T β€ 2 β
10^{14}) β the number of crosswords and the time Adilbek has to spend, respectively.
The second line contains n integers t_1, t_2, ..., t_n (1 β€ t_i β€ 10^9), where t_i is the time it takes a crossword expert to solve the i-th crossword.
Note that Adilbek solves the crosswords in the order they are given in the input without skipping any of them.
Output
Print one integer β the expected value of the number of crosswords Adilbek solves in T seconds, expressed in the form of P β
Q^{-1} mod (10^9 + 7).
Examples
Input
3 5
2 2 2
Output
750000007
Input
3 5
2 1 2
Output
125000003
Note
The answer for the first sample is equal to 14/8.
The answer for the second sample is equal to 17/8.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
mod = 10 ** 9 + 7
MAX = 2 * 10 ** 5+2
r = [1] * MAX
factorial = [1] * MAX
rfactorial = [1] * MAX
rp = [1] * MAX
#Permite precalcular factorial hasta "MAX", para evitar tener que calcularlo varias veces
#dentro de la ejecucion del programa.
for i in range(2, MAX):
factorial[i] = i * factorial[i - 1] % mod
r[i] = mod - (mod // i) * r[mod%i] % mod
rfactorial[i] = rfactorial[i-1] * r[i] % mod
#Calcula el inverso de "p" para evitar usar fracciones racionales.
for i in range(1, MAX):
rp[i] = rp[i - 1] * (mod + 1) // 2 % mod
n, T = list(map(int, input().split()))
t = list(map(int, input().split()))
t.append(10**10+1)
#Permite calcular las Combinacione de n en k.
def Combination(n,k):
return factorial[n]*rfactorial[k]*rfactorial[n-k]
S=0
E=0
for i in range(0,n+1):
sim = 0
for add in range(2):
l_, r_ = max(0, T-S-t[i] + add), min(i, T-S)
for x in range(l_, r_+1):
sim += Combination(i,x) * rp[i+1]
E = (E + i * sim) % mod
S += t[i]
print(E)
``` | vfc_36341 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n2 2 2\n",
"output": "750000007\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 5\n2 1 2\n",
"output": "125000003\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 30\n1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1\n",
"output": "310937903\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 31\n2 2 1 2 1 1 2 1 2 2 1 2 1 2 1 1 1 2 1 2\n",
"output": "153515832\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 26\n1 2 1 1 1 2 1 1 2 2 2 1 2 1 2 1 1 2 2 1\n",
"output": "509799974\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 28\n2 1 1 2 2 1 2 2 2 1 2 1 1 1 1 2 1 1 2 1\n",
"output": "81361785\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1211_C. Ice Cream | Solve the following coding problem using the programming language python:
Summer in Berland lasts n days, the price of one portion of ice cream on the i-th day is c_i. Over the summer, Tanya wants to eat exactly k portions of ice cream. At the same time, on the i-th day, she decided that she would eat at least a_i portions, but not more than b_i (a_i β€ b_i) portions. In other words, let d_i be equal to the number of portions that she eats on the i-th day. Then d_1+d_2+...+d_n=k and a_i β€ d_i β€ b_i for each i.
Given that portions of ice cream can only be eaten on the day of purchase, find the minimum amount of money that Tanya can spend on ice cream in the summer.
Input
The first line contains two integers n and k (1 β€ n β€ 2β
10^5, 0 β€ k β€ 10^9) β the number of days and the total number of servings of ice cream that Tanya will eat in the summer.
The following n lines contain descriptions of the days, one description per line. Each description consists of three integers a_i, b_i, c_i (0 β€ a_i β€ b_i β€ 10^9, 1 β€ c_i β€ 10^6).
Output
Print the minimum amount of money that Tanya can spend on ice cream in the summer. If there is no way for Tanya to buy and satisfy all the requirements, then print -1.
Examples
Input
3 7
3 5 6
0 3 4
3 3 3
Output
31
Input
1 45000
40000 50000 100000
Output
4500000000
Input
3 100
2 10 50
50 60 16
20 21 25
Output
-1
Input
4 12
2 5 1
1 2 2
2 3 7
3 10 4
Output
35
Note
In the first example, Tanya needs to eat 3 portions of ice cream on the first day, 1 portions of ice cream on the second day and 3 portions of ice cream on the third day. In this case, the amount of money spent is 3β
6+1β
4+3β
3=31. It can be shown that any other valid way to eat exactly 7 portions of ice cream costs more.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36345 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 7\n3 5 6\n0 3 4\n3 3 3\n",
"output": "\n31\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 45000\n40000 50000 100000\n",
"output": "\n4500000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 100\n2 10 50\n50 60 16\n20 21 25\n",
"output": "\n-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 12\n2 5 1\n1 2 2\n2 3 7\n3 10 4\n",
"output": "\n35\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1234_B1. Social Network (easy version) | Solve the following coding problem using the programming language python:
The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0).
Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.
You (suddenly!) have the ability to see the future. You know that during the day you will receive n messages, the i-th message will be received from the friend with ID id_i (1 β€ id_i β€ 10^9).
If you receive a message from id_i in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.
Otherwise (i.e. if there is no conversation with id_i on the screen):
* Firstly, if the number of conversations displayed on the screen is k, the last conversation (which has the position k) is removed from the screen.
* Now the number of conversations on the screen is guaranteed to be less than k and the conversation with the friend id_i is not displayed on the screen.
* The conversation with the friend id_i appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down.
Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all n messages.
Input
The first line of the input contains two integers n and k (1 β€ n, k β€ 200) β the number of messages and the number of conversations your smartphone can show.
The second line of the input contains n integers id_1, id_2, ..., id_n (1 β€ id_i β€ 10^9), where id_i is the ID of the friend which sends you the i-th message.
Output
In the first line of the output print one integer m (1 β€ m β€ min(n, k)) β the number of conversations shown after receiving all n messages.
In the second line print m integers ids_1, ids_2, ..., ids_m, where ids_i should be equal to the ID of the friend corresponding to the conversation displayed on the position i after receiving all n messages.
Examples
Input
7 2
1 2 3 2 1 3 2
Output
2
2 1
Input
10 4
2 3 3 1 1 2 1 2 3 3
Output
3
1 3 2
Note
In the first example the list of conversations will change in the following way (in order from the first to last message):
* [];
* [1];
* [2, 1];
* [3, 2];
* [3, 2];
* [1, 3];
* [1, 3];
* [2, 1].
In the second example the list of conversations will change in the following way:
* [];
* [2];
* [3, 2];
* [3, 2];
* [1, 3, 2];
* and then the list will not change till the end.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def line():
return map(int, input().split())
def num():
return int(input())
from collections import OrderedDict as od
n,k = line()
ids = list(line())
screen = od()
for id in ids:
if id not in screen:
if len(screen)==k:
screen.popitem(last=False)
screen[id]=None
print(len(screen))
print(' '.join(map(str, reversed(screen))))
``` | vfc_36349 | {
"difficulty": "8",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 4\n2 3 3 1 1 2 1 2 3 3\n",
"output": "3\n1 3 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 2\n1 2 3 2 1 3 2\n",
"output": "2\n2 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 2\n1 2 3 4 5 6 7 8 9\n",
"output": "2\n9 8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 4\n1\n",
"output": "1\n1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1252_L. Road Construction | Solve the following coding problem using the programming language python:
There are N cities in the country of Numbata, numbered from 1 to N. Currently, there is no road connecting them. Therefore, each of these N cities proposes a road candidate to be constructed.
City i likes to connect with city A_i, so city i proposes to add a direct bidirectional road connecting city i and city A_i. It is guaranteed that no two cities like to connect with each other. In other words, there is no pair of integers i and j where A_i = j and A_j = i. It is also guaranteed that any pair of cities are connected by a sequence of road proposals. In other words, if all proposed roads are constructed, then any pair of cities are connected by a sequence of constructed road.
City i also prefers the road to be constructed using a specific material. Each material can be represented by an integer (for example, 0 for asphalt, 1 for wood, etc.). The material that can be used for the road connecting city i and city A_i is represented by an array B_i containing M_i integers: [(B_i)_1, (B_i)_2, ..., (B_i)_{M_i}]. This means that the road connecting city i and city A_i can be constructed with either of the material in B_i.
There are K workers to construct the roads. Each worker is only familiar with one material, thus can only construct a road with a specific material. In particular, the i^{th} worker can only construct a road with material C_i. Each worker can only construct at most one road. You want to assign each worker to construct a road such that any pair of cities are connected by a sequence of constructed road.
Input
Input begins with a line containing two integers: N K (3 β€ N β€ 2000; 1 β€ K β€ 2000) representing the number of cities and the number of workers, respectively. The next N lines each contains several integers: A_i M_i (B_i)_1, (B_i)_2, β
β
β
, (B_i)_{M_i} (1 β€ A_i β€ N; A_i β i; 1 β€ M_i β€ 10 000; 0 β€ (B_i)_1 < (B_i)_2 < ... < (B_i)_{M_i} β€ 10^9) representing the bidirectional road that city i likes to construct. It is guaranteed that the sum of M_i does not exceed 10 000. It is also guaranteed that no two cities like to connect with each other and any pair of cities are connected by a sequence of road proposals. The next line contains K integers: C_i (0 β€ C_i β€ 10^9) representing the material that is familiarized by the workers.
Output
If it is not possible to assign each worker to construct a road such that any pair of cities are connected by a sequence of constructed road, simply output -1 in a line. Otherwise, for each worker in the same order as input, output in a line two integers (separated by a single space): u and v in any order. This means that the worker constructs a direct bidirectional road connecting city u and v. If the worker does not construct any road, output "0 0" (without quotes) instead. Each pair of cities can only be assigned to at most one worker. You may output any assignment as long as any pair of cities are connected by a sequence of constructed road.
Examples
Input
4 5
2 2 1 2
3 2 2 3
4 2 3 4
2 2 4 5
1 2 3 4 5
Output
1 2
2 3
3 4
0 0
4 2
Input
4 5
2 2 10 20
3 2 2 3
4 2 3 4
2 2 4 5
1 2 3 4 5
Output
-1
Note
Explanation for the sample input/output #1
We can assign the workers to construct the following roads:
* The first worker constructs a road connecting city 1 and city 2.
* The second worker constructs a road connecting city 2 and city 3.
* The third worker constructs a road connecting city 3 and city 4.
* The fourth worker does not construct any road.
* The fifth worker constructs a road connecting city 4 and city 2.
Therefore, any pair of cities are now connected by a sequence of constructed road.
Explanation for the sample input/output #2
There is no worker that can construct a road connecting city 1, thus city 1 is certainly isolated.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36353 | {
"difficulty": "19",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 5\n2 2 1 2\n3 2 2 3\n4 2 3 4\n2 2 4 5\n1 2 3 4 5\n",
"output": "\n1 2\n2 3\n3 4\n0 0\n4 2\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 131_F. Present to Mom | Solve the following coding problem using the programming language python:
How many stars are there in the sky? A young programmer Polycarpus can't get this question out of his head! He took a photo of the starry sky using his digital camera and now he analyzes the resulting monochrome digital picture. The picture is represented by a rectangular matrix consisting of n lines each containing m characters. A character equals '1', if the corresponding photo pixel is white and '0', if it is black.
Polycarpus thinks that he has found a star on the photo if he finds a white pixel surrounded by four side-neighboring pixels that are also white:
1
111
1
a star on the photo
Polycarpus whats to cut out a rectangular area from the photo and give his mom as a present. This area should contain no less than k stars. The stars can intersect, have shared white pixels on the photo. The boy will cut out the rectangular area so that its borders will be parallel to the sides of the photo and the cuts will go straight between the pixel borders.
Now Polycarpus keeps wondering how many ways there are to cut an area out of the photo so that it met the conditions given above. Help Polycarpus find this number.
Input
The first line of the input data contains three integers n, m and k (1 β€ n, m β€ 500;1 β€ k β€ nm). Then follow n lines, containing the description of the given photo as a sequence of lines. Each line contains m characters '0' or '1'.
Output
Print the required number of areas on the given photo.
Examples
Input
4 6 2
111000
111100
011011
000111
Output
6
Input
5 5 4
11111
11111
11111
11111
11111
Output
9
Note
We'll number the rows and columns below starting from 1, the coordinates (p, q) will denote a cell in row p, column q.
In the first sample Polycarpus should cut out any area containing a rectangle whose opposite corners lie in cells (1, 1) and (3, 4). Only rectangles with opposite corners in (1, 1) and (x, y), where x β₯ 3 and y β₯ 4 fit the conditions.
In the second sample any rectangle whose each side is no less than four, will do. The possible rectangle sizes are 4 Γ 4, 4 Γ 5, 5 Γ 4 and 5 Γ 5. Such figures can be cut in 4 ways, 2 ways, 2 ways and 1 way correspondingly.
Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cin, cout streams or the %I64d specificator.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36365 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 5, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 5 4\n11111\n11111\n11111\n11111\n11111\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 6 2\n111000\n111100\n011011\n000111\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1 1\n1\n1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1339_C. Powered Addition | Solve the following coding problem using the programming language python:
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{x-1} for j = 1, 2, β¦, k. Note that you are allowed to not select any indices at all.
You have to make a nondecreasing as fast as possible. Find the smallest number T such that you can make the array nondecreasing after at most T seconds.
Array a is nondecreasing if and only if a_{1} β€ a_{2} β€ β¦ β€ a_{n}.
You have to answer t independent test cases.
Input
The first line contains a single integer t (1 β€ t β€ 10^{4}) β the number of test cases.
The first line of each test case contains single integer n (1 β€ n β€ 10^{5}) β the length of array a. It is guaranteed that the sum of values of n over all test cases in the input does not exceed 10^{5}.
The second line of each test case contains n integers a_{1}, a_{2}, β¦, a_{n} (-10^{9} β€ a_{i} β€ 10^{9}).
Output
For each test case, print the minimum number of seconds in which you can make a nondecreasing.
Example
Input
3
4
1 7 6 5
5
1 2 3 4 5
2
0 -4
Output
2
0
3
Note
In the first test case, if you select indices 3, 4 at the 1-st second and 4 at the 2-nd second, then a will become [1, 7, 7, 8]. There are some other possible ways to make a nondecreasing in 2 seconds, but you can't do it faster.
In the second test case, a is already nondecreasing, so answer is 0.
In the third test case, if you do nothing at first 2 seconds and select index 2 at the 3-rd second, a will become [0, 0].
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import math
n = int(input())
for i in range(n):
m = int(input())
nums = [int(i) for i in input().split()]
highest = nums[0]
mostDiff = 0
for j in range(len(nums)):
if highest - nums[j] > mostDiff:
mostDiff = highest - nums[j]
if nums[j] > highest:
highest = nums[j]
if mostDiff == 0:
print(0)
else:
print(int(math.log(mostDiff, 2)+1))
``` | vfc_36369 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n4\n1 7 6 5\n5\n1 2 3 4 5\n2\n0 -4\n",
"output": "2\n0\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n3\n1000000000 0 -1000000000\n1\n6\n2\n-1000000000 1000000000\n2\n1000000000 -1000000000\n2\n1000000000 1000000000\n2\n-1000000000 -1000000000\n",
"output": "31\n0\n0\n31\n0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n3\n1000000000 0 -1000000000\n1\n6\n2\n-1000000000 1000000000\n2\n1000000000 -1000000000\n2\n1000000000 1000000100\n2\n-1000000000 -1000000000\n",
"output": "31\n0\n0\n31\n0\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n4\n1 12 6 5\n5\n1 2 3 4 5\n2\n0 -4\n",
"output": "3\n0\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n4\n1 12 6 5\n5\n1 2 3 4 5\n2\n-1 -4\n",
"output": "3\n0\n2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1360_G. A/B Matrix | Solve the following coding problem using the programming language python:
You are given four positive integers n, m, a, b (1 β€ b β€ n β€ 50; 1 β€ a β€ m β€ 50). Find any such rectangular matrix of size n Γ m that satisfies all of the following conditions:
* each row of the matrix contains exactly a ones;
* each column of the matrix contains exactly b ones;
* all other elements are zeros.
If the desired matrix does not exist, indicate this.
For example, for n=3, m=6, a=2, b=1, there exists a matrix satisfying the conditions above:
$$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\\ 1 & 0 & 0 & 1 & 0 & 0 \\\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$
Input
The first line contains an integer t (1 β€ t β€ 1000) β the number of test cases. Then t test cases follow.
Each test case is described by four positive integers n, m, a, b (1 β€ b β€ n β€ 50; 1 β€ a β€ m β€ 50), where n and m are the sizes of the matrix, and a and b are the number of ones for rows and columns, respectively.
Output
For each test case print:
* "YES" (without quotes) and the required matrix (if there are several answers, print any) if it exists, or
* "NO" (without quotes) if it does not exist.
To print the matrix n Γ m, print n rows, each of which consists of m numbers 0 or 1 describing a row of the matrix. Numbers must be printed without spaces.
Example
Input
5
3 6 2 1
2 2 2 1
2 2 2 2
4 4 2 2
2 1 1 2
Output
YES
010001
100100
001010
NO
YES
11
11
YES
1100
1100
0011
0011
YES
1
1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
for q in range(int(input())):
n, m, a, b = map(int, input().split())
if n*a != m*b:
print('NO')
continue
print('YES')
t = '1'*a+'0'*(m-a)
for i in range(n):
print(t)
t = t[m-a:]+t[:m-a]
``` | vfc_36373 | {
"difficulty": "13",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n3 6 2 1\n2 2 2 1\n2 2 2 2\n4 4 2 2\n2 1 1 2\n",
"output": "YES\n110000\n001100\n000011\nNO\nYES\n11\n11\nYES\n1100\n0011\n1100\n0011\nYES\n1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3 6 2 1\n2 2 2 1\n2 2 2 2\n4 4 2 2\n2 1 1 2\n",
"output": "YES\n110000\n001100\n000011\nNO\nYES\n11\n11\nYES\n1100\n0011\n1100\n0011\nYES\n1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3 6 2 1\n2 2 2 1\n2 2 2 2\n4 4 1 2\n2 1 1 2\n",
"output": "YES\n110000\n001100\n000011\nNO\nYES\n11\n11\nNO\nYES\n1\n1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1401_A. Distance and Axis | Solve the following coding problem using the programming language python:
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k.
<image> The description of the first test case.
Since sometimes it's impossible to find such point B, we can, in one step, increase or decrease the coordinate of A by 1. What is the minimum number of steps we should do to make such point B exist?
Input
The first line contains one integer t (1 β€ t β€ 6000) β the number of test cases.
The only line of each test case contains two integers n and k (0 β€ n, k β€ 10^6) β the initial position of point A and desirable absolute difference.
Output
For each test case, print the minimum number of steps to make point B exist.
Example
Input
6
4 0
5 8
0 1000000
0 0
1 0
1000000 1000000
Output
0
3
1000000
0
1
0
Note
In the first test case (picture above), if we set the coordinate of B as 2 then the absolute difference will be equal to |(2 - 0) - (4 - 2)| = 0 and we don't have to move A. So the answer is 0.
In the second test case, we can increase the coordinate of A by 3 and set the coordinate of B as 0 or 8. The absolute difference will be equal to |8 - 0| = 8, so the answer is 3.
<image>
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
for _ in range(int(input())):
n, k = map(int, input().split())
if n<k:print(k-n)
elif n%2 == k%2: print(0)
else: print(1)
``` | vfc_36381 | {
"difficulty": "7",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n4 0\n5 8\n0 1000000\n0 0\n1 0\n1000000 1000000\n",
"output": "0\n3\n1000000\n0\n1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n7 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n15 0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000 0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n3 0\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1424_H. Lookup Tables | Solve the following coding problem using the programming language python:
John has Q closed intervals of consecutive 2K-bit numbers [l_i, r_i] and one 16-bit value v_i for each interval. (0 β€ i < Q)
John wants to implement a function F that maps 2K-bit numbers to 16-bit numbers in such a way that inputs from each interval are mapped to that interval's value. In other words: $$$F(x) = v_i, \; for every 0 β€ i < Q \; , and every x β [l_i, r_i]$$$ The output of F for other inputs is unimportant.
John wants to make his implementation of F fast so he has decided to use lookup tables. A single 2K-bit lookup table would be too large to fit in memory, so instead John plans to use two K-bit lookup tables, LSBTable and MSBTable. His implementation will look like this: $$$ F(x) = LSBTable[lowKBits(x)] \; \& \; MSBTable[highKBits(x)]$$$ In other words it returns the "bitwise and" of results of looking up the K least significant bits in LSBTable and the K most significant bits in MSBTable.
John needs your help. Given K, Q and Q intervals [l_i, r_i] and values v_i, find any two lookup tables which can implement F or report that such tables don't exist.
Input
The first line contains two integers K and Q ( 1 <= K <= 16, 1 <= Q <= 2β
10^5).
Each of the next Q lines contains three integers l_i, r_i and v_i. ( 0 β€ l_i β€ r_i < 2^{2K}, 0 β€ v_i < 2^{16}).
Output
On the first line output "possible" (without quotes) if two tables satisfying the conditions exist, or "impossible" (without quotes) if they don't exist.
If a solution exists, in the next 2 β
2^K lines your program should output all values of the two lookup tables (LSBTable and MSBTable) it found. When there are multiple pairs of tables satisfying the conditions, your program may output any such pair.
On lines 1 + i output LSBTable[i]. (0 β€ i < 2^K, 0 β€ LSBTable[i] < 2^{16}).
On lines 1 + 2^K + i output MSBTable[i]. (0 β€ i < 2^K, 0 β€ MSBTable[i] < 2^{16}).
Examples
Input
1 2
0 2 1
3 3 3
Output
possible
1
3
1
3
Input
2 4
4 5 3
6 7 2
0 3 0
12 13 1
Output
possible
3
3
2
2
0
3
0
1
Input
2 3
4 4 3
5 6 2
12 14 1
Output
impossible
Note
A closed interval [a, b] includes both a and b.
In the first sample, tables LSBTable = [1,3] and MSBTable = [1,3] satisfy the conditions: F[0] = LSBTable[0] \& MSBTable[0] = 1 \& 1 = 1, F[1] = LSBTable[1] \& MSBTable[0] = 3 \& 1 = 1, F[2] = LSBTable[0] \& MSBTable[1] = 1 \& 3 = 1, F[3] = LSBTable[1] \& MSBTable[1] = 3 \& 3 = 3.
In the second sample, tables LSBTable = [3,3,2,2] and MSBTable = [0,3,0,1] satisfy all the conditions.
In the third sample there are no two lookup tables which can satisfy the conditions.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36385 | {
"difficulty": "14",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 2\n0 2 1\n3 3 3\n",
"output": "possible\n1\n3\n1\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n4 4 3\n5 6 2\n12 14 1\n",
"output": "impossible\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 4\n4 5 3\n6 7 2\n0 3 0\n12 13 1\n",
"output": "possible\n3\n3\n2\n2\n0\n3\n0\n1\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1445_D. Divide and Sum | Solve the following coding problem using the programming language python:
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
def ncr(n, r, p):
# initialize numerator
# and denominator
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
n = int(input())
a = sorted(list(map(int, input().split())))
ans = 0
for i in range(n):
ans += abs(a[i] - a[2*n-1-i])
fac = ncr(2*n, n, 998244353)
print((fac * ans) % 998244353)
``` | vfc_36389 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 512000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n13 8 35 94 9284 34 54 69 123 846\n",
"output": "2588544",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2 1 2 1\n",
"output": "12",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 2 2 2 2 2\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 4\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n2 5 6 25 22 21 7 9 7 22 25 25 22 24\n",
"output": "370656",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "16\n998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244362 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363 998244363\n",
"output": "633087063",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 146_D. Lucky Number 2 | Solve the following coding problem using the programming language python:
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
shit =False
if s < 0 or f < 0:
if(a[2] == a[3]):
ans = "74"*a[2]+"7"
shit = True
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
ans = "-1"
elif s>0 or f>0:
s+=1
f+=1
if ans[:2] == "47":
if(ans[-1] == "4"):
ans = "4"*f + "7" + ans[2:-1] + "7"*(s-1) + "4"
else:
ans = "4"*f + "7" + ans[2:] + "7"*(s-1)
else:
if(ans[-1] == "4"):
ans = "7" + "4"*f + ans[2:-1] + "7"*(s-1) + "4"
else:
ans = "7" + "4"*f + ans[2:] + "7"*(s-1)
print(ans)
``` | vfc_36393 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2 1 1\n",
"output": "4774\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 7 3 1\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10 1 2\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1 3 1\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1495_F. Squares | Solve the following coding problem using the programming language python:
There are n squares drawn from left to right on the floor. The i-th square has three integers p_i,a_i,b_i, written on it. The sequence p_1,p_2,...,p_n forms a permutation.
Each round you will start from the leftmost square 1 and jump to the right. If you are now on the i-th square, you can do one of the following two operations:
1. Jump to the i+1-th square and pay the cost a_i. If i=n, then you can end the round and pay the cost a_i.
2. Jump to the j-th square and pay the cost b_i, where j is the leftmost square that satisfies j > i, p_j > p_i. If there is no such j then you can end the round and pay the cost b_i.
There are q rounds in the game. To make the game more difficult, you need to maintain a square set S (initially it is empty). You must pass through these squares during the round (other squares can also be passed through). The square set S for the i-th round is obtained by adding or removing a square from the square set for the (i-1)-th round.
For each round find the minimum cost you should pay to end it.
Input
The first line contains two integers n, q (1β€ n,qβ€ 2 β
10^5) β the number of squares and the number of rounds.
The second line contains n distinct integers p_1,p_2,...,p_n (1β€ p_iβ€ n). It is guaranteed that the sequence p_1,p_2,...,p_n forms a permutation.
The third line contains n integers a_1,a_2,β¦,a_n (-10^9β€ a_iβ€ 10^9).
The fourth line contains n integers b_1,b_2,...,b_n (-10^9β€ b_iβ€ 10^9).
Then q lines follow, i-th of them contains a single integer x_i (1β€ x_iβ€ n). If x_i was in the set S on the (i-1)-th round you should remove it, otherwise, you should add it.
Output
Print q lines, each of them should contain a single integer β the minimum cost you should pay to end the corresponding round.
Examples
Input
3 2
2 1 3
10 -5 4
3 -2 3
1
2
Output
6
8
Input
5 4
2 1 5 3 4
6 -5 3 -10 -1
0 3 2 7 2
1
2
3
2
Output
-8
-7
-7
-8
Note
Let's consider the character T as the end of a round. Then we can draw two graphs for the first and the second test.
<image> <image>
In the first round of the first test, the set that you must pass through is \{1\}. The path you can use is 1β 3β T and its cost is 6.
In the second round of the first test, the set that you must pass through is \{1,2\}. The path you can use is 1β 2β 3β T and its cost is 8.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36397 | {
"difficulty": "12",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 4\n2 1 5 3 4\n6 -5 3 -10 -1\n0 3 2 7 2\n1\n2\n3\n2\n",
"output": "\n-8\n-7\n-7\n-8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 2\n2 1 3\n10 -5 4\n3 -2 3\n1\n2\n",
"output": "\n6\n8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n-1\n2\n1\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n-2\n2\n1\n",
"output": "-2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 4\n2 1 5 3 4\n6 -4 3 -10 -1\n0 3 2 7 2\n1\n2\n3\n2\n",
"output": "-8\n-6\n-6\n-8\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 1519_C. Berland Regional | Solve the following coding problem using the programming language python:
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
for _ in range(int(input())):
n = int(input())
u = list(map(int, input().split()))
s = list(map(int, input().split()))
p = max(u)
l = [[] for i in range(p)]
for i in range(n):
l[u[i]-1].append(s[i])
l.sort(key = len, reverse = True)
for i in range(p):
l[i].sort(reverse = True)
for j in range(1, len(l[i])):
l[i][j]+=l[i][j-1]
ans = []
for i in range(1, n+1):
res = 0
for j in range(p):
x = len(l[j])
if i<=x:
res+=l[j][x-x%i-1]
else:
break
ans.append(res)
print(*ans)
``` | vfc_36401 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n3083\n",
"output": "\n29 28 26 19 0 0 0 \n24907 20705 22805 9514 0 0 0 0 0 0 \n43 43 43 32 38 43 \n3083 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n313\n",
"output": "29 28 26 19 0 0 0\n24907 20705 22805 9514 0 0 0 0 0 0\n43 43 43 32 38 43\n313\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 9\n10\n1 1 1 2 2 2 2 3 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n3083\n",
"output": "33 32 30 23 0 0 0\n24907 20705 22805 9514 0 0 0 0 0 0\n43 43 43 32 38 43\n3083\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 6 3 3\n3435 3014 2241 2233 2893 2102 2286 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n313\n",
"output": "29 28 26 19 0 0 0\n24907 20491 16102 9514 0 0 0 0 0 0\n43 43 43 32 38 43\n313\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 6 3 3\n3435 3014 2241 2233 2893 2102 3437 2175 1961 2567\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n313\n",
"output": "29 28 26 19 0 0 0\n26058 21642 17253 10665 0 0 0 0 0 0\n43 43 43 32 38 43\n313\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n7\n1 2 1 2 1 2 1\n6 8 3 1 5 1 5\n10\n1 1 1 2 2 2 2 6 3 3\n3435 3014 2241 2233 2893 2102 3437 2175 1961 3983\n6\n3 3 3 3 3 3\n5 9 6 7 9 7\n1\n1\n313\n",
"output": "29 28 26 19 0 0 0\n27474 23058 17253 10665 0 0 0 0 0 0\n43 43 43 32 38 43\n313\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 1546_C. AquaMoon and Strange Sort | Solve the following coding problem using the programming language python:
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
from math import *
from collections import defaultdict as dt
from sys import stdin
inp = lambda : stdin.readline().strip()
I = lambda : int(inp())
M = lambda : map(int,inp().split())
L = lambda : list(M())
mod = 1000000007
inf = 100000000000000000000
ss = "abcdefghijklmnopqrstuvwxyz"
############## All the best start coding #############
def solve():
n=I()
a=L()
b=sorted(a)
d=dt(lambda:[0,0])
for i in range(n):
if i%2:
d[a[i]][0]+=1
else:
d[a[i]][1]+=1
for i in range(n):
if i%2:
if d[b[i]][0]==0:
print("No")
return
d[b[i]][0]-=1
else:
if d[b[i]][1]==0:
print("No")
return
d[b[i]][1]-=1
print("Yes")
##################### Submit now #####################
tt=1
tt=I()
for _ in range(tt):
solve()
``` | vfc_36405 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 1, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n4\n4 3 2 5\n4\n3 3 2 2\n5\n1 2 3 5 4\n",
"output": "YES\nYES\nNO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n64\n8 7 7 2 4 9 3 7 9 4 7 10 6 7 6 4 9 9 10 2 2 2 10 3 8 9 3 1 5 10 6 5 7 4 3 5 7 10 7 5 8 4 5 7 10 7 10 8 2 3 8 10 1 3 8 3 9 2 9 2 5 10 5 5\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2\n4 3\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n1 1 1 3 2\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n6\n3 2 3 2 3 2\n6\n1 1 4 5 1 4\n",
"output": "NO\nYES\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 173_D. Deputies | Solve the following coding problem using the programming language python:
The Trinitarian kingdom has exactly n = 3k cities. All of them are located on the shores of river Trissisipi, which flows through the whole kingdom. Some of the cities are located on one side of the river, and all the rest are on the other side.
Some cities are connected by bridges built between them. Each bridge connects two cities that are located on the opposite sides of the river. Between any two cities exists no more than one bridge.
The recently inaugurated King Tristan the Third is busy distributing his deputies among cities. In total there are k deputies and the king wants to commission each of them to control exactly three cities. However, no deputy can be entrusted to manage the cities, which are connected by a bridge β the deputy can set a too high fee for travelling over the bridge to benefit his pocket, which is bad for the reputation of the king.
Help King Tristan the Third distribute the deputies between the cities, if it is possible.
Input
The first line contains two integers n and m β the number of cities and bridges (3 β€ n < 105, n = 3k, 0 β€ m β€ 105). Next m lines describe the bridges. The i-th line contains two integers ai and bi β the numbers of cities that are connected by the i-th bridge (1 β€ ai, bi β€ n, ai β bi, 1 β€ i β€ m).
It is guaranteed that no bridge connects a city with itself and that any two cities are connected with no more than one bridge.
Output
If distributing the deputies in the required manner is impossible, print in a single line "NO" (without the quotes).
Otherwise, in the first line print "YES" (without the quotes), and in the second line print which deputy should be put in charge of each city. The i-th number should represent the number of the deputy (from 1 to k), who should be in charge of city numbered i-th in the input β overall there should be n numbers.
If there are multiple solutions, print any of them.
Examples
Input
6 6
1 2
4 1
3 5
6 5
2 6
4 6
Output
YES
1 2 1 2 2 1
Input
3 1
1 2
Output
NO
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36409 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1\n1 2\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 6\n1 2\n4 1\n3 5\n6 5\n2 6\n4 6\n",
"output": "YES\n1 2 1 2 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 16\n1 2\n1 3\n4 5\n4 6\n7 2\n7 3\n7 5\n7 6\n8 2\n8 3\n8 5\n8 6\n9 2\n9 3\n9 5\n9 6\n",
"output": "YES\n1 2 2 2 1 1 3 3 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 10\n1 5\n1 6\n1 7\n1 8\n1 9\n2 3\n2 4\n2 7\n2 8\n2 9\n",
"output": "YES\n1 2 1 1 2 2 3 3 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 5\n1 2\n1 3\n1 4\n1 5\n1 6\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 193_E. Fibonacci Number | Solve the following coding problem using the programming language python:
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
low_n = 1000
high_m = 15000
limit = int(10 ** 13)
f = int(input())
inputList = []
def customFunction(i):
if i == 0:
return (0, 1)
a, b = customFunction(i >> 1)
a, b = ((2 * a * b - a * a) % low_n, (b * b + a * a) % low_n)
if i & 1:
a, b = (b % low_n, (a + b) % low_n)
return (a, b)
i = 0
while i < high_m:
if customFunction(i)[0] == f % low_n:
inputList.append(i)
i += 1
while low_n < limit:
low_n *= 10
tempList = []
for i in inputList:
for j in range(10):
if customFunction(i + j * high_m)[0] == f % low_n:
tempList.append(i + j * high_m)
inputList = tempList
high_m *= 10
if inputList == []:
break
if inputList == []:
print(-1)
else:
inputList = sorted(inputList)
print(inputList[0])
``` | vfc_36413 | {
"difficulty": "11",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 3, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "13\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "377\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "53824509026\n",
"output": "895481947599\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6138242440179\n",
"output": "14000000000092\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 217_E. Alien DNA | Solve the following coding problem using the programming language python:
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations β each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as s1s2... s11, its mangled copy is s2s4s6s8s10s1s3s5s7s9s11.
For example, if the original sequence was "ACTGG" and the mutation happened on the segment [2, 4] (that is the activated subsequence is "CTG"), the mutated DNA is: "ACTGTCGG". The mangled copy of the activated subsequence is marked with bold font.
Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first k elements of the DNA sequence after all the mutations.
Input
The first line of input contains the original DNA sequence, consisting only of letters "A", "C", "T" and "G" and not exceeding 3Β·106 in length.
The second line contains a single integer k (1 β€ k β€ 3Β·106).
The third line contains a single integer n (0 β€ n β€ 5000) β the number of mutations. The next n lines describe the mutations in chronological order β each mutation is described by two numbers li and ri (1 β€ li β€ ri β€ 109), meaning that the continuous subsequence [li, ri] has become active and cloned itself, joining itself with the mangled copy.
It is guaranteed that the input data is correct, that is, no mutation acts on non-existing elements of the DNA sequence, and the resulting DNA sequence has at least k elements.
Assume that the DNA elements are indexed starting from 1 and that the notation [l, r] meaning the continuous subsequence of DNA sequence that consists of r - l + 1 elements starting at the l-th DNA sequence element and ending at the r-th DNA sequence element.
Output
Output a single line, containing the first k letters of the mutated DNA sequence.
Examples
Input
GAGA
4
0
Output
GAGA
Input
ACGTACGT
16
2
1 2
2 8
Output
ACCAGTACCGACATCG
Note
In the second example, after the first mutation the sequence is "ACCAGTACGT". After the second mutation it's "ACCAGTACCGACATCGT".
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36417 | {
"difficulty": "11",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "ACGTACGT\n16\n2\n1 2\n2 8\n",
"output": "ACCAGTACCGACATCG\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "GAGA\n4\n0\n",
"output": "GAGA\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ACGT\n274\n20\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 13\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n",
"output": "ACGTCCCCCCCCCCCCCCCCCCCCTCCCCCCCCCAGCCCCCCCCCCTCCCCCCCCCAGCCCCCCCCCTCCCCCCCCAGCCCCCCCCCTCCCCCCCCAGCCCCCCCCTCCCCCCCAGCCCCCCCCTCCCCCCCAGCCCCCCCTCCCCCCAGCCCCCCCTCCCCCCAGCCCCCCTCCCCCAGCCCCCCTCCCCCAGCCCCCTCCCCAGCCCCCTCCCCAGCCCCTCCCAGCCCCTCCCAGCCCTCCAGCCCTCCAGCCTCAGCCTCAGCTAGCTAG\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ACGT\n274\n20\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 13\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n",
"output": "ACGTCCCCCCCCCCCCCCCCCCCCTCCCCCCCCCAGCCCCCCCCCCTCCCCCCCCCAGCCCCCCCCCTCCCCCCCCAGCCCCCCCCCTCCCCCCCCAGCCCCCCCCTCCCCCCCAGCCCCCCCCTCCCCCCCAGCCCCCCCTCCCCCCAGCCCCCCCTCCCCCCAGCCCCCCTCCCCCAGCCCCCCTCCCCCAGCCCCCTCCCCAGCCCCCTCCCCAGCCCCTCCCAGCCCCTCCCAGCCCTCCAGCCCTCCAGCCTCAGCCTCAGCTAGCTAG\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ACGT\n274\n20\n1 4\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 22\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n",
"output": "ACGTCCCCCCCCCTCCCCCCCCCCTCCCCTCCCCAGCCCCCCCCCCTCCCCTCCCCAGCCCCCCCCCTCCCCTCCCAGCCCCCCCCCTCCCCTCCCAGCCCCCCCCTCCCCTCCAGCCCCCCCCTCCCCTCCAGCCCCCCCTCCCCTCAGCCCCCCCTCCCCTCAGCCCCCCTCCCCTAGCCCCCCTCCCCTAGCCCCCCCCCAGCCCTCCCCTCCGCAGCCCCCCCACCCTCCCAGCCCCTCCCAGCCCTCCAGCCCTCCAGCCTCAGCCTCA\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ACGT\n274\n20\n1 2\n1 5\n1 6\n1 7\n1 8\n1 9\n1 10\n1 11\n1 12\n1 22\n1 14\n1 15\n1 16\n1 17\n1 18\n1 19\n1 20\n1 21\n1 22\n1 23\n",
"output": "ACCAGCCCCCCCCACCCCCCCCCCACCCCACCCCACGCCCCCCCCCACCCCACCCCACGCCCCCCCCACCCCACCCACGCCCCCCCCACCCCACCCACGCCCCCCCACCCCACCACGCCCCCCCACCCCACCACGCCCCCCACCCCACACGCCCCCCACCCCACACGCCCCCACCCCAACGCCCCCACCCCAACGCCCCCCCCACGCCACCCCACCCCACGCCCCCCAGCCACCCACGCCCACCCACGCCACCACGCCACCACGCACACGCACA\n",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 241_D. Numbers | Solve the following coding problem using the programming language python:
You have a sequence of n distinct integers a1, a2, ..., an (1 β€ ai β€ n). You want to remove some integers in such a way that the resulting sequence of integers satisfies the following three conditions:
1. the resulting sequence is not empty;
2. the exclusive or (xor operation) of all the integers in the resulting sequence equals 0;
3. if you write all the integers of the resulting sequence (from beginning to the end) in a row in the decimal numeral system and without any spaces, the written number is divisible by p.
You are given the sequence of n integers a and a prime number p, find a way to satisfy the described conditions.
Input
The first line of the input contains two integers n and p (1 β€ n, p β€ 50000). Next line contains n space-separated distinct integers a1, a2, ..., an (1 β€ ai β€ n).
It is guaranteed that p is a prime number.
Output
If there is no solution for the given input, print "No" (without quotes) in the only line of the output.
Otherwise print "Yes" in the first line of output. The second line should contain an integer k (k > 0) specifying the number of remaining elements and the third line should contain k distinct integers x1, x2, ..., xk (1 β€ xi β€ n). These integers mean that you should remove all integers from the sequence except integers ax1, ax2, ..., axk to satisfy the described conditions.
If there are multiple solutions, any of them will be accepted.
Examples
Input
3 3
1 2 3
Output
Yes
3
1 2 3
Input
3 5
1 2 3
Output
No
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36421 | {
"difficulty": "10",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 4, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5\n1 2 3\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 2 3\n",
"output": "Yes\n3\n1 2 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 2\n7 8 10 1 5 11 3 9 2 4 6\n",
"output": "Yes\n3\n9 10 11 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 5\n5 7 4 11 9 2 8 3 1 6 10\n",
"output": "Yes\n4\n7 8 9 11 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "11 2\n7 8 10 1 5 11 3 9 2 4 6\n",
"output": "Yes\n3\n9 10 11 ",
"type": "stdin_stdout"
}
]
} |
|
code_contests | verifiable_code | 266_C. Below the Diagonal | Solve the following coding problem using the programming language python:
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import os
from io import BytesIO, IOBase
import sys
def main():
n = int(input())
row = [0] * n
col = [0] * n
a = [[0 for j in range(n)] for i in range(n)]
for i in range(n - 1):
x, y = map(int, input().split())
row[x - 1] += 1
col[y - 1] += 1
a[x - 1][y - 1] = 1
ans = []
for i in range(n):
zci = -1 # zero column index
for j in range(n - i):
if col[j] == 0:
zci = j
break
if zci == -1:
break
if zci != (n - i - 1):
ans.append([2, zci + 1, n - i])
col[n - i - 1], col[zci] = col[zci], col[n - i - 1]
for j in range(n - i):
a[j][zci], a[j][n - i - 1] = a[j][n - i - 1], a[j][zci]
nzri = -1 # non zero row index
for j in range(n - i):
if row[j] != 0:
nzri = j
break
if nzri == -1:
break
if nzri != (n - i - 1):
ans.append([1, nzri + 1, n - i])
row[nzri], row[n - i - 1] = row[n - i - 1], row[nzri]
for j in range(n - i):
if a[nzri][j] == 1:
col[j] -= 1
a[nzri][j], a[n - i - 1][j] = a[n - i - 1][j], a[nzri][j]
print(len(ans))
for i in ans:
print(*i)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | vfc_36425 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 1\n1 3\n",
"output": "3\n2 2 3\n1 1 3\n1 1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 2\n",
"output": "2\n2 1 2\n1 1 2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n2 1\n3 2\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\n5 12\n4 5\n1 2\n1 5\n12 11\n11 14\n15 3\n7 2\n10 6\n3 10\n1 4\n9 9\n8 13\n11 5\n",
"output": "21\n1 5 2\n2 12 1\n1 4 3\n2 5 2\n1 1 4\n2 5 3\n1 4 5\n1 12 6\n2 11 5\n1 11 7\n2 14 6\n1 15 8\n2 11 7\n1 11 9\n2 14 9\n1 1 11\n1 5 12\n1 1 13\n2 14 12\n1 15 14\n1 7 15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 1\n1 4\n1 1\n",
"output": "5\n2 2 4\n1 1 4\n2 2 3\n1 2 3\n2 1 2\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 28_C. Bath Queue | Solve the following coding problem using the programming language python:
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 50) β the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 β€ ai β€ 50). ai means the amount of wash basins in the i-th room.
Output
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
Examples
Input
1 1
2
Output
1.00000000000000000000
Input
2 2
1 1
Output
1.50000000000000000000
Input
2 3
1 1 1
Output
1.33333333333333350000
Input
7 5
1 1 2 3 1
Output
2.50216960000000070000
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
import sys
MAX_N = 55
line = list(map(int, sys.stdin.readline().split(" ")))
studc = line[0]
roomc = line[1]
arr = list(map(int, sys.stdin.readline().split(" ")))
ncr = [[0 for i in range(MAX_N)] for j in range(MAX_N)]
ncr[0][0] = 1
for i in range(1, MAX_N):
ncr[i][0] = 1;
for j in range(1, MAX_N):
ncr[i][j] = ncr[i - 1][j - 1] + ncr[i - 1][j]
upto = [0 for i in range(MAX_N)] # upto[i] of ways to pick such that no queue exceeds i people
for i in range(1, MAX_N):
dp = [[0 for j in range(MAX_N)] for k in range(MAX_N)]
dp[0][0] = 1
for j in range(roomc):
for k in range(0, min(studc, i * arr[j]) + 1):
for l in range(0, studc - k + 1):
dp[j + 1][k + l] += dp[j][l] * ncr[studc - l][k]
upto[i] = dp[roomc][studc]
ans = 0;
for i in range(1, MAX_N):
ans += (upto[i] - upto[i - 1]) * i
print('%.12f' % (ans / (roomc ** studc)))
``` | vfc_36429 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n1 1\n",
"output": "1.500000000000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n1 1 1\n",
"output": "1.333333333333333\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 5\n1 1 2 3 1\n",
"output": "2.502169600000002\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 315_C. Sereja and Contest | Solve the following coding problem using the programming language python:
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | ```python
n, k = map(int, input().split())
arr = map(int, input().split())
s, j, all_res = 0, 0, []
for i, q in enumerate(arr, 1):
if s - j * (n - i) * q < k:
all_res.append(str(i))
else:
s += q * j
j += 1
print('\n'.join(all_res))
``` | vfc_36433 | {
"difficulty": "9",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 2, 'nanos': 0}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 0\n5 3 4 1 2\n",
"output": "2\n3\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 -10\n5 5 1 7 5 1 2 4 9 2\n",
"output": "2\n4\n5\n7\n8\n9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 0\n5 5 4 1 2\n",
"output": "2\n3\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 -10\n5 5 1 7 4 1 2 4 9 2\n",
"output": "2\n4\n5\n7\n8\n9\n",
"type": "stdin_stdout"
}
]
} |
code_contests | verifiable_code | 337_E. Divisor Tree | Solve the following coding problem using the programming language python:
A divisor tree is a rooted tree that meets the following conditions:
* Each vertex of the tree contains a positive integer number.
* The numbers written in the leaves of the tree are prime numbers.
* For any inner vertex, the number within it is equal to the product of the numbers written in its children.
Manao has n distinct integers a1, a2, ..., an. He tries to build a divisor tree which contains each of these numbers. That is, for each ai, there should be at least one vertex in the tree which contains ai. Manao loves compact style, but his trees are too large. Help Manao determine the minimum possible number of vertices in the divisor tree sought.
Input
The first line contains a single integer n (1 β€ n β€ 8). The second line contains n distinct space-separated integers ai (2 β€ ai β€ 1012).
Output
Print a single integer β the minimum number of vertices in the divisor tree that contains each of the numbers ai.
Examples
Input
2
6 10
Output
7
Input
4
6 72 8 4
Output
12
Input
1
7
Output
1
Note
Sample 1. The smallest divisor tree looks this way: <image>
Sample 2. In this case you can build the following divisor tree: <image>
Sample 3. Note that the tree can consist of a single vertex.
The input will be given via stdin and the output should be printed to stdout by your code.
Now solve the problem by providing the code. | vfc_36437 | {
"difficulty": "11",
"memory_limit": null,
"memory_limit_bytes": 256000000,
"problem_url": null,
"time_limit": "{'seconds': 0, 'nanos': 500000000}"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n7\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n6 72 8 4\n",
"output": "12\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n6 10\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n737120440565 378229914051 983957160307 761546687166\n",
"output": "21\n",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.