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 |
---|---|---|---|---|---|---|---|
apps | verifiable_code | 872 | Solve the following coding problem using the programming language python:
You're given an array $a$ of length $n$. You can perform the following operation on it as many times as you want: Pick two integers $i$ and $j$ $(1 \le i,j \le n)$ such that $a_i+a_j$ is odd, then swap $a_i$ and $a_j$.
What is lexicographically the smallest array you can obtain?
An array $x$ is lexicographically smaller than an array $y$ if there exists an index $i$ such that $x_i<y_i$, and $x_j=y_j$ for all $1 \le j < i$. Less formally, at the first index $i$ in which they differ, $x_i<y_i$
-----Input-----
The first line contains an integer $n$ ($1 \le n \le 10^5$) — the number of elements in the array $a$.
The second line contains $n$ space-separated integers $a_1$, $a_2$, $\ldots$, $a_{n}$ ($1 \le a_i \le 10^9$) — the elements of the array $a$.
-----Output-----
The only line contains $n$ space-separated integers, the lexicographically smallest array you can obtain.
-----Examples-----
Input
3
4 1 7
Output
1 4 7
Input
2
1 1
Output
1 1
-----Note-----
In the first example, we can swap $1$ and $4$ since $1+4=5$, which is odd.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
from collections import deque, defaultdict
from sys import stdin, stdout
input = stdin.readline
# print = stdout.write
listin = lambda : list(map(int, input().split()))
mapin = lambda : map(int, input().split())
n = input()
a = listin()
odd = 0
even = 0
for i in a:
if i%2:
odd+=1
else:
even+=1
if (even == 0 or odd == 0):
print(*a)
else:
a.sort()
print(*a)
``` | vfc_13242 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1174/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n4 1 7\n",
"output": "1 4 7 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n",
"output": "1 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n943081371\n",
"output": "943081371 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n658442931 871874608\n",
"output": "658442931 871874608 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 873 | Solve the following coding problem using the programming language python:
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
[Image]
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of disks on the combination lock.
The second line contains a string of n digits — the original state of the disks.
The third line contains a string of n digits — Scrooge McDuck's combination that opens the lock.
-----Output-----
Print a single integer — the minimum number of moves Scrooge McDuck needs to open the lock.
-----Examples-----
Input
5
82195
64723
Output
13
-----Note-----
In the sample he needs 13 moves:
1 disk: $8 \rightarrow 7 \rightarrow 6$ 2 disk: $2 \rightarrow 3 \rightarrow 4$ 3 disk: $1 \rightarrow 0 \rightarrow 9 \rightarrow 8 \rightarrow 7$ 4 disk: $9 \rightarrow 0 \rightarrow 1 \rightarrow 2$ 5 disk: $5 \rightarrow 4 \rightarrow 3$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
s = input()
code = input()
res = 0
for i in range(n):
k = abs(int(s[i]) - int(code[i]))
res += min(k, 10 - k)
print(res)
``` | vfc_13246 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/540/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n82195\n64723\n",
"output": "13\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 874 | Solve the following coding problem using the programming language python:
A permutation is a sequence of integers p_1, p_2, ..., p_{n}, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as p_{i}. We'll call number n the size of permutation p_1, p_2, ..., p_{n}.
Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold p_{p}_{i} = i and p_{i} ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.
-----Input-----
A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.
-----Output-----
If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p_1, p_2, ..., p_{n} — permutation p, that is perfect. Separate printed numbers by whitespaces.
-----Examples-----
Input
1
Output
-1
Input
2
Output
2 1
Input
4
Output
2 1 4 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
if(n%2==1):
print(-1)
else:
L=list(range(1,n+1))
for i in range(0,n,2):
t=L[i]
L[i]=L[i+1]
L[i+1]=t
for i in range(n-1):
print(L[i],end=" ")
print(L[-1])
``` | vfc_13250 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/233/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n",
"output": "2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n",
"output": "2 1 4 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 875 | Solve the following coding problem using the programming language python:
You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are three stones positioned on three distinct vertices. All stones are the same. With one move you can move the stone to another free vertex along some diagonal. The color of this diagonal must be the same as the color of the diagonal, connecting another two stones.
Your goal is to move stones in such way that the only vertices occupied by stones are 1, 2 and 3. You must achieve such position using minimal number of moves. Write a program which plays this game in an optimal way.
-----Input-----
In the first line there is one integer n (3 ≤ n ≤ 70) — the number of points. In the second line there are three space-separated integer from 1 to n — numbers of vertices, where stones are initially located.
Each of the following n lines contains n symbols — the matrix denoting the colors of the diagonals. Colors are denoted by lowercase English letters. The symbol j of line i denotes the color of diagonal between points i and j. Matrix is symmetric, so j-th symbol of i-th line is equal to i-th symbol of j-th line. Main diagonal is filled with '*' symbols because there is no diagonal, connecting point to itself.
-----Output-----
If there is no way to put stones on vertices 1, 2 and 3, print -1 on a single line. Otherwise, on the first line print minimal required number of moves and in the next lines print the description of each move, one move per line. To describe a move print two integers. The point from which to remove the stone, and the point to which move the stone. If there are several optimal solutions, print any of them.
-----Examples-----
Input
4
2 3 4
*aba
a*ab
ba*b
abb*
Output
1
4 1
Input
4
2 3 4
*abc
a*ab
ba*b
cbb*
Output
-1
-----Note-----
In the first example we can move stone from point 4 to point 1 because this points are connected by the diagonal of color 'a' and the diagonal connection point 2 and 3, where the other stones are located, are connected by the diagonal of the same color. After that stones will be on the points 1, 2 and 3.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import deque
__author__ = 'asmn'
n = int(input())
end = tuple(sorted(map(lambda x: int(x) - 1, input().split())))
st = (0, 1, 2)
mat = [input() for i in range(n)]
v = set([st])
path = {}
dist = {st: 0}
queue = deque([st])
while end not in v and len(queue) > 0:
p = queue.popleft()
for x in range(-2, 1):
p1, p2, p3 = p[x], p[x + 1], p[x + 2]
for i in range(n):
if i not in (p1, p2, p3) and mat[i][p3] == mat[p1][p2]:
np = tuple(sorted((p1, p2, i)))
if np not in v:
v.add(np)
queue.append(np)
path[np] = p
dist[np] = dist[p] + 1
def pathinfo(fr, to):
return str((set(fr) - set(to)).pop() + 1) + ' ' + str((set(to) - set(fr)).pop() + 1)
if end not in dist:
print(-1)
return
print(dist[end])
while end in path:
print(pathinfo(end, path[end]))
end = path[end]
``` | vfc_13254 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/386/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n2 3 4\n*aba\na*ab\nba*b\nabb*\n",
"output": "1\n4 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n2 3 4\n*abc\na*ab\nba*b\ncbb*\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 3\n*aa\na*a\naa*\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n9 8 6\n*abbbababb\na*babbaaaa\nbb*bbaabab\nbab*bbbaab\nbbbb*baaab\nababb*baaa\nbaabab*bba\naabaaab*ab\nbaaaaaba*a\nbabbbaaba*\n",
"output": "3\n8 2\n9 1\n6 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3 9 5\n*aabbbaaaa\na*abbaaaaa\naa*baaaabb\nbbb*bbbaba\nbbab*babaa\nbaabb*bbab\naaabab*aaa\naaaabba*ab\naabbaaaa*b\naabaababb*\n",
"output": "2\n5 2\n9 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 876 | Solve the following coding problem using the programming language python:
Consider the function p(x), where x is an array of m integers, which returns an array y consisting of m + 1 integers such that y_{i} is equal to the sum of first i elements of array x (0 ≤ i ≤ m).
You have an infinite sequence of arrays A^0, A^1, A^2..., where A^0 is given in the input, and for each i ≥ 1 A^{i} = p(A^{i} - 1). Also you have a positive integer k. You have to find minimum possible i such that A^{i} contains a number which is larger or equal than k.
-----Input-----
The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k ≤ 10^18). n is the size of array A^0.
The second line contains n integers A^0_0, A^0_1... A^0_{n} - 1 — the elements of A^0 (0 ≤ A^0_{i} ≤ 10^9). At least two elements of A^0 are positive.
-----Output-----
Print the minimum i such that A^{i} contains a number which is larger or equal than k.
-----Examples-----
Input
2 2
1 1
Output
1
Input
3 6
1 1 1
Output
2
Input
3 1
1 0 1
Output
0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,k = list(map(int,input().split()));
a = list(map(int,input().split()));
if max(a) >= k:
print(0)
return
lx = 0
while a[lx] == 0:
lx+=1
lo,hi = 1,k
def can(x):
bc = 1
tot = 0
for i in range(n-lx):
if(bc >= k):
return True
tot += bc*a[n-1-i]
bc *= (x+i)
bc = bc//(i+1)
if(tot >= k):
return True
return tot >= k
while lo < hi :
mid = (lo+hi)//2
cancan = can(mid)
#print(mid,cancan)
if cancan : hi = mid
else : lo = mid + 1
print(lo)
``` | vfc_13258 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/837/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n1 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 6\n1 1 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\n1 0 1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1000000000000000000\n5 4 5\n",
"output": "632455531\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1000000000000000000\n0 4 4 5\n",
"output": "707106780\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 877 | Solve the following coding problem using the programming language python:
There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules: Problemset of each division should be non-empty. Each problem should be used in exactly one division (yes, it is unusual requirement). Each problem used in division 1 should be harder than any problem used in division 2. If two problems are similar, they should be used in different divisions.
Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.
Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.
-----Input-----
The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000) — the number of problems prepared for the round and the number of pairs of similar problems, respectively.
Each of the following m lines contains a pair of similar problems u_{i} and v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}). It's guaranteed, that no pair of problems meets twice in the input.
-----Output-----
Print one integer — the number of ways to split problems in two divisions.
-----Examples-----
Input
5 2
1 4
5 2
Output
2
Input
3 3
1 2
2 3
1 3
Output
0
Input
3 2
3 1
3 2
Output
1
-----Note-----
In the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.
In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.
Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math
import sys
from collections import Counter
def solve():
n, m = [int(x) for x in input().split()]
L, R = 1, n
for line in sys.stdin:
x, y = [int(x) for x in line.split()]
x, y = min(x, y), max(x, y)
L, R = max(L, x), min(R, y)
return max(R - L, 0)
print(solve())
``` | vfc_13262 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/673/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\n1 4\n5 2\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 878 | Solve the following coding problem using the programming language python:
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier.
Future students will be asked just a single question. They are given a sequence of integer numbers $a_1, a_2, \dots, a_n$, each number is from $1$ to $3$ and $a_i \ne a_{i + 1}$ for each valid $i$. The $i$-th number represents a type of the $i$-th figure:
circle; isosceles triangle with the length of height equal to the length of base; square.
The figures of the given sequence are placed somewhere on a Cartesian plane in such a way that:
$(i + 1)$-th figure is inscribed into the $i$-th one; each triangle base is parallel to OX; the triangle is oriented in such a way that the vertex opposite to its base is at the top; each square sides are parallel to the axes; for each $i$ from $2$ to $n$ figure $i$ has the maximum possible length of side for triangle and square and maximum radius for circle.
Note that the construction is unique for some fixed position and size of just the first figure.
The task is to calculate the number of distinct points (not necessarily with integer coordinates) where figures touch. The trick is, however, that the number is sometimes infinite. But that won't make the task difficult for you, will it?
So can you pass the math test and enroll into Berland State University?
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 100$) — the number of figures.
The second line contains $n$ integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 3$, $a_i \ne a_{i + 1}$) — types of the figures.
-----Output-----
The first line should contain either the word "Infinite" if the number of distinct points where figures touch is infinite or "Finite" otherwise.
If the number is finite than print it in the second line. It's guaranteed that the number fits into 32-bit integer type.
-----Examples-----
Input
3
2 1 3
Output
Finite
7
Input
3
1 2 3
Output
Infinite
-----Note-----
Here are the glorious pictures for the examples. Note that the triangle is not equilateral but just isosceles with the length of height equal to the length of base. Thus it fits into a square in a unique way.
The distinct points where figures touch are marked red.
In the second example the triangle and the square touch each other for the whole segment, it contains infinite number of points.
[Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
N = int(input())
A = [int(a) for a in input().split()]
for i in range(1, N):
if A[i] + A[i-1] == 5:
print("Infinite")
break
else:
ans = 0
for i in range(1, N):
if A[i] == 2:
if i == 1 or A[i-2] == 2:
ans += 3
else:
ans += 2
elif A[i] == 3:
ans += 4
else:
if A[i-1] == 2:
ans += 3
else:
ans += 4
print("Finite")
print(ans)
``` | vfc_13266 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1156/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 1 3\n",
"output": "Finite\n7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 879 | Solve the following coding problem using the programming language python:
Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $p_i$ — the index of the router to which the $i$-th router was connected after being purchased ($p_i < i$).
There are $n$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $n$-th router.
-----Input-----
The first line contains integer number $n$ ($2 \le n \le 200000$) — the number of the routers. The following line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i < i$), where $p_i$ is equal to index of the router to which the $i$-th was connected after purchase.
-----Output-----
Print the path from the $1$-st to the $n$-th router. It starts with $1$ and ends with $n$. All the elements in the path should be distinct.
-----Examples-----
Input
8
1 1 2 2 3 2 5
Output
1 2 5 8
Input
6
1 2 3 4 5
Output
1 2 3 4 5 6
Input
7
1 1 2 3 4 3
Output
1 3 7
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def prog():
n = int(input())
inp = list(map(int,input().split()))
temp = []
while(n!=1):
temp += [n]
n = inp[n-2]
temp += [1]
temp.reverse()
for i in temp:
print(i,end=' ')
prog()
``` | vfc_13270 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1057/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8\n1 1 2 2 3 2 5\n",
"output": "1 2 5 8 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 2 3 4 5\n",
"output": "1 2 3 4 5 6 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n1 1 2 3 4 3\n",
"output": "1 3 7 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1\n",
"output": "1 2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 880 | Solve the following coding problem using the programming language python:
Let $n$ be an integer. Consider all permutations on integers $1$ to $n$ in lexicographic order, and concatenate them into one big sequence $p$. For example, if $n = 3$, then $p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$. The length of this sequence will be $n \cdot n!$.
Let $1 \leq i \leq j \leq n \cdot n!$ be a pair of indices. We call the sequence $(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$ a subarray of $p$. Its length is defined as the number of its elements, i.e., $j - i + 1$. Its sum is the sum of all its elements, i.e., $\sum_{k=i}^j p_k$.
You are given $n$. Find the number of subarrays of $p$ of length $n$ having sum $\frac{n(n+1)}{2}$. Since this number may be large, output it modulo $998244353$ (a prime number).
-----Input-----
The only line contains one integer $n$ ($1 \leq n \leq 10^6$), as described in the problem statement.
-----Output-----
Output a single integer — the number of subarrays of length $n$ having sum $\frac{n(n+1)}{2}$, modulo $998244353$.
-----Examples-----
Input
3
Output
9
Input
4
Output
56
Input
10
Output
30052700
-----Note-----
In the first sample, there are $16$ subarrays of length $3$. In order of appearance, they are:
$[1, 2, 3]$, $[2, 3, 1]$, $[3, 1, 3]$, $[1, 3, 2]$, $[3, 2, 2]$, $[2, 2, 1]$, $[2, 1, 3]$, $[1, 3, 2]$, $[3, 2, 3]$, $[2, 3, 1]$, $[3, 1, 3]$, $[1, 3, 1]$, $[3, 1, 2]$, $[1, 2, 3]$, $[2, 3, 2]$, $[3, 2, 1]$.
Their sums are $6$, $6$, $7$, $6$, $7$, $5$, $6$, $6$, $8$, $6$, $7$, $5$, $6$, $6$, $7$, $6$. As $\frac{n(n+1)}{2} = 6$, the answer is $9$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
MOD = 998244353
list_size = 1000001
f_list = [1] * list_size
f_r_list = [1] * list_size
for i in range(list_size - 1):
f_list[i + 1] = int((f_list[i] * (i + 2)) % MOD)
def power(n, x):
if x == 1:
return n
elif x % 2 == 0:
return power(int((n * n) % MOD), int(x / 2))
else:
return int((n * power(n, x - 1)) % MOD)
f_r_list[-1] = power(f_list[-1], MOD - 2)
for i in range(2, list_size + 1):
f_r_list[-i] = int((f_r_list[-i + 1] * (list_size + 2 - i)) % MOD)
def comb(n, r):
if n < r:
return 0
elif n == 0 or r == 0 or n == r:
return 1
else:
return (((f_list[n - 1] * f_r_list[n - r - 1]) % MOD) * f_r_list[r - 1]) % MOD
n = int(input())
ans = f_list[n-1]
for i in range(2, n):
ans = (ans + comb(n, i) * (f_list[i-1] - 1) * f_list[n-i-1]) % MOD
print(ans)
``` | vfc_13274 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1091/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n",
"output": "9\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 882 | Solve the following coding problem using the programming language python:
Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.
Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.
He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.
The anthem is the string s of no more than 10^5 small Latin letters and question marks. The most glorious victory is the string t of no more than 10^5 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.
Note that the occurrences of string t in s can overlap. Check the third example for clarification.
-----Input-----
The first line contains string of small Latin letters and question marks s (1 ≤ |s| ≤ 10^5).
The second line contains string of small Latin letters t (1 ≤ |t| ≤ 10^5).
Product of lengths of strings |s|·|t| won't exceed 10^7.
-----Output-----
Output the maximum number of occurrences of string t you can achieve by replacing all the question marks in string s with small Latin letters.
-----Examples-----
Input
winlose???winl???w??
win
Output
5
Input
glo?yto?e??an?
or
Output
3
Input
??c?????
abcab
Output
2
-----Note-----
In the first example the resulting string s is "winlosewinwinlwinwin"
In the second example the resulting string s is "glorytoreorand". The last letter of the string can be arbitrary.
In the third example occurrences of string t are overlapping. String s with maximal number of occurrences of t is "abcabcab".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t=input()
s=input()
n=len(s)
h=[0]*(n+1)
h[0]=0
j=0
fa=[0]*(n+1)
for i in range(2,n+1) :
while j and s[i-1]!=s[j]:
#j=fa[j-1];
j=fa[j];
if s[i-1]==s[j]:
j+=1
fa[i]=j;
#print(fa)
l=list()
j=fa[n]
while(j>0):
l.append(j)
j=fa[j]
tmp=t
t=s
s=tmp
n=len(s)
dp=[0]*(n)
m=[0]*n
'''if len(s)<len(t):
print(0)'''
for i in range(len(t)-1,len(s)):
can=True
for j in range(len(t)):
if s[i-len(t)+1+j]=='?':
continue
if s[i-len(t)+1+j]!=t[j]:
can=False
break
if can:
dp[i]=1
for d in l:
d=len(t)-d
dp[i]=max(dp[i],1+dp[i-d])
if i-len(t)>=0:
dp[i]=max(dp[i],m[i-len(t)]+1)
m[i]=max(m[i-1],dp[i])
print(m[-1])
``` | vfc_13282 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/808/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "winlose???winl???w??\nwin\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "glo?yto?e??an?\nor\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "??c?????\nabcab\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ddddd\nd\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ww?ww\nw\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "?????\nn\n",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 883 | Solve the following coding problem using the programming language python:
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 100) — the number of Dima's friends. Dima himself isn't considered to be his own friend. The second line contains n positive integers, not exceeding 5, representing, how many fingers the Dima's friends will show.
The numbers in the lines are separated by a single space.
-----Output-----
In a single line print the answer to the problem.
-----Examples-----
Input
1
1
Output
3
Input
1
2
Output
2
Input
2
3 5
Output
3
-----Note-----
In the first sample Dima can show 1, 3 or 5 fingers. If Dima shows 3 fingers, then the counting-out will go like that: Dima, his friend, Dima, his friend.
In the second sample Dima can show 2 or 4 fingers.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input()) + 1
s = sum(map (int, input().split()))
ans = 5
for i in range (1, 6):
if (s + i) % n == 1: ans -= 1
print(ans)
``` | vfc_13286 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/272/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n1\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 884 | Solve the following coding problem using the programming language python:
— This is not playing but duty as allies of justice, Nii-chan!
— Not allies but justice itself, Onii-chan!
With hands joined, go everywhere at a speed faster than our thoughts! This time, the Fire Sisters — Karen and Tsukihi — is heading for somewhere they've never reached — water-surrounded islands!
There are three clusters of islands, conveniently coloured red, blue and purple. The clusters consist of a, b and c distinct islands respectively.
Bridges have been built between some (possibly all or none) of the islands. A bridge bidirectionally connects two different islands and has length 1. For any two islands of the same colour, either they shouldn't be reached from each other through bridges, or the shortest distance between them is at least 3, apparently in order to prevent oddities from spreading quickly inside a cluster.
The Fire Sisters are ready for the unknown, but they'd also like to test your courage. And you're here to figure out the number of different ways to build all bridges under the constraints, and give the answer modulo 998 244 353. Two ways are considered different if a pair of islands exist, such that there's a bridge between them in one of them, but not in the other.
-----Input-----
The first and only line of input contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 5 000) — the number of islands in the red, blue and purple clusters, respectively.
-----Output-----
Output one line containing an integer — the number of different ways to build bridges, modulo 998 244 353.
-----Examples-----
Input
1 1 1
Output
8
Input
1 2 2
Output
63
Input
1 3 5
Output
3264
Input
6 2 9
Output
813023575
-----Note-----
In the first example, there are 3 bridges that can possibly be built, and no setup of bridges violates the restrictions. Thus the answer is 2^3 = 8.
In the second example, the upper two structures in the figure below are instances of valid ones, while the lower two are invalid due to the blue and purple clusters, respectively. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
m = 998244353
n = 5050
mi = [1] * n
for i in range(2, n):
mi[i] = (-(m//i) * mi[m%i]) % m;
f = [1] * n
g = [1] * n
for i in range(2, n):
f[i] = (f[i-1] * i) % m
g[i] = (g[i-1] * mi[i]) % m
def calc(x, y):
s = 1
p = f[x] * f[y]
for i in range(1, min(x, y)+1):
den = g[i] * g[x-i] * g[y-i]
s += p * den % m
return s
a, b, c = map(int, input().split())
ans = calc(a, b) * calc(b, c) * calc(c, a) % m
print(ans)
``` | vfc_13290 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/869/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1 1\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2 2\n",
"output": "63\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 885 | Solve the following coding problem using the programming language python:
Eric is the teacher of graph theory class. Today, Eric teaches independent set and edge-induced subgraph.
Given a graph $G=(V,E)$, an independent set is a subset of vertices $V' \subset V$ such that for every pair $u,v \in V'$, $(u,v) \not \in E$ (i.e. no edge in $E$ connects two vertices from $V'$).
An edge-induced subgraph consists of a subset of edges $E' \subset E$ and all the vertices in the original graph that are incident on at least one edge in the subgraph.
Given $E' \subset E$, denote $G[E']$ the edge-induced subgraph such that $E'$ is the edge set of the subgraph. Here is an illustration of those definitions: [Image]
In order to help his students get familiar with those definitions, he leaves the following problem as an exercise:
Given a tree $G=(V,E)$, calculate the sum of $w(H)$ over all except null edge-induced subgraph $H$ of $G$, where $w(H)$ is the number of independent sets in $H$. Formally, calculate $\sum \limits_{\emptyset \not= E' \subset E} w(G[E'])$.
Show Eric that you are smarter than his students by providing the correct answer as quickly as possible. Note that the answer might be large, you should output the answer modulo $998,244,353$.
-----Input-----
The first line contains a single integer $n$ ($2 \le n \le 3 \cdot 10^5$), representing the number of vertices of the graph $G$.
Each of the following $n-1$ lines contains two integers $u$ and $v$ ($1 \le u,v \le n$, $u \not= v$), describing edges of the given tree.
It is guaranteed that the given edges form a tree.
-----Output-----
Output one integer, representing the desired value modulo $998,244,353$.
-----Examples-----
Input
2
2 1
Output
3
Input
3
1 2
3 2
Output
11
-----Note-----
For the second example, all independent sets are listed below. $\vdots : \vdots : \vdots$
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
readline = sys.stdin.readline
def parorder(Edge, p):
N = len(Edge)
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stack.pop()
apo(vn)
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
ast(vf)
return par, order
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
N = int(readline())
MOD = 998244353
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
P, L = parorder(Edge, 0)
C = getcld(P)
dp = [[1, 1, 0, 0, 1] for _ in range(N)]
for p in L[::-1]:
if not C[p]:
continue
res = 1
res2 = 1
res3 = 1
for ci in C[p]:
res = (res*(dp[ci][2] + dp[ci][3] + dp[ci][4])) % MOD
res2 = (res2*(dp[ci][1] + dp[ci][2] + 2*dp[ci][3] + dp[ci][4])) % MOD
res3 = (res3*(sum(dp[ci]) + dp[ci][2] + dp[ci][3])) % MOD
dp[p][0] = res
dp[p][1] = res
dp[p][2] = (res2 - res)%MOD
dp[p][3] = (res3 - res)%MOD
dp[p][4] = res
print((dp[0][2] + dp[0][3] + dp[0][4] - 1) %MOD)
``` | vfc_13294 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1332/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n2 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2\n3 2\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n1 5\n3 4\n6 1\n3 2\n3 1\n",
"output": "296\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 3\n4 1\n4 2\n",
"output": "33\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 886 | Solve the following coding problem using the programming language python:
Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.
Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!
-----Input-----
The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 10^5, inclusive. The representation of n doesn't contain any leading zeroes.
-----Output-----
If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print - 1.
Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.
-----Examples-----
Input
527
Output
572
Input
4573
Output
3574
Input
1357997531
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
"""
Codeforces Contest 288 Div 2 Problem B
Author : chaotic_iak
Language: Python 3.4.2
"""
################################################### SOLUTION
def main():
n = read(0)
ld = int(n[-1])
last = -1
for i in range(len(n)-1):
c = int(n[i])
if c%2 == 0 and c < ld:
return n[:i] + n[-1] + n[i+1:-1] + n[i]
if c%2 == 0:
last = i
if last == -1:
return -1
return n[:last] + n[-1] + n[last+1:-1] + n[last]
#################################################### HELPERS
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0: return inputs
if mode == 1: return inputs.split()
if mode == 2: return list(map(int, inputs.split()))
def write(s="\n"):
if s is None: s = ""
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
write(main())
``` | vfc_13298 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/508/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "527\n",
"output": "572\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4573\n",
"output": "3574\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1357997531\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "444443\n",
"output": "444434\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "22227\n",
"output": "72222\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "24683\n",
"output": "34682\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 887 | Solve the following coding problem using the programming language python:
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.
You are given a jacket with n buttons. Determine if it is fastened in a right way.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 1000) — the number of buttons on the jacket.
The second line contains n integers a_{i} (0 ≤ a_{i} ≤ 1). The number a_{i} = 0 if the i-th button is not fastened. Otherwise a_{i} = 1.
-----Output-----
In the only line print the word "YES" if the jacket is fastened in a right way. Otherwise print the word "NO".
-----Examples-----
Input
3
1 0 1
Output
YES
Input
3
1 0 0
Output
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = sum(list(map(int, input().split())))
if n == 1:
if a == 1:
print("YES")
else:
print("NO")
else:
if a == n - 1:
print("YES")
else:
print("NO")
``` | vfc_13302 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/691/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 0 1\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 0 0\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 888 | Solve the following coding problem using the programming language python:
Anton loves transforming one permutation into another one by swapping elements for money, and Ira doesn't like paying for stupid games. Help them obtain the required permutation by paying as little money as possible.
More formally, we have two permutations, p and s of numbers from 1 to n. We can swap p_{i} and p_{j}, by paying |i - j| coins for it. Find and print the smallest number of coins required to obtain permutation s from permutation p. Also print the sequence of swap operations at which we obtain a solution.
-----Input-----
The first line contains a single number n (1 ≤ n ≤ 2000) — the length of the permutations.
The second line contains a sequence of n numbers from 1 to n — permutation p. Each number from 1 to n occurs exactly once in this line.
The third line contains a sequence of n numbers from 1 to n — permutation s. Each number from 1 to n occurs once in this line.
-----Output-----
In the first line print the minimum number of coins that you need to spend to transform permutation p into permutation s.
In the second line print number k (0 ≤ k ≤ 2·10^6) — the number of operations needed to get the solution.
In the next k lines print the operations. Each line must contain two numbers i and j (1 ≤ i, j ≤ n, i ≠ j), which means that you need to swap p_{i} and p_{j}.
It is guaranteed that the solution exists.
-----Examples-----
Input
4
4 2 1 3
3 2 4 1
Output
3
2
4 3
3 1
-----Note-----
In the first sample test we swap numbers on positions 3 and 4 and permutation p becomes 4 2 3 1. We pay |3 - 4| = 1 coins for that. On second turn we swap numbers on positions 1 and 3 and get permutation 3241 equal to s. We pay |3 - 1| = 2 coins for that. In total we pay three coins.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
c = {}
for i in range(n):
c[b[i]] = i
b = []
for i in range(n):
a[i] = c[a[i]]
print(sum(abs(a[i] - i) for i in range(n)) >> 1)
while True:
for i in range(n):
if a[i] < i:
for j in range(a[i], i):
if a[j] >= i:
a[i], a[j] = a[j], a[i]
b += [(i+1, j+1)]
break
break
else:
break
print(len(b))
for e in b:
print(*e)
``` | vfc_13306 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/584/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n4 2 1 3\n3 2 4 1\n",
"output": "3\n2\n3 4\n1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n1\n",
"output": "0\n0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 889 | Solve the following coding problem using the programming language python:
In the city of Ultima Thule job applicants are often offered an IQ test.
The test is as follows: the person gets a piece of squared paper with a 4 × 4 square painted on it. Some of the square's cells are painted black and others are painted white. Your task is to repaint at most one cell the other color so that the picture has a 2 × 2 square, completely consisting of cells of the same color. If the initial picture already has such a square, the person should just say so and the test will be completed.
Your task is to write a program that determines whether it is possible to pass the test. You cannot pass the test if either repainting any cell or no action doesn't result in a 2 × 2 square, consisting of cells of the same color.
-----Input-----
Four lines contain four characters each: the j-th character of the i-th line equals "." if the cell in the i-th row and the j-th column of the square is painted white, and "#", if the cell is black.
-----Output-----
Print "YES" (without the quotes), if the test can be passed and "NO" (without the quotes) otherwise.
-----Examples-----
Input
####
.#..
####
....
Output
YES
Input
####
....
####
....
Output
NO
-----Note-----
In the first test sample it is enough to repaint the first cell in the second row. After such repainting the required 2 × 2 square is on the intersection of the 1-st and 2-nd row with the 1-st and 2-nd column.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
L=[]
for i in range(4):
L.append(input())
ans="NO"
for i in range(3):
for j in range(3):
x=L[i][j]+L[i][j+1]+L[i+1][j]+L[i+1][j+1]
if(x.count('#')==3 or x.count('.')==3 or x.count('#')==4 or x.count('.')==4):
ans="YES"
print(ans)
``` | vfc_13310 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/287/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "####\n.#..\n####\n....\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "####\n....\n####\n....\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "....\n....\n....\n....\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "###.\n...#\n###.\n...#\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": ".##.\n#..#\n.##.\n#..#\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 890 | Solve the following coding problem using the programming language python:
You have n problems. You have estimated the difficulty of the i-th one as integer c_{i}. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least l and at most r. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least x.
Find the number of ways to choose a problemset for the contest.
-----Input-----
The first line contains four integers n, l, r, x (1 ≤ n ≤ 15, 1 ≤ l ≤ r ≤ 10^9, 1 ≤ x ≤ 10^6) — the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively.
The second line contains n integers c_1, c_2, ..., c_{n} (1 ≤ c_{i} ≤ 10^6) — the difficulty of each problem.
-----Output-----
Print the number of ways to choose a suitable problemset for the contest.
-----Examples-----
Input
3 5 6 1
1 2 3
Output
2
Input
4 40 50 10
10 20 30 25
Output
2
Input
5 25 35 10
10 10 20 10 20
Output
6
-----Note-----
In the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems.
In the second example, two sets of problems are suitable — the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30.
In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
aa=0
a, b, c, d = (list(map(int, input().split(' '))))
l = list(map(int, input().split(' ')))
for i in range(2**a):
k = bin(i)[2:]
t = 0
k = '0' * (a-len(k)) + k
x = []
for j in range(a):
if k[j] == '1':
x.append(l[j])
t += 1
if t >= 2:
if b <= sum(x) <= c and max(x) - min(x) >= d:
aa+=1
print(aa)
``` | vfc_13314 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/550/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 5 6 1\n1 2 3\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 40 50 10\n10 20 30 25\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 25 35 10\n10 10 20 10 20\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 15 60 10\n10 20 30 25\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10 20 1\n15\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 891 | Solve the following coding problem using the programming language python:
There are $n$ chips arranged in a circle, numbered from $1$ to $n$.
Initially each chip has black or white color. Then $k$ iterations occur. During each iteration the chips change their colors according to the following rules. For each chip $i$, three chips are considered: chip $i$ itself and two its neighbours. If the number of white chips among these three is greater than the number of black chips among these three chips, then the chip $i$ becomes white. Otherwise, the chip $i$ becomes black.
Note that for each $i$ from $2$ to $(n - 1)$ two neighbouring chips have numbers $(i - 1)$ and $(i + 1)$. The neighbours for the chip $i = 1$ are $n$ and $2$. The neighbours of $i = n$ are $(n - 1)$ and $1$.
The following picture describes one iteration with $n = 6$. The chips $1$, $3$ and $4$ are initially black, and the chips $2$, $5$ and $6$ are white. After the iteration $2$, $3$ and $4$ become black, and $1$, $5$ and $6$ become white.
[Image]
Your task is to determine the color of each chip after $k$ iterations.
-----Input-----
The first line contains two integers $n$ and $k$ $(3 \le n \le 200\,000, 1 \le k \le 10^{9})$ — the number of chips and the number of iterations, respectively.
The second line contains a string consisting of $n$ characters "W" and "B". If the $i$-th character is "W", then the $i$-th chip is white initially. If the $i$-th character is "B", then the $i$-th chip is black initially.
-----Output-----
Print a string consisting of $n$ characters "W" and "B". If after $k$ iterations the $i$-th chip is white, then the $i$-th character should be "W". Otherwise the $i$-th character should be "B".
-----Examples-----
Input
6 1
BWBBWW
Output
WBBBWW
Input
7 3
WBWBWBW
Output
WWWWWWW
Input
6 4
BWBWBW
Output
BWBWBW
-----Note-----
The first example is described in the statement.
The second example: "WBWBWBW" $\rightarrow$ "WWBWBWW" $\rightarrow$ "WWWBWWW" $\rightarrow$ "WWWWWWW". So all chips become white.
The third example: "BWBWBW" $\rightarrow$ "WBWBWB" $\rightarrow$ "BWBWBW" $\rightarrow$ "WBWBWB" $\rightarrow$ "BWBWBW".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
a = list(input()) * 2
iter1 = [0] * (2 * n)
iter2 = [0] * (2 * n)
changes = 0
for i in range(1, 2 * n):
if a[i] != a[i - 1]:
changes += 1
else:
changes = 0
iter1[i] = changes
changes = 0
for i in range(2 * n - 2, -1, -1):
if a[i] != a[i + 1]:
changes += 1
else:
changes = 0
iter2[i] = changes
iters = [min(iter1[n + i], iter2[i]) for i in range(n)]
for i in range(n):
if iters[i] > n // 2:
iters[i] = 10 ** 9 + 1
it = min(iters[i], k)
if it % 2 != 0:
if a[i] == "B":
a[i] = "W"
else:
a[i] = "B"
print("".join(a[:n]))
``` | vfc_13318 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1244/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 1\nBWBBWW\n",
"output": "WBBBWW\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 3\nWBWBWBW\n",
"output": "WWWWWWW\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 4\nBWBWBW\n",
"output": "BWBWBW\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 892 | Solve the following coding problem using the programming language python:
You are given array a with n elements and the number m. Consider some subsequence of a and the value of least common multiple (LCM) of its elements. Denote LCM as l. Find any longest subsequence of a with the value l ≤ m.
A subsequence of a is an array we can get by erasing some elements of a. It is allowed to erase zero or all elements.
The LCM of an empty array equals 1.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 10^6) — the size of the array a and the parameter from the problem statement.
The second line contains n integers a_{i} (1 ≤ a_{i} ≤ 10^9) — the elements of a.
-----Output-----
In the first line print two integers l and k_{max} (1 ≤ l ≤ m, 0 ≤ k_{max} ≤ n) — the value of LCM and the number of elements in optimal subsequence.
In the second line print k_{max} integers — the positions of the elements from the optimal subsequence in the ascending order.
Note that you can find and print any subsequence with the maximum length.
-----Examples-----
Input
7 8
6 2 9 2 7 2 3
Output
6 5
1 2 4 6 7
Input
6 4
2 2 2 3 3 3
Output
2 3
1 2 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
n, m = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
B, C = [0]*(m+1), [0]*(m+1)
for a in A:
if a <= m: B[a] += 1
for i in range(2, m + 1):
for j in range(i, m+1, i):
C[j] += B[i]
k, l = 1, 0
for i in range(2, m+1):
if C[i] > l:
l = C[i]
k = i
print(k, l + B[1])
for i, a in enumerate(A):
if k%a == 0: sys.stdout.write(str(i+1) + ' ')
``` | vfc_13322 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/632/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 8\n6 2 9 2 7 2 3\n",
"output": "6 5\n1 2 4 6 7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 893 | Solve the following coding problem using the programming language python:
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value a_{i} associated with it.
We call a set S of tree nodes valid if following conditions are satisfied: S is non-empty. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S. $\operatorname{max}_{u \in S} a_{u} - \operatorname{min}_{v \in S} a_{v} \leq d$.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (10^9 + 7).
-----Input-----
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a_1, a_2, ..., a_{n}(1 ≤ a_{i} ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
-----Output-----
Print the number of valid sets modulo 1000000007.
-----Examples-----
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
-----Note-----
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
f = lambda: map(int, input().split())
m = 1000000007
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
u -= 1
v -= 1
p[u].append(v)
p[v].append(u)
def g(u, x, a, b, q):
k = 1
for v in p[u]:
if a < t[v] <= b or t[v] == a and v > q:
if v != x: k += k * g(v, u, a, b, q) % m
return k
s = 0
for q in range(n):
a = t[q]
b = a + d
s += g(q, -1, a, b, q)
print(s % m)
``` | vfc_13326 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/486/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 4\n2 1 3 2\n1 2\n1 3\n3 4\n",
"output": "8\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 894 | Solve the following coding problem using the programming language python:
Vasily the bear has a favorite rectangle, it has one vertex at point (0, 0), and the opposite vertex at point (x, y). Of course, the sides of Vasya's favorite rectangle are parallel to the coordinate axes.
Vasya also loves triangles, if the triangles have one vertex at point B = (0, 0). That's why today he asks you to find two points A = (x_1, y_1) and C = (x_2, y_2), such that the following conditions hold: the coordinates of points: x_1, x_2, y_1, y_2 are integers. Besides, the following inequation holds: x_1 < x_2; the triangle formed by point A, B and C is rectangular and isosceles ($\angle A B C$ is right); all points of the favorite rectangle are located inside or on the border of triangle ABC; the area of triangle ABC is as small as possible.
Help the bear, find the required points. It is not so hard to proof that these points are unique.
-----Input-----
The first line contains two integers x, y ( - 10^9 ≤ x, y ≤ 10^9, x ≠ 0, y ≠ 0).
-----Output-----
Print in the single line four integers x_1, y_1, x_2, y_2 — the coordinates of the required points.
-----Examples-----
Input
10 5
Output
0 15 15 0
Input
-10 5
Output
-15 0 0 15
-----Note-----
[Image]
Figure to the first sample
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
x,y = [int(x) for x in input().split()]
if x*y > 0:
if x < 0:
print(x+y,0,0,x+y)
else:
print(0,x+y,x+y,0)
else:
if x < 0:
print(x-y,0,0,y-x)
else:
print(0,y-x,x-y,0)
``` | vfc_13330 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/336/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "10 5\n",
"output": "0 15 15 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "-10 5\n",
"output": "-15 0 0 15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "20 -10\n",
"output": "0 -30 30 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "-10 -1000000000\n",
"output": "-1000000010 0 0 -1000000010\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 895 | Solve the following coding problem using the programming language python:
Everyone loves a freebie. Especially students.
It is well-known that if in the night before exam a student opens window, opens the student's record-book and shouts loudly three times "Fly, freebie, fly!" — then flown freebie helps him to pass the upcoming exam.
In the night before the exam on mathematical analysis n students living in dormitory shouted treasured words. The i-th student made a sacrament at the time t_{i}, where t_{i} is the number of seconds elapsed since the beginning of the night.
It is known that the freebie is a capricious and willful lady. That night the freebie was near dormitory only for T seconds. Therefore, if for two students their sacrament times differ for more than T, then the freebie didn't visit at least one of them.
Since all students are optimists, they really want to know what is the maximal number of students visited by the freebie can be.
-----Input-----
The first line of the input contains integer n (1 ≤ n ≤ 100), where n — the number of students shouted "Fly, freebie, fly!" The second line contains n positive integers t_{i} (1 ≤ t_{i} ≤ 1000).
The last line contains integer T (1 ≤ T ≤ 1000) — the time interval during which the freebie was near the dormitory.
-----Output-----
Print a single integer — the largest number of people who will pass exam tomorrow because of the freebie visit.
-----Examples-----
Input
6
4 1 7 8 3 8
1
Output
3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
L=list(map(int,input().split()))
T=int(input())
X=[0]*1005
for i in range(len(L)):
X[L[i]]+=1
for i in range(1,1005):
X[i]+=X[i-1]
best=0
for i in range(1+T,1005):
if(X[i]-X[i-T-1]>best):
best=X[i]-X[i-T-1]
print(best)
``` | vfc_13334 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/386/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n4 1 7 8 3 8\n1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 2 1 5\n2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n4 7 1 3 8 5 2 1 8 4\n3\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n39 49 37 28 40 17 50 2\n10\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 1\n2\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 896 | Solve the following coding problem using the programming language python:
Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!
Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a_1, a_2, ..., a_{n} denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b_1, b_2, ..., b_{m} denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.
Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.
-----Input-----
The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix.
The second line contains n numbers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 10^9), where a_{i} is the xor of all elements in row i.
The third line contains m numbers b_1, b_2, ..., b_{m} (0 ≤ b_{i} ≤ 10^9), where b_{i} is the xor of all elements in column i.
-----Output-----
If there is no matrix satisfying the given constraints in the first line, output "NO".
Otherwise, on the first line output "YES", and then n rows of m numbers in each c_{i}1, c_{i}2, ... , c_{im} (0 ≤ c_{ij} ≤ 2·10^9) — the description of the matrix.
If there are several suitable matrices, it is allowed to print any of them.
-----Examples-----
Input
2 3
2 9
5 3 13
Output
YES
3 4 5
6 7 8
Input
3 3
1 7 6
2 15 12
Output
NO
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
t1, t2 = 0, 0
for i in a:
t1 ^= i
for i in b:
t2 ^= i
if t1 != t2:
print('NO')
else:
print('YES')
for i in range(n-1):
for j in range(m-1):
print(0, end=' ')
print(a[i])
tmp = 0
for j in range(m-1):
print(b[j], end=' ')
tmp ^= b[j]
print(a[n-1]^tmp)
``` | vfc_13338 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1016/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n2 9\n5 3 13\n",
"output": "YES\n0 0 2 \n5 3 15 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3\n1 7 6\n2 15 12\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 897 | Solve the following coding problem using the programming language python:
Ancient Egyptians are known to have used a large set of symbols $\sum$ to write on the walls of the temples. Fafa and Fifa went to one of the temples and found two non-empty words S_1 and S_2 of equal lengths on the wall of temple written one below the other. Since this temple is very ancient, some symbols from the words were erased. The symbols in the set $\sum$ have equal probability for being in the position of any erased symbol.
Fifa challenged Fafa to calculate the probability that S_1 is lexicographically greater than S_2. Can you help Fafa with this task?
You know that $|\sum|= m$, i. e. there were m distinct characters in Egyptians' alphabet, in this problem these characters are denoted by integers from 1 to m in alphabet order. A word x is lexicographically greater than a word y of the same length, if the words are same up to some position, and then the word x has a larger character, than the word y.
We can prove that the probability equals to some fraction $P / Q$, where P and Q are coprime integers, and $Q \neq 0 \text{mod}(10^{9} + 7)$. Print as the answer the value $R = P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, i. e. such a non-negative integer less than 10^9 + 7, such that $R \cdot Q \equiv P \operatorname{mod}(10^{9} + 7)$, where $a \equiv b \text{mod}(m)$ means that a and b give the same remainders when divided by m.
-----Input-----
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the length of each of the two words and the size of the alphabet $\sum$, respectively.
The second line contains n integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ m) — the symbols of S_1. If a_{i} = 0, then the symbol at position i was erased.
The third line contains n integers representing S_2 with the same format as S_1.
-----Output-----
Print the value $P \cdot Q^{-1} \operatorname{mod}(10^{9} + 7)$, where P and Q are coprime and $P / Q$ is the answer to the problem.
-----Examples-----
Input
1 2
0
1
Output
500000004
Input
1 2
1
0
Output
0
Input
7 26
0 15 12 9 13 0 14
11 1 0 13 15 12 0
Output
230769233
-----Note-----
In the first sample, the first word can be converted into (1) or (2). The second option is the only one that will make it lexicographically larger than the second word. So, the answer to the problem will be $\frac{1}{2} \operatorname{mod}(10^{9} + 7)$, that is 500000004, because $(500000004 \cdot 2) \operatorname{mod}(10^{9} + 7) = 1$.
In the second example, there is no replacement for the zero in the second word that will make the first one lexicographically larger. So, the answer to the problem is $\frac{0}{1} \operatorname{mod}(10^{9} + 7)$, that is 0.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
mult = 1
mod = 10 ** 9 + 7
res = 0
m_inv = pow(m, mod - 2, mod)
for x, y in zip(a, b):
if x and y:
if x > y:
res += mult
res %= mod
break
elif x == y:
continue
else:
break
elif x:
res += mult * (x-1) * m_inv % mod
res %= mod
mult = mult * m_inv % mod
elif y:
res += mult * (m - y) * m_inv % mod
res %= mod
mult = mult * m_inv % mod
else:
res += mult * m * (m - 1) // 2 * m_inv * m_inv % mod
res %= mod
mult = mult * m_inv % mod
print(res)
``` | vfc_13342 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/935/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 2\n0\n1\n",
"output": "500000004\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n1\n0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 26\n0 15 12 9 13 0 14\n11 1 0 13 15 12 0\n",
"output": "230769233\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 26\n14 5 19 18 9 14\n0 0 0 0 0 0\n",
"output": "182369325\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 901 | Solve the following coding problem using the programming language python:
Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them.
There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.
Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility). [Image]
Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world).
Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2^{n} possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.
-----Input-----
The first line of input contains two integers n and m (1 ≤ n, m ≤ 10^4) — number of universes and number of groups respectively.
The next m lines contain the information about the groups. i-th of them first contains an integer k (number of times someone joined i-th group, k > 0) followed by k integers v_{i}, 1, v_{i}, 2, ..., v_{i}, k. If v_{i}, j is negative, it means that Rick from universe number - v_{i}, j has joined this group and otherwise it means that Morty from universe number v_{i}, j has joined it.
Sum of k for all groups does not exceed 10^4.
-----Output-----
In a single line print the answer to Summer's question. Print "YES" if she should cancel the event and "NO" otherwise.
-----Examples-----
Input
4 2
1 -3
4 -2 3 2 -3
Output
YES
Input
5 2
5 3 -2 1 -1 5
3 -5 2 5
Output
NO
Input
7 2
3 -1 6 7
7 -5 4 2 4 7 -3 4
Output
YES
-----Note-----
In the first sample testcase, 1st group only contains the Rick from universe number 3, so in case he's a traitor, then all members of this group are traitors and so Summer should cancel the event.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = map(int,input().split())
for i in range(m):
a, *b = map(int,input().split())
b = set(b)
for j in b:
if -j in b:
break
else:
print("YES")
break
else:
print("NO")
``` | vfc_13358 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/787/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 2\n1 -3\n4 -2 3 2 -3\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n5 3 -2 1 -1 5\n3 -5 2 5\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 902 | Solve the following coding problem using the programming language python:
n people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins k games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
-----Input-----
The first line contains two integers: n and k (2 ≤ n ≤ 500, 2 ≤ k ≤ 10^12) — the number of people and the number of wins.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) — powers of the player. It's guaranteed that this line contains a valid permutation, i.e. all a_{i} are distinct.
-----Output-----
Output a single integer — power of the winner.
-----Examples-----
Input
2 2
1 2
Output
2
Input
4 2
3 1 2 4
Output
3
Input
6 2
6 5 3 1 2 4
Output
6
Input
2 10000000000
2 1
Output
2
-----Note-----
Games in the second sample:
3 plays with 1. 3 wins. 1 goes to the end of the line.
3 plays with 2. 3 wins. He wins twice in a row. He becomes the winner.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
tmp = list(map(int,input().split()))
n,k = tmp[0],tmp[1]
a = list(map(int,input().split()))
cur = a[0]
w = 0
OK = False
for i in range(1,10000):
op = a[i]
if cur > op:
a.append(op)
w += 1
else:
cur = op
a.append(cur)
w = 1
if w >= k:
OK = True
break
if OK:
print(cur)
else:
print(max(a))
``` | vfc_13362 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/879/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n1 2\n",
"output": "2 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 2\n3 1 2 4\n",
"output": "3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6 2\n6 5 3 1 2 4\n",
"output": "6 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 903 | Solve the following coding problem using the programming language python:
You are given an array $a$ of $n$ integers, where $n$ is odd. You can make the following operation with it: Choose one of the elements of the array (for example $a_i$) and increase it by $1$ (that is, replace it with $a_i + 1$).
You want to make the median of the array the largest possible using at most $k$ operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $[1, 5, 2, 3, 5]$ is $3$.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$, $n$ is odd, $1 \le k \le 10^9$) — the number of elements in the array and the largest number of operations you can make.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($1 \le a_i \le 10^9$).
-----Output-----
Print a single integer — the maximum possible median after the operations.
-----Examples-----
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
-----Note-----
In the first example, you can increase the second element twice. Than array will be $[1, 5, 5]$ and it's median is $5$.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $3$.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $[5, 1, 2, 5, 3, 5, 5]$ and the median will be $5$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
def getN():
return int(input())
def getList():
return list(map(int, input().split()))
import math
from bisect import bisect_left
n, k = getList()
nums = getList()
nums.sort()
half = (n // 2) + 1
nums = nums[half-1:]
sm = sum(nums)
def check(arr, k, tgt):
for num in arr:
sub = max(0, (tgt - num))
if sub == 0:
return True
k -= sub
if k < 0:
return False
return True
mn = 0
mx = 3 * (10 ** 9)
# print(nums, sm)
while(mx-mn > 1):
md = (mx+mn) // 2
# print(md)
if check(nums, k, md):
mn = md
else:
mx = md
if not check(nums, k, md):
md -= 1
print(md)
``` | vfc_13366 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1201/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n1 3 5\n",
"output": "5",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 904 | Solve the following coding problem using the programming language python:
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
-----Input-----
The first line contains one integer number n (1 ≤ n ≤ 200) — length of the text.
The second line contains text of single-space separated words s_1, s_2, ..., s_{i}, consisting only of small and capital Latin letters.
-----Output-----
Print one integer number — volume of text.
-----Examples-----
Input
7
NonZERO
Output
5
Input
24
this is zero answer text
Output
0
Input
24
Harbour Space University
Output
1
-----Note-----
In the first example there is only one word, there are 5 capital letters in it.
In the second example all of the words contain 0 capital letters.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
input()
def v(x):
ret = 0
for i in x:
if ord('A') <= ord(i) <= ord('Z'):
ret += 1
return ret
print(max(v(i) for i in input().strip().split()))
``` | vfc_13370 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/837/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7\nNonZERO\n",
"output": "5\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 905 | Solve the following coding problem using the programming language python:
Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.
Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).
Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.
-----Input-----
The first line contains two space-separated integers n, s (1 ≤ n, s ≤ 100).
The i-th of the next n lines contains two integers x_{i}, y_{i} (1 ≤ x_{i} ≤ 100; 0 ≤ y_{i} < 100), where x_{i} represents the number of dollars and y_{i} the number of cents needed in order to buy the i-th type of sugar.
-----Output-----
Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.
-----Examples-----
Input
5 10
3 90
12 0
9 70
5 50
7 0
Output
50
Input
5 5
10 10
20 20
30 30
40 40
50 50
Output
-1
-----Note-----
In the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import itertools
import math
import random
import time
def timer(f):
def tmp(*args, **kwargs):
t = time.time()
res = f(*args, **kwargs)
print("Время выполнения функции: %f" % (time.time()-t))
return res
return tmp
def genArray(length, lower, upper):
return [random.randint(lower, upper) for i in range(length)]
n, s = list(map(int, input().split(' ')))
array = [list(map(int, input().split(' '))) for i in range(n)]
res = -100;
for i in range(n):
if array[i][0]+array[i][1]/100 <= s:
sdacha = 100 - array[i][1]
if array[i][1]== 0:
sdacha = 0
if sdacha>res:
res = sdacha
if res == -100:
print(-1)
else:
print(res)
``` | vfc_13374 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/463/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 10\n3 90\n12 0\n9 70\n5 50\n7 0\n",
"output": "50\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n10 10\n20 20\n30 30\n40 40\n50 50\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 906 | Solve the following coding problem using the programming language python:
Ralph has a magic field which is divided into n × m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the product of integers in each row and each column equals to k, where k is either 1 or -1.
Now Ralph wants you to figure out the number of ways to put numbers in each block in such a way that the magic field works properly. Two ways are considered different if and only if there exists at least one block where the numbers in the first way and in the second way are different. You are asked to output the answer modulo 1000000007 = 10^9 + 7.
Note that there is no range of the numbers to put in the blocks, but we can prove that the answer is not infinity.
-----Input-----
The only line contains three integers n, m and k (1 ≤ n, m ≤ 10^18, k is either 1 or -1).
-----Output-----
Print a single number denoting the answer modulo 1000000007.
-----Examples-----
Input
1 1 -1
Output
1
Input
1 3 1
Output
1
Input
3 3 -1
Output
16
-----Note-----
In the first example the only way is to put -1 into the only block.
In the second example the only way is to put 1 into every block.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m, k = map(int, input().split())
if k == -1 and n % 2 != m % 2:
print(0)
else:
print(pow(2, (n - 1) * (m - 1), 10**9 + 7))
``` | vfc_13378 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/894/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 1 -1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3 1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 -1\n",
"output": "16\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 908 | Solve the following coding problem using the programming language python:
Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.
Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).
To reverse the i-th string Vasiliy has to spent c_{i} units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.
String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.
For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.
-----Input-----
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings.
The second line contains n integers c_{i} (0 ≤ c_{i} ≤ 10^9), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.
Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.
-----Output-----
If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.
-----Examples-----
Input
2
1 2
ba
ac
Output
1
Input
3
1 3 1
aa
ba
ac
Output
1
Input
2
5 5
bbb
aaa
Output
-1
Input
2
3 3
aaa
aa
Output
-1
-----Note-----
In the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.
In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is - 1.
In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is - 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
c = list(map(int, input().split(" ")))
nodes = dict()
nodes[""] = 0
# print(nodes)
depth = 0
while depth < n:
# expand
new_nodes = dict()
s = input()
for node in nodes.keys():
if s >= node:
# not reverse
if s in new_nodes:
new_nodes[s] = min(new_nodes[s], nodes[node])
else:
new_nodes[s] = nodes[node]
if s[::-1] >= node:
# not reverse
if s[::-1] in new_nodes:
new_nodes[s[::-1]] = min(new_nodes[s[::-1]], nodes[node] + c[depth])
else:
new_nodes[s[::-1]] = nodes[node] + c[depth]
nodes = new_nodes
# print(depth,nodes)
depth += 1
# print(nodes)
if len(nodes) > 0:
print(min(nodes.values()))
else:
print(-1)
``` | vfc_13386 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/706/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n1 2\nba\nac\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 3 1\naa\nba\nac\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n5 5\nbbb\naaa\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n3 3\naaa\naa\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n0 0 8 6\nbi\nqp\nbt\nya\n",
"output": "8\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n8 0 4 8 2\nac\ncl\ngg\ngm\nfs\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 909 | Solve the following coding problem using the programming language python:
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting expression is as large as possible. Let's consider an example: assume that the teacher wrote numbers 1, 2 and 3 on the blackboard. Here are some ways of placing signs and brackets: 1+2*3=7 1*(2+3)=5 1*2*3=6 (1+2)*3=9
Note that you can insert operation signs only between a and b, and between b and c, that is, you cannot swap integers. For instance, in the given sample you cannot get expression (1+3)*2.
It's easy to see that the maximum value that you can obtain is 9.
Your task is: given a, b and c print the maximum value that you can get.
-----Input-----
The input contains three integers a, b and c, each on a single line (1 ≤ a, b, c ≤ 10).
-----Output-----
Print the maximum value of the expression that you can obtain.
-----Examples-----
Input
1
2
3
Output
9
Input
2
10
3
Output
60
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a = int(input())
b = int(input())
c = int(input())
print(max(a*b*c, a+b*c, a*b+c, a*(b+c), (a+b)*c, a+b+c))
``` | vfc_13390 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/479/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n2\n3\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n10\n3\n",
"output": "60\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n2\n1\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n10\n10\n",
"output": "1000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1\n3\n",
"output": "20\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 910 | Solve the following coding problem using the programming language python:
There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.
New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hall
We know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.
Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.
-----Input-----
The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.
-----Output-----
If there is no way to assigns seats to parliamentarians in a proper way print -1.
Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.
-----Examples-----
Input
3 2 2
Output
0 3
1 2
Input
8 4 3
Output
7 8 3
0 1 4
6 0 5
0 2 0
Input
10 2 2
Output
-1
-----Note-----
In the first sample there are many other possible solutions. For example, 3 2
0 1
and 2 1
3 0
The following assignment 3 2
1 0
is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# You lost the game.
n, a, b = map(int, input().split())
dem = n//2 + n%2
i = 1
while dem > 0 and i <= a:
dem -= b//2 + (i%2)*(b%2)
i += 1
if dem > 0:
print(-1)
else:
dem = n//2 + n%2
demo = [2*k+1 for k in range(dem)]
rep = [2*k for k in range(1,n//2+1)]
d = 0
r = 0
l = 0
for i in range(a):
l = 1-l
e = l
for j in range(b):
if e and d < dem:
print(demo[d],end=" ")
d += 1
elif e == 0 and r < n//2:
print(rep[r],end=" ")
r += 1
else:
print(0,end=" ")
e = 1-e
print()
``` | vfc_13394 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/644/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2 2\n",
"output": "1 2 \n0 3 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 911 | Solve the following coding problem using the programming language python:
Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score p_{i} and it takes exactly t_{i} minutes to solve it. Problems are sorted by difficulty — it's guaranteed that p_{i} < p_{i} + 1 and t_{i} < t_{i} + 1.
A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0, p_{i} - c·x) points.
Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by p_{i}). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by p_{i}). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.
You may assume that the duration of the competition is greater or equal than the sum of all t_{i}. That means both Limak and Radewoosh will accept all n problems.
-----Input-----
The first line contains two integers n and c (1 ≤ n ≤ 50, 1 ≤ c ≤ 1000) — the number of problems and the constant representing the speed of loosing points.
The second line contains n integers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ 1000, p_{i} < p_{i} + 1) — initial scores.
The third line contains n integers t_1, t_2, ..., t_{n} (1 ≤ t_{i} ≤ 1000, t_{i} < t_{i} + 1) where t_{i} denotes the number of minutes one needs to solve the i-th problem.
-----Output-----
Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.
-----Examples-----
Input
3 2
50 85 250
10 15 25
Output
Limak
Input
3 6
50 85 250
10 15 25
Output
Radewoosh
Input
8 1
10 20 30 40 50 60 70 80
8 10 58 63 71 72 75 76
Output
Tie
-----Note-----
In the first sample, there are 3 problems. Limak solves them as follows:
Limak spends 10 minutes on the 1-st problem and he gets 50 - c·10 = 50 - 2·10 = 30 points. Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2·25 = 35 points. He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2·50 = 150 points.
So, Limak got 30 + 35 + 150 = 215 points.
Radewoosh solves problem in the reversed order:
Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2·25 = 200 points. He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2·40 = 5 points for this problem. He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2·50) = max(0, - 50) = 0 points.
Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins.
In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway.
In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 2 = 4.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n,c = list(map(int, input().split()))
P = list(map(int, input().split()))
T = list(map(int, input().split()))
a = 0
t = 0
for i in range(n):
t += T[i]
a += max(0,P[i]-c*t)
t = 0
b = 0
for i in range(n-1,-1,-1):
t += T[i]
b += max(0,P[i]-c*t)
if a > b:
print("Limak")
elif a < b:
print("Radewoosh")
else:
print("Tie")
``` | vfc_13398 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/658/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n50 85 250\n10 15 25\n",
"output": "Limak\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 6\n50 85 250\n10 15 25\n",
"output": "Radewoosh\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 912 | Solve the following coding problem using the programming language python:
Sakuzyo - Imprinting
A.R.C. Markland-N is a tall building with $n$ floors numbered from $1$ to $n$. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.
ConneR's office is at floor $s$ of the building. On each floor (including floor $s$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $k$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.
CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.
Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!
-----Input-----
The first line contains one integer $t$ ($1 \le t \le 1000$) — the number of test cases in the test. Then the descriptions of $t$ test cases follow.
The first line of a test case contains three integers $n$, $s$ and $k$ ($2 \le n \le 10^9$, $1 \le s \le n$, $1 \le k \le \min(n-1, 1000)$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.
The second line of a test case contains $k$ distinct integers $a_1, a_2, \ldots, a_k$ ($1 \le a_i \le n$) — the floor numbers of the currently closed restaurants.
It is guaranteed that the sum of $k$ over all test cases does not exceed $1000$.
-----Output-----
For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $s$ to a floor with an open restaurant.
-----Example-----
Input
5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
Output
2
0
4
0
2
-----Note-----
In the first example test case, the nearest floor with an open restaurant would be the floor $4$.
In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.
In the third example test case, the closest open restaurant is on the $6$-th floor.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
t=int(input())
for i in range(t):
n,s,k=list(map(int,input().split()))
a=list(map(int,input().split()))
s=s-1
for i in range(n):
if (s-i)>-1:
if not (s-i+1) in a:
print(i)
break
if (s+i)<n:
if not (s+i+1) in a:
print(i)
break
``` | vfc_13402 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1293/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n5 2 3\n1 2 3\n4 3 3\n4 1 2\n10 2 6\n1 2 3 4 5 7\n2 1 1\n2\n100 76 8\n76 75 36 67 41 74 10 77\n",
"output": "2\n0\n4\n0\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n5 1 4\n3 2 1 4\n5 5 4\n4 5 2 3\n",
"output": "4\n4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n10 3 3\n8 10 4\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n10 1 1\n1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n10 10 2\n9 10\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n10 10 3\n8 9 10\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 914 | Solve the following coding problem using the programming language python:
Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.
-----Input-----
The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).
-----Output-----
On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.
-----Examples-----
Input
banana
4
Output
2
baan
Input
banana
3
Output
3
nab
Input
banana
2
Output
-1
-----Note-----
In the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import Counter
s = input()
n = int(input())
d = Counter()
for c in s:
d[c] += 1
if len(d) > n:
print(-1)
else:
left = 0
right = 10**10
s = ""
lastok = ("", 0)
while left + 1 < right:
mid = (left + right) // 2
s = ""
for (c, cnt) in list(d.items()):
cntnow = (cnt - 1) // mid + 1
s += c * cntnow
if len(s) < n:
s += 'a' * (n - len(s))
if len(s) == n:
lastok = (s, mid)
right = mid
else:
left = mid
print(lastok[1])
print(lastok[0])
``` | vfc_13410 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/335/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "banana\n4\n",
"output": "2\nbaan\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "banana\n3\n",
"output": "3\nnab\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "banana\n2\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "b\n1\n",
"output": "1\nb\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aba\n2\n",
"output": "2\nab\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 915 | Solve the following coding problem using the programming language python:
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least $k$ subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one.
Formally, a codeforces subsequence of a string $s$ is a subset of ten characters of $s$ that read codeforces from left to right. For example, codeforces contains codeforces a single time, while codeforcesisawesome contains codeforces four times: codeforcesisawesome, codeforcesisawesome, codeforcesisawesome, codeforcesisawesome.
Help Karl find any shortest string that contains at least $k$ codeforces subsequences.
-----Input-----
The only line contains a single integer $k$ ($1 \leq k \leq 10^{16})$.
-----Output-----
Print a shortest string of lowercase English letters that contains at least $k$ codeforces subsequences. If there are several such strings, print any of them.
-----Examples-----
Input
1
Output
codeforces
Input
3
Output
codeforcesss
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
k = int(input())
codeforces = "codeforces"
ans = [1 for _ in range(len(codeforces))]
i = 0
tot = 1
while tot < k:
tot //= ans[i]
ans[i] += 1
tot *= ans[i]
i += 1
i %= len(codeforces)
for i in range(len(codeforces)):
print(codeforces[i] * ans[i], end = "")
print()
``` | vfc_13414 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1368/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n",
"output": "codeforces\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 916 | Solve the following coding problem using the programming language python:
Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has a_{i} apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).
Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.
In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things: eat the apples, if the node is a leaf. move the apples to one of the children, if the node is non-leaf.
Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.
Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair.
-----Input-----
The first line will contain one integer n (2 ≤ n ≤ 10^5) — the number of nodes in the apple tree.
The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^7) — the number of apples on each node of the tree.
The third line will contain n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} ≤ n) — the parent of each node of the tree. Node i has parent p_{i} (for 2 ≤ i ≤ n). Node 1 is the root of the tree.
It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
-----Output-----
On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair.
-----Examples-----
Input
3
2 2 3
1 1
Output
1
Input
3
1 2 3
1 1
Output
0
Input
8
7 2 2 5 4 3 1 1
1 1 1 4 4 5 6
Output
4
-----Note-----
In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.
In the second sample, There is no swap that will make Sagheer win the game.
Note that Sagheer must make the swap even if he can win with the initial tree.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def coloring(i, ancestors, color):
while i != 0 and color[ancestors[i - 1]] is None:
color[ancestors[i - 1]] = not color[i]
i = ancestors[i - 1]
def main():
n = int(input())
a = list(map(int, input().split()))
ancestors = list([int(x) - 1 for x in input().split()])
descendants = [[] for i in range(n)]
for i in range(n - 1):
descendants[ancestors[i]].append(i + 1)
color = [None for i in range(n)]
for i in range(n):
if not descendants[i]:
color[i] = True
coloring(i, ancestors, color)
reds = 0
blues = 0
xor = 0
count_red = dict()
count_blue = dict()
for i in range(n):
if color[i]:
blues += 1
xor ^= a[i]
if str(a[i]) in count_blue:
count_blue[str(a[i])] += 1
else:
count_blue[str(a[i])] = 1
else:
reds += 1
if str(a[i]) in count_red:
count_red[str(a[i])] += 1
else:
count_red[str(a[i])] = 1
res = 0
if xor == 0:
res += (blues - 1) * blues // 2
res += (reds - 1) * reds // 2
for i in list(count_blue.items()):
if i[0] in count_red:
res += i[1] * count_red[i[0]]
else:
for i in list(count_blue.items()):
if str(xor ^ int(i[0])) in count_red:
res += i[1] * count_red[str(xor ^ int(i[0]))]
print(res)
main()
``` | vfc_13418 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/812/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n2 2 3\n1 1\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 917 | Solve the following coding problem using the programming language python:
You are planning to build housing on a street. There are $n$ spots available on the street on which you can build a house. The spots are labeled from $1$ to $n$ from left to right. In each spot, you can build a house with an integer height between $0$ and $h$.
In each spot, if a house has height $a$, you will gain $a^2$ dollars from it.
The city has $m$ zoning restrictions. The $i$-th restriction says that the tallest house from spots $l_i$ to $r_i$ (inclusive) must be at most $x_i$.
You would like to build houses to maximize your profit. Determine the maximum profit possible.
-----Input-----
The first line contains three integers $n$, $h$, and $m$ ($1 \leq n,h,m \leq 50$) — the number of spots, the maximum height, and the number of restrictions.
Each of the next $m$ lines contains three integers $l_i$, $r_i$, and $x_i$ ($1 \leq l_i \leq r_i \leq n$, $0 \leq x_i \leq h$) — left and right limits (inclusive) of the $i$-th restriction and the maximum possible height in that range.
-----Output-----
Print a single integer, the maximum profit you can make.
-----Examples-----
Input
3 3 3
1 1 1
2 2 3
3 3 2
Output
14
Input
4 10 2
2 3 8
3 4 7
Output
262
-----Note-----
In the first example, there are $3$ houses, the maximum height of a house is $3$, and there are $3$ restrictions. The first restriction says the tallest house between $1$ and $1$ must be at most $1$. The second restriction says the tallest house between $2$ and $2$ must be at most $3$. The third restriction says the tallest house between $3$ and $3$ must be at most $2$.
In this case, it is optimal to build houses with heights $[1, 3, 2]$. This fits within all the restrictions. The total profit in this case is $1^2 + 3^2 + 2^2 = 14$.
In the second example, there are $4$ houses, the maximum height of a house is $10$, and there are $2$ restrictions. The first restriction says the tallest house from $2$ to $3$ must be at most $8$. The second restriction says the tallest house from $3$ to $4$ must be at most $7$.
In this case, it's optimal to build houses with heights $[10, 8, 7, 7]$. We get a profit of $10^2+8^2+7^2+7^2 = 262$. Note that there are two restrictions on house $3$ and both of them must be satisfied. Also, note that even though there isn't any explicit restrictions on house $1$, we must still limit its height to be at most $10$ ($h=10$).
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, h, m = map(int, input().split())
a = [h] * n
for i in range(m):
l, r, x = map(int, input().split())
for i in range(l - 1, r):
a[i] = min(a[i], x)
s = 0
for i in range(n):
s += a[i] ** 2
print(s)
``` | vfc_13422 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1162/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3 3\n1 1 1\n2 2 3\n3 3 2\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 10 2\n2 3 8\n3 4 7\n",
"output": "262\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50 50 1\n1 50 0\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50 50 50\n17 40 12\n33 36 47\n8 43 35\n25 29 42\n18 36 6\n25 35 18\n36 48 47\n17 40 13\n20 27 37\n32 32 28\n17 20 13\n4 14 6\n13 18 47\n18 45 28\n3 50 45\n6 6 6\n3 25 36\n28 48 42\n14 34 32\n28 41 35\n29 35 25\n25 48 24\n32 40 40\n18 38 44\n6 16 2\n1 36 7\n14 48 2\n18 29 40\n11 16 37\n8 40 19\n12 16 44\n44 46 21\n19 24 26\n24 45 44\n22 22 15\n6 15 32\n19 42 7\n21 33 20\n1 13 26\n16 27 40\n46 48 30\n21 39 1\n1 9 32\n14 34 20\n35 38 11\n19 47 23\n13 38 15\n28 29 28\n7 20 40\n2 21 46\n",
"output": "4384\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "50 50 50\n20 34 50\n10 36 27\n46 49 19\n15 22 21\n5 10 21\n40 47 0\n26 43 48\n15 34 5\n29 48 49\n2 45 25\n5 40 42\n1 27 0\n43 50 47\n5 19 23\n1 42 20\n18 50 16\n13 38 14\n14 30 22\n5 26 2\n32 46 15\n10 49 37\n33 37 24\n10 31 45\n16 45 37\n22 41 7\n23 49 29\n22 44 49\n3 44 22\n26 32 4\n30 40 19\n19 28 5\n6 34 14\n16 21 40\n12 43 46\n9 36 42\n2 19 39\n13 45 12\n2 30 6\n5 28 35\n18 45 7\n39 46 29\n29 43 33\n3 16 24\n20 40 24\n35 36 8\n2 14 8\n3 29 47\n31 32 0\n27 49 16\n1 37 45\n",
"output": "1111\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 918 | Solve the following coding problem using the programming language python:
Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.
The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.
Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.
-----Input-----
The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland.
Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive).
It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.
-----Output-----
Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.
-----Examples-----
Input
5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503
Output
Sidorov Ivanov
Andreev Semenov
Input
5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503
Output
?
Andreev Semenov
-----Note-----
In the first sample region teams are uniquely determined.
In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import defaultdict
n, m = list(map(int, input().split()))
data = defaultdict(dict)
for _ in range(n):
name, region, score = input().split()
region = int(region)
score = int(score)
if region not in data:
data[region] = defaultdict(list)
data[region][score].append(name)
for r in range(1, m + 1):
scores = data[r]
score_list = list(scores)
score_list.sort()
best = score_list[-1]
if len(scores[best]) > 2:
print('?')
elif len(scores[best]) == 1:
second = score_list[-2]
if len(scores[second]) >= 2:
print('?')
else:
name1 = scores[best][0]
name2 = scores[second][0]
print(name1, name2)
else:
print(' '.join(scores[best]))
``` | vfc_13426 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/659/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 2\nIvanov 1 763\nAndreev 2 800\nPetrov 1 595\nSidorov 1 790\nSemenov 2 503\n",
"output": "Sidorov Ivanov\nAndreev Semenov\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\nIvanov 1 800\nAndreev 2 763\nPetrov 1 800\nSidorov 1 800\nSemenov 2 503\n",
"output": "?\nAndreev Semenov\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 2\nSHiBIEz 2 628\nXxwaAxB 1 190\nXwR 2 290\nRKjOf 2 551\nTUP 1 333\nFarsFvyH 1 208\nCGDYnq 1 482\nqaM 2 267\nVfiLunRz 1 416\nuVMHLk 2 754\n",
"output": "CGDYnq VfiLunRz\nuVMHLk SHiBIEz\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 3\nfeDtYWSlR 2 361\nZEtQAWn 3 208\nE 2 564\noSXtUXr 3 750\nP 3 520\nPhYCykFvA 2 487\nvMQ 1 797\nZtE 1 141\nlrELK 1 736\nab 2 6\n",
"output": "vMQ lrELK\nE PhYCykFvA\noSXtUXr P\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 4\nigtVqPgoW 3 24\nuc 1 381\nOxmovZAv 4 727\nxyRAaAk 2 378\nvYCV 4 67\nuf 2 478\nDawOytiYiH 2 775\nRS 1 374\npLhTehhjA 2 38\nYkWfb 3 595\n",
"output": "uc RS\nDawOytiYiH uf\nYkWfb igtVqPgoW\nOxmovZAv vYCV\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 1\nOAELh 1 733\nbFGs 1 270\n",
"output": "OAELh bFGs\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 919 | Solve the following coding problem using the programming language python:
Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are $n$ stages available. The rocket must contain exactly $k$ of them. Stages in the rocket should be ordered by their weight. So, after the stage with some letter can go only stage with a letter, which is at least two positions after in the alphabet (skipping one letter in between, or even more). For example, after letter 'c' can't go letters 'a', 'b', 'c' and 'd', but can go letters 'e', 'f', ..., 'z'.
For the rocket to fly as far as possible, its weight should be minimal. The weight of the rocket is equal to the sum of the weights of its stages. The weight of the stage is the number of its letter in the alphabet. For example, the stage 'a 'weighs one ton,' b 'weighs two tons, and' z' — $26$ tons.
Build the rocket with the minimal weight or determine, that it is impossible to build a rocket at all. Each stage can be used at most once.
-----Input-----
The first line of input contains two integers — $n$ and $k$ ($1 \le k \le n \le 50$) – the number of available stages and the number of stages to use in the rocket.
The second line contains string $s$, which consists of exactly $n$ lowercase Latin letters. Each letter defines a new stage, which can be used to build the rocket. Each stage can be used at most once.
-----Output-----
Print a single integer — the minimal total weight of the rocket or -1, if it is impossible to build the rocket at all.
-----Examples-----
Input
5 3
xyabd
Output
29
Input
7 4
problem
Output
34
Input
2 2
ab
Output
-1
Input
12 1
abaabbaaabbb
Output
1
-----Note-----
In the first example, the following rockets satisfy the condition:
"adx" (weight is $1+4+24=29$);
"ady" (weight is $1+4+25=30$);
"bdx" (weight is $2+4+24=30$);
"bdy" (weight is $2+4+25=31$).
Rocket "adx" has the minimal weight, so the answer is $29$.
In the second example, target rocket is "belo". Its weight is $2+5+12+15=34$.
In the third example, $n=k=2$, so the rocket must have both stages: 'a' and 'b'. This rocket doesn't satisfy the condition, because these letters are adjacent in the alphabet. Answer is -1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = map(int, input().split())
s = sorted(list(input()))
prev = 0
w = 0
for el in s:
if k == 0:
break
if ord(el) >= prev + 2:
k -= 1
w += ord(el) - ord('a') + 1
prev = ord(el)
if k == 0:
print(w)
else:
print(-1)
``` | vfc_13430 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1011/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 3\nxyabd\n",
"output": "29",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7 4\nproblem\n",
"output": "34",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\nab\n",
"output": "-1",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 921 | Solve the following coding problem using the programming language python:
Polycarp invited all his friends to the tea party to celebrate the holiday. He has n cups, one for each of his n friends, with volumes a_1, a_2, ..., a_{n}. His teapot stores w milliliters of tea (w ≤ a_1 + a_2 + ... + a_{n}). Polycarp wants to pour tea in cups in such a way that: Every cup will contain tea for at least half of its volume Every cup will contain integer number of milliliters of tea All the tea from the teapot will be poured into cups All friends will be satisfied.
Friend with cup i won't be satisfied, if there exists such cup j that cup i contains less tea than cup j but a_{i} > a_{j}.
For each cup output how many milliliters of tea should be poured in it. If it's impossible to pour all the tea and satisfy all conditions then output -1.
-----Input-----
The first line contains two integer numbers n and w (1 ≤ n ≤ 100, $1 \leq w \leq \sum_{i = 1}^{n} a_{i}$).
The second line contains n numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 100).
-----Output-----
Output how many milliliters of tea every cup should contain. If there are multiple answers, print any of them.
If it's impossible to pour all the tea and satisfy all conditions then output -1.
-----Examples-----
Input
2 10
8 7
Output
6 4
Input
4 4
1 1 1 1
Output
1 1 1 1
Input
3 10
9 8 10
Output
-1
-----Note-----
In the third example you should pour to the first cup at least 5 milliliters, to the second one at least 4, to the third one at least 5. It sums up to 14, which is greater than 10 milliliters available.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, w = list(map(int, input().split()))
Cup = list(map(int, input().split()))
Water = []
for a in Cup:
Water.append((a + 1) // 2)
res = w - sum(Water)
if res < 0:
print(-1)
else:
while res > 0:
i = Cup.index(max(Cup))
num = min(res, Cup[i] - Water[i])
Water[i] += num
res -= num
Cup[i] = 0
s = str(Water[0])
for c in range(1, len(Water)):
s += " " + str(Water[c])
print(s)
``` | vfc_13438 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/808/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 10\n8 7\n",
"output": "6 4 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4\n1 1 1 1\n",
"output": "1 1 1 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 10\n9 8 10\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1\n",
"output": "1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n2\n",
"output": "1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 10\n20\n",
"output": "10 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 922 | Solve the following coding problem using the programming language python:
Polycarp has n dice d_1, d_2, ..., d_{n}. The i-th dice shows numbers from 1 to d_{i}. Polycarp rolled all the dice and the sum of numbers they showed is A. Agrippina didn't see which dice showed what number, she knows only the sum A and the values d_1, d_2, ..., d_{n}. However, she finds it enough to make a series of statements of the following type: dice i couldn't show number r. For example, if Polycarp had two six-faced dice and the total sum is A = 11, then Agrippina can state that each of the two dice couldn't show a value less than five (otherwise, the remaining dice must have a value of at least seven, which is impossible).
For each dice find the number of values for which it can be guaranteed that the dice couldn't show these values if the sum of the shown values is A.
-----Input-----
The first line contains two integers n, A (1 ≤ n ≤ 2·10^5, n ≤ A ≤ s) — the number of dice and the sum of shown values where s = d_1 + d_2 + ... + d_{n}.
The second line contains n integers d_1, d_2, ..., d_{n} (1 ≤ d_{i} ≤ 10^6), where d_{i} is the maximum value that the i-th dice can show.
-----Output-----
Print n integers b_1, b_2, ..., b_{n}, where b_{i} is the number of values for which it is guaranteed that the i-th dice couldn't show them.
-----Examples-----
Input
2 8
4 4
Output
3 3
Input
1 3
5
Output
4
Input
2 3
2 3
Output
0 1
-----Note-----
In the first sample from the statement A equal to 8 could be obtained in the only case when both the first and the second dice show 4. Correspondingly, both dice couldn't show values 1, 2 or 3.
In the second sample from the statement A equal to 3 could be obtained when the single dice shows 3. Correspondingly, it couldn't show 1, 2, 4 or 5.
In the third sample from the statement A equal to 3 could be obtained when one dice shows 1 and the other dice shows 2. That's why the first dice doesn't have any values it couldn't show and the second dice couldn't show 3.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, s = list(map(int, input().split()))
a = list(map(int, input().split()))
total = sum(a)
ans = []
for i in range(n):
high = s - (total - a[i])
low = s - (n - 1)
cur = 0
if low <= a[i]:
cur += a[i] - low
if high > 0:
cur += high - 1
ans.append(cur)
print(' '.join(map(str, ans)))
``` | vfc_13442 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/534/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 8\n4 4\n",
"output": "3 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 3\n5\n",
"output": "4 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n2 3\n",
"output": "0 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n3\n",
"output": "2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 923 | Solve the following coding problem using the programming language python:
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.
Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.
Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.
-----Input-----
The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears.
The second line contains n digits a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number a_{i}.
-----Output-----
In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.
-----Examples-----
Input
3
1 0 0
Output
Yes
Input
5
4 2 1 4 3
Output
Yes
Input
4
0 2 3 1
Output
No
-----Note-----
In the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(map(int, input().split()))
for i in range(n + 1):
for j in range(n):
if j % 2 == 0:
a[j] = (a[j] + 1) % n
else:
a[j] = (a[j] - 1) % n
for j in range(n):
if a[j] != j:
break
else:
print("Yes")
return
print("No")
``` | vfc_13446 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/556/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 0 0\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n4 2 1 4 3\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n0 2 3 1\n",
"output": "No\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0\n",
"output": "Yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n1 0\n",
"output": "Yes\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 924 | Solve the following coding problem using the programming language python:
Bob and Alice are often participating in various programming competitions. Like many competitive programmers, Alice and Bob have good and bad days. They noticed, that their lucky and unlucky days are repeating with some period. For example, for Alice days $[l_a; r_a]$ are lucky, then there are some unlucky days: $[r_a + 1; l_a + t_a - 1]$, and then there are lucky days again: $[l_a + t_a; r_a + t_a]$ and so on. In other words, the day is lucky for Alice if it lies in the segment $[l_a + k t_a; r_a + k t_a]$ for some non-negative integer $k$.
The Bob's lucky day have similar structure, however the parameters of his sequence are different: $l_b$, $r_b$, $t_b$. So a day is a lucky for Bob if it lies in a segment $[l_b + k t_b; r_b + k t_b]$, for some non-negative integer $k$.
Alice and Bob want to participate in team competitions together and so they want to find out what is the largest possible number of consecutive days, which are lucky for both Alice and Bob.
-----Input-----
The first line contains three integers $l_a$, $r_a$, $t_a$ ($0 \le l_a \le r_a \le t_a - 1, 2 \le t_a \le 10^9$) and describes Alice's lucky days.
The second line contains three integers $l_b$, $r_b$, $t_b$ ($0 \le l_b \le r_b \le t_b - 1, 2 \le t_b \le 10^9$) and describes Bob's lucky days.
It is guaranteed that both Alice and Bob have some unlucky days.
-----Output-----
Print one integer: the maximum number of days in the row that are lucky for both Alice and Bob.
-----Examples-----
Input
0 2 5
1 3 5
Output
2
Input
0 1 3
2 3 6
Output
1
-----Note-----
The graphs below correspond to the two sample tests and show the lucky and unlucky days of Alice and Bob as well as the possible solutions for these tests.
[Image]
[Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import string
from math import gcd
import getpass
import math
from decimal import Decimal
import pprint
def ria():
return [int(i) for i in input().split()]
if getpass.getuser() != 'frohenk':
filename = 'half'
# sys.stdin = open('input.txt')
# sys.stdout = open('output.txt', 'w')
else:
sys.stdin = open('input.txt')
# sys.stdin.close()
# sys.stdout = open('output.txt', 'w')
la, ra, ta = ria()
lb, rb, tb = ria()
if ta > tb:
la, ra, ta, lb, rb, tb = lb, rb, tb, la, ra, ta
gc = gcd(tb, ta)
if gc == 1:
print(min(ra - la + 1, rb - lb + 1))
return
def get(st):
nonlocal la, ra, ta, lb, rb, tb
lc = la + st
rc = ra + st
return max(min(rc, rb) - max(lc, lb) + 1, 0)
sta = la // gc
stb = lb // gc
fna = ra // gc
fnb = rb // gc
mx = 0
mx = max(mx, get((stb - sta) * gc))
mx = max(mx, get((stb - sta + 1) * gc))
mx = max(mx, get((stb - sta + 2) * gc))
mx = max(mx, get((stb - sta - 1) * gc))
mx = max(mx, get((stb - sta - 2) * gc))
mx = max(mx, get((fnb - fna) * gc))
mx = max(mx, get((fnb - fna + 1) * gc))
mx = max(mx, get((fnb - fna + 2) * gc))
mx = max(mx, get((fnb - fna - 1) * gc))
mx = max(mx, get((fnb - fna - 2) * gc))
#print(stb - sta)
print(mx)
``` | vfc_13450 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1055/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "0 2 5\n1 3 5\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "0 1 3\n2 3 6\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 925 | Solve the following coding problem using the programming language python:
Malek lives in an apartment block with 100 floors numbered from 0 to 99. The apartment has an elevator with a digital counter showing the floor that the elevator is currently on. The elevator shows each digit of a number with 7 light sticks by turning them on or off. The picture below shows how the elevator shows each digit.[Image]
One day when Malek wanted to go from floor 88 to floor 0 using the elevator he noticed that the counter shows number 89 instead of 88. Then when the elevator started moving the number on the counter changed to 87. After a little thinking Malek came to the conclusion that there is only one explanation for this: One of the sticks of the counter was broken. Later that day Malek was thinking about the broken stick and suddenly he came up with the following problem.
Suppose the digital counter is showing number n. Malek calls an integer x (0 ≤ x ≤ 99) good if it's possible that the digital counter was supposed to show x but because of some(possibly none) broken sticks it's showing n instead. Malek wants to know number of good integers for a specific n. So you must write a program that calculates this number. Please note that the counter always shows two digits.
-----Input-----
The only line of input contains exactly two digits representing number n (0 ≤ n ≤ 99). Note that n may have a leading zero.
-----Output-----
In the only line of the output print the number of good integers.
-----Examples-----
Input
89
Output
2
Input
00
Output
4
Input
73
Output
15
-----Note-----
In the first sample the counter may be supposed to show 88 or 89.
In the second sample the good integers are 00, 08, 80 and 88.
In the third sample the good integers are 03, 08, 09, 33, 38, 39, 73, 78, 79, 83, 88, 89, 93, 98, 99.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# -*- coding: utf-8 -*-
ngoods = {
'0': 2,
'1': 7,
'2': 2,
'3': 3,
'4': 3,
'5': 4,
'6': 2,
'7': 5,
'8': 1,
'9': 2
}
digits = input().strip()
print(ngoods[digits[0]] * ngoods[digits[1]])
``` | vfc_13454 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/495/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "89\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "00\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "73\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "08\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "26\n",
"output": "4\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 926 | Solve the following coding problem using the programming language python:
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere.
Zahar has n stones which are rectangular parallelepipeds. The edges sizes of the i-th of them are a_{i}, b_{i} and c_{i}. He can take no more than two stones and present them to Kostya.
If Zahar takes two stones, he should glue them together on one of the faces in order to get a new piece of rectangular parallelepiped of marble. Thus, it is possible to glue a pair of stones together if and only if two faces on which they are glued together match as rectangles. In such gluing it is allowed to rotate and flip the stones in any way.
Help Zahar choose such a present so that Kostya can carve a sphere of the maximum possible volume and present it to Zahar.
-----Input-----
The first line contains the integer n (1 ≤ n ≤ 10^5).
n lines follow, in the i-th of which there are three integers a_{i}, b_{i} and c_{i} (1 ≤ a_{i}, b_{i}, c_{i} ≤ 10^9) — the lengths of edges of the i-th stone. Note, that two stones may have exactly the same sizes, but they still will be considered two different stones.
-----Output-----
In the first line print k (1 ≤ k ≤ 2) the number of stones which Zahar has chosen. In the second line print k distinct integers from 1 to n — the numbers of stones which Zahar needs to choose. Consider that stones are numbered from 1 to n in the order as they are given in the input data.
You can print the stones in arbitrary order. If there are several answers print any of them.
-----Examples-----
Input
6
5 5 5
3 2 4
1 4 1
2 1 3
3 2 4
3 3 4
Output
1
1
Input
7
10 7 8
5 10 3
4 2 6
5 5 5
10 2 8
4 2 1
7 7 7
Output
2
1 5
-----Note-----
In the first example we can connect the pairs of stones: 2 and 4, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 2 and 5, the size of the parallelepiped: 3 × 2 × 8 or 6 × 2 × 4 or 3 × 4 × 4, the radius of the inscribed sphere 1, or 1, or 1.5 respectively. 2 and 6, the size of the parallelepiped: 3 × 5 × 4, the radius of the inscribed sphere 1.5 4 and 5, the size of the parallelepiped: 3 × 2 × 5, the radius of the inscribed sphere 1 5 and 6, the size of the parallelepiped: 3 × 4 × 5, the radius of the inscribed sphere 1.5
Or take only one stone: 1 the size of the parallelepiped: 5 × 5 × 5, the radius of the inscribed sphere 2.5 2 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 3 the size of the parallelepiped: 1 × 4 × 1, the radius of the inscribed sphere 0.5 4 the size of the parallelepiped: 2 × 1 × 3, the radius of the inscribed sphere 0.5 5 the size of the parallelepiped: 3 × 2 × 4, the radius of the inscribed sphere 1 6 the size of the parallelepiped: 3 × 3 × 4, the radius of the inscribed sphere 1.5
It is most profitable to take only the first stone.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
mv = 0
mn = []
data = {}
for i in range (n):
cur = list(sorted(map(int, input().split())))
key = (cur[1], cur[2])
if key in data:
old, k = data[key]
res = [old + cur[0], cur[1], cur[2]]
m = min(res)
if m > mv:
mv = m
mn = [k, i]
if old < cur[0]:
data[key] = (cur[0], i)
else:
data[key] = (cur[0], i)
m = cur[0]
if m > mv:
mv = m
mn = [i]
print(len(mn))
print(" ".join(map(lambda x: str(x+1), mn)))
``` | vfc_13458 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/733/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n5 5 5\n3 2 4\n1 4 1\n2 1 3\n3 2 4\n3 3 4\n",
"output": "1\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\n10 7 8\n5 10 3\n4 2 6\n5 5 5\n10 2 8\n4 2 1\n7 7 7\n",
"output": "2\n1 5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1 1 1\n",
"output": "1\n1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 932 | Solve the following coding problem using the programming language python:
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner:
$a_{1} OR a_{2} OR \ldots OR a_{k}$ where $a_{i} \in \{0,1 \}$ is equal to 1 if some a_{i} = 1, otherwise it is equal to 0.
Nam has a matrix A consisting of m rows and n columns. The rows are numbered from 1 to m, columns are numbered from 1 to n. Element at row i (1 ≤ i ≤ m) and column j (1 ≤ j ≤ n) is denoted as A_{ij}. All elements of A are either 0 or 1. From matrix A, Nam creates another matrix B of the same size using formula:
[Image].
(B_{ij} is OR of all elements in row i and column j of matrix A)
Nam gives you matrix B and challenges you to guess matrix A. Although Nam is smart, he could probably make a mistake while calculating matrix B, since size of A can be large.
-----Input-----
The first line contains two integer m and n (1 ≤ m, n ≤ 100), number of rows and number of columns of matrices respectively.
The next m lines each contain n integers separated by spaces describing rows of matrix B (each element of B is either 0 or 1).
-----Output-----
In the first line, print "NO" if Nam has made a mistake when calculating B, otherwise print "YES". If the first line is "YES", then also print m rows consisting of n integers representing matrix A that can produce given matrix B. If there are several solutions print any one.
-----Examples-----
Input
2 2
1 0
0 0
Output
NO
Input
2 3
1 1 1
1 1 1
Output
YES
1 1 1
1 1 1
Input
2 3
0 1 0
1 1 1
Output
YES
0 0 0
0 1 0
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
m, n = map(int, input().split())
a = []
for _ in range(m):
a.append(list(map(int, input().split())))
b = [[1]*n for _ in range(m)]
for i in range(m):
for j in range(n):
if(a[i][j] == 0):
b[i] = [0]*n
for k in range(m):
b[k][j] = 0
for i in range(m):
for j in range(n):
if(a[i][j] == 1):
good = False
if(1 in b[i]):
good = True
else:
for k in range(m):
if(b[k][j] == 1):
good = True
if not good:
print('NO')
return
print("YES")
for i in b:
print(' '.join([str(t) for t in i]))
``` | vfc_13482 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/486/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n1 0\n0 0\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n1 1 1\n1 1 1\n",
"output": "YES\n1 1 1\n1 1 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n0 1 0\n1 1 1\n",
"output": "YES\n0 0 0\n0 1 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n1 1 1 1 1\n1 0 0 0 0\n1 0 0 0 0\n1 0 0 0 0\n1 0 0 0 0\n",
"output": "YES\n1 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 933 | Solve the following coding problem using the programming language python:
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.
In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).
Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
-----Input-----
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
-----Output-----
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters.
If there are multiple solutions, print any of them.
-----Examples-----
Input
helloo
Output
hello
Input
woooooow
Output
woow
-----Note-----
The second valid answer to the test from the statement is "heloo".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input().strip()
if len(s)<=2:
print(s)
return
ne = s[0]+s[1]
for i in range(2,len(s)):
if s[i]!=s[i-1] or s[i]!=s[i-2]:
ne+=s[i]
ne2 = ne[:3]
for i in range(3,len(ne),1):
if ne2[-3]==ne2[-2] and ne2[-1]==ne[i]:
pass
else:
ne2+=ne[i]
print(ne2)
``` | vfc_13486 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/363/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "helloo\n",
"output": "hello\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "woooooow\n",
"output": "woow\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aabbaa\n",
"output": "aabaa\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "yesssssss\n",
"output": "yess\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aabbaabbaabbaabbaabbaabbcccccc\n",
"output": "aabaabaabaabaabaabcc\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaa\n",
"output": "aa\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 934 | Solve the following coding problem using the programming language python:
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of $52$ cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or Hearts — H), and a rank (2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K, or A).
At the start of the game, there is one card on the table and you have five cards in your hand. You can play a card from your hand if and only if it has the same rank or the same suit as the card on the table.
In order to check if you'd be a good playing partner, Gennady has prepared a task for you. Given the card on the table and five cards in your hand, check if you can play at least one card.
-----Input-----
The first line of the input contains one string which describes the card on the table. The second line contains five strings which describe the cards in your hand.
Each string is two characters long. The first character denotes the rank and belongs to the set $\{{\tt 2}, {\tt 3}, {\tt 4}, {\tt 5}, {\tt 6}, {\tt 7}, {\tt 8}, {\tt 9}, {\tt T}, {\tt J}, {\tt Q}, {\tt K}, {\tt A}\}$. The second character denotes the suit and belongs to the set $\{{\tt D}, {\tt C}, {\tt S}, {\tt H}\}$.
All the cards in the input are different.
-----Output-----
If it is possible to play a card from your hand, print one word "YES". Otherwise, print "NO".
You can print each letter in any case (upper or lower).
-----Examples-----
Input
AS
2H 4C TH JH AD
Output
YES
Input
2H
3D 4C AC KD AS
Output
NO
Input
4D
AS AC AD AH 5H
Output
YES
-----Note-----
In the first example, there is an Ace of Spades (AS) on the table. You can play an Ace of Diamonds (AD) because both of them are Aces.
In the second example, you cannot play any card.
In the third example, you can play an Ace of Diamonds (AD) because it has the same suit as a Four of Diamonds (4D), which lies on the table.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
c = input()
s = list(input().split())
print('YES' if any(c[0] == x[0] or c[1] == x[1] for x in s) else 'NO')
``` | vfc_13490 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1097/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "AS\n2H 4C TH JH AD\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2H\n3D 4C AC KD AS\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4D\nAS AC AD AH 5H\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3D\n8S 4S 2C AS 6H\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 935 | Solve the following coding problem using the programming language python:
After winning gold and silver in IOI 2014, Akshat and Malvika want to have some fun. Now they are playing a game on a grid made of n horizontal and m vertical sticks.
An intersection point is any point on the grid which is formed by the intersection of one horizontal stick and one vertical stick.
In the grid shown below, n = 3 and m = 3. There are n + m = 6 sticks in total (horizontal sticks are shown in red and vertical sticks are shown in green). There are n·m = 9 intersection points, numbered from 1 to 9.
[Image]
The rules of the game are very simple. The players move in turns. Akshat won gold, so he makes the first move. During his/her move, a player must choose any remaining intersection point and remove from the grid all sticks which pass through this point. A player will lose the game if he/she cannot make a move (i.e. there are no intersection points remaining on the grid at his/her move).
Assume that both players play optimally. Who will win the game?
-----Input-----
The first line of input contains two space-separated integers, n and m (1 ≤ n, m ≤ 100).
-----Output-----
Print a single line containing "Akshat" or "Malvika" (without the quotes), depending on the winner of the game.
-----Examples-----
Input
2 2
Output
Malvika
Input
2 3
Output
Malvika
Input
3 3
Output
Akshat
-----Note-----
Explanation of the first sample:
The grid has four intersection points, numbered from 1 to 4.
[Image]
If Akshat chooses intersection point 1, then he will remove two sticks (1 - 2 and 1 - 3). The resulting grid will look like this.
[Image]
Now there is only one remaining intersection point (i.e. 4). Malvika must choose it and remove both remaining sticks. After her move the grid will be empty.
In the empty grid, Akshat cannot make any move, hence he will lose.
Since all 4 intersection points of the grid are equivalent, Akshat will lose no matter which one he picks.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a, b = list(map(int, input().split()))
print('Malvika' if min(a, b) % 2 == 0 else 'Akshat')
``` | vfc_13494 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/451/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2\n",
"output": "Malvika\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 3\n",
"output": "Malvika\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 936 | Solve the following coding problem using the programming language python:
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the total likes to the published photoes.
The second line contains n positive integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1 000 000), where a_{i} is the identifier of the photo which got the i-th like.
-----Output-----
Print the identifier of the photo which won the elections.
-----Examples-----
Input
5
1 3 2 2 1
Output
2
Input
9
100 200 300 200 100 300 300 100 200
Output
300
-----Note-----
In the first test sample the photo with id 1 got two likes (first and fifth), photo with id 2 got two likes (third and fourth), and photo with id 3 got one like (second).
Thus, the winner is the photo with identifier 2, as it got: more likes than the photo with id 3; as many likes as the photo with id 1, but the photo with the identifier 2 got its second like earlier.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = [int(x) for x in input().split()]
score = dict()
sup, winner = -2**31, None
for v in a:
score[v] = score[v] + 1 if v in score else 1
if score[v] > sup:
sup, winner = score[v], v
print(winner)
``` | vfc_13498 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/637/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 3 2 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n100 200 300 200 100 300 300 100 200\n",
"output": "300\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n5\n",
"output": "5\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000\n",
"output": "1000000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 3 4 2 2\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n2 1 2 3 1 5 8 7 4 8\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 937 | Solve the following coding problem using the programming language python:
Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells a_{i} theorems during the i-th minute.
Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then t_{i} will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — a_{i} during the i-th minute. Otherwise he writes nothing.
You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that $j \in [ i, i + k - 1 ]$ and will write down all the theorems lecturer tells.
You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
-----Input-----
The first line of the input contains two integer numbers n and k (1 ≤ k ≤ n ≤ 10^5) — the duration of the lecture in minutes and the number of minutes you can keep Mishka awake.
The second line of the input contains n integer numbers a_1, a_2, ... a_{n} (1 ≤ a_{i} ≤ 10^4) — the number of theorems lecturer tells during the i-th minute.
The third line of the input contains n integer numbers t_1, t_2, ... t_{n} (0 ≤ t_{i} ≤ 1) — type of Mishka's behavior at the i-th minute of the lecture.
-----Output-----
Print only one integer — the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.
-----Example-----
Input
6 3
1 3 5 2 5 4
1 1 0 1 0 0
Output
16
-----Note-----
In the sample case the better way is to use the secret technique at the beginning of the third minute. Then the number of theorems Mishka will be able to write down will be equal to 16.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
mask = list(map(int, input().split()))
result = sum(a[i] if mask[i] == 1 else 0 for i in range(n))
h = [a[i] if mask[i] == 0 else 0 for i in range(len(a))]
best_awake = sum(h[:k])
curr = best_awake
for j in range(k, n):
curr += h[j]
curr -= h[j - k]
best_awake = max(best_awake, curr)
print(result + best_awake)
``` | vfc_13502 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/961/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 3\n1 3 5 2 5 4\n1 1 0 1 0 0\n",
"output": "16\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 3\n1 9999 10000 10000 10000\n0 0 0 0 0\n",
"output": "30000\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 938 | Solve the following coding problem using the programming language python:
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.
Lesha knows that today he can study for at most $a$ hours, and he will have $b$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $k$ in $k$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.
Thus, the student has to fully read several lecture notes today, spending at most $a$ hours in total, and fully read several lecture notes tomorrow, spending at most $b$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?
-----Input-----
The only line of input contains two integers $a$ and $b$ ($0 \leq a, b \leq 10^{9}$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.
-----Output-----
In the first line print a single integer $n$ ($0 \leq n \leq a$) — the number of lecture notes Lesha has to read in the first day. In the second line print $n$ distinct integers $p_1, p_2, \ldots, p_n$ ($1 \leq p_i \leq a$), the sum of all $p_i$ should not exceed $a$.
In the third line print a single integer $m$ ($0 \leq m \leq b$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $m$ distinct integers $q_1, q_2, \ldots, q_m$ ($1 \leq q_i \leq b$), the sum of all $q_i$ should not exceed $b$.
All integers $p_i$ and $q_i$ should be distinct. The sum $n + m$ should be largest possible.
-----Examples-----
Input
3 3
Output
1
3
2
2 1
Input
9 12
Output
2
3 6
4
1 2 4 5
-----Note-----
In the first example Lesha can read the third note in $3$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $3$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.
In the second example Lesha should read the third and the sixth notes in the first day, spending $9$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $12$ hours in total.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a, b = list(map(int,input().split()))
if a <= b:
l = 0
r = a + 1
while r - l > 1:
m = (l + r) // 2
if m * (m + 1) // 2 > a:
r = m
else:
l = m
n = l
a -= n*(n+1) // 2
c = 1
N = [i + 1 for i in range(n)]
if a > 0:
c = n + 1 - a
N.pop(c - 1)
N.append(c + a)
N[-1] = c + a
D = []
if a != 0:
b -= c
D = [c]
n = n + 1
n += 1
while b >= 0:
b -= n
D.append(n)
n += 1
D.pop(-1)
print(len(N))
if len(N) != 0:
print(*N)
print(len(D))
if len(D) != 0:
print(*D)
else:
c = a
a = b
b = c
l = 0
r = a + 1
while r - l > 1:
m = (l + r) // 2
if m * (m + 1) // 2 > a:
r = m
else:
l = m
n = l
a -= n*(n+1) // 2
c = 1
N = [i + 1 for i in range(n)]
if a > 0:
c = n + 1 - a
N.pop(c - 1)
N.append(c + a)
N[-1] = c + a
D = []
if a != 0:
b -= c
D = [c]
n = n + 1
n += 1
while b >= 0:
b -= n
D.append(n)
n += 1
D.pop(-1)
print(len(D))
if len(D) != 0:
print(*D)
print(len(N))
if len(N) != 0:
print(*N)
``` | vfc_13506 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1031/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 3\n",
"output": "1\n3 \n2\n2 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 12\n",
"output": "3\n4 3 2 \n3\n6 5 1 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 939 | Solve the following coding problem using the programming language python:
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland).
The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance.
You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.
-----Input-----
The first line contains two space-separated integers n (3 ≤ n ≤ 10^5) and m (1 ≤ m ≤ 10^5) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.
-----Output-----
Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.
-----Examples-----
Input
7 3
1 2 3
1 4 5
4 6 7
Output
1 2 3 3 2 2 1
Input
9 3
3 6 9
2 5 8
1 4 7
Output
1 1 1 2 2 2 3 3 3
Input
5 2
4 1 5
3 1 2
Output
2 3 1 1 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys;
nbDancers, nbDances = list(map(int, sys.stdin.readline().split(' ')));
dancers = [0]*(nbDancers+1);
for line in sys.stdin:
taken = [False, False, False, False];
ds = list(map(int, line.split(' ')));
for d in ds:
taken[dancers[d]] = True;
for d in ds:
if dancers[d] == 0:
if not taken[1]:
dancers[d] = 1;
taken[1] = True;
elif not taken[2]:
dancers[d] = 2;
taken[2] = True;
elif not taken[3]:
dancers[d] = 3;
taken[3] = True;
print((' '.join(map(str, dancers[1:]))));
``` | vfc_13510 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/357/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "7 3\n1 2 3\n1 4 5\n4 6 7\n",
"output": "1 2 3 3 2 2 1 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9 3\n3 6 9\n2 5 8\n1 4 7\n",
"output": "1 1 1 2 2 2 3 3 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n4 1 5\n3 1 2\n",
"output": "2 3 1 1 3 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 940 | Solve the following coding problem using the programming language python:
Masha has three sticks of length $a$, $b$ and $c$ centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.
What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a triangle of positive area. Sticks should be used as triangle's sides (one stick for one side) and their endpoints should be located at triangle's vertices.
-----Input-----
The only line contains tree integers $a$, $b$ and $c$ ($1 \leq a, b, c \leq 100$) — the lengths of sticks Masha possesses.
-----Output-----
Print a single integer — the minimum number of minutes that Masha needs to spend in order to be able to make the triangle of positive area from her sticks.
-----Examples-----
Input
3 4 5
Output
0
Input
2 5 3
Output
1
Input
100 10 10
Output
81
-----Note-----
In the first example, Masha can make a triangle from the sticks without increasing the length of any of them.
In the second example, Masha can't make a triangle of positive area from the sticks she has at the beginning, but she can spend one minute to increase the length $2$ centimeter stick by one and after that form a triangle with sides $3$, $3$ and $5$ centimeters.
In the third example, Masha can take $33$ minutes to increase one of the $10$ centimeters sticks by $33$ centimeters, and after that take $48$ minutes to increase another $10$ centimeters stick by $48$ centimeters. This way she can form a triangle with lengths $43$, $58$ and $100$ centimeters in $81$ minutes. One can show that it is impossible to get a valid triangle faster.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a, b, c = sorted(map(int, input().split()))
print(max(0, c - a - b + 1))
``` | vfc_13514 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1064/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4 5\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 5 3\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 942 | Solve the following coding problem using the programming language python:
Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.
Chouti remembered that $n$ persons took part in that party. To make the party funnier, each person wore one hat among $n$ kinds of weird hats numbered $1, 2, \ldots n$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.
After the party, the $i$-th person said that there were $a_i$ persons wearing a hat differing from his own.
It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $b_i$ be the number of hat type the $i$-th person was wearing, Chouti wants you to find any possible $b_1, b_2, \ldots, b_n$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 10^5$), the number of persons in the party.
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le n-1$), the statements of people.
-----Output-----
If there is no solution, print a single line "Impossible".
Otherwise, print "Possible" and then $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$).
If there are multiple answers, print any of them.
-----Examples-----
Input
3
0 0 0
Output
Possible
1 1 1
Input
5
3 3 2 2 2
Output
Possible
1 1 2 2 2
Input
4
0 1 2 3
Output
Impossible
-----Note-----
In the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $1$.
In the answer to the second example, the first and the second person wore the hat with type $1$ and all other wore a hat of type $2$.
So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.
In the third example, it can be shown that no solution exists.
In the first and the second example, other possible configurations are possible.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
input()
l = list(map(int, input().split()))
d = {}
d2 = {}
ans = []
n = 1
for i in l:
i = len(l) - i
if i not in d:
d[i] = n
n += 1
if i not in d2:
d2[i] = 0
if d2[i] >= i:
d[i] = n
d2[i] = 0
n += 1
ans.append(d[i])
d2[i] += 1
nums = {}
tot = 0
for i in ans:
tot += 1
if i not in nums:
nums[i] = 0
nums[i] += 1
for i in range(len(ans)):
if tot - nums[ans[i]] != l[i]:
print("Impossible")
return
print("Possible")
print(" ".join(map(str, ans)))
``` | vfc_13522 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1081/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n0 0 0\n",
"output": "Possible\n1 1 1 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n3 3 2 2 2\n",
"output": "Possible\n1 1 2 2 2 ",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 943 | Solve the following coding problem using the programming language python:
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark.
Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.
-----Input-----
The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 10^9, inclusive.
-----Output-----
Print the maximum possible even sum that can be obtained if we use some of the given integers.
-----Examples-----
Input
3
1 2 3
Output
6
Input
5
999999999 999999999 999999999 999999999 999999999
Output
3999999996
-----Note-----
In the first sample, we can simply take all three integers for a total sum of 6.
In the second sample Wet Shark should take any four out of five integers 999 999 999.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
n = int(input())
a = [int(i) for i in input().split()]
cnt = 0
mi = 10 ** 9
for i in a:
if i % 2 == 1:
cnt ^= 1
mi = min(mi, i)
if not cnt:
mi = 0
print(sum(a) - mi)
main()
``` | vfc_13526 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/621/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "6",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n999999999 999999999 999999999 999999999 999999999\n",
"output": "3999999996",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\n39 52 88 78 46 95 84 98 55 3 68 42 6 18 98\n",
"output": "870",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "15\n59 96 34 48 8 72 67 90 15 85 7 90 97 47 25\n",
"output": "840",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 944 | Solve the following coding problem using the programming language python:
In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.
In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.
Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.
-----Input-----
The first line of the input contains a positive integer n (2 ≤ n ≤ 200 000) — the number of cities in Berland.
Each of the next n - 1 lines contains two numbers u_{i}, v_{i}, meaning that the i-th road connects city u_{i} and city v_{i} (1 ≤ u_{i}, v_{i} ≤ n, u_{i} ≠ v_{i}).
-----Output-----
First print number k — the minimum number of days needed to repair all the roads in Berland.
In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number d_{i} — the number of roads that should be repaired on the i-th day, and then d_{i} space-separated integers — the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one.
If there are multiple variants, you can print any of them.
-----Examples-----
Input
4
1 2
3 4
3 2
Output
2
2 2 1
1 3
Input
6
3 4
5 4
3 2
1 3
4 6
Output
3
1 1
2 2 3
2 4 5
-----Note-----
In the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 — on the second day.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
import threading
from collections import defaultdict
def put():
return map(int, input().split())
def dfs(i, p, m):
cnt = 1
z = 0
for j in tree[i]:
if j==p: continue
if cnt==m: cnt+=1
index = edge_index[(i,j)]
ans[cnt].append(index)
z = max(dfs(j,i,cnt), z)
cnt+=1
return max(z,cnt-1)
def solve():
l = dfs(1,0,0)
print(l)
for i in range(1, l+1):
print(len(ans[i]), *ans[i])
n = int(input())
edge_index = defaultdict()
ans = [[] for i in range(n+1)]
tree = [[] for i in range(n+1)]
for i in range(n-1):
x,y = put()
edge_index[(x,y)]=i+1
edge_index[(y,x)]=i+1
tree[x].append(y)
tree[y].append(x)
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
``` | vfc_13530 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/638/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n1 2\n3 4\n3 2\n",
"output": "2\n2 1 2 \n1 3 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n3 4\n5 4\n3 2\n1 3\n4 6\n",
"output": "3\n1 1 \n2 2 3 \n2 4 5 \n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n1 3\n1 6\n3 4\n6 2\n5 6\n6 7\n7 8\n",
"output": "4\n3 2 3 7 \n2 1 4 \n1 5 \n1 6 \n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 945 | Solve the following coding problem using the programming language python:
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.
The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them by semi-circus in a certain order: first connect the first point with the second one, then connect the second point with the third one, then the third one with the fourth one and so on to the n-th point. Two points with coordinates (x_1, 0) and (x_2, 0) should be connected by a semi-circle that passes above the abscissa axis with the diameter that coincides with the segment between points. Seryozha needs to find out if the line on the picture intersects itself. For clarifications, see the picture Seryozha showed to Dima (the left picture has self-intersections, the right picture doesn't have any). [Image]
Seryozha is not a small boy, so the coordinates of the points can be rather large. Help Dima cope with the problem.
-----Input-----
The first line contains a single integer n (1 ≤ n ≤ 10^3). The second line contains n distinct integers x_1, x_2, ..., x_{n} ( - 10^6 ≤ x_{i} ≤ 10^6) — the i-th point has coordinates (x_{i}, 0). The points are not necessarily sorted by their x coordinate.
-----Output-----
In the single line print "yes" (without the quotes), if the line has self-intersections. Otherwise, print "no" (without the quotes).
-----Examples-----
Input
4
0 10 5 15
Output
yes
Input
4
0 15 5 10
Output
no
-----Note-----
The first test from the statement is on the picture to the left, the second test is on the picture to the right.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def Intersect(aa,bb,xx,yy):
a=min(aa,bb)
b=max(aa,bb)
x=min(xx,yy)
y=max(xx,yy)
if(a>=x and b<=y):
return False
if(x>=a and y<=b):
return False
if(b<=x):
return False
if(y<=a):
return False
return True
N=int(input())
case=False
L=list(map(int,input().split()))
for i in range(N-1):
for j in range(i+1,N-1):
if(Intersect(L[i],L[i+1],L[j],L[j+1])):
case=True
if(case):
print("yes")
else:
print("no")
``` | vfc_13534 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/358/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n0 10 5 15\n",
"output": "yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n0 15 5 10\n",
"output": "no\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n0 1000 2000 3000 1500\n",
"output": "yes\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n-724093 710736 -383722 -359011 439613\n",
"output": "no\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 946 | Solve the following coding problem using the programming language python:
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked $n$ people about their opinions. Each person answered whether this problem is easy or hard.
If at least one of these $n$ people has answered that the problem is hard, the coordinator decides to change the problem. For the given responses, check if the problem is easy enough.
-----Input-----
The first line contains a single integer $n$ ($1 \le n \le 100$) — the number of people who were asked to give their opinions.
The second line contains $n$ integers, each integer is either $0$ or $1$. If $i$-th integer is $0$, then $i$-th person thinks that the problem is easy; if it is $1$, then $i$-th person thinks that the problem is hard.
-----Output-----
Print one word: "EASY" if the problem is easy according to all responses, or "HARD" if there is at least one person who thinks the problem is hard.
You may print every letter in any register: "EASY", "easy", "EaSY" and "eAsY" all will be processed correctly.
-----Examples-----
Input
3
0 0 1
Output
HARD
Input
1
0
Output
EASY
-----Note-----
In the first example the third person says it's a hard problem, so it should be replaced.
In the second example the problem easy for the only person, so it doesn't have to be replaced.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
input()
l = list(map(int, input().split()))
if 1 in l:
print('HARD')
else:
print('EASY')
``` | vfc_13538 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1030/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n0 0 1\n",
"output": "HARD\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0\n",
"output": "EASY\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "HARD\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 947 | Solve the following coding problem using the programming language python:
In Omkar's last class of math, he learned about the least common multiple, or $LCM$. $LCM(a, b)$ is the smallest positive integer $x$ which is divisible by both $a$ and $b$.
Omkar, having a laudably curious mind, immediately thought of a problem involving the $LCM$ operation: given an integer $n$, find positive integers $a$ and $b$ such that $a + b = n$ and $LCM(a, b)$ is the minimum value possible.
Can you help Omkar solve his ludicrously challenging math problem?
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \leq t \leq 10$). Description of the test cases follows.
Each test case consists of a single integer $n$ ($2 \leq n \leq 10^{9}$).
-----Output-----
For each test case, output two positive integers $a$ and $b$, such that $a + b = n$ and $LCM(a, b)$ is the minimum possible.
-----Example-----
Input
3
4
6
9
Output
2 2
3 3
3 6
-----Note-----
For the first test case, the numbers we can choose are $1, 3$ or $2, 2$. $LCM(1, 3) = 3$ and $LCM(2, 2) = 2$, so we output $2 \ 2$.
For the second test case, the numbers we can choose are $1, 5$, $2, 4$, or $3, 3$. $LCM(1, 5) = 5$, $LCM(2, 4) = 4$, and $LCM(3, 3) = 3$, so we output $3 \ 3$.
For the third test case, $LCM(3, 6) = 6$. It can be shown that there are no other pairs of numbers which sum to $9$ that have a lower $LCM$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from math import sqrt
def solve():
n = int(input())
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
x = n // i
print(x, x * (i-1))
return
print(n-1,1)
for i in range(int(input())):
solve()
``` | vfc_13542 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1372/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n4\n6\n9\n",
"output": "2 2\n3 3\n3 6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n4\n5\n2\n",
"output": "2 2\n1 4\n1 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n527\n622\n63\n423\n147\n791\n838\n903\n",
"output": "31 496\n311 311\n21 42\n141 282\n49 98\n113 678\n419 419\n301 602\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n861605021\n68328580\n877214985\n692261986\n3399371\n684035729\n",
"output": "1 861605020\n34164290 34164290\n292404995 584809990\n346130993 346130993\n199963 3199408\n52618133 631417596\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n201963219\n303973760\n54544086\n751923241\n687055210\n1649300\n203977471\n402504158\n14556710\n207186606\n",
"output": "67321073 134642146\n151986880 151986880\n27272043 27272043\n17486587 734436654\n343527605 343527605\n824650 824650\n1 203977470\n201252079 201252079\n7278355 7278355\n103593303 103593303\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 948 | Solve the following coding problem using the programming language python:
The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them.
In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face".
You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.
-----Input-----
The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively.
Next n lines define the image. Each line contains m lowercase Latin letters.
-----Output-----
In the single line print the number of faces on the image.
-----Examples-----
Input
4 4
xxxx
xfax
xcex
xxxx
Output
1
Input
4 2
xx
cf
ae
xx
Output
1
Input
2 3
fac
cef
Output
2
Input
1 4
face
Output
0
-----Note-----
In the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column: [Image]
In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.
In the third sample two faces are shown: $\text{fac}$
In the fourth sample the image has no faces on it.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, m = list(map(int, input().split()))
field = []
for i in range(n):
field.append(input())
ans = 0
for i in range(n - 1):
for j in range(m - 1):
t = set()
t.add(field[i][j])
t.add(field[i + 1][j + 1])
t.add(field[i + 1][j])
t.add(field[i][j + 1])
if t == set('face'):
ans += 1
print(ans)
``` | vfc_13546 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/549/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 4\nxxxx\nxfax\nxcex\nxxxx\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 949 | Solve the following coding problem using the programming language python:
Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm.
Formally, find the biggest integer d, such that all integers a, a + 1, a + 2, ..., b are divisible by d. To make the problem even more complicated we allow a and b to be up to googol, 10^100 — such number do not fit even in 64-bit integer type!
-----Input-----
The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10^100).
-----Output-----
Output one integer — greatest common divisor of all integers from a to b inclusive.
-----Examples-----
Input
1 2
Output
1
Input
61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576
Output
61803398874989484820458683436563811772030917980576
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a,b = input().split()
if (a==b):
print(a)
else:
print(1)
``` | vfc_13550 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/664/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1 2\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "61803398874989484820458683436563811772030917980576 61803398874989484820458683436563811772030917980576\n",
"output": "61803398874989484820458683436563811772030917980576\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 100\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 950 | Solve the following coding problem using the programming language python:
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: There is at least one digit in the string, There is at least one lowercase (small) letter of the Latin alphabet in the string, There is at least one of three listed symbols in the string: '#', '*', '&'. [Image]
Considering that these are programming classes it is not easy to write the password.
For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).
During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.
You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.
-----Input-----
The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.
Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'.
You have such input data that you can always get a valid password.
-----Output-----
Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.
-----Examples-----
Input
3 4
1**2
a3*0
c4**
Output
1
Input
5 5
#*&#*
*a1c&
&q2w*
#a3c#
*&#*&
Output
3
-----Note-----
In the first test it is necessary to move the pointer of the third string to one left to get the optimal answer. [Image]
In the second test one of possible algorithms will be: to move the pointer of the second symbol once to the right. to move the pointer of the third symbol twice to the right. [Image]
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import math, re, itertools as it;prime = lambda n: len([i for i in range(2, int(math.sqrt(n) + 1)) if n % i == 0]) == 0;gcd = lambda a, b: gcd(b, a % b) if b else a;fact = lambda x: x * fact(x - 1) if x else 1;bino = lambda n, k: fact(n) / fact(k) / fact(n - k);fib11 = lambda n: 1 if n < 2 else fib11(n - 1) + fib11(n - 2);fib01 = lambda n: 0 if n == 0 else 1 if n == 1 else fib01(n - 1) + fib01(n - 2);sumofd = lambda x: x if x < 10 else sumofd(x // 10) + x % 10
n, m = map(int, input().split(' '))
a = []
dp = []
sc = st = sl = 1000000
for _ in range(n):
a.append(input())
c = t = l = 1000000
for i in range(len(a[-1])):
if a[-1][i] in '0123456789':
c = min(c, i, len(a[-1]) - i)
if a[-1][i] in '#*&':
t = min(t, i, len(a[-1]) - i)
if 'a' <= a[-1][i] <= 'z':
l = min(l, i, len(a[-1]) - i)
'''if c == t == 1000000 or c == l == 1000000 or l == t == 1000000:
if c == t == 1000000:
sl = 0
if c == l == 1000000:
st = 0
if l == t == 1000000:
sc = 0
continue'''
dp.append([c, t, l])
mm = 1000000
kk = it.permutations(list(range(n)), 3)
for i in kk:
mm = min(mm, dp[i[0]][0] + dp[i[1]][1] + dp[i[2]][2])
print(mm)
``` | vfc_13554 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/761/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\n1**2\na3*0\nc4**\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 5\n#*&#*\n*a1c&\n&q2w*\n#a3c#\n*&#*&\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n&l\n*0\n*9\n*#\n#o\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "25 16\nvza**ooxkmd#*ywa\ndip#*#&ef&z&&&pv\nwggob&&72#*&&nku\nrsb##*&jm&#u**te\nzif#lu#t&2w#jbqb\nwfo&#&***0xp#&hp\njbw##h*###nkmkdn\nqrn*&y#3cnf&d*rc\nend*zg&0f*&g*&ak\niayh&r#8om#o**yq\nwym&e&*v0j&#zono\ntzu*vj&i18iew&ht\nhpfnceb193&#&acf\ngesvq&l&*&m*l*ru\nfot#u&pq&0y&s*pg\nqdfgs&hk*wob&&bw\nbqd&&&lnv&&ax&ql\nell#&t&k*p#n*rlg\nclfou#ap#*vxulmt\nfhp*gax&s1&pinql\nyihmh*yy&2&#&prc\nrmv**#h*bxyf&&eq\nziu##ku#f#uh*fek\nhmg&&cvx0p*#odgw\nquu&csv*aph#dkiq\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 5\n*****\n1***a\n**a**\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 2\n&e\n#j\n&&\n*2\n94\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 951 | Solve the following coding problem using the programming language python:
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.
You have to find the minimum number of digits in which these two numbers can differ.
-----Input-----
The first line contains integer k (1 ≤ k ≤ 10^9).
The second line contains integer n (1 ≤ n < 10^100000).
There are no leading zeros in n. It's guaranteed that this situation is possible.
-----Output-----
Print the minimum number of digits in which the initial number and n can differ.
-----Examples-----
Input
3
11
Output
1
Input
3
99
Output
0
-----Note-----
In the first example, the initial number could be 12.
In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
k = int(input())
n = input()
digit = [0]*10
for c in n:
digit[int(c)]+= 1
dsum = sum(i*digit[i] for i in range(10))
i = 0
change = 0
while dsum < k:
if digit[i] == 0:
i+= 1
continue
digit[i]-= 1
digit[9]+= 1
change+= 1
dsum+= 9-i
print(change)
``` | vfc_13558 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/835/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n11\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n99\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n5205602270\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "70\n3326631213\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "200\n1000000010000000000000000000010000000000000001000001000000000000000000000000000000000000000000000000\n",
"output": "22\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 952 | Solve the following coding problem using the programming language python:
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to insidious taxi drivers.
The mayor of the city decided to change the direction of certain roads so that the taxi drivers wouldn't be able to increase the cost of the trip endlessly. More formally, if the taxi driver is on a certain crossroads, they wouldn't be able to reach it again if he performs a nonzero trip.
Traffic controllers are needed in order to change the direction the road goes. For every road it is known how many traffic controllers are needed to change the direction of the road to the opposite one. It is allowed to change the directions of roads one by one, meaning that each traffic controller can participate in reversing two or more roads.
You need to calculate the minimum number of traffic controllers that you need to hire to perform the task and the list of the roads that need to be reversed.
-----Input-----
The first line contains two integers $n$ and $m$ ($2 \leq n \leq 100\,000$, $1 \leq m \leq 100\,000$) — the number of crossroads and the number of roads in the city, respectively.
Each of the following $m$ lines contain three integers $u_{i}$, $v_{i}$ and $c_{i}$ ($1 \leq u_{i}, v_{i} \leq n$, $1 \leq c_{i} \leq 10^9$, $u_{i} \ne v_{i}$) — the crossroads the road starts at, the crossroads the road ends at and the number of traffic controllers required to reverse this road.
-----Output-----
In the first line output two integers the minimal amount of traffic controllers required to complete the task and amount of roads $k$ which should be reversed. $k$ should not be minimized.
In the next line output $k$ integers separated by spaces — numbers of roads, the directions of which should be reversed. The roads are numerated from $1$ in the order they are written in the input. If there are many solutions, print any of them.
-----Examples-----
Input
5 6
2 1 1
5 2 6
2 3 2
3 4 3
4 5 5
1 5 4
Output
2 2
1 3
Input
5 7
2 1 5
3 2 3
1 3 3
2 4 1
4 3 5
5 4 1
1 5 3
Output
3 3
3 4 7
-----Note-----
There are two simple cycles in the first example: $1 \rightarrow 5 \rightarrow 2 \rightarrow 1$ and $2 \rightarrow 3 \rightarrow 4 \rightarrow 5 \rightarrow 2$. One traffic controller can only reverse the road $2 \rightarrow 1$ and he can't destroy the second cycle by himself. Two traffic controllers can reverse roads $2 \rightarrow 1$ and $2 \rightarrow 3$ which would satisfy the condition.
In the second example one traffic controller can't destroy the cycle $ 1 \rightarrow 3 \rightarrow 2 \rightarrow 1 $. With the help of three controllers we can, for example, reverse roads $1 \rightarrow 3$ ,$ 2 \rightarrow 4$, $1 \rightarrow 5$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# problem http://codeforces.com/contest/1100/problem/E
import copy
import sys
def find_loop(g, w, k, n):
visited = [False] * n
visited_int = [False] * n
for i in range(n):
if visited[i]:
continue
stack = [g[i][:]]
path = [i]
visited[i] = True
visited_int[i] = True
while stack:
if not stack[-1]:
stack.pop()
visited_int[path[-1]] = False
path.pop()
continue
nxt = stack[-1][-1]
stack[-1].pop()
if w[(path[-1], nxt)] <= k:
continue
if visited_int[nxt]:
return True
if visited[nxt]:
continue
visited[nxt] = True
visited_int[nxt] = True
stack.append(g[nxt][:])
path.append(nxt)
return False
def top_sort(g, w, k, n):
visited = [False] * n
order = [-1] * n
cnt = 0
for i in range(n):
if visited[i]:
continue
stack = [g[i][:]]
path = [i]
visited[i] = True
while stack:
if not stack[-1]:
order[path[-1]] = cnt
path.pop()
stack.pop()
cnt += 1
continue
nxt = stack[-1][-1]
stack[-1].pop()
if w[(path[-1], nxt)] <= k:
continue
if visited[nxt]:
continue
visited[nxt] = True
stack.append(g[nxt][:])
path.append(nxt)
to_reverse = []
for a, b in list(w.items()):
if b > k:
continue
if order[a[0]] < order[a[1]]:
to_reverse.append(a)
return to_reverse
def __starting_point():
n, m = list(map(int, input().split()))
w = {}
g = [[] for _ in range(n)]
w_tmp = {}
c_m = 0
kk = [0]
lines = sys.stdin.readlines()
for i, line in enumerate(lines): #range(1, m + 1):
u, v, c = list(map(int, line.split()))
g[u - 1].append(v - 1)
if (u - 1, v - 1) in list(w.keys()):
w[(u - 1, v - 1)] = max(w[(u - 1, v - 1)], c)
else:
w[(u - 1, v - 1)] = c
if (u - 1, v - 1) in list(w_tmp.keys()):
w_tmp[(u - 1, v - 1)].append(str(i + 1))
else:
w_tmp[(u - 1, v - 1)] = [str(i + 1)]
kk.append(c)
# c_m = max(c, c_m)
# print(find_loop(copy.deepcopy(g), copy.deepcopy(w), 0, n))
kk.sort()
l, r = 0, len(kk)
if not find_loop(g, w, kk[l], n):
print(0, 0)
return
if find_loop(g, w, kk[-1], n):
kkk = kk[-1]
else:
while l + 1 != r:
m = int((l + r) / 2)
# if find_loop(copy.deepcopy(g), copy.deepcopy(w), kk[m], n):
if find_loop(g, w, kk[m], n):
l = m
else:
r = m
kkk = kk[l+1]
to_reverse = top_sort(g, w, kkk, n)
num = 0
s = []
for t in to_reverse:
num += len(w_tmp[t])
s.extend(w_tmp[t])
print(kkk, num)
print(" ".join(s))
__starting_point()
``` | vfc_13562 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1100/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 6\n2 1 1\n5 2 6\n2 3 2\n3 4 3\n4 5 5\n1 5 4\n",
"output": "2 2\n1 3 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 7\n2 1 5\n3 2 3\n1 3 3\n2 4 1\n4 3 5\n5 4 1\n1 5 3\n",
"output": "3 3\n3 4 7 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 45\n5 6 8\n9 4 8\n7 1 1\n9 7 1\n7 2 1\n1 4 2\n5 7 7\n10 5 7\n7 8 8\n8 5 4\n4 7 3\n1 8 7\n3 1 9\n9 1 3\n10 2 7\n6 2 7\n2 5 7\n5 4 7\n6 7 6\n4 2 7\n6 8 10\n6 10 2\n3 6 3\n10 3 6\n4 3 6\n3 9 8\n5 1 4\n2 3 7\n3 8 1\n9 10 4\n9 8 7\n4 6 6\n2 8 1\n7 3 5\n9 5 4\n7 10 2\n4 8 8\n10 4 10\n10 8 5\n10 1 10\n5 3 9\n9 6 2\n6 1 5\n2 1 1\n2 9 5\n",
"output": "7 19\n4 6 7 10 11 12 17 19 22 23 25 28 30 32 33 35 36 42 45 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 45\n5 6 894\n9 4 197\n7 1 325\n9 7 232\n7 2 902\n1 4 183\n5 7 41\n10 5 481\n7 8 495\n8 5 266\n4 7 152\n1 8 704\n3 1 790\n9 1 458\n10 2 546\n6 2 258\n2 5 30\n5 4 366\n6 7 747\n4 2 546\n6 8 332\n6 10 816\n3 6 523\n10 3 683\n4 3 771\n3 9 152\n5 1 647\n2 3 967\n3 8 785\n9 10 793\n9 8 62\n4 6 915\n2 8 864\n7 3 667\n9 5 972\n7 10 536\n4 8 678\n10 4 183\n10 8 290\n10 1 164\n5 3 533\n9 6 374\n6 1 932\n2 1 943\n2 9 508\n",
"output": "523 8\n6 8 10 17 23 26 38 45 ",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 16\n1 4 8\n1 2 8\n10 4 1\n9 10 1\n10 8 1\n1 3 2\n7 1 7\n10 6 7\n1 6 8\n9 1 4\n10 3 3\n1 5 7\n10 2 9\n10 5 3\n10 7 7\n1 8 7\n",
"output": "0 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 16\n1 4 894\n1 2 197\n10 4 325\n9 10 232\n10 8 902\n1 3 183\n7 1 41\n10 6 481\n1 6 495\n9 1 266\n10 3 152\n1 5 704\n10 2 790\n10 5 458\n10 7 546\n1 8 258\n",
"output": "0 0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 954 | Solve the following coding problem using the programming language python:
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character of the word to the beginning of the word. He calls this a cyclic shift. He can apply cyclic shift many times. For example, consecutively applying cyclic shift operation to the word "abracadabra" Hongcow will get words "aabracadabr", "raabracadab" and so on.
Hongcow is now wondering how many distinct words he can generate by doing the cyclic shift arbitrarily many times. The initial string is also counted.
-----Input-----
The first line of input will be a single string s (1 ≤ |s| ≤ 50), the word Hongcow initially learns how to spell. The string s consists only of lowercase English letters ('a'–'z').
-----Output-----
Output a single integer equal to the number of distinct strings that Hongcow can obtain by applying the cyclic shift arbitrarily many times to the given string.
-----Examples-----
Input
abcd
Output
4
Input
bbb
Output
1
Input
yzyz
Output
2
-----Note-----
For the first sample, the strings Hongcow can generate are "abcd", "dabc", "cdab", and "bcda".
For the second sample, no matter how many times Hongcow does the cyclic shift, Hongcow can only generate "bbb".
For the third sample, the two strings Hongcow can generate are "yzyz" and "zyzy".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
s = input()
res = set()
for i in range(len(s) + 5):
s = s[1:] + s[0]
res.add(s)
print(len(list(res)))
``` | vfc_13570 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/745/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abcd\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "bbb\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "yzyz\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 955 | Solve the following coding problem using the programming language python:
Berland shop sells $n$ kinds of juices. Each juice has its price $c_i$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.
Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.
-----Input-----
The first line contains a single integer $n$ $(1 \le n \le 1\,000)$ — the number of juices.
Each of the next $n$ lines contains an integer $c_i$ $(1 \le c_i \le 100\,000)$ and a string $s_i$ — the price of the $i$-th juice and the vitamins it contains. String $s_i$ contains from $1$ to $3$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $s_i$. The order of letters in strings $s_i$ is arbitrary.
-----Output-----
Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.
-----Examples-----
Input
4
5 C
6 B
16 BAC
4 A
Output
15
Input
2
10 AB
15 BA
Output
-1
Input
5
10 A
9 BC
11 CA
4 A
5 B
Output
13
Input
6
100 A
355 BCA
150 BC
160 AC
180 B
190 CA
Output
250
Input
2
5 BA
11 CB
Output
16
-----Note-----
In the first example Petya buys the first, the second and the fourth juice. He spends $5 + 6 + 4 = 15$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $16$, which isn't optimal.
In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
def func(v):
res = 0
if "A" in v: res |= 1
if "B" in v: res |= 2
if "C" in v: res |= 4
return res
cost = [10 ** 10] * 8
cost[0] = 0
for _ in range(n):
c, v = input().split()
c = int(c)
v = func(v)
for i in range(8):
cost[i | v] = min(cost[i | v], cost[i] + c)
print(cost[7] if cost[7] < 10 ** 10 else -1)
``` | vfc_13574 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1042/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4\n5 C\n6 B\n16 BAC\n4 A\n",
"output": "15\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n10 AB\n15 BA\n",
"output": "-1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n10 A\n9 BC\n11 CA\n4 A\n5 B\n",
"output": "13\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "6\n100 A\n355 BCA\n150 BC\n160 AC\n180 B\n190 CA\n",
"output": "250\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n5 BA\n11 CB\n",
"output": "16\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 956 | Solve the following coding problem using the programming language python:
Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если a является другом b, то b также является другом a.
В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.
У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 10^9. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.
-----Входные данные-----
В первой строке следуют два целых числа m и k (1 ≤ m ≤ 100, 0 ≤ k ≤ 100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом.
В последующих m строках записано по два числа a_{i}, b_{i} (1 ≤ a_{i}, b_{i} ≤ 10^9, a_{i} ≠ b_{i}), обозначающих идентификаторы пользователей, являющихся друзьями.
Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.
-----Выходные данные-----
Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id: k id_1 id_2 ... id_{k}", где id — это id самого человека, k — количество его предполагаемых друзей, а id_1, id_2, ..., id_{k} — идентификаторы его предполагаемых друзей в возрастающем порядке.
-----Примеры-----
Входные данные
5 51
10 23
23 42
39 42
10 39
39 58
Выходные данные
10: 1 42
23: 1 39
39: 1 23
42: 1 10
58: 2 10 42
Входные данные
5 100
1 2
1 3
1 4
2 3
2 4
Выходные данные
1: 0
2: 0
3: 1 4
4: 1 3
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
m, k = [int(x) for x in input().split()]
seen = 0
users = set()
friendsof = {}
for i in range(m):
a, b = [int(x) for x in input().split()]
users.add(a)
users.add(b)
if a in friendsof:
friendsof[a].add(b)
else:
friendsof[a] = set((b,))
if b in friendsof:
friendsof[b].add(a)
else:
friendsof[b] = set((a,))
users_sorted = list(users)
users_sorted.sort()
for u in users_sorted:
possible = []
this_friends = friendsof[u]
for v in users_sorted:
if v in this_friends: continue
if v == u: continue
common = friendsof[v].intersection(this_friends)
if len(common) * 100 >= k * len(this_friends):
possible.append(v)
print('{}:'.format(u), len(possible), *possible)
``` | vfc_13578 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/524/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 51\n10 23\n23 42\n39 42\n10 39\n39 58\n",
"output": "10: 1 42\n23: 1 39\n39: 1 23\n42: 1 10\n58: 2 10 42\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 100\n1 2\n1 3\n1 4\n2 3\n2 4\n",
"output": "1: 0\n2: 0\n3: 1 4\n4: 1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n1 2\n1 3\n2 3\n4 5\n",
"output": "1: 0\n2: 0\n3: 0\n4: 0\n5: 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 100\n60976680 603454792\n575754027 696647370\n7534463 570826751\n117972518 472387015\n35713567 439985965\n439985965 928160845\n443596853 828504858\n689509731 117972518\n909843480 592765058\n251752353 490387136\n",
"output": "7534463: 0\n35713567: 1 928160845\n60976680: 0\n117972518: 0\n251752353: 0\n439985965: 0\n443596853: 0\n472387015: 1 689509731\n490387136: 0\n570826751: 0\n575754027: 0\n592765058: 0\n603454792: 0\n689509731: 1 472387015\n696647370: 0\n828504858: 0\n909843480: 0\n928160845: 1 35713567\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 50\n389900784 512305545\n839319681 243581524\n653226215 616982889\n448655722 826601897\n681021965 23289895\n719595063 481480420\n919744525 839319681\n231872856 784056465\n971842495 248017394\n653226215 297224467\n",
"output": "23289895: 0\n231872856: 0\n243581524: 1 919744525\n248017394: 0\n297224467: 1 616982889\n389900784: 0\n448655722: 0\n481480420: 0\n512305545: 0\n616982889: 1 297224467\n653226215: 0\n681021965: 0\n719595063: 0\n784056465: 0\n826601897: 0\n839319681: 0\n919744525: 1 243581524\n971842495: 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 50\n946010975 207263044\n923545573 749203275\n862015642 426425906\n749203275 839134958\n910721783 289091881\n827003531 333726912\n49704846 538788252\n382891592 207263044\n333726912 438209022\n974360048 49704846\n",
"output": "49704846: 0\n207263044: 0\n289091881: 0\n333726912: 0\n382891592: 1 946010975\n426425906: 0\n438209022: 1 827003531\n538788252: 1 974360048\n749203275: 0\n827003531: 1 438209022\n839134958: 1 923545573\n862015642: 0\n910721783: 0\n923545573: 1 839134958\n946010975: 1 382891592\n974360048: 1 538788252\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 957 | Solve the following coding problem using the programming language python:
As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...
-----Input-----
The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).
-----Output-----
Output YES if the string s contains heidi as a subsequence and NO otherwise.
-----Examples-----
Input
abcheaibcdi
Output
YES
Input
hiedi
Output
NO
-----Note-----
A string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
string = input()
now = 0
for i in range(len(string)):
if now == 0 and string[i] == "h":
now += 1
if now == 1 and string[i] == "e":
now += 1
if now == 2 and string[i] == "i":
now += 1
if now == 3 and string[i] == "d":
now += 1
if now == 4 and string[i] == "i":
now += 1
if now == 5:
print("YES")
else:
print("NO")
``` | vfc_13582 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/802/G",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abcheaibcdi\n",
"output": "YES",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "hiedi\n",
"output": "NO",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ihied\n",
"output": "NO",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 958 | Solve the following coding problem using the programming language python:
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.
The distance between two letters is defined as the difference between their positions in the alphabet. For example, $\operatorname{dist}(c, e) = \operatorname{dist}(e, c) = 2$, and $\operatorname{dist}(a, z) = \operatorname{dist}(z, a) = 25$.
Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, $\operatorname{dist}(a f, d b) = \operatorname{dist}(a, d) + \operatorname{dist}(f, b) = 3 + 4 = 7$, and $\text{dist(bear, roar)} = 16 + 10 + 0 + 0 = 26$.
Limak gives you a nice string s and an integer k. He challenges you to find any nice string s' that $\operatorname{dist}(s, s^{\prime}) = k$. Find any s' satisfying the given conditions, or print "-1" if it's impossible to do so.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
-----Input-----
The first line contains two integers n and k (1 ≤ n ≤ 10^5, 0 ≤ k ≤ 10^6).
The second line contains a string s of length n, consisting of lowercase English letters.
-----Output-----
If there is no string satisfying the given conditions then print "-1" (without the quotes).
Otherwise, print any nice string s' that $\operatorname{dist}(s, s^{\prime}) = k$.
-----Examples-----
Input
4 26
bear
Output
roar
Input
2 7
af
Output
db
Input
3 1000
hey
Output
-1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def check(s, k):
ans = 0
for i in range(len(s)):
ans += abs(ord(s[i]) - ord(k[i]))
return ans
n, k = list(map(int, input().split()))
s = input()
cnt = 0
for i in s:
cnt += max(ord('z') - ord(i), ord(i) - ord('a'))
if k > cnt:
print(-1)
return
else:
ans = ''
cr = 0
while k != 0:
ps1 = ord(s[cr]) - ord('a')
ps2 = ord('z') - ord(s[cr])
if ps1 > k:
ans += chr(ord(s[cr]) - k)
k = 0
elif ps2 > k:
ans += chr(ord(s[cr]) + k)
k = 0
else:
if ps2 >= ps1:
ans += 'z'
k -= ps2
else:
ans += 'a'
k -= ps1
cr += 1
ans += s[len(ans):]
print(ans)
#print(check(ans, s))
``` | vfc_13586 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/628/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 26\nbear\n",
"output": "zcar\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 959 | Solve the following coding problem using the programming language python:
An n × n square matrix is special, if: it is binary, that is, each cell contains either a 0, or a 1; the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones.
As the required value can be rather large, print the remainder after dividing the value by the given number mod.
-----Input-----
The first line of the input contains three integers n, m, mod (2 ≤ n ≤ 500, 0 ≤ m ≤ n, 2 ≤ mod ≤ 10^9). Then m lines follow, each of them contains n characters — the first rows of the required special matrices. Each of these lines contains exactly two characters '1', the rest characters are '0'. Each column of the given m × n table contains at most two numbers one.
-----Output-----
Print the remainder after dividing the required value by number mod.
-----Examples-----
Input
3 1 1000
011
Output
2
Input
4 4 100500
0110
1010
0101
1001
Output
1
-----Note-----
For the first test the required matrices are:
011
101
110
011
110
101
In the second test the required matrix is already fully given, so the answer is 1.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a,b,mod = list(map(int, input().split()))
g = [2] * a
for i in range(b):
t = input()
for x, y in enumerate(t):
if y == '1':
g[x] -= 1
one = two = 0
for q in g:
if q < 0:
print(0)
return
if q == 1:
one+=1
if q == 2:
two+=1
mat = [[0]*600 for x in range(600)]
mat[0][0] = 1
#int(one, two)
for j in range(a + 1):
for i in range(a + 1):
if i-2>=0:
mat[i][j] += i*(i-1) // 2 * mat[i-2][j];
#print('in',i,j, mat[i][j], i*(i-1)//2, mat[i-2][j], i-2, mat[0][0])
if j-1>=0:
mat[i][j] += i*j * mat[i][j -1];
if j-2>=0 :
mat[i][j] += j *(j-1)//2 * mat[i+2][j -2];
mat[i][j] %= mod
#print(mat[2][0])
#print(mat[0][2])
print(mat[one][two])
``` | vfc_13590 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/489/F",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 1 1000\n011\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 4 100500\n0110\n1010\n0101\n1001\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 0 1000\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 960 | Solve the following coding problem using the programming language python:
Vasya likes to solve equations. Today he wants to solve $(x~\mathrm{div}~k) \cdot (x \bmod k) = n$, where $\mathrm{div}$ and $\mathrm{mod}$ stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, $k$ and $n$ are positive integer parameters, and $x$ is a positive integer unknown. If there are several solutions, Vasya wants to find the smallest possible $x$. Can you help him?
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \leq n \leq 10^6$, $2 \leq k \leq 1000$).
-----Output-----
Print a single integer $x$ — the smallest positive integer solution to $(x~\mathrm{div}~k) \cdot (x \bmod k) = n$. It is guaranteed that this equation has at least one positive integer solution.
-----Examples-----
Input
6 3
Output
11
Input
1 2
Output
3
Input
4 6
Output
10
-----Note-----
The result of integer division $a~\mathrm{div}~b$ is equal to the largest integer $c$ such that $b \cdot c \leq a$. $a$ modulo $b$ (shortened $a \bmod b$) is the only integer $c$ such that $0 \leq c < b$, and $a - c$ is divisible by $b$.
In the first sample, $11~\mathrm{div}~3 = 3$ and $11 \bmod 3 = 2$. Since $3 \cdot 2 = 6$, then $x = 11$ is a solution to $(x~\mathrm{div}~3) \cdot (x \bmod 3) = 6$. One can see that $19$ is the only other positive integer solution, hence $11$ is the smallest one.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = list(map(int, input().split()))
result = 10 ** 26
for i in range(1, k):
if n % i == 0:
t = n // i
result = min(result, t * k + i)
print(result)
``` | vfc_13594 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1085/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6 3\n",
"output": "11\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 6\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000000 1000\n",
"output": "1250800\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 961 | Solve the following coding problem using the programming language python:
Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:
Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code a_{i} is known (the code of the city in which they are going to).
Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.
Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.
Total comfort of a train trip is equal to sum of comfort for each segment.
Help Vladik to know maximal possible total comfort.
-----Input-----
First line contains single integer n (1 ≤ n ≤ 5000) — number of people.
Second line contains n space-separated integers a_1, a_2, ..., a_{n} (0 ≤ a_{i} ≤ 5000), where a_{i} denotes code of the city to which i-th person is going.
-----Output-----
The output should contain a single integer — maximal possible total comfort.
-----Examples-----
Input
6
4 4 2 5 2 3
Output
14
Input
9
5 1 3 1 5 2 4 2 5
Output
9
-----Note-----
In the first test case best partition into segments is: [4, 4] [2, 5, 2] [3], answer is calculated as follows: 4 + (2 xor 5) + 3 = 4 + 7 + 3 = 14
In the second test case best partition into segments is: 5 1 [3] 1 5 [2, 4, 2] 5, answer calculated as follows: 3 + (2 xor 4) = 3 + 6 = 9.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def dp():
dparr = [0] * len(sections)
for i in range(len(sections) - 1, -1, -1):
_, curend, curcomfort = sections[i]
nextsection = i + 1
try:
while sections[nextsection][0] <= curend:
nextsection += 1
except IndexError:
# Loop til end
inc = curcomfort
else:
inc = curcomfort + dparr[nextsection]
exc = 0 if i == len(sections) - 1 else dparr[i + 1]
dparr[i] = max(inc, exc)
return dparr[0]
n = int(input())
zs = list(map(int, input().split()))
sections = []
seenstartz = set()
first = {z: i for i, z in reversed(list(enumerate(zs)))}
last = {z: i for i, z in enumerate(zs)}
for start, z in enumerate(zs):
if z in seenstartz:
continue
seenstartz.add(z)
end = last[z]
comfort = 0
i = start
while i <= end:
if first[zs[i]] < start:
break
if i == last[zs[i]]:
comfort ^= zs[i]
end = max(end, last[zs[i]])
i += 1
else:
sections.append((start, end, comfort))
ans = dp()
print(ans)
``` | vfc_13598 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/811/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n4 4 2 5 2 3\n",
"output": "14\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "9\n5 1 3 1 5 2 4 2 5\n",
"output": "9\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1558 4081 3591 1700 3232\n",
"output": "14162\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n3838 1368 4825 2068 4755 2048 1342 4909 2837 4854\n",
"output": "32844\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n4764 4867 2346 1449 1063 2002 2577 2089 1566 614\n",
"output": "23337\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 965 | Solve the following coding problem using the programming language python:
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".
Find the number of cows that can currently show their hands without affecting any betting decisions.
-----Input-----
The first line contains a single integer, n (2 ≤ n ≤ 2·10^5). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".
-----Output-----
The first line should contain a single integer denoting the number of players that can currently show their hands.
-----Examples-----
Input
6
AFFAAA
Output
4
Input
3
AFI
Output
1
-----Note-----
In the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n=int(input())
a=input()
cnt=0
A=0
for i in range(0,n):
if(a[i]=='I'): cnt+=1
if(a[i]=='A'): A+=1
if(cnt==0):
print(A)
elif(cnt==1):
print(1)
else :print(0)
``` | vfc_13614 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/284/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\nAFFAAA\n",
"output": "4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\nAFI\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 966 | Solve the following coding problem using the programming language python:
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has only distinct digits.
-----Input-----
The single line contains integer y (1000 ≤ y ≤ 9000) — the year number.
-----Output-----
Print a single integer — the minimum year number that is strictly larger than y and all it's digits are distinct. It is guaranteed that the answer exists.
-----Examples-----
Input
1987
Output
2013
Input
2013
Output
2014
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def find(ins):
ins += 1
test = [int(i) for i in str(ins)]
inlist = []
for i in test:
if i in inlist:
test = find(ins)
break
else:
inlist.append(i)
return ''.join(str(x) for x in test)
ins = int(input())
print(find(ins))
``` | vfc_13618 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/271/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1987\n",
"output": "2013\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2013\n",
"output": "2014\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1000\n",
"output": "1023\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1001\n",
"output": "1023\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 967 | Solve the following coding problem using the programming language python:
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages.
Recent actions shows a list of n different threads ordered by the time of the latest message in the thread. When a new message is posted in a thread that thread jumps on the top of the list. No two messages of different threads are ever posted at the same time.
Emuskald has just finished reading all his opened threads and refreshes the main page for some more messages to feed his addiction. He notices that no new threads have appeared in the list and at the i-th place in the list there is a thread that was at the a_{i}-th place before the refresh. He doesn't want to waste any time reading old messages so he wants to open only threads with new messages.
Help Emuskald find out the number of threads that surely have new messages. A thread x surely has a new message if there is no such sequence of thread updates (posting messages) that both conditions hold: thread x is not updated (it has no new messages); the list order 1, 2, ..., n changes to a_1, a_2, ..., a_{n}.
-----Input-----
The first line of input contains an integer n, the number of threads (1 ≤ n ≤ 10^5). The next line contains a list of n space-separated integers a_1, a_2, ..., a_{n} where a_{i} (1 ≤ a_{i} ≤ n) is the old position of the i-th thread in the new list. It is guaranteed that all of the a_{i} are distinct.
-----Output-----
Output a single integer — the number of threads that surely contain a new message.
-----Examples-----
Input
5
5 2 1 3 4
Output
2
Input
3
1 2 3
Output
0
Input
4
4 3 2 1
Output
3
-----Note-----
In the first test case, threads 2 and 5 are placed before the thread 1, so these threads must contain new messages. Threads 1, 3 and 4 may contain no new messages, if only threads 2 and 5 have new messages.
In the second test case, there may be no new messages at all, since the thread order hasn't changed.
In the third test case, only thread 1 can contain no new messages.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, ar = int(input()), [int(x) for x in input().split()][::-1]
ans = 0
for i in range(1, n):
if ar[i] > ar[i - 1]:
ans = n - i
break
print(ans)
``` | vfc_13622 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/270/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n5 2 1 3 4\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n1 2 3\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\n4 3 2 1\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n1 2 5 3 4\n",
"output": "3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 969 | Solve the following coding problem using the programming language python:
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.
First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.
Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.
-----Input-----
First line of the input contains the string s — the coating that is present in the shop. Second line contains the string t — the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.
-----Output-----
The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating.
If the answer is not -1, then the following n lines should contain two integers x_{i} and y_{i} — numbers of ending blocks in the corresponding piece. If x_{i} ≤ y_{i} then this piece is used in the regular order, and if x_{i} > y_{i} piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.
-----Examples-----
Input
abc
cbaabc
Output
2
3 1
1 3
Input
aaabrytaaa
ayrat
Output
3
1 1
6 5
8 7
Input
ami
no
Output
-1
-----Note-----
In the first sample string "cbaabc" = "cba" + "abc".
In the second sample: "ayrat" = "a" + "yr" + "at".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def solve(s,t):
hash_s = [False] * 256
hash_t = [False] * 256
arr = []
n = len(s)
for c in s:
hash_s[ord(c)] = True
for c in t:
hash_t[ord(c)] = True
for i in range(256):
if not hash_s[i] and hash_t[i]:
print(-1)
return
rev = s[::-1]
i,j = 0,0
while i < len(t):
flag = True
temp = t[i]
j = i + 1
while j < len(t):
temp += t[j]
if temp not in s and temp not in rev:
flag = False
break
j += 1
if flag:
x = s.find(temp)
if x != -1:
arr.append((x + 1,x + len(temp)))
# print('1',x + 1,x + len(temp))
else:
y = rev.find(temp)
arr.append((n - y,n - y - len(temp) + 1))
# print('2',n - y,n - y - len(temp) + 1)
else:
x = s.find(temp[:-1])
if x != -1:
arr.append((x + 1,x + len(temp) - 1))
# print('3',x + 1,x + len(temp) - 1)
else:
x = rev.find(temp[:-1])
arr.append((n - x,n - x - len(temp) + 2))
# print('4',n - x,n - x - len(temp) + 2)
i = j
print(len(arr))
for x,y in arr:
print(x,y)
s = input()
t = input()
solve(s,t)
``` | vfc_13630 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/615/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "abc\ncbaabc\n",
"output": "2\n3 1\n1 3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "aaabrytaaa\nayrat\n",
"output": "3\n1 1\n6 5\n8 7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "ami\nno\n",
"output": "-1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 970 | Solve the following coding problem using the programming language python:
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to $\frac{n}{2}$.
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
-----Input-----
The first line of the input contains one integer n (2 ≤ n ≤ 100, n is even) — the size of the chessboard.
The second line of the input contains $\frac{n}{2}$ integer numbers $p_{1}, p_{2}, \ldots, p_{\frac{n}{2}}$ (1 ≤ p_{i} ≤ n) — initial positions of the pieces. It is guaranteed that all the positions are distinct.
-----Output-----
Print one integer — the minimum number of moves you have to make to place all the pieces in the cells of the same color.
-----Examples-----
Input
6
1 2 6
Output
2
Input
10
1 2 3 4 5
Output
10
-----Note-----
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move $5 \rightarrow 9$ in 4 moves, then $4 \rightarrow 7$ in 3 moves, $3 \rightarrow 5$ in 2 moves and $2 \rightarrow 3$ in 1 move.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def ii():
return int(input())
def mi():
return map(int, input().split())
def li():
return list(mi())
n = ii()
a = li()
a.sort()
c1 = 0
p = 1
for ai in a:
c1 += abs(ai - p)
p += 2
c2 = 0
p = 2
for ai in a:
c2 += abs(ai - p)
p += 2
ans = min(c1, c2)
print(ans)
``` | vfc_13634 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/985/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "6\n1 2 6\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n1 2 3 4 5\n",
"output": "10\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n2\n",
"output": "0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 971 | Solve the following coding problem using the programming language python:
Kolya is going to make fresh orange juice. He has n oranges of sizes a_1, a_2, ..., a_{n}. Kolya will put them in the juicer in the fixed order, starting with orange of size a_1, then orange of size a_2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.
The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?
-----Input-----
The first line of the input contains three integers n, b and d (1 ≤ n ≤ 100 000, 1 ≤ b ≤ d ≤ 1 000 000) — the number of oranges, the maximum size of the orange that fits in the juicer and the value d, which determines the condition when the waste section should be emptied.
The second line contains n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 1 000 000) — sizes of the oranges listed in the order Kolya is going to try to put them in the juicer.
-----Output-----
Print one integer — the number of times Kolya will have to empty the waste section.
-----Examples-----
Input
2 7 10
5 6
Output
1
Input
1 5 10
7
Output
0
Input
3 10 10
5 7 7
Output
1
Input
1 1 1
1
Output
0
-----Note-----
In the first sample, Kolya will squeeze the juice from two oranges and empty the waste section afterwards.
In the second sample, the orange won't fit in the juicer so Kolya will have no juice at all.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
# You lost the game.
n,b,d = list(map(int, input().split()))
L = list(map(int, input().split()))
r = 0
c = 0
for i in range(n):
if L[i] <= b:
c += L[i]
if c > d:
r += 1
c = 0
print(r)
``` | vfc_13638 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/709/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 7 10\n5 6\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 5 10\n7\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 10 10\n5 7 7\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1 1\n1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 951637 951638\n44069 951637\n",
"output": "1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 972 | Solve the following coding problem using the programming language python:
Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path. [Image]
You're given a painted grid in the input. Tell Lenny if the grid is convex or not.
-----Input-----
The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid.
It's guaranteed that the grid has at least one black cell.
-----Output-----
On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.
-----Examples-----
Input
3 4
WWBW
BWWW
WWWB
Output
NO
Input
3 1
B
B
W
Output
YES
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def f():
n, m = map(int, input().split())
t = [input() for j in range(n)]
p = [''.join(i) for i in zip(*t)]
if h(p): return 1
i = 0
while i < n and not 'B' in t[i]: i += 1
while i < n:
a = t[i].find('B')
if a < 0:
i += 1
break
b = t[i].rfind('B')
if 'W' in t[i][a: b + 1]: return 1
for j in range(i + 1, n):
if a > 0 and t[j][a - 1] == 'B' and t[j][b] == 'W': return 1
if b < m - 1 and t[j][b + 1] == 'B' and t[j][a] == 'W': return 1
i += 1
while i < n:
if 'B' in t[i]: return 1
i += 1
return 0
def h(t):
i, n = 0, len(t)
while i < n and not 'B' in t[i]: i += 1
while i < n:
a = t[i].find('B')
if a < 0:
i += 1
break
b = t[i].rfind('B')
if 'W' in t[i][a: b + 1]: return 1
i += 1
while i < n:
if 'B' in t[i]: return 1
i += 1
return 0
print('YNEOS'[f():: 2])
``` | vfc_13642 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/275/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\nWWBW\nBWWW\nWWWB\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 1\nB\nB\nW\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\nB\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 2\nBB\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 974 | Solve the following coding problem using the programming language python:
Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.
Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.
That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.
Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.
-----Input-----
The first line of input contains the integer n (1 ≤ n ≤ 3·10^5) — the number of boxes.
Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 ≤ x ≤ n) follows, indicating that Daru should add the box with number x to the top of the stack.
It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.
-----Output-----
Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.
-----Examples-----
Input
3
add 1
remove
add 2
add 3
remove
remove
Output
1
Input
7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove
Output
2
-----Note-----
In the first sample, Daru should reorder the boxes after adding box 3 to the stack.
In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
def main():
n = int(input())
n = n*2
u = 0
res = 0
x = []
for i in range(n):
s = sys.stdin.readline()
if s[0] == 'r':
u+=1
if len(x)==0:
continue
if x[-1] == u:
x.pop()
else:
x = []
res +=1
else:
a,b = s.split()
x.append(int(b))
print(res)
main()
``` | vfc_13650 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/821/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\nadd 1\nremove\nadd 2\nadd 3\nremove\nremove\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "7\nadd 3\nadd 2\nadd 1\nremove\nadd 4\nremove\nremove\nremove\nadd 6\nadd 7\nadd 5\nremove\nremove\nremove\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4\nadd 1\nadd 3\nremove\nadd 4\nadd 2\nremove\nremove\nremove\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 975 | Solve the following coding problem using the programming language python:
After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their cards one by one. If two digits are not equal, then the player, whose digit is smaller gets a flick (knock in the forehead usually made with a forefinger) from the other player. For example, if n = 3, Sherlock's card is 123 and Moriarty's card has number 321, first Sherlock names 1 and Moriarty names 3 so Sherlock gets a flick. Then they both digit 2 so no one gets a flick. Finally, Sherlock names 3, while Moriarty names 1 and gets a flick.
Of course, Sherlock will play honestly naming digits one by one in the order they are given, while Moriary, as a true villain, plans to cheat. He is going to name his digits in some other order (however, he is not going to change the overall number of occurences of each digit). For example, in case above Moriarty could name 1, 2, 3 and get no flicks at all, or he can name 2, 3 and 1 to give Sherlock two flicks.
Your goal is to find out the minimum possible number of flicks Moriarty will get (no one likes flicks) and the maximum possible number of flicks Sherlock can get from Moriarty. Note, that these two goals are different and the optimal result may be obtained by using different strategies.
-----Input-----
The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of digits in the cards Sherlock and Moriarty are going to use.
The second line contains n digits — Sherlock's credit card number.
The third line contains n digits — Moriarty's credit card number.
-----Output-----
First print the minimum possible number of flicks Moriarty will get. Then print the maximum possible number of flicks that Sherlock can get from Moriarty.
-----Examples-----
Input
3
123
321
Output
0
2
Input
2
88
00
Output
2
0
-----Note-----
First sample is elaborated in the problem statement. In the second sample, there is no way Moriarty can avoid getting two flicks.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n = int(input())
a = list(input())
b = list(input())
a = [int(i) for i in a]
b = [int(i) for i in b]
a.sort()
b.sort()
c = a[::]
d = b[::]
ans1 = 0
ans2 = 0
for i in a:
for j in range(len(b)):
if b[j] > i:
del b[j]
ans2 += 1
break
for i in c:
for j in range(len(d)):
if d[j] >= i:
del d[j]
break
else:
ans1 += 1
print(ans1)
print(ans2)
``` | vfc_13654 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/777/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n123\n321\n",
"output": "0\n2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n88\n00\n",
"output": "2\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n4\n5\n",
"output": "0\n1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n8\n7\n",
"output": "1\n0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2\n55\n55\n",
"output": "0\n0\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 976 | Solve the following coding problem using the programming language python:
You have decided to watch the best moments of some movie. There are two buttons on your player: Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie. Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t + x).
Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the l_{i}-th minute and ends at the r_{i}-th minute (more formally, the i-th best moment consists of minutes: l_{i}, l_{i} + 1, ..., r_{i}).
Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?
-----Input-----
The first line contains two space-separated integers n, x (1 ≤ n ≤ 50, 1 ≤ x ≤ 10^5) — the number of the best moments of the movie and the value of x for the second button.
The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space l_{i}, r_{i} (1 ≤ l_{i} ≤ r_{i} ≤ 10^5).
It is guaranteed that for all integers i from 2 to n the following condition holds: r_{i} - 1 < l_{i}.
-----Output-----
Output a single number — the answer to the problem.
-----Examples-----
Input
2 3
5 6
10 12
Output
6
Input
1 1
1 100000
Output
100000
-----Note-----
In the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.
In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, x = list(map(int, input().split()))
result = 0
cur = 1
for i in range(n):
l, r = list(map(int, input().split()))
result += r - l + 1
result += (l - cur) % x
cur = r + 1
print(result)
``` | vfc_13658 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/499/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 3\n5 6\n10 12\n",
"output": "6\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1 1\n1 100000\n",
"output": "100000\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 1\n2156 3497\n4784 7775\n14575 31932\n33447 35902\n36426 47202\n48772 60522\n63982 68417\n78537 79445\n90081 90629\n94325 95728\n",
"output": "53974\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 3\n2156 3497\n4784 7775\n14575 31932\n33447 35902\n36426 47202\n48772 60522\n63982 68417\n78537 79445\n90081 90629\n94325 95728\n",
"output": "53983\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10 10\n2156 3497\n4784 7775\n14575 31932\n33447 35902\n36426 47202\n48772 60522\n63982 68417\n78537 79445\n90081 90629\n94325 95728\n",
"output": "54038\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 977 | Solve the following coding problem using the programming language python:
This is the easy version of the problem. The difference between versions is the constraints on $n$ and $a_i$. You can make hacks only if all versions of the problem are solved.
First, Aoi came up with the following idea for the competitive programming problem:
Yuzu is a girl who collecting candies. Originally, she has $x$ candies. There are also $n$ enemies numbered with integers from $1$ to $n$. Enemy $i$ has $a_i$ candies.
Yuzu is going to determine a permutation $P$. A permutation is an array consisting of $n$ distinct integers from $1$ to $n$ in arbitrary order. For example, $\{2,3,1,5,4\}$ is a permutation, but $\{1,2,2\}$ is not a permutation ($2$ appears twice in the array) and $\{1,3,4\}$ is also not a permutation (because $n=3$ but there is the number $4$ in the array).
After that, she will do $n$ duels with the enemies with the following rules: If Yuzu has equal or more number of candies than enemy $P_i$, she wins the duel and gets $1$ candy. Otherwise, she loses the duel and gets nothing. The candy which Yuzu gets will be used in the next duels.
Yuzu wants to win all duels. How many valid permutations $P$ exist?
This problem was easy and wasn't interesting for Akari, who is a friend of Aoi. And Akari made the following problem from the above idea:
Let's define $f(x)$ as the number of valid permutations for the integer $x$.
You are given $n$, $a$ and a prime number $p \le n$. Let's call a positive integer $x$ good, if the value $f(x)$ is not divisible by $p$. Find all good integers $x$.
Your task is to solve this problem made by Akari.
-----Input-----
The first line contains two integers $n$, $p$ $(2 \le p \le n \le 2000)$. It is guaranteed, that the number $p$ is prime (it has exactly two divisors $1$ and $p$).
The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ $(1 \le a_i \le 2000)$.
-----Output-----
In the first line, print the number of good integers $x$.
In the second line, output all good integers $x$ in the ascending order.
It is guaranteed that the number of good integers $x$ does not exceed $10^5$.
-----Examples-----
Input
3 2
3 4 5
Output
1
3
Input
4 3
2 3 5 6
Output
2
3 4
Input
4 3
9 1 1 1
Output
0
-----Note-----
In the first test, $p=2$. If $x \le 2$, there are no valid permutations for Yuzu. So $f(x)=0$ for all $x \le 2$. The number $0$ is divisible by $2$, so all integers $x \leq 2$ are not good. If $x = 3$, $\{1,2,3\}$ is the only valid permutation for Yuzu. So $f(3)=1$, so the number $3$ is good. If $x = 4$, $\{1,2,3\} , \{1,3,2\} , \{2,1,3\} , \{2,3,1\}$ are all valid permutations for Yuzu. So $f(4)=4$, so the number $4$ is not good. If $x \ge 5$, all $6$ permutations are valid for Yuzu. So $f(x)=6$ for all $x \ge 5$, so all integers $x \ge 5$ are not good.
So, the only good number is $3$.
In the third test, for all positive integers $x$ the value $f(x)$ is divisible by $p = 3$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
from bisect import bisect_right as br
input = sys.stdin.readline
n, p = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
table = [0] * (10 ** 5 + 1)
for x in range(10 ** 5 + 1):
r = br(a, x)
table[x] = r
res = []
#print(table[: 100])
for x in range(1, 2001):
t = 1
q = x + 0
for i in range(n):
t *= max(0, table[q] - i)
t %= p
q += 1
if t % p: res.append(x)
print(len(res))
print(*res)
``` | vfc_13662 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1371/E1",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 2\n3 4 5\n",
"output": "1\n3\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n2 3 5 6\n",
"output": "2\n3 4\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 3\n9 1 1 1\n",
"output": "0\n\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "2 2\n654 1162\n",
"output": "1\n1161\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 978 | Solve the following coding problem using the programming language python:
Cucumber boy is fan of Kyubeat, a famous music game.
Kyubeat has 16 panels for playing arranged in 4 × 4 table. When a panel lights up, he has to press that panel.
Each panel has a timing to press (the preffered time when a player should press it), and Cucumber boy is able to press at most k panels in a time with his one hand. Cucumber boy is trying to press all panels in perfect timing, that is he wants to press each panel exactly in its preffered time. If he cannot press the panels with his two hands in perfect timing, his challenge to press all the panels in perfect timing will fail.
You are given one scene of Kyubeat's panel from the music Cucumber boy is trying. Tell him is he able to press all the panels in perfect timing.
-----Input-----
The first line contains a single integer k (1 ≤ k ≤ 5) — the number of panels Cucumber boy can press with his one hand.
Next 4 lines contain 4 characters each (digits from 1 to 9, or period) — table of panels. If a digit i was written on the panel, it means the boy has to press that panel in time i. If period was written on the panel, he doesn't have to press that panel.
-----Output-----
Output "YES" (without quotes), if he is able to press all the panels in perfect timing. If not, output "NO" (without quotes).
-----Examples-----
Input
1
.135
1247
3468
5789
Output
YES
Input
5
..1.
1111
..1.
..1.
Output
YES
Input
1
....
12.1
.2..
.2..
Output
NO
-----Note-----
In the third sample boy cannot press all panels in perfect timing. He can press all the panels in timing in time 1, but he cannot press the panels in time 2 in timing with his two hands.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
k=int(input())
L={}
s=".123456789"
for item in s:
L[item]=0
for i in range(4):
s=input()
for item in s:
L[item]+=1
s="123456789"
done=True
for item in s:
if(L[item]>2*k):
print("NO")
done=False
break
if(done):
print("YES")
``` | vfc_13666 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/373/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "1\n.135\n1247\n3468\n5789\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n..1.\n1111\n..1.\n..1.\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n....\n12.1\n.2..\n.2..\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n....\n....\n....\n....\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n6981\n.527\n4163\n2345\n",
"output": "YES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n9999\n9999\n9999\n9999\n",
"output": "NO\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 979 | Solve the following coding problem using the programming language python:
To become the king of Codeforces, Kuroni has to solve the following problem.
He is given $n$ numbers $a_1, a_2, \dots, a_n$. Help Kuroni to calculate $\prod_{1\le i<j\le n} |a_i - a_j|$. As result can be very big, output it modulo $m$.
If you are not familiar with short notation, $\prod_{1\le i<j\le n} |a_i - a_j|$ is equal to $|a_1 - a_2|\cdot|a_1 - a_3|\cdot$ $\dots$ $\cdot|a_1 - a_n|\cdot|a_2 - a_3|\cdot|a_2 - a_4|\cdot$ $\dots$ $\cdot|a_2 - a_n| \cdot$ $\dots$ $\cdot |a_{n-1} - a_n|$. In other words, this is the product of $|a_i - a_j|$ for all $1\le i < j \le n$.
-----Input-----
The first line contains two integers $n$, $m$ ($2\le n \le 2\cdot 10^5$, $1\le m \le 1000$) — number of numbers and modulo.
The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$).
-----Output-----
Output the single number — $\prod_{1\le i<j\le n} |a_i - a_j| \bmod m$.
-----Examples-----
Input
2 10
8 5
Output
3
Input
3 12
1 4 5
Output
0
Input
3 7
1 4 9
Output
1
-----Note-----
In the first sample, $|8 - 5| = 3 \equiv 3 \bmod 10$.
In the second sample, $|1 - 4|\cdot|1 - 5|\cdot|4 - 5| = 3\cdot 4 \cdot 1 = 12 \equiv 0 \bmod 12$.
In the third sample, $|1 - 4|\cdot|1 - 9|\cdot|4 - 9| = 3 \cdot 8 \cdot 5 = 120 \equiv 1 \bmod 7$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from sys import stdin
input = stdin.readline
n,m = map(int,input().split())
l = list(map(int,input().split()))
if n > m:
print(0)
else:
res = 1
for i in range(n-1):
for j in range(i+1,n):
res = ((res*abs(l[i]-l[j])) % m)
print(res%m)
``` | vfc_13670 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1305/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 10\n8 5\n",
"output": "3",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 12\n1 4 5\n",
"output": "0",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 980 | Solve the following coding problem using the programming language python:
We had a string s consisting of n lowercase Latin letters. We made k copies of this string, thus obtaining k identical strings s_1, s_2, ..., s_{k}. After that, in each of these strings we swapped exactly two characters (the characters we swapped could be identical, but they had different indices in the string).
You are given k strings s_1, s_2, ..., s_{k}, and you have to restore any string s so that it is possible to obtain these strings by performing aforementioned operations. Note that the total length of the strings you are given doesn't exceed 5000 (that is, k·n ≤ 5000).
-----Input-----
The first line contains two integers k and n (1 ≤ k ≤ 2500, 2 ≤ n ≤ 5000, k · n ≤ 5000) — the number of strings we obtained, and the length of each of these strings.
Next k lines contain the strings s_1, s_2, ..., s_{k}, each consisting of exactly n lowercase Latin letters.
-----Output-----
Print any suitable string s, or -1 if such string doesn't exist.
-----Examples-----
Input
3 4
abac
caab
acba
Output
acab
Input
3 4
kbbu
kbub
ubkb
Output
kbub
Input
5 4
abcd
dcba
acbd
dbca
zzzz
Output
-1
-----Note-----
In the first example s_1 is obtained by swapping the second and the fourth character in acab, s_2 is obtained by swapping the first and the second character, and to get s_3, we swap the third and the fourth character.
In the second example s_1 is obtained by swapping the third and the fourth character in kbub, s_2 — by swapping the second and the fourth, and s_3 — by swapping the first and the third.
In the third example it's impossible to obtain given strings by aforementioned operations.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
read=lambda:list(map(int,input().split()))
from collections import Counter as co
k,n=read()
s=input()
repeated=(len(s)!=len(set(s)))
etalon=co(s)
a=[]
kk=[]
ap=a.append
for i in range(k-1):
ap(input())
if co(a[-1])!=etalon:
print(-1)
return
ss=False
for i in a:
if i!=s:
ss=i
for j in range(len(s)):
if s[j]!=ss[j]:
kk.append(j)
break
if len(kk)>4:
print(-1)
return
if ss:
if repeated:
for i in a:
k = 0
for j in range(len(i)):
if s[j] != i[j]: k += 1
if k != 0 and k != 2: break
else:
print(s)
return
if len(kk)!=2:
for i in range(len(kk)):
for j in range(i):
stry=s[:kk[j]]+s[kk[i]]+s[kk[j]+1:kk[i]]+s[kk[j]]+s[kk[i]+1:]
#print(stry)
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
#print(stry,i,k)
if not(k==0 and repeated) and k != 2: break
else:
print(stry)
return
if len(kk)==2:
for change in kk:
for i in range(len(s)):
if change==i:
continue
if i >change:
stry = s[:change] + s[i] + s[change + 1:i] + s[change] + s[i + 1:]
else:
stry = s[:i] + s[change] + s[i + 1:change] + s[i] + s[change + 1:]
for u in a:
k = 0
for j in range(len(u)):
if stry[j] != u[j]: k += 1
#print(stry,i,k)
if not(k==0 and repeated) and k != 2: break
else:
print(stry)
return
print(-1)
else:
if repeated:
print(s)
return
print(s[1]+s[0]+s[2:])
``` | vfc_13674 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/903/E",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3 4\nabac\ncaab\nacba\n",
"output": "acab\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 4\nkbbu\nkbub\nubkb\n",
"output": "kbub\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 982 | Solve the following coding problem using the programming language python:
You got a job as a marketer in a pet shop, and your current task is to boost sales of cat food. One of the strategies is to sell cans of food in packs with discounts.
Suppose you decided to sell packs with $a$ cans in a pack with a discount and some customer wants to buy $x$ cans of cat food. Then he follows a greedy strategy: he buys $\left\lfloor \frac{x}{a} \right\rfloor$ packs with a discount; then he wants to buy the remaining $(x \bmod a)$ cans one by one.
$\left\lfloor \frac{x}{a} \right\rfloor$ is $x$ divided by $a$ rounded down, $x \bmod a$ is the remainer of $x$ divided by $a$.
But customers are greedy in general, so if the customer wants to buy $(x \bmod a)$ cans one by one and it happens that $(x \bmod a) \ge \frac{a}{2}$ he decides to buy the whole pack of $a$ cans (instead of buying $(x \bmod a)$ cans). It makes you, as a marketer, happy since the customer bought more than he wanted initially.
You know that each of the customers that come to your shop can buy any number of cans from $l$ to $r$ inclusive. Can you choose such size of pack $a$ that each customer buys more cans than they wanted initially?
-----Input-----
The first line contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases.
The first and only line of each test case contains two integers $l$ and $r$ ($1 \le l \le r \le 10^9$) — the range of the number of cans customers can buy.
-----Output-----
For each test case, print YES if you can choose such size of pack $a$ that each customer buys more cans than they wanted initially. Otherwise, print NO.
You can print each character in any case.
-----Example-----
Input
3
3 4
1 2
120 150
Output
YES
NO
YES
-----Note-----
In the first test case, you can take, for example, $a = 5$ as the size of the pack. Then if a customer wants to buy $3$ cans, he'll buy $5$ instead ($3 \bmod 5 = 3$, $\frac{5}{2} = 2.5$). The one who wants $4$ cans will also buy $5$ cans.
In the second test case, there is no way to choose $a$.
In the third test case, you can take, for example, $a = 80$.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
def main():
#n = int(sys.stdin.readline().strip())
n, m = map(int, sys.stdin.readline().split())
#q = list(map(int, sys.stdin.readline().split()))
if n * 2 > m:
print("YES")
else:
print("NO")
for i in range(int(sys.stdin.readline().strip())):
main()
``` | vfc_13682 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/1437/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n3 4\n1 2\n120 150\n",
"output": "YES\nNO\nYES\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n500000000 1000000000\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n100000001 200000002\n",
"output": "NO\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n1000000000 1000000000\n",
"output": "YES\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 983 | Solve the following coding problem using the programming language python:
Professor Dumbledore is helping Harry destroy the Horcruxes. He went to Gaunt Shack as he suspected a Horcrux to be present there. He saw Marvolo Gaunt's Ring and identified it as a Horcrux. Although he destroyed it, he is still affected by its curse. Professor Snape is helping Dumbledore remove the curse. For this, he wants to give Dumbledore exactly x drops of the potion he made.
Value of x is calculated as maximum of p·a_{i} + q·a_{j} + r·a_{k} for given p, q, r and array a_1, a_2, ... a_{n} such that 1 ≤ i ≤ j ≤ k ≤ n. Help Snape find the value of x. Do note that the value of x may be negative.
-----Input-----
First line of input contains 4 integers n, p, q, r ( - 10^9 ≤ p, q, r ≤ 10^9, 1 ≤ n ≤ 10^5).
Next line of input contains n space separated integers a_1, a_2, ... a_{n} ( - 10^9 ≤ a_{i} ≤ 10^9).
-----Output-----
Output a single integer the maximum value of p·a_{i} + q·a_{j} + r·a_{k} that can be obtained provided 1 ≤ i ≤ j ≤ k ≤ n.
-----Examples-----
Input
5 1 2 3
1 2 3 4 5
Output
30
Input
5 1 2 -3
-1 -2 -3 -4 -5
Output
12
-----Note-----
In the first sample case, we can take i = j = k = 5, thus making the answer as 1·5 + 2·5 + 3·5 = 30.
In second sample case, selecting i = j = 1 and k = 5 gives the answer 12.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
#sys.stdin=open("data.txt")
input=sys.stdin.readline
n,p,q,r=map(int,input().split())
a=list(map(int,input().split()))
s1=[a[i]*p for i in range(n)]
s2=[]
m=s1[0]
for i in range(n):
m=max(m,s1[i])
s2.append(m+a[i]*q)
s3=[]
m=s2[0]
for i in range(n):
m=max(m,s2[i])
s3.append(m+a[i]*r)
print(max(s3))
``` | vfc_13686 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/855/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5 1 2 3\n1 2 3 4 5\n",
"output": "30\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5 1 2 -3\n-1 -2 -3 -4 -5\n",
"output": "12\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 984 | Solve the following coding problem using the programming language python:
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T: Set pointer to the root of a tree. Return success if the value in the current vertex is equal to the number you are looking for Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
-----Input-----
First line contains integer number n (1 ≤ n ≤ 10^5) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 10^9) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
-----Output-----
Print number of times when search algorithm will fail.
-----Examples-----
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
-----Note-----
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
from collections import deque
nodes = []
parents = []
values = []
broken = []
upperBound = []
lowerBound = []
n = int(input())
for _ in range(n):
v, l, r = map(int, input().split())
nodes.append((v, l - 1, r - 1))
parents.append(-1)
values.append(v)
broken.append(False)
upperBound.append(10 ** 9)
lowerBound.append(-10 ** 9)
for i, (v, l, r) in enumerate(nodes):
if l > -1:
parents[l] = i
if r > -1:
parents[r] = i
root = -1
for i in range(n):
if parents[i] == -1:
root = i
proc = deque([root])
while len(proc) > 0:
node = proc.popleft()
v, l, r = nodes[node]
if l > -1:
proc.append(l)
upperBound[l] = min(upperBound[node], v)
lowerBound[l] = lowerBound[node]
if not (lowerBound[l] <= nodes[l][0] <= upperBound[l]):
broken[l] = True
if r > -1:
proc.append(r)
upperBound[r] = upperBound[node]
lowerBound[r] = max(lowerBound[node], v)
if not (lowerBound[r] <= nodes[r][0] <= upperBound[r]):
broken[r] = True
s = set([])
for v, b in zip(values, broken):
if not b:
s.add(v)
ans = 0
for v in values:
if v not in s:
ans += 1
print(ans)
``` | vfc_13690 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/797/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "3\n15 -1 -1\n10 1 3\n5 -1 -1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "8\n6 2 3\n3 4 5\n12 6 7\n1 -1 8\n4 -1 -1\n5 -1 -1\n14 -1 -1\n2 -1 -1\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n493041212 -1 -1\n",
"output": "0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n921294733 5 9\n341281094 -1 -1\n35060484 10 -1\n363363160 -1 -1\n771156014 6 8\n140806462 -1 -1\n118732846 4 2\n603229555 -1 -1\n359289513 3 7\n423237010 -1 -1\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n911605217 -1 -1\n801852416 -1 -1\n140035920 -1 9\n981454947 10 2\n404988051 6 3\n307545107 8 7\n278188888 4 1\n523010786 -1 -1\n441817740 -1 -1\n789680429 -1 -1\n",
"output": "7\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "10\n921072710 6 8\n727122964 -1 -1\n248695736 2 -1\n947477665 -1 -1\n41229309 -1 -1\n422047611 3 9\n424558429 -1 4\n665046372 -1 5\n74510531 -1 -1\n630373520 7 1\n",
"output": "7\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 985 | Solve the following coding problem using the programming language python:
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right.
Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the only criteria, so two bishops may attack each other (according to Wet Shark) even if there is another bishop located between them. Now Wet Shark wants to count the number of pairs of bishops that attack each other.
-----Input-----
The first line of the input contains n (1 ≤ n ≤ 200 000) — the number of bishops.
Each of next n lines contains two space separated integers x_{i} and y_{i} (1 ≤ x_{i}, y_{i} ≤ 1000) — the number of row and the number of column where i-th bishop is positioned. It's guaranteed that no two bishops share the same position.
-----Output-----
Output one integer — the number of pairs of bishops which attack each other.
-----Examples-----
Input
5
1 1
1 5
3 3
5 1
5 5
Output
6
Input
3
1 1
2 3
3 5
Output
0
-----Note-----
In the first sample following pairs of bishops attack each other: (1, 3), (1, 5), (2, 3), (2, 4), (3, 4) and (3, 5). Pairs (1, 2), (1, 4), (2, 5) and (4, 5) do not attack each other because they do not share the same diagonal.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
a=[0]*2222
b=[0]*2222
r=0
for _ in range(int(input())):
x,y=map(int,input().split())
r+=a[x+y]+b[x-y+1111]
a[x+y]+=1
b[x-y+1111]+=1
print(r)
``` | vfc_13694 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/621/B",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "5\n1 1\n1 5\n3 3\n5 1\n5 5\n",
"output": "6\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 986 | Solve the following coding problem using the programming language python:
Your search for Heidi is over – you finally found her at a library, dressed up as a human. In fact, she has spent so much time there that she now runs the place! Her job is to buy books and keep them at the library so that people can borrow and read them. There are n different books, numbered 1 through n.
We will look at the library's operation during n consecutive days. Heidi knows in advance that on the i-th day (1 ≤ i ≤ n) precisely one person will come to the library, request to borrow the book a_{i}, read it in a few hours, and return the book later on the same day.
Heidi desperately wants to please all her guests, so she will make sure to always have the book a_{i} available in the library on the i-th day. During the night before the i-th day, she has the option of going to the bookstore (which operates at nights to avoid competition with the library) and buying any book for the price of 1 CHF. Of course, if she already has a book at the library, she does not need to buy it again. Initially, the library contains no books.
There is a problem, though. The capacity of the library is k – this means that at any time, there can be at most k books at the library. If buying a new book would cause Heidi to have more than k books, she must first get rid of some book that she already has, in order to make room for the new book. If she later needs a book that she got rid of, she will need to buy that book again.
You are given k and the sequence of requests for books a_1, a_2, ..., a_{n}. What is the minimum cost (in CHF) of buying new books to satisfy all the requests?
-----Input-----
The first line of input will contain two integers n and k (1 ≤ n, k ≤ 80). The second line will contain n integers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ n) – the sequence of book requests.
-----Output-----
On a single line print the minimum cost of buying books at the store so as to satisfy all requests.
-----Examples-----
Input
4 80
1 2 2 1
Output
2
Input
4 1
1 2 2 1
Output
3
Input
4 2
1 2 3 1
Output
3
-----Note-----
In the first test case, Heidi is able to keep all books forever. Therefore, she only needs to buy the book 1 before the first day and the book 2 before the second day.
In the second test case, she can only keep one book at a time. Therefore she will need to buy new books on the first, second and fourth day.
In the third test case, before buying book 3 on the third day, she must decide which of the books 1 and 2 she should get rid of. Of course, she should keep the book 1, which will be requested on the fourth day.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
library = []
money = 0
for i in range(len(a)):
if a[i] not in library:
money += 1
if len(library) < k:
library.append(a[i])
else:
curmin = n
curindex = 0
found = [n] * len(library)
for j in range(len(a[i+1::])):
if (a[i+j+1] in library) and (found[library.index(a[i+j+1])]==n):
found[library.index(a[i+j+1])] = j
library[found.index(max(found))] = a[i]
print(money)
``` | vfc_13698 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/802/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "4 80\n1 2 2 1\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "4 1\n1 2 2 1\n",
"output": "3\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 988 | Solve the following coding problem using the programming language python:
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right.
Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture: [Image]
Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard.
You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'.
Find any of the most convenient vacant places for Petya.
-----Input-----
The input consists of 6 lines. Each line describes one row of desks, starting from the closest to the blackboard. Each line is given in the following format: two characters, each is '*' or '.' — the description of the left desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the center desk in the current row; a character '-' — the aisle; two characters, each is '*' or '.' — the description of the right desk in the current row. So, the length of each of the six lines is 8.
It is guaranteed that there is at least one vacant place in the classroom.
-----Output-----
Print the plan of the classroom after Petya takes one of the most convenient for him places. Mark this place with the letter 'P'. There should be exactly one letter 'P' in the plan. Petya can only take a vacant place. In all other places the output should coincide with the input.
If there are multiple answers, print any.
-----Examples-----
Input
..-**-..
..-**-..
..-..-..
..-..-..
..-..-..
..-..-..
Output
..-**-..
..-**-..
..-..-..
..-P.-..
..-..-..
..-..-..
Input
**-**-**
**-**-**
..-**-.*
**-**-**
..-..-..
..-**-..
Output
**-**-**
**-**-**
..-**-.*
**-**-**
..-P.-..
..-**-..
Input
**-**-*.
*.-*.-**
**-**-**
**-**-**
..-..-..
..-**-..
Output
**-**-*.
*.-*P-**
**-**-**
**-**-**
..-..-..
..-**-..
-----Note-----
In the first example the maximum convenience is 3.
In the second example the maximum convenience is 2.
In the third example the maximum convenience is 4.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
import sys
fin = sys.stdin
fout = sys.stdout
a = [0] * 6
for i in range(6):
a[i] = [0] * 6
for i in range(2):
a[i][0] = 3
a[i][1] = 3
a[i][2] = 4
a[i][3] = 4
a[i][4] = 3
a[i][5] = 3
for i in range(2, 4):
a[i][0] = 2
a[i][1] = 2
a[i][2] = 3
a[i][3] = 3
a[i][4] = 2
a[i][5] = 2
for i in range(4, 6):
a[i][0] = 1
a[i][1] = 1
a[i][2] = 2
a[i][3] = 2
a[i][4] = 1
a[i][5] = 1
ansI = -1
ansJ = -1
max = -1
ansL = []
for i in range(6):
s = fin.readline().strip()
ansL.append(s)
s = s.replace("-", "")
for j in range(6):
if s[j] == '.' and a[i][j] > max:
max = a[i][j]
ansI = i
ansJ = j
# print(ansI, ansJ)
for i in range(len(ansL)):
cur = ansL[i]
realJ = -1
for j in range(len(cur)):
if (cur[j] != '-'):
realJ += 1
if i == ansI and realJ == ansJ and cur[j] != '-':
fout.write('P')
else:
fout.write(cur[j])
fout.write("\n")
fin.close()
fout.close()
``` | vfc_13706 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/926/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "..-**-..\n..-**-..\n..-..-..\n..-..-..\n..-..-..\n..-..-..\n",
"output": "..-**-..\n..-**-..\n..-..-..\n..-P.-..\n..-..-..\n..-..-..\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-..-..\n..-**-..\n",
"output": "**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-P.-..\n..-**-..\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 994 | Solve the following coding problem using the programming language python:
A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer h_{i}. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |h_{i} - h_{i} + 1| ≤ 1 holds.
At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |h_{i} - h_{i} + 1| ≤ 1.
-----Input-----
The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 10^8, 1 ≤ m ≤ 10^5) — the number of days of the hike and the number of notes left in the journal.
Next m lines contain two space-separated integers d_{i} and h_{d}_{i} (1 ≤ d_{i} ≤ n, 0 ≤ h_{d}_{i} ≤ 10^8) — the number of the day when the i-th note was made and height on the d_{i}-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: d_{i} < d_{i} + 1.
-----Output-----
If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route.
If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).
-----Examples-----
Input
8 2
2 0
7 0
Output
2
Input
8 3
2 0
7 0
8 3
Output
IMPOSSIBLE
-----Note-----
For the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).
In the second sample the inequality between h_7 and h_8 does not hold, thus the information is inconsistent.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
3
import sys
(n, m) = list(map(int, input().split()))
firstData = None
maxHeight = -1
for i in range(m):
(d, h) = list(map(int, input().split()))
if firstData is None:
firstData = (d, h)
else:
if (d - prevD) < abs(h - prevH):
print ("IMPOSSIBLE")
return
maxH = max(h, prevH)
minH = min(h, prevH)
resource = d - prevD - (maxH - minH) # "free" days for going up-down
possibleH = maxH + resource // 2
maxHeight = max(maxHeight, possibleH)
(prevD, prevH) = (d, h)
lastData = (d, h)
maxHeight = max(maxHeight, firstData[1] + firstData[0] - 1)
maxHeight = max(maxHeight, lastData[1] + (n - lastData[0]))
print (maxHeight)
``` | vfc_13730 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/538/C",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "8 2\n2 0\n7 0\n",
"output": "2\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 995 | Solve the following coding problem using the programming language python:
SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square.
Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array.
SaMer wishes to create more cases from the test case he already has. His test case has an array $A$ of $n$ integers, and he needs to find the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$ for each integer $k$ between $1$ and $n$ (inclusive).
-----Input-----
The first line of input contains a single integer $n$ ($1 \leq n \leq 5000$), the size of the array.
The second line contains $n$ integers $a_1$,$a_2$,$\dots$,$a_n$ ($-10^8 \leq a_i \leq 10^8$), the values of the array.
-----Output-----
Output $n$ space-separated integers, the $k$-th integer should be the number of contiguous subarrays of $A$ that have an answer to the problem equal to $k$.
-----Examples-----
Input
2
5 5
Output
3 0
Input
5
5 -4 2 1 8
Output
5 5 3 2 0
Input
1
0
Output
1
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
from math import sqrt
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307,
311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421,
431, 433, 439, 443, 449, 457, 461, 463]
psq = [p*p for p in primes]
def sqfree(x):
if x == 0:
return x
y = 1
for p, pp in zip(primes, psq):
while x % pp == 0:
x //= pp
if x % p == 0:
x //= p
y *= p
if abs(x) < p:
break
if int(sqrt(abs(x)))**2 == abs(x):
return (y if x > 0 else -y)
else:
return x * y
n = int(input().strip())
ais = list(map(int, input().strip().split()))
bis = list(map(sqfree, ais))
prev = [-1 for i in range(n)]
last = {}
for i, b in enumerate(bis):
if b in last:
prev[i] = last[b]
last[b] = i
res = [0 for i in range(n)]
for l in range(n):
cnt = 0
for r in range(l, n):
if bis[r] != 0 and prev[r] < l:
cnt += 1
res[max(cnt - 1, 0)] += 1
print(' '.join(map(str, res)))
``` | vfc_13734 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/980/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2\n5 5\n",
"output": "3 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n5 -4 2 1 8\n",
"output": "5 5 3 2 0\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n0\n",
"output": "1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3\n-10 -5 7\n",
"output": "3 2 1\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "5\n-6 -7 -2 -3 -10\n",
"output": "5 4 3 2 1\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 996 | Solve the following coding problem using the programming language python:
A super computer has been built in the Turtle Academy of Sciences. The computer consists of n·m·k CPUs. The architecture was the paralellepiped of size n × m × k, split into 1 × 1 × 1 cells, each cell contains exactly one CPU. Thus, each CPU can be simultaneously identified as a group of three numbers from the layer number from 1 to n, the line number from 1 to m and the column number from 1 to k.
In the process of the Super Computer's work the CPUs can send each other messages by the famous turtle scheme: CPU (x, y, z) can send messages to CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) (of course, if they exist), there is no feedback, that is, CPUs (x + 1, y, z), (x, y + 1, z) and (x, y, z + 1) cannot send messages to CPU (x, y, z).
Over time some CPUs broke down and stopped working. Such CPUs cannot send messages, receive messages or serve as intermediates in transmitting messages. We will say that CPU (a, b, c) controls CPU (d, e, f) , if there is a chain of CPUs (x_{i}, y_{i}, z_{i}), such that (x_1 = a, y_1 = b, z_1 = c), (x_{p} = d, y_{p} = e, z_{p} = f) (here and below p is the length of the chain) and the CPU in the chain with number i (i < p) can send messages to CPU i + 1.
Turtles are quite concerned about the denial-proofness of the system of communication between the remaining CPUs. For that they want to know the number of critical CPUs. A CPU (x, y, z) is critical, if turning it off will disrupt some control, that is, if there are two distinctive from (x, y, z) CPUs: (a, b, c) and (d, e, f), such that (a, b, c) controls (d, e, f) before (x, y, z) is turned off and stopped controlling it after the turning off.
-----Input-----
The first line contains three integers n, m and k (1 ≤ n, m, k ≤ 100) — the dimensions of the Super Computer.
Then n blocks follow, describing the current state of the processes. The blocks correspond to the layers of the Super Computer in the order from 1 to n. Each block consists of m lines, k characters in each — the description of a layer in the format of an m × k table. Thus, the state of the CPU (x, y, z) is corresponded to the z-th character of the y-th line of the block number x. Character "1" corresponds to a working CPU and character "0" corresponds to a malfunctioning one. The blocks are separated by exactly one empty line.
-----Output-----
Print a single integer — the number of critical CPUs, that is, such that turning only this CPU off will disrupt some control.
-----Examples-----
Input
2 2 3
000
000
111
111
Output
2
Input
3 3 3
111
111
111
111
111
111
111
111
111
Output
19
Input
1 1 10
0101010101
Output
0
-----Note-----
In the first sample the whole first layer of CPUs is malfunctional. In the second layer when CPU (2, 1, 2) turns off, it disrupts the control by CPU (2, 1, 3) over CPU (2, 1, 1), and when CPU (2, 2, 2) is turned off, it disrupts the control over CPU (2, 2, 3) by CPU (2, 2, 1).
In the second sample all processors except for the corner ones are critical.
In the third sample there is not a single processor controlling another processor, so the answer is 0.
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
def main():
s = input().split()
n, m, k = int(s[0]), int(s[1]), int(s[2])
processor = []
for x in range(n):
for y in range(m):
s = input()
for z in s:
processor.append(int(z) == 1)
if x < n - 1:
emptyLine = input()
counter = 0
mk = m * k
nmk = n * mk
for i in range(nmk):
if not processor[i]:
continue
# back
if i >= mk:
if processor[i - mk]:
# front
if i < (nmk - mk):
if processor[i + mk]:
counter += 1
continue
# right
if (i % k) < (k - 1):
if processor[i + 1]:
if not processor[i - mk + 1]:
counter += 1
continue
# down
if (i % mk) < (mk - k):
if processor[i + k]:
if not processor[i - mk + k]:
counter += 1
continue
# left
if (i % k) > 0:
if processor[i - 1]:
# front
if i < (nmk - mk):
if processor[i + mk]:
if not processor[i + mk - 1]:
counter += 1
continue
# right
if (i % k) < (k - 1):
if processor[i + 1]:
counter += 1
continue
# down
if (i % mk) < (mk - k):
if processor[i + k]:
if not processor[i + k - 1]:
counter += 1
continue
# up
if (i % mk) >= k:
if processor[i - k]:
# front
if i < (nmk - mk):
if processor[i + mk]:
if not processor[i + mk - k]:
counter += 1
continue
# right
if (i % k) < (k - 1):
if processor[i + 1]:
if not processor[i - k + 1]:
counter += 1
continue
# down
if (i % mk) < (mk - k):
if processor[i + k]:
counter += 1
continue
print(counter)
main()
``` | vfc_13738 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/638/D",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "2 2 3\n000\n000\n\n111\n111\n",
"output": "2\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "3 3 3\n111\n111\n111\n\n111\n111\n111\n\n111\n111\n111\n",
"output": "19\n",
"type": "stdin_stdout"
}
]
} |
apps | verifiable_code | 997 | Solve the following coding problem using the programming language python:
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.
You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).
Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.
For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".
-----Input-----
The only line of input contains the string s (1 ≤ |s| ≤ 10^5). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
-----Output-----
Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34).
If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
-----Examples-----
Input
aba,123;1a;0
Output
"123,0"
"aba,1a"
Input
1;;01,a0,
Output
"1"
",01,a0,"
Input
1
Output
"1"
-
Input
a
Output
-
"a"
-----Note-----
In the second example the string s contains five words: "1", "", "01", "a0", "".
The input will be stdin and you should print your solution to stdout
Now solve the problem and return the code. | ```python
#!/usr/bin/env python3
import re
try:
while True:
a = [ ]
b = [ ]
for word in re.split(R"[,;]", input()):
(a if re.match(R"^(0|[1-9][0-9]*)$", word) else b).append(word)
print('"%s"' % ','.join(a) if a else '-')
print('"%s"' % ','.join(b) if b else '-')
except EOFError:
pass
``` | vfc_13742 | {
"difficulty": "interview",
"memory_limit": null,
"memory_limit_bytes": null,
"problem_url": "https://codeforces.com/problemset/problem/600/A",
"time_limit": "None"
} | {
"language": "python",
"test_cases": [
{
"fn_name": null,
"input": "aba,123;1a;0\n",
"output": "\"123,0\"\n\"aba,1a\"\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1;;01,a0,\n",
"output": "\"1\"\n\",01,a0,\"\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "1\n",
"output": "\"1\"\n-\n",
"type": "stdin_stdout"
},
{
"fn_name": null,
"input": "a\n",
"output": "-\n\"a\"\n",
"type": "stdin_stdout"
}
]
} |
Subsets and Splits